]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/resolve_lifetime.rs
Auto merge of #28651 - dotdash:exhaustive_match, r=eddyb
[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::visit::{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     visit::walk_crate(&mut LifetimeContext {
99         sess: sess,
100         named_region_map: &mut named_region_map,
101         scope: &ROOT_SCOPE,
102         def_map: def_map,
103         trait_ref_hack: false,
104         labels_in_fn: vec![],
105     }, krate);
106     sess.abort_if_errors();
107     named_region_map
108 }
109
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![]);
115
116         // Items always introduce a new root scope
117         self.with(RootScope, |_, this| {
118             match item.node {
119                 hir::ItemFn(..) => {
120                     // Fn lifetimes get added in visit_fn below:
121                     visit::walk_item(this, item);
122                 }
123                 hir::ItemExternCrate(_) |
124                 hir::ItemUse(_) |
125                 hir::ItemMod(..) |
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);
132                 }
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);
144                     });
145                 }
146             }
147         });
148
149         // Done traversing the item; restore saved set of labels.
150         replace(&mut self.labels_in_fn, saved);
151     }
152
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![]);
157
158         // Items always introduce a new root scope
159         self.with(RootScope, |_, this| {
160             match item.node {
161                 hir::ForeignItemFn(_, ref generics) => {
162                     this.visit_early_late(subst::FnSpace, generics, |this| {
163                         visit::walk_foreign_item(this, item);
164                     })
165                 }
166                 hir::ForeignItemStatic(..) => {
167                     visit::walk_foreign_item(this, item);
168                 }
169             }
170         });
171
172         // Done traversing the item; restore saved set of labels.
173         replace(&mut self.labels_in_fn, saved);
174     }
175
176     fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v hir::FnDecl,
177                 b: &'v hir::Block, s: Span, _: ast::NodeId) {
178         match fk {
179             FnKind::ItemFn(_, generics, _, _, _, _) => {
180                 self.visit_early_late(subst::FnSpace, generics, |this| {
181                     this.walk_fn(fk, fd, b, s)
182                 })
183             }
184             FnKind::Method(_, sig, _) => {
185                 self.visit_early_late(subst::FnSpace, &sig.generics, |this| {
186                     this.walk_fn(fk, fd, b, s)
187                 })
188             }
189             FnKind::Closure(..) => {
190                 self.walk_fn(fk, fd, b, s)
191             }
192         }
193     }
194
195     fn visit_ty(&mut self, ty: &hir::Ty) {
196         match ty.node {
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);
204                 });
205             }
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);
213                         });
214                     }
215                     _ => {
216                         visit::walk_ty(self, ty);
217                     }
218                 }
219             }
220             _ => {
221                 visit::walk_ty(self, ty)
222             }
223         }
224     }
225
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![]);
230
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))
235         } else {
236             visit::walk_trait_item(self, trait_item);
237         }
238
239         replace(&mut self.labels_in_fn, saved);
240     }
241
242     fn visit_block(&mut self, b: &hir::Block) {
243         self.with(BlockScope(region::DestructionScopeData::new(b.id),
244                              self.scope),
245                   |_, this| visit::walk_block(this, b));
246     }
247
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);
251             return;
252         }
253         self.resolve_lifetime_ref(lifetime_ref);
254     }
255
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),
261                 None => {}
262             }
263         }
264         for predicate in &generics.where_clause.predicates {
265             match predicate {
266                 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ ref bounded_ty,
267                                                                                ref bounds,
268                                                                                ref bound_lifetimes,
269                                                                                .. }) => {
270                     if !bound_lifetimes.is_empty() {
271                         self.trait_ref_hack = true;
272                         let result = self.with(LateScope(bound_lifetimes, self.scope),
273                                                |old_scope, this| {
274                             this.check_lifetime_defs(old_scope, bound_lifetimes);
275                             this.visit_ty(&**bounded_ty);
276                             visit::walk_ty_param_bounds_helper(this, bounds);
277                         });
278                         self.trait_ref_hack = false;
279                         result
280                     } else {
281                         self.visit_ty(&**bounded_ty);
282                         visit::walk_ty_param_bounds_helper(self, bounds);
283                     }
284                 }
285                 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
286                                                                                 ref bounds,
287                                                                                 .. }) => {
288
289                     self.visit_lifetime_ref(lifetime);
290                     for bound in bounds {
291                         self.visit_lifetime_ref(bound);
292                     }
293                 }
294                 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ id,
295                                                                          ref path,
296                                                                          ref ty,
297                                                                          .. }) => {
298                     self.visit_path(path, id);
299                     self.visit_ty(&**ty);
300                 }
301             }
302         }
303     }
304
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);
309
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");
315             }
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);
320                 }
321                 visit::walk_path(this, &trait_ref.trait_ref.path)
322             })
323         } else {
324             self.visit_trait_ref(&trait_ref.trait_ref)
325         }
326     }
327 }
328
329 #[derive(Copy, Clone, PartialEq)]
330 enum ShadowKind { Label, Lifetime }
331 struct Original { kind: ShadowKind, span: Span }
332 struct Shadower { kind: ShadowKind, span: Span }
333
334 fn original_label(span: Span) -> Original {
335     Original { kind: ShadowKind::Label, span: span }
336 }
337 fn shadower_label(span: Span) -> Shadower {
338     Shadower { kind: ShadowKind::Label, span: span }
339 }
340 fn original_lifetime(l: &hir::Lifetime) -> Original {
341     Original { kind: ShadowKind::Lifetime, span: l.span }
342 }
343 fn shadower_lifetime(l: &hir::Lifetime) -> Shadower {
344     Shadower { kind: ShadowKind::Lifetime, span: l.span }
345 }
346
347 impl ShadowKind {
348     fn desc(&self) -> &'static str {
349         match *self {
350             ShadowKind::Label => "label",
351             ShadowKind::Lifetime => "lifetime",
352         }
353     }
354 }
355
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());
364     } else {
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()));
371     }
372     sess.span_note(orig.span,
373                    &format!("shadowed {} `{}` declared here",
374                             orig.kind.desc(), name));
375 }
376
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) {
380
381     struct GatherLabels<'a> {
382         sess: &'a Session,
383         scope: Scope<'a>,
384         labels_in_fn: &'a mut Vec<(ast::Name, Span)>,
385     }
386
387     let mut gather = GatherLabels {
388         sess: ctxt.sess,
389         scope: ctxt.scope,
390         labels_in_fn: &mut ctxt.labels_in_fn,
391     };
392     gather.visit_block(b);
393     return;
394
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
399             // labels_in_fn
400             if let hir::ExprClosure(..) = ex.node {
401                 return
402             }
403             if let Some(label) = expression_label(ex) {
404                 for &(prior, prior_span) in &self.labels_in_fn[..] {
405                     // FIXME (#24278): non-hygienic comparison
406                     if label == prior {
407                         signal_shadowing_problem(self.sess,
408                                                  label,
409                                                  original_label(prior_span),
410                                                  shadower_label(ex.span));
411                     }
412                 }
413
414                 check_if_label_shadows_lifetime(self.sess,
415                                                 self.scope,
416                                                 label,
417                                                 ex.span);
418
419                 self.labels_in_fn.push((label, ex.span));
420             }
421             visit::walk_expr(self, ex)
422         }
423
424         fn visit_item(&mut self, _: &hir::Item) {
425             // do not recurse into items defined in the block
426         }
427     }
428
429     fn expression_label(ex: &hir::Expr) -> Option<ast::Name> {
430         match ex.node {
431             hir::ExprWhile(_, _, Some(label)) |
432             hir::ExprLoop(_, Some(label)) => Some(label.name),
433             _ => None,
434         }
435     }
436
437     fn check_if_label_shadows_lifetime<'a>(sess: &'a Session,
438                                            mut scope: Scope<'a>,
439                                            label: ast::Name,
440                                            label_span: Span) {
441         loop {
442             match *scope {
443                 BlockScope(_, s) => { scope = s; }
444                 RootScope => { return; }
445
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(
452                                 sess,
453                                 label,
454                                 original_lifetime(&lifetime_def.lifetime),
455                                 shadower_label(label_span));
456                             return;
457                         }
458                     }
459                     scope = s;
460                 }
461             }
462         }
463     }
464 }
465
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,
471                    fk: FnKind,
472                    fd: &hir::FnDecl,
473                    fb: &'b hir::Block,
474                    _span: Span) {
475         match fk {
476             FnKind::ItemFn(_, generics, _, _, _, _) => {
477                 visit::walk_fn_decl(self, fd);
478                 self.visit_generics(generics);
479             }
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);
484             }
485             FnKind::Closure(..) => {
486                 visit::walk_fn_decl(self, fd);
487             }
488         }
489
490         // After inpsecting the decl, add all labels from the body to
491         // `self.labels_in_fn`.
492         extract_labels(self, fb);
493
494         self.visit_block(fb);
495     }
496
497     fn with<F>(&mut self, wrap_scope: ScopeChain, f: F) where
498         F: FnOnce(Scope, &mut LifetimeContext),
499     {
500         let LifetimeContext {sess, ref mut named_region_map, ..} = *self;
501         let mut this = LifetimeContext {
502             sess: sess,
503             named_region_map: *named_region_map,
504             scope: &wrap_scope,
505             def_map: self.def_map,
506             trait_ref_hack: self.trait_ref_hack,
507             labels_in_fn: self.labels_in_fn.clone(),
508         };
509         debug!("entering scope {:?}", this.scope);
510         f(self.scope, &mut this);
511         debug!("exiting scope {:?}", this.scope);
512     }
513
514     /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
515     ///
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.
519     ///
520     /// For example:
521     ///
522     ///    fn foo<'a,'b,'c,T:Trait<'b>>(...)
523     ///
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.
526     ///
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,
535                            walk: F) where
536         F: FnOnce(&mut LifetimeContext),
537     {
538         let referenced_idents = early_bound_lifetime_names(generics);
539
540         debug!("visit_early_late: referenced_idents={:?}",
541                referenced_idents);
542
543         let (early, late): (Vec<_>, _) = generics.lifetimes.iter().cloned().partition(
544             |l| referenced_idents.iter().any(|&i| i == l.lifetime.name));
545
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);
549                 walk(this);
550             });
551         });
552     }
553
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
560         // search.
561         let mut late_depth = 0;
562         let mut scope = self.scope;
563         loop {
564             match *scope {
565                 BlockScope(blk_scope, s) => {
566                     return self.resolve_free_lifetime_ref(blk_scope, lifetime_ref, s);
567                 }
568
569                 RootScope => {
570                     break;
571                 }
572
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);
579                             return;
580                         }
581                         None => {
582                             scope = s;
583                         }
584                     }
585                 }
586
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);
594                             return;
595                         }
596
597                         None => {
598                             late_depth += 1;
599                             scope = s;
600                         }
601                     }
602                 }
603             }
604         }
605
606         self.unresolved_lifetime_ref(lifetime_ref);
607     }
608
609     fn resolve_free_lifetime_ref(&mut self,
610                                  scope_data: region::DestructionScopeData,
611                                  lifetime_ref: &hir::Lifetime,
612                                  scope: Scope) {
613         debug!("resolve_free_lifetime_ref \
614                 scope_data: {:?} lifetime_ref: {:?} scope: {:?}",
615                scope_data, lifetime_ref, scope);
616
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;
623         loop {
624             debug!("resolve_free_lifetime_ref \
625                     scope_data: {:?} scope: {:?} search_result: {:?}",
626                    scope_data, scope, search_result);
627             match *scope {
628                 BlockScope(blk_scope_data, s) => {
629                     scope_data = blk_scope_data;
630                     scope = s;
631                 }
632
633                 RootScope => {
634                     break;
635                 }
636
637                 EarlyScope(_, lifetimes, s) |
638                 LateScope(lifetimes, s) => {
639                     search_result = search_lifetimes(lifetimes, lifetime_ref);
640                     if search_result.is_some() {
641                         break;
642                     }
643                     scope = s;
644                 }
645             }
646         }
647
648         match search_result {
649             Some((_depth, lifetime)) => {
650                 let def = DefFreeRegion(scope_data, lifetime.id);
651                 self.insert_lifetime(lifetime_ref, def);
652             }
653
654             None => {
655                 self.unresolved_lifetime_ref(lifetime_ref);
656             }
657         }
658
659     }
660
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 `{}`",
664                     lifetime_ref.name);
665     }
666
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];
670
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);
676                 }
677             }
678
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];
682
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 \
686                                 the same scope",
687                                 lifetime_j.lifetime.name);
688                 }
689             }
690
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);
693
694             for bound in &lifetime_i.bounds {
695                 self.resolve_lifetime_ref(bound);
696             }
697         }
698     }
699
700     fn check_lifetime_def_for_shadowing(&self,
701                                         mut old_scope: Scope,
702                                         lifetime: &hir::Lifetime)
703     {
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,
708                                          lifetime.name,
709                                          original_label(label_span),
710                                          shadower_lifetime(&lifetime));
711                 return;
712             }
713         }
714
715         loop {
716             match *old_scope {
717                 BlockScope(_, s) => {
718                     old_scope = s;
719                 }
720
721                 RootScope => {
722                     return;
723                 }
724
725                 EarlyScope(_, lifetimes, s) |
726                 LateScope(lifetimes, s) => {
727                     if let Some((_, lifetime_def)) = search_lifetimes(lifetimes, lifetime) {
728                         signal_shadowing_problem(
729                             self.sess,
730                             lifetime.name,
731                             original_lifetime(&lifetime_def),
732                             shadower_lifetime(&lifetime));
733                         return;
734                     }
735
736                     old_scope = s;
737                 }
738             }
739         }
740     }
741
742     fn insert_lifetime(&mut self,
743                        lifetime_ref: &hir::Lifetime,
744                        def: DefRegion) {
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");
749         }
750
751         debug!("lifetime_ref={:?} id={:?} resolved to {:?}",
752                 lifetime_to_string(lifetime_ref),
753                 lifetime_ref.id,
754                 def);
755         self.named_region_map.insert(lifetime_ref.id, def);
756     }
757 }
758
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));
765         }
766     }
767     return None;
768 }
769
770 ///////////////////////////////////////////////////////////////////////////
771
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() {
775         return Vec::new();
776     }
777
778     generics.lifetimes.iter()
779         .filter(|l| referenced_idents.iter().any(|&i| i == l.lifetime.name))
780         .cloned()
781         .collect()
782 }
783
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
790     // them.
791     let mut early_bound = Vec::new();
792     let mut late_bound = generics.lifetimes.iter()
793                                            .map(|l| l.lifetime.name)
794                                            .collect();
795
796     // Any lifetime that appears in a type bound is early.
797     {
798         let mut collector =
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);
803         }
804         for predicate in &generics.where_clause.predicates {
805             match predicate {
806                 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bounds,
807                                                                               ref bounded_ty,
808                                                                               ..}) => {
809                     collector.visit_ty(&**bounded_ty);
810                     visit::walk_ty_param_bounds_helper(&mut collector, bounds);
811                 }
812                 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
813                                                                                 ref bounds,
814                                                                                 ..}) => {
815                     collector.visit_lifetime_ref(lifetime);
816
817                     for bound in bounds {
818                         collector.visit_lifetime_ref(bound);
819                     }
820                 }
821                 &hir::WherePredicate::EqPredicate(_) => unimplemented!()
822             }
823         }
824     }
825
826     // Any lifetime that either has a bound or is referenced by a
827     // bound is early.
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,
834                         bound.name);
835             }
836         }
837     }
838     return early_bound;
839
840     struct FreeLifetimeCollector<'a> {
841         early_bound: &'a mut Vec<ast::Name>,
842         late_bound: &'a mut Vec<ast::Name>,
843     }
844
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,
848                     lifetime_ref.name);
849         }
850     }
851
852     fn shuffle(early_bound: &mut Vec<ast::Name>,
853                late_bound: &mut Vec<ast::Name>,
854                name: ast::Name) {
855         match late_bound.iter().position(|n| *n == name) {
856             Some(index) => {
857                 late_bound.swap_remove(index);
858                 early_bound.push(name);
859             }
860             None => { }
861         }
862     }
863 }
864
865 impl<'a> fmt::Debug for ScopeChain<'a> {
866     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
867         match *self {
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"),
872         }
873     }
874 }