]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/resolve_lifetime.rs
Auto merge of #29962 - aturon:coherence-errors, r=nmatsakis
[rust.git] / src / librustc / middle / resolve_lifetime.rs
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.
4 //
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.
10
11 //! Name resolution for lifetimes.
12 //!
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.
17
18 pub use self::DefRegion::*;
19 use self::ScopeChain::*;
20
21 use session::Session;
22 use middle::def::{self, DefMap};
23 use middle::region;
24 use middle::subst;
25 use middle::ty;
26 use std::fmt;
27 use std::mem::replace;
28 use syntax::ast;
29 use syntax::codemap::Span;
30 use syntax::parse::token::special_idents;
31 use util::nodemap::NodeMap;
32
33 use rustc_front::hir;
34 use rustc_front::print::pprust::lifetime_to_string;
35 use rustc_front::intravisit::{self, Visitor, FnKind};
36
37 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
38 pub enum DefRegion {
39     DefStaticRegion,
40     DefEarlyBoundRegion(/* space */ subst::ParamSpace,
41                         /* index */ u32,
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),
47 }
48
49 // Maps the id of each lifetime reference to the lifetime decl
50 // that it corresponds to.
51 pub type NamedRegionMap = NodeMap<DefRegion>;
52
53 struct LifetimeContext<'a> {
54     sess: &'a Session,
55     named_region_map: &'a mut NamedRegionMap,
56     scope: Scope<'a>,
57     def_map: &'a DefMap,
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).
66
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.
71
72     // I'm sorry.
73     trait_ref_hack: bool,
74
75     // List of labels in the function/method currently under analysis.
76     labels_in_fn: Vec<(ast::Name, Span)>,
77 }
78
79 enum ScopeChain<'a> {
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
87     /// to that block.
88     BlockScope(region::DestructionScopeData, Scope<'a>),
89     RootScope
90 }
91
92 type Scope<'a> = &'a ScopeChain<'a>;
93
94 static ROOT_SCOPE: ScopeChain<'static> = RootScope;
95
96 pub fn krate(sess: &Session, krate: &hir::Crate, def_map: &DefMap) -> NamedRegionMap {
97     let mut named_region_map = NodeMap();
98     sess.abort_if_new_errors(|| {
99         krate.visit_all_items(&mut LifetimeContext {
100             sess: sess,
101             named_region_map: &mut named_region_map,
102             scope: &ROOT_SCOPE,
103             def_map: def_map,
104             trait_ref_hack: false,
105             labels_in_fn: vec![],
106         });
107     });
108     named_region_map
109 }
110
111 impl<'a, 'v> Visitor<'v> for LifetimeContext<'a> {
112     fn visit_item(&mut self, item: &hir::Item) {
113         assert!(self.labels_in_fn.is_empty());
114
115         // Items always introduce a new root scope
116         self.with(RootScope, |_, this| {
117             match item.node {
118                 hir::ItemFn(..) => {
119                     // Fn lifetimes get added in visit_fn below:
120                     intravisit::walk_item(this, item);
121                 }
122                 hir::ItemExternCrate(_) |
123                 hir::ItemUse(_) |
124                 hir::ItemMod(..) |
125                 hir::ItemDefaultImpl(..) |
126                 hir::ItemForeignMod(..) |
127                 hir::ItemStatic(..) |
128                 hir::ItemConst(..) => {
129                     // These sorts of items have no lifetime parameters at all.
130                     intravisit::walk_item(this, item);
131                 }
132                 hir::ItemTy(_, ref generics) |
133                 hir::ItemEnum(_, ref generics) |
134                 hir::ItemStruct(_, ref generics) |
135                 hir::ItemTrait(_, ref generics, _, _) |
136                 hir::ItemImpl(_, _, ref generics, _, _, _) => {
137                     // These kinds of items have only early bound lifetime parameters.
138                     let lifetimes = &generics.lifetimes;
139                     let early_scope = EarlyScope(subst::TypeSpace, lifetimes, &ROOT_SCOPE);
140                     this.with(early_scope, |old_scope, this| {
141                         this.check_lifetime_defs(old_scope, lifetimes);
142                         intravisit::walk_item(this, item);
143                     });
144                 }
145             }
146         });
147
148         // Done traversing the item; remove any labels it created
149         self.labels_in_fn.truncate(0);
150     }
151
152     fn visit_foreign_item(&mut self, item: &hir::ForeignItem) {
153         // Items save/restore the set of labels. This way inner items
154         // can freely reuse names, be they loop labels or lifetimes.
155         let saved = replace(&mut self.labels_in_fn, vec![]);
156
157         // Items always introduce a new root scope
158         self.with(RootScope, |_, this| {
159             match item.node {
160                 hir::ForeignItemFn(_, ref generics) => {
161                     this.visit_early_late(subst::FnSpace, generics, |this| {
162                         intravisit::walk_foreign_item(this, item);
163                     })
164                 }
165                 hir::ForeignItemStatic(..) => {
166                     intravisit::walk_foreign_item(this, item);
167                 }
168             }
169         });
170
171         // Done traversing the item; restore saved set of labels.
172         replace(&mut self.labels_in_fn, saved);
173     }
174
175     fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v hir::FnDecl,
176                 b: &'v hir::Block, s: Span, _: ast::NodeId) {
177         match fk {
178             FnKind::ItemFn(_, generics, _, _, _, _) => {
179                 self.visit_early_late(subst::FnSpace, generics, |this| {
180                     this.walk_fn(fk, fd, b, s)
181                 })
182             }
183             FnKind::Method(_, sig, _) => {
184                 self.visit_early_late(subst::FnSpace, &sig.generics, |this| {
185                     this.walk_fn(fk, fd, b, s)
186                 })
187             }
188             FnKind::Closure => {
189                 self.walk_fn(fk, fd, b, s)
190             }
191         }
192     }
193
194     fn visit_ty(&mut self, ty: &hir::Ty) {
195         match ty.node {
196             hir::TyBareFn(ref c) => {
197                 self.with(LateScope(&c.lifetimes, self.scope), |old_scope, this| {
198                     // a bare fn has no bounds, so everything
199                     // contained within is scoped within its binder.
200                     this.check_lifetime_defs(old_scope, &c.lifetimes);
201                     intravisit::walk_ty(this, ty);
202                 });
203             }
204             hir::TyPath(None, ref path) => {
205                 // if this path references a trait, then this will resolve to
206                 // a trait ref, which introduces a binding scope.
207                 match self.def_map.get(&ty.id).map(|d| (d.base_def, d.depth)) {
208                     Some((def::DefTrait(..), 0)) => {
209                         self.with(LateScope(&Vec::new(), self.scope), |_, this| {
210                             this.visit_path(path, ty.id);
211                         });
212                     }
213                     _ => {
214                         intravisit::walk_ty(self, ty);
215                     }
216                 }
217             }
218             _ => {
219                 intravisit::walk_ty(self, ty)
220             }
221         }
222     }
223
224     fn visit_trait_item(&mut self, trait_item: &hir::TraitItem) {
225         // We reset the labels on every trait item, so that different
226         // methods in an impl can reuse label names.
227         let saved = replace(&mut self.labels_in_fn, vec![]);
228
229         if let hir::MethodTraitItem(ref sig, None) = trait_item.node {
230             self.visit_early_late(
231                 subst::FnSpace, &sig.generics,
232                 |this| intravisit::walk_trait_item(this, trait_item))
233         } else {
234             intravisit::walk_trait_item(self, trait_item);
235         }
236
237         replace(&mut self.labels_in_fn, saved);
238     }
239
240     fn visit_block(&mut self, b: &hir::Block) {
241         self.with(BlockScope(region::DestructionScopeData::new(b.id),
242                              self.scope),
243                   |_, this| intravisit::walk_block(this, b));
244     }
245
246     fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
247         if lifetime_ref.name == special_idents::static_lifetime.name {
248             self.insert_lifetime(lifetime_ref, DefStaticRegion);
249             return;
250         }
251         self.resolve_lifetime_ref(lifetime_ref);
252     }
253
254     fn visit_generics(&mut self, generics: &hir::Generics) {
255         for ty_param in generics.ty_params.iter() {
256             walk_list!(self, visit_ty_param_bound, &ty_param.bounds);
257             match ty_param.default {
258                 Some(ref ty) => self.visit_ty(&**ty),
259                 None => {}
260             }
261         }
262         for predicate in &generics.where_clause.predicates {
263             match predicate {
264                 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ ref bounded_ty,
265                                                                                ref bounds,
266                                                                                ref bound_lifetimes,
267                                                                                .. }) => {
268                     if !bound_lifetimes.is_empty() {
269                         self.trait_ref_hack = true;
270                         let result = self.with(LateScope(bound_lifetimes, self.scope),
271                                                |old_scope, this| {
272                             this.check_lifetime_defs(old_scope, bound_lifetimes);
273                             this.visit_ty(&**bounded_ty);
274                             walk_list!(this, visit_ty_param_bound, bounds);
275                         });
276                         self.trait_ref_hack = false;
277                         result
278                     } else {
279                         self.visit_ty(&**bounded_ty);
280                         walk_list!(self, visit_ty_param_bound, bounds);
281                     }
282                 }
283                 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
284                                                                                 ref bounds,
285                                                                                 .. }) => {
286
287                     self.visit_lifetime(lifetime);
288                     for bound in bounds {
289                         self.visit_lifetime(bound);
290                     }
291                 }
292                 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ id,
293                                                                          ref path,
294                                                                          ref ty,
295                                                                          .. }) => {
296                     self.visit_path(path, id);
297                     self.visit_ty(&**ty);
298                 }
299             }
300         }
301     }
302
303     fn visit_poly_trait_ref(&mut self,
304                             trait_ref: &hir::PolyTraitRef,
305                             _modifier: &hir::TraitBoundModifier) {
306         debug!("visit_poly_trait_ref trait_ref={:?}", trait_ref);
307
308         if !self.trait_ref_hack || !trait_ref.bound_lifetimes.is_empty() {
309             if self.trait_ref_hack {
310                 println!("{:?}", trait_ref.span);
311                 span_err!(self.sess, trait_ref.span, E0316,
312                           "nested quantification of lifetimes");
313             }
314             self.with(LateScope(&trait_ref.bound_lifetimes, self.scope), |old_scope, this| {
315                 this.check_lifetime_defs(old_scope, &trait_ref.bound_lifetimes);
316                 for lifetime in &trait_ref.bound_lifetimes {
317                     this.visit_lifetime_def(lifetime);
318                 }
319                 intravisit::walk_path(this, &trait_ref.trait_ref.path)
320             })
321         } else {
322             self.visit_trait_ref(&trait_ref.trait_ref)
323         }
324     }
325 }
326
327 #[derive(Copy, Clone, PartialEq)]
328 enum ShadowKind { Label, Lifetime }
329 struct Original { kind: ShadowKind, span: Span }
330 struct Shadower { kind: ShadowKind, span: Span }
331
332 fn original_label(span: Span) -> Original {
333     Original { kind: ShadowKind::Label, span: span }
334 }
335 fn shadower_label(span: Span) -> Shadower {
336     Shadower { kind: ShadowKind::Label, span: span }
337 }
338 fn original_lifetime(l: &hir::Lifetime) -> Original {
339     Original { kind: ShadowKind::Lifetime, span: l.span }
340 }
341 fn shadower_lifetime(l: &hir::Lifetime) -> Shadower {
342     Shadower { kind: ShadowKind::Lifetime, span: l.span }
343 }
344
345 impl ShadowKind {
346     fn desc(&self) -> &'static str {
347         match *self {
348             ShadowKind::Label => "label",
349             ShadowKind::Lifetime => "lifetime",
350         }
351     }
352 }
353
354 fn signal_shadowing_problem(
355     sess: &Session, name: ast::Name, orig: Original, shadower: Shadower) {
356     if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
357         // lifetime/lifetime shadowing is an error
358         span_err!(sess, shadower.span, E0496,
359                   "{} name `{}` shadows a \
360                    {} name that is already in scope",
361                   shadower.kind.desc(), name, orig.kind.desc());
362     } else {
363         // shadowing involving a label is only a warning, due to issues with
364         // labels and lifetimes not being macro-hygienic.
365         sess.span_warn(shadower.span,
366                       &format!("{} name `{}` shadows a \
367                                 {} name that is already in scope",
368                                shadower.kind.desc(), name, orig.kind.desc()));
369     }
370     sess.span_note(orig.span,
371                    &format!("shadowed {} `{}` declared here",
372                             orig.kind.desc(), name));
373 }
374
375 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
376 // if one of the label shadows a lifetime or another label.
377 fn extract_labels<'v, 'a>(ctxt: &mut LifetimeContext<'a>, b: &'v hir::Block) {
378
379     struct GatherLabels<'a> {
380         sess: &'a Session,
381         scope: Scope<'a>,
382         labels_in_fn: &'a mut Vec<(ast::Name, Span)>,
383     }
384
385     let mut gather = GatherLabels {
386         sess: ctxt.sess,
387         scope: ctxt.scope,
388         labels_in_fn: &mut ctxt.labels_in_fn,
389     };
390     gather.visit_block(b);
391     return;
392
393     impl<'v, 'a> Visitor<'v> for GatherLabels<'a> {
394         fn visit_expr(&mut self, ex: &'v hir::Expr) {
395             // do not recurse into closures defined in the block
396             // since they are treated as separate fns from the POV of
397             // labels_in_fn
398             if let hir::ExprClosure(..) = ex.node {
399                 return
400             }
401             if let Some(label) = expression_label(ex) {
402                 for &(prior, prior_span) in &self.labels_in_fn[..] {
403                     // FIXME (#24278): non-hygienic comparison
404                     if label == prior {
405                         signal_shadowing_problem(self.sess,
406                                                  label,
407                                                  original_label(prior_span),
408                                                  shadower_label(ex.span));
409                     }
410                 }
411
412                 check_if_label_shadows_lifetime(self.sess,
413                                                 self.scope,
414                                                 label,
415                                                 ex.span);
416
417                 self.labels_in_fn.push((label, ex.span));
418             }
419             intravisit::walk_expr(self, ex)
420         }
421
422         fn visit_item(&mut self, _: &hir::Item) {
423             // do not recurse into items defined in the block
424         }
425     }
426
427     fn expression_label(ex: &hir::Expr) -> Option<ast::Name> {
428         match ex.node {
429             hir::ExprWhile(_, _, Some(label)) |
430             hir::ExprLoop(_, Some(label)) => Some(label.unhygienic_name),
431             _ => None,
432         }
433     }
434
435     fn check_if_label_shadows_lifetime<'a>(sess: &'a Session,
436                                            mut scope: Scope<'a>,
437                                            label: ast::Name,
438                                            label_span: Span) {
439         loop {
440             match *scope {
441                 BlockScope(_, s) => { scope = s; }
442                 RootScope => { return; }
443
444                 EarlyScope(_, lifetimes, s) |
445                 LateScope(lifetimes, s) => {
446                     for lifetime_def in lifetimes {
447                         // FIXME (#24278): non-hygienic comparison
448                         if label == lifetime_def.lifetime.name {
449                             signal_shadowing_problem(
450                                 sess,
451                                 label,
452                                 original_lifetime(&lifetime_def.lifetime),
453                                 shadower_label(label_span));
454                             return;
455                         }
456                     }
457                     scope = s;
458                 }
459             }
460         }
461     }
462 }
463
464 impl<'a> LifetimeContext<'a> {
465     // This is just like intravisit::walk_fn, except that it extracts the
466     // labels of the function body and swaps them in before visiting
467     // the function body itself.
468     fn walk_fn<'b>(&mut self,
469                    fk: FnKind,
470                    fd: &hir::FnDecl,
471                    fb: &'b hir::Block,
472                    _span: Span) {
473         match fk {
474             FnKind::ItemFn(_, generics, _, _, _, _) => {
475                 intravisit::walk_fn_decl(self, fd);
476                 self.visit_generics(generics);
477             }
478             FnKind::Method(_, sig, _) => {
479                 intravisit::walk_fn_decl(self, fd);
480                 self.visit_generics(&sig.generics);
481                 self.visit_explicit_self(&sig.explicit_self);
482             }
483             FnKind::Closure => {
484                 intravisit::walk_fn_decl(self, fd);
485             }
486         }
487
488         // After inpsecting the decl, add all labels from the body to
489         // `self.labels_in_fn`.
490         extract_labels(self, fb);
491
492         self.visit_block(fb);
493     }
494
495     fn with<F>(&mut self, wrap_scope: ScopeChain, f: F) where
496         F: FnOnce(Scope, &mut LifetimeContext),
497     {
498         let LifetimeContext {sess, ref mut named_region_map, ..} = *self;
499         let mut this = LifetimeContext {
500             sess: sess,
501             named_region_map: *named_region_map,
502             scope: &wrap_scope,
503             def_map: self.def_map,
504             trait_ref_hack: self.trait_ref_hack,
505             labels_in_fn: self.labels_in_fn.clone(),
506         };
507         debug!("entering scope {:?}", this.scope);
508         f(self.scope, &mut this);
509         debug!("exiting scope {:?}", this.scope);
510     }
511
512     /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
513     ///
514     /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
515     /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
516     /// within type bounds; those are early bound lifetimes, and the rest are late bound.
517     ///
518     /// For example:
519     ///
520     ///    fn foo<'a,'b,'c,T:Trait<'b>>(...)
521     ///
522     /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
523     /// lifetimes may be interspersed together.
524     ///
525     /// If early bound lifetimes are present, we separate them into their own list (and likewise
526     /// for late bound). They will be numbered sequentially, starting from the lowest index that is
527     /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
528     /// bound lifetimes are resolved by name and associated with a binder id (`binder_id`), so the
529     /// ordering is not important there.
530     fn visit_early_late<F>(&mut self,
531                            early_space: subst::ParamSpace,
532                            generics: &hir::Generics,
533                            walk: F) where
534         F: FnOnce(&mut LifetimeContext),
535     {
536         let referenced_idents = early_bound_lifetime_names(generics);
537
538         debug!("visit_early_late: referenced_idents={:?}",
539                referenced_idents);
540
541         let (early, late): (Vec<_>, _) = generics.lifetimes.iter().cloned().partition(
542             |l| referenced_idents.iter().any(|&i| i == l.lifetime.name));
543
544         self.with(EarlyScope(early_space, &early, self.scope), move |old_scope, this| {
545             this.with(LateScope(&late, this.scope), move |_, this| {
546                 this.check_lifetime_defs(old_scope, &generics.lifetimes);
547                 walk(this);
548             });
549         });
550     }
551
552     fn resolve_lifetime_ref(&mut self, lifetime_ref: &hir::Lifetime) {
553         // Walk up the scope chain, tracking the number of fn scopes
554         // that we pass through, until we find a lifetime with the
555         // given name or we run out of scopes. If we encounter a code
556         // block, then the lifetime is not bound but free, so switch
557         // over to `resolve_free_lifetime_ref()` to complete the
558         // search.
559         let mut late_depth = 0;
560         let mut scope = self.scope;
561         loop {
562             match *scope {
563                 BlockScope(blk_scope, s) => {
564                     return self.resolve_free_lifetime_ref(blk_scope, lifetime_ref, s);
565                 }
566
567                 RootScope => {
568                     break;
569                 }
570
571                 EarlyScope(space, lifetimes, s) => {
572                     match search_lifetimes(lifetimes, lifetime_ref) {
573                         Some((index, lifetime_def)) => {
574                             let decl_id = lifetime_def.id;
575                             let def = DefEarlyBoundRegion(space, index, decl_id);
576                             self.insert_lifetime(lifetime_ref, def);
577                             return;
578                         }
579                         None => {
580                             scope = s;
581                         }
582                     }
583                 }
584
585                 LateScope(lifetimes, s) => {
586                     match search_lifetimes(lifetimes, lifetime_ref) {
587                         Some((_index, lifetime_def)) => {
588                             let decl_id = lifetime_def.id;
589                             let debruijn = ty::DebruijnIndex::new(late_depth + 1);
590                             let def = DefLateBoundRegion(debruijn, decl_id);
591                             self.insert_lifetime(lifetime_ref, def);
592                             return;
593                         }
594
595                         None => {
596                             late_depth += 1;
597                             scope = s;
598                         }
599                     }
600                 }
601             }
602         }
603
604         self.unresolved_lifetime_ref(lifetime_ref);
605     }
606
607     fn resolve_free_lifetime_ref(&mut self,
608                                  scope_data: region::DestructionScopeData,
609                                  lifetime_ref: &hir::Lifetime,
610                                  scope: Scope) {
611         debug!("resolve_free_lifetime_ref \
612                 scope_data: {:?} lifetime_ref: {:?} scope: {:?}",
613                scope_data, lifetime_ref, scope);
614
615         // Walk up the scope chain, tracking the outermost free scope,
616         // until we encounter a scope that contains the named lifetime
617         // or we run out of scopes.
618         let mut scope_data = scope_data;
619         let mut scope = scope;
620         let mut search_result = None;
621         loop {
622             debug!("resolve_free_lifetime_ref \
623                     scope_data: {:?} scope: {:?} search_result: {:?}",
624                    scope_data, scope, search_result);
625             match *scope {
626                 BlockScope(blk_scope_data, s) => {
627                     scope_data = blk_scope_data;
628                     scope = s;
629                 }
630
631                 RootScope => {
632                     break;
633                 }
634
635                 EarlyScope(_, lifetimes, s) |
636                 LateScope(lifetimes, s) => {
637                     search_result = search_lifetimes(lifetimes, lifetime_ref);
638                     if search_result.is_some() {
639                         break;
640                     }
641                     scope = s;
642                 }
643             }
644         }
645
646         match search_result {
647             Some((_depth, lifetime)) => {
648                 let def = DefFreeRegion(scope_data, lifetime.id);
649                 self.insert_lifetime(lifetime_ref, def);
650             }
651
652             None => {
653                 self.unresolved_lifetime_ref(lifetime_ref);
654             }
655         }
656
657     }
658
659     fn unresolved_lifetime_ref(&self, lifetime_ref: &hir::Lifetime) {
660         span_err!(self.sess, lifetime_ref.span, E0261,
661             "use of undeclared lifetime name `{}`",
662                     lifetime_ref.name);
663     }
664
665     fn check_lifetime_defs(&mut self, old_scope: Scope, lifetimes: &Vec<hir::LifetimeDef>) {
666         for i in 0..lifetimes.len() {
667             let lifetime_i = &lifetimes[i];
668
669             let special_idents = [special_idents::static_lifetime];
670             for lifetime in lifetimes {
671                 if special_idents.iter().any(|&i| i.name == lifetime.lifetime.name) {
672                     span_err!(self.sess, lifetime.lifetime.span, E0262,
673                         "invalid lifetime parameter name: `{}`", lifetime.lifetime.name);
674                 }
675             }
676
677             // It is a hard error to shadow a lifetime within the same scope.
678             for j in i + 1..lifetimes.len() {
679                 let lifetime_j = &lifetimes[j];
680
681                 if lifetime_i.lifetime.name == lifetime_j.lifetime.name {
682                     span_err!(self.sess, lifetime_j.lifetime.span, E0263,
683                         "lifetime name `{}` declared twice in \
684                                 the same scope",
685                                 lifetime_j.lifetime.name);
686                 }
687             }
688
689             // It is a soft error to shadow a lifetime within a parent scope.
690             self.check_lifetime_def_for_shadowing(old_scope, &lifetime_i.lifetime);
691
692             for bound in &lifetime_i.bounds {
693                 self.resolve_lifetime_ref(bound);
694             }
695         }
696     }
697
698     fn check_lifetime_def_for_shadowing(&self,
699                                         mut old_scope: Scope,
700                                         lifetime: &hir::Lifetime)
701     {
702         for &(label, label_span) in &self.labels_in_fn {
703             // FIXME (#24278): non-hygienic comparison
704             if lifetime.name == label {
705                 signal_shadowing_problem(self.sess,
706                                          lifetime.name,
707                                          original_label(label_span),
708                                          shadower_lifetime(&lifetime));
709                 return;
710             }
711         }
712
713         loop {
714             match *old_scope {
715                 BlockScope(_, s) => {
716                     old_scope = s;
717                 }
718
719                 RootScope => {
720                     return;
721                 }
722
723                 EarlyScope(_, lifetimes, s) |
724                 LateScope(lifetimes, s) => {
725                     if let Some((_, lifetime_def)) = search_lifetimes(lifetimes, lifetime) {
726                         signal_shadowing_problem(
727                             self.sess,
728                             lifetime.name,
729                             original_lifetime(&lifetime_def),
730                             shadower_lifetime(&lifetime));
731                         return;
732                     }
733
734                     old_scope = s;
735                 }
736             }
737         }
738     }
739
740     fn insert_lifetime(&mut self,
741                        lifetime_ref: &hir::Lifetime,
742                        def: DefRegion) {
743         if lifetime_ref.id == ast::DUMMY_NODE_ID {
744             self.sess.span_bug(lifetime_ref.span,
745                                "lifetime reference not renumbered, \
746                                probably a bug in syntax::fold");
747         }
748
749         debug!("lifetime_ref={:?} id={:?} resolved to {:?}",
750                 lifetime_to_string(lifetime_ref),
751                 lifetime_ref.id,
752                 def);
753         self.named_region_map.insert(lifetime_ref.id, def);
754     }
755 }
756
757 fn search_lifetimes<'a>(lifetimes: &'a Vec<hir::LifetimeDef>,
758                     lifetime_ref: &hir::Lifetime)
759                     -> Option<(u32, &'a hir::Lifetime)> {
760     for (i, lifetime_decl) in lifetimes.iter().enumerate() {
761         if lifetime_decl.lifetime.name == lifetime_ref.name {
762             return Some((i as u32, &lifetime_decl.lifetime));
763         }
764     }
765     return None;
766 }
767
768 ///////////////////////////////////////////////////////////////////////////
769
770 pub fn early_bound_lifetimes<'a>(generics: &'a hir::Generics) -> Vec<hir::LifetimeDef> {
771     let referenced_idents = early_bound_lifetime_names(generics);
772     if referenced_idents.is_empty() {
773         return Vec::new();
774     }
775
776     generics.lifetimes.iter()
777         .filter(|l| referenced_idents.iter().any(|&i| i == l.lifetime.name))
778         .cloned()
779         .collect()
780 }
781
782 /// Given a set of generic declarations, returns a list of names containing all early bound
783 /// lifetime names for those generics. (In fact, this list may also contain other names.)
784 fn early_bound_lifetime_names(generics: &hir::Generics) -> Vec<ast::Name> {
785     // Create two lists, dividing the lifetimes into early/late bound.
786     // Initially, all of them are considered late, but we will move
787     // things from late into early as we go if we find references to
788     // them.
789     let mut early_bound = Vec::new();
790     let mut late_bound = generics.lifetimes.iter()
791                                            .map(|l| l.lifetime.name)
792                                            .collect();
793
794     // Any lifetime that appears in a type bound is early.
795     {
796         let mut collector =
797             FreeLifetimeCollector { early_bound: &mut early_bound,
798                                     late_bound: &mut late_bound };
799         for ty_param in generics.ty_params.iter() {
800             walk_list!(&mut collector, visit_ty_param_bound, &ty_param.bounds);
801         }
802         for predicate in &generics.where_clause.predicates {
803             match predicate {
804                 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bounds,
805                                                                               ref bounded_ty,
806                                                                               ..}) => {
807                     collector.visit_ty(&**bounded_ty);
808                     walk_list!(&mut collector, visit_ty_param_bound, bounds);
809                 }
810                 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
811                                                                                 ref bounds,
812                                                                                 ..}) => {
813                     collector.visit_lifetime(lifetime);
814
815                     for bound in bounds {
816                         collector.visit_lifetime(bound);
817                     }
818                 }
819                 &hir::WherePredicate::EqPredicate(_) => unimplemented!()
820             }
821         }
822     }
823
824     // Any lifetime that either has a bound or is referenced by a
825     // bound is early.
826     for lifetime_def in &generics.lifetimes {
827         if !lifetime_def.bounds.is_empty() {
828             shuffle(&mut early_bound, &mut late_bound,
829                     lifetime_def.lifetime.name);
830             for bound in &lifetime_def.bounds {
831                 shuffle(&mut early_bound, &mut late_bound,
832                         bound.name);
833             }
834         }
835     }
836     return early_bound;
837
838     struct FreeLifetimeCollector<'a> {
839         early_bound: &'a mut Vec<ast::Name>,
840         late_bound: &'a mut Vec<ast::Name>,
841     }
842
843     impl<'a, 'v> Visitor<'v> for FreeLifetimeCollector<'a> {
844         fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
845             shuffle(self.early_bound, self.late_bound,
846                     lifetime_ref.name);
847         }
848     }
849
850     fn shuffle(early_bound: &mut Vec<ast::Name>,
851                late_bound: &mut Vec<ast::Name>,
852                name: ast::Name) {
853         match late_bound.iter().position(|n| *n == name) {
854             Some(index) => {
855                 late_bound.swap_remove(index);
856                 early_bound.push(name);
857             }
858             None => { }
859         }
860     }
861 }
862
863 impl<'a> fmt::Debug for ScopeChain<'a> {
864     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
865         match *self {
866             EarlyScope(space, defs, _) => write!(fmt, "EarlyScope({:?}, {:?})", space, defs),
867             LateScope(defs, _) => write!(fmt, "LateScope({:?})", defs),
868             BlockScope(id, _) => write!(fmt, "BlockScope({:?})", id),
869             RootScope => write!(fmt, "RootScope"),
870         }
871     }
872 }