]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/resolve_lifetime.rs
c65fd25950deab808fe80638c0d01258a81c6919
[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 dep_graph::DepNode;
22 use hir::map::Map;
23 use session::Session;
24 use hir::def::{Def, DefMap};
25 use hir::def_id::DefId;
26 use middle::region;
27 use ty;
28 use std::mem::replace;
29 use syntax::ast;
30 use syntax::symbol::keywords;
31 use syntax_pos::Span;
32 use util::nodemap::NodeMap;
33
34 use rustc_data_structures::fx::FxHashSet;
35 use hir;
36 use hir::print::lifetime_to_string;
37 use hir::intravisit::{self, Visitor, FnKind};
38
39 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
40 pub enum DefRegion {
41     DefStaticRegion,
42     DefEarlyBoundRegion(/* index */ u32,
43                         /* lifetime decl */ ast::NodeId),
44     DefLateBoundRegion(ty::DebruijnIndex,
45                        /* lifetime decl */ ast::NodeId),
46     DefFreeRegion(region::CallSiteScopeData,
47                   /* lifetime decl */ ast::NodeId),
48 }
49
50 // Maps the id of each lifetime reference to the lifetime decl
51 // that it corresponds to.
52 pub struct NamedRegionMap {
53     // maps from every use of a named (not anonymous) lifetime to a
54     // `DefRegion` describing how that region is bound
55     pub defs: NodeMap<DefRegion>,
56
57     // the set of lifetime def ids that are late-bound; late-bound ids
58     // are named regions appearing in fn arguments that do not appear
59     // in where-clauses
60     pub late_bound: NodeMap<ty::Issue32330>,
61 }
62
63 struct LifetimeContext<'a, 'tcx: 'a> {
64     sess: &'a Session,
65     hir_map: &'a Map<'tcx>,
66     map: &'a mut NamedRegionMap,
67     scope: Scope<'a>,
68     def_map: &'a DefMap,
69     // Deep breath. Our representation for poly trait refs contains a single
70     // binder and thus we only allow a single level of quantification. However,
71     // the syntax of Rust permits quantification in two places, e.g., `T: for <'a> Foo<'a>`
72     // and `for <'a, 'b> &'b T: Foo<'a>`. In order to get the de Bruijn indices
73     // correct when representing these constraints, we should only introduce one
74     // scope. However, we want to support both locations for the quantifier and
75     // during lifetime resolution we want precise information (so we can't
76     // desugar in an earlier phase).
77
78     // SO, if we encounter a quantifier at the outer scope, we set
79     // trait_ref_hack to true (and introduce a scope), and then if we encounter
80     // a quantifier at the inner scope, we error. If trait_ref_hack is false,
81     // then we introduce the scope at the inner quantifier.
82
83     // I'm sorry.
84     trait_ref_hack: bool,
85
86     // List of labels in the function/method currently under analysis.
87     labels_in_fn: Vec<(ast::Name, Span)>,
88 }
89
90 #[derive(PartialEq, Debug)]
91 enum ScopeChain<'a> {
92     /// EarlyScope(['a, 'b, ...], start, s) extends s with early-bound
93     /// lifetimes, with consecutive parameter indices from `start`.
94     /// That is, 'a has index `start`, 'b has index `start + 1`, etc.
95     /// Indices before `start` correspond to other generic parameters
96     /// of a parent item (trait/impl of a method), or `Self` in traits.
97     EarlyScope(&'a [hir::LifetimeDef], u32, Scope<'a>),
98     /// LateScope(['a, 'b, ...], s) extends s with late-bound
99     /// lifetimes introduced by the declaration binder_id.
100     LateScope(&'a [hir::LifetimeDef], Scope<'a>),
101
102     /// lifetimes introduced by a fn are scoped to the call-site for that fn.
103     FnScope { fn_id: ast::NodeId, body_id: ast::NodeId, s: Scope<'a> },
104     RootScope
105 }
106
107 type Scope<'a> = &'a ScopeChain<'a>;
108
109 static ROOT_SCOPE: ScopeChain<'static> = RootScope;
110
111 pub fn krate(sess: &Session,
112              hir_map: &Map,
113              def_map: &DefMap)
114              -> Result<NamedRegionMap, usize> {
115     let _task = hir_map.dep_graph.in_task(DepNode::ResolveLifetimes);
116     let krate = hir_map.krate();
117     let mut map = NamedRegionMap {
118         defs: NodeMap(),
119         late_bound: NodeMap(),
120     };
121     sess.track_errors(|| {
122         intravisit::walk_crate(&mut LifetimeContext {
123             sess: sess,
124             hir_map: hir_map,
125             map: &mut map,
126             scope: &ROOT_SCOPE,
127             def_map: def_map,
128             trait_ref_hack: false,
129             labels_in_fn: vec![],
130         }, krate);
131     })?;
132     Ok(map)
133 }
134
135 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
136     // Override the nested functions -- lifetimes follow lexical scope,
137     // so it's convenient to walk the tree in lexical order.
138     fn nested_visit_map(&mut self) -> Option<&hir::map::Map<'tcx>> {
139         Some(&self.hir_map)
140     }
141
142     fn visit_item(&mut self, item: &'tcx hir::Item) {
143         // Save labels for nested items.
144         let saved_labels_in_fn = replace(&mut self.labels_in_fn, vec![]);
145
146         // Items always introduce a new root scope
147         self.with(RootScope, |_, this| {
148             match item.node {
149                 hir::ItemFn(..) => {
150                     // Fn lifetimes get added in visit_fn below:
151                     intravisit::walk_item(this, item);
152                 }
153                 hir::ItemExternCrate(_) |
154                 hir::ItemUse(_) |
155                 hir::ItemMod(..) |
156                 hir::ItemDefaultImpl(..) |
157                 hir::ItemForeignMod(..) |
158                 hir::ItemStatic(..) |
159                 hir::ItemConst(..) => {
160                     // These sorts of items have no lifetime parameters at all.
161                     intravisit::walk_item(this, item);
162                 }
163                 hir::ItemTy(_, ref generics) |
164                 hir::ItemEnum(_, ref generics) |
165                 hir::ItemStruct(_, ref generics) |
166                 hir::ItemUnion(_, ref generics) |
167                 hir::ItemTrait(_, ref generics, ..) |
168                 hir::ItemImpl(_, _, ref generics, ..) => {
169                     // These kinds of items have only early bound lifetime parameters.
170                     let lifetimes = &generics.lifetimes;
171                     let start = if let hir::ItemTrait(..) = item.node {
172                         1 // Self comes before lifetimes
173                     } else {
174                         0
175                     };
176                     this.with(EarlyScope(lifetimes, start, &ROOT_SCOPE), |old_scope, this| {
177                         this.check_lifetime_defs(old_scope, lifetimes);
178                         intravisit::walk_item(this, item);
179                     });
180                 }
181             }
182         });
183
184         // Done traversing the item; remove any labels it created
185         self.labels_in_fn = saved_labels_in_fn;
186     }
187
188     fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
189         // Items save/restore the set of labels. This way inner items
190         // can freely reuse names, be they loop labels or lifetimes.
191         let saved = replace(&mut self.labels_in_fn, vec![]);
192
193         // Items always introduce a new root scope
194         self.with(RootScope, |_, this| {
195             match item.node {
196                 hir::ForeignItemFn(ref decl, ref generics) => {
197                     this.visit_early_late(item.id, decl, generics, |this| {
198                         intravisit::walk_foreign_item(this, item);
199                     })
200                 }
201                 hir::ForeignItemStatic(..) => {
202                     intravisit::walk_foreign_item(this, item);
203                 }
204             }
205         });
206
207         // Done traversing the item; restore saved set of labels.
208         replace(&mut self.labels_in_fn, saved);
209     }
210
211     fn visit_fn(&mut self, fk: FnKind<'tcx>, decl: &'tcx hir::FnDecl,
212                 b: &'tcx hir::Expr, s: Span, fn_id: ast::NodeId) {
213         match fk {
214             FnKind::ItemFn(_, generics, ..) => {
215                 self.visit_early_late(fn_id,decl, generics, |this| {
216                     this.add_scope_and_walk_fn(fk, decl, b, s, fn_id)
217                 })
218             }
219             FnKind::Method(_, sig, ..) => {
220                 self.visit_early_late(
221                     fn_id,
222                     decl,
223                     &sig.generics,
224                     |this| this.add_scope_and_walk_fn(fk, decl, b, s, fn_id));
225             }
226             FnKind::Closure(_) => {
227                 // Closures have their own set of labels, save labels just
228                 // like for foreign items above.
229                 let saved = replace(&mut self.labels_in_fn, vec![]);
230                 let result = self.add_scope_and_walk_fn(fk, decl, b, s, fn_id);
231                 replace(&mut self.labels_in_fn, saved);
232                 result
233             }
234         }
235     }
236
237     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
238         match ty.node {
239             hir::TyBareFn(ref c) => {
240                 self.with(LateScope(&c.lifetimes, self.scope), |old_scope, this| {
241                     // a bare fn has no bounds, so everything
242                     // contained within is scoped within its binder.
243                     this.check_lifetime_defs(old_scope, &c.lifetimes);
244                     intravisit::walk_ty(this, ty);
245                 });
246             }
247             hir::TyPath(hir::QPath::Resolved(None, ref path)) => {
248                 // if this path references a trait, then this will resolve to
249                 // a trait ref, which introduces a binding scope.
250                 match self.def_map.get(&ty.id).map(|d| (d.base_def, d.depth)) {
251                     Some((Def::Trait(..), 0)) => {
252                         self.with(LateScope(&[], self.scope), |_, this| {
253                             this.visit_path(path, ty.id);
254                         });
255                     }
256                     _ => {
257                         intravisit::walk_ty(self, ty);
258                     }
259                 }
260             }
261             _ => {
262                 intravisit::walk_ty(self, ty)
263             }
264         }
265     }
266
267     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
268         // We reset the labels on every trait item, so that different
269         // methods in an impl can reuse label names.
270         let saved = replace(&mut self.labels_in_fn, vec![]);
271
272         if let hir::MethodTraitItem(ref sig, None) = trait_item.node {
273             self.visit_early_late(
274                 trait_item.id,
275                 &sig.decl, &sig.generics,
276                 |this| intravisit::walk_trait_item(this, trait_item))
277         } else {
278             intravisit::walk_trait_item(self, trait_item);
279         }
280
281         replace(&mut self.labels_in_fn, saved);
282     }
283
284     fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
285         if lifetime_ref.name == keywords::StaticLifetime.name() {
286             self.insert_lifetime(lifetime_ref, DefStaticRegion);
287             return;
288         }
289         self.resolve_lifetime_ref(lifetime_ref);
290     }
291
292     fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
293         for ty_param in generics.ty_params.iter() {
294             walk_list!(self, visit_ty_param_bound, &ty_param.bounds);
295             if let Some(ref ty) = ty_param.default {
296                 self.visit_ty(&ty);
297             }
298         }
299         for predicate in &generics.where_clause.predicates {
300             match predicate {
301                 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ ref bounded_ty,
302                                                                                ref bounds,
303                                                                                ref bound_lifetimes,
304                                                                                .. }) => {
305                     if !bound_lifetimes.is_empty() {
306                         self.trait_ref_hack = true;
307                         let result = self.with(LateScope(bound_lifetimes, self.scope),
308                                                |old_scope, this| {
309                             this.check_lifetime_defs(old_scope, bound_lifetimes);
310                             this.visit_ty(&bounded_ty);
311                             walk_list!(this, visit_ty_param_bound, bounds);
312                         });
313                         self.trait_ref_hack = false;
314                         result
315                     } else {
316                         self.visit_ty(&bounded_ty);
317                         walk_list!(self, visit_ty_param_bound, bounds);
318                     }
319                 }
320                 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
321                                                                                 ref bounds,
322                                                                                 .. }) => {
323
324                     self.visit_lifetime(lifetime);
325                     for bound in bounds {
326                         self.visit_lifetime(bound);
327                     }
328                 }
329                 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ id,
330                                                                          ref path,
331                                                                          ref ty,
332                                                                          .. }) => {
333                     self.visit_path(path, id);
334                     self.visit_ty(&ty);
335                 }
336             }
337         }
338     }
339
340     fn visit_poly_trait_ref(&mut self,
341                             trait_ref: &'tcx hir::PolyTraitRef,
342                             _modifier: &'tcx hir::TraitBoundModifier) {
343         debug!("visit_poly_trait_ref trait_ref={:?}", trait_ref);
344
345         if !self.trait_ref_hack || !trait_ref.bound_lifetimes.is_empty() {
346             if self.trait_ref_hack {
347                 span_err!(self.sess, trait_ref.span, E0316,
348                           "nested quantification of lifetimes");
349             }
350             self.with(LateScope(&trait_ref.bound_lifetimes, self.scope), |old_scope, this| {
351                 this.check_lifetime_defs(old_scope, &trait_ref.bound_lifetimes);
352                 for lifetime in &trait_ref.bound_lifetimes {
353                     this.visit_lifetime_def(lifetime);
354                 }
355                 intravisit::walk_path(this, &trait_ref.trait_ref.path)
356             })
357         } else {
358             self.visit_trait_ref(&trait_ref.trait_ref)
359         }
360     }
361 }
362
363 #[derive(Copy, Clone, PartialEq)]
364 enum ShadowKind { Label, Lifetime }
365 struct Original { kind: ShadowKind, span: Span }
366 struct Shadower { kind: ShadowKind, span: Span }
367
368 fn original_label(span: Span) -> Original {
369     Original { kind: ShadowKind::Label, span: span }
370 }
371 fn shadower_label(span: Span) -> Shadower {
372     Shadower { kind: ShadowKind::Label, span: span }
373 }
374 fn original_lifetime(l: &hir::Lifetime) -> Original {
375     Original { kind: ShadowKind::Lifetime, span: l.span }
376 }
377 fn shadower_lifetime(l: &hir::Lifetime) -> Shadower {
378     Shadower { kind: ShadowKind::Lifetime, span: l.span }
379 }
380
381 impl ShadowKind {
382     fn desc(&self) -> &'static str {
383         match *self {
384             ShadowKind::Label => "label",
385             ShadowKind::Lifetime => "lifetime",
386         }
387     }
388 }
389
390 fn signal_shadowing_problem(sess: &Session, name: ast::Name, orig: Original, shadower: Shadower) {
391     let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
392         // lifetime/lifetime shadowing is an error
393         struct_span_err!(sess, shadower.span, E0496,
394                          "{} name `{}` shadows a \
395                           {} name that is already in scope",
396                          shadower.kind.desc(), name, orig.kind.desc())
397     } else {
398         // shadowing involving a label is only a warning, due to issues with
399         // labels and lifetimes not being macro-hygienic.
400         sess.struct_span_warn(shadower.span,
401                               &format!("{} name `{}` shadows a \
402                                         {} name that is already in scope",
403                                        shadower.kind.desc(), name, orig.kind.desc()))
404     };
405     err.span_label(orig.span, &"first declared here");
406     err.span_label(shadower.span,
407                    &format!("lifetime {} already in scope", name));
408     err.emit();
409 }
410
411 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
412 // if one of the label shadows a lifetime or another label.
413 fn extract_labels(ctxt: &mut LifetimeContext, b: &hir::Expr) {
414     struct GatherLabels<'a> {
415         sess: &'a Session,
416         scope: Scope<'a>,
417         labels_in_fn: &'a mut Vec<(ast::Name, Span)>,
418     }
419
420     let mut gather = GatherLabels {
421         sess: ctxt.sess,
422         scope: ctxt.scope,
423         labels_in_fn: &mut ctxt.labels_in_fn,
424     };
425     gather.visit_expr(b);
426     return;
427
428     impl<'v, 'a> Visitor<'v> for GatherLabels<'a> {
429         fn visit_expr(&mut self, ex: &'v hir::Expr) {
430             // do not recurse into closures defined in the block
431             // since they are treated as separate fns from the POV of
432             // labels_in_fn
433             if let hir::ExprClosure(..) = ex.node {
434                 return
435             }
436             if let Some((label, label_span)) = expression_label(ex) {
437                 for &(prior, prior_span) in &self.labels_in_fn[..] {
438                     // FIXME (#24278): non-hygienic comparison
439                     if label == prior {
440                         signal_shadowing_problem(self.sess,
441                                                  label,
442                                                  original_label(prior_span),
443                                                  shadower_label(label_span));
444                     }
445                 }
446
447                 check_if_label_shadows_lifetime(self.sess,
448                                                 self.scope,
449                                                 label,
450                                                 label_span);
451
452                 self.labels_in_fn.push((label, label_span));
453             }
454             intravisit::walk_expr(self, ex)
455         }
456
457         fn visit_item(&mut self, _: &hir::Item) {
458             // do not recurse into items defined in the block
459         }
460     }
461
462     fn expression_label(ex: &hir::Expr) -> Option<(ast::Name, Span)> {
463         match ex.node {
464             hir::ExprWhile(.., Some(label)) |
465             hir::ExprLoop(_, Some(label), _) => Some((label.node, label.span)),
466             _ => None,
467         }
468     }
469
470     fn check_if_label_shadows_lifetime<'a>(sess: &'a Session,
471                                            mut scope: Scope<'a>,
472                                            label: ast::Name,
473                                            label_span: Span) {
474         loop {
475             match *scope {
476                 FnScope { s, .. } => { scope = s; }
477                 RootScope => { return; }
478
479                 EarlyScope(lifetimes, _, s) |
480                 LateScope(lifetimes, s) => {
481                     for lifetime_def in lifetimes {
482                         // FIXME (#24278): non-hygienic comparison
483                         if label == lifetime_def.lifetime.name {
484                             signal_shadowing_problem(
485                                 sess,
486                                 label,
487                                 original_lifetime(&lifetime_def.lifetime),
488                                 shadower_label(label_span));
489                             return;
490                         }
491                     }
492                     scope = s;
493                 }
494             }
495         }
496     }
497 }
498
499 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
500     fn add_scope_and_walk_fn(&mut self,
501                              fk: FnKind<'tcx>,
502                              fd: &'tcx hir::FnDecl,
503                              fb: &'tcx hir::Expr,
504                              _span: Span,
505                              fn_id: ast::NodeId) {
506         match fk {
507             FnKind::ItemFn(_, generics, ..) => {
508                 intravisit::walk_fn_decl(self, fd);
509                 self.visit_generics(generics);
510             }
511             FnKind::Method(_, sig, ..) => {
512                 intravisit::walk_fn_decl(self, fd);
513                 self.visit_generics(&sig.generics);
514             }
515             FnKind::Closure(_) => {
516                 intravisit::walk_fn_decl(self, fd);
517             }
518         }
519
520         // After inpsecting the decl, add all labels from the body to
521         // `self.labels_in_fn`.
522         extract_labels(self, fb);
523
524         self.with(FnScope { fn_id: fn_id, body_id: fb.id, s: self.scope },
525                   |_old_scope, this| this.visit_expr(fb))
526     }
527
528     // FIXME(#37666) this works around a limitation in the region inferencer
529     fn hack<F>(&mut self, f: F) where
530         F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
531     {
532         f(self)
533     }
534
535     fn with<F>(&mut self, wrap_scope: ScopeChain, f: F) where
536         F: for<'b> FnOnce(Scope, &mut LifetimeContext<'b, 'tcx>),
537     {
538         let LifetimeContext {sess, hir_map, ref mut map, ..} = *self;
539         let mut this = LifetimeContext {
540             sess: sess,
541             hir_map: hir_map,
542             map: *map,
543             scope: &wrap_scope,
544             def_map: self.def_map,
545             trait_ref_hack: self.trait_ref_hack,
546             labels_in_fn: self.labels_in_fn.clone(),
547         };
548         debug!("entering scope {:?}", this.scope);
549         f(self.scope, &mut this);
550         debug!("exiting scope {:?}", this.scope);
551     }
552
553     /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
554     ///
555     /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
556     /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
557     /// within type bounds; those are early bound lifetimes, and the rest are late bound.
558     ///
559     /// For example:
560     ///
561     ///    fn foo<'a,'b,'c,T:Trait<'b>>(...)
562     ///
563     /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
564     /// lifetimes may be interspersed together.
565     ///
566     /// If early bound lifetimes are present, we separate them into their own list (and likewise
567     /// for late bound). They will be numbered sequentially, starting from the lowest index that is
568     /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
569     /// bound lifetimes are resolved by name and associated with a binder id (`binder_id`), so the
570     /// ordering is not important there.
571     fn visit_early_late<F>(&mut self,
572                            fn_id: ast::NodeId,
573                            decl: &'tcx hir::FnDecl,
574                            generics: &'tcx hir::Generics,
575                            walk: F) where
576         F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
577     {
578         let fn_def_id = self.hir_map.local_def_id(fn_id);
579         insert_late_bound_lifetimes(self.map,
580                                     fn_def_id,
581                                     decl,
582                                     generics);
583
584         let (late, early): (Vec<_>, _) =
585             generics.lifetimes
586                     .iter()
587                     .cloned()
588                     .partition(|l| self.map.late_bound.contains_key(&l.lifetime.id));
589
590         // Find the start of nested early scopes, e.g. in methods.
591         let mut start = 0;
592         if let EarlyScope(..) = *self.scope {
593             let parent = self.hir_map.expect_item(self.hir_map.get_parent(fn_id));
594             if let hir::ItemTrait(..) = parent.node {
595                 start += 1; // Self comes first.
596             }
597             match parent.node {
598                 hir::ItemTrait(_, ref generics, ..) |
599                 hir::ItemImpl(_, _, ref generics, ..) => {
600                     start += generics.lifetimes.len() + generics.ty_params.len();
601                 }
602                 _ => {}
603             }
604         }
605
606         self.with(EarlyScope(&early, start as u32, self.scope), move |old_scope, this| {
607             this.with(LateScope(&late, this.scope), move |_, this| {
608                 this.check_lifetime_defs(old_scope, &generics.lifetimes);
609                 this.hack(walk); // FIXME(#37666) workaround in place of `walk(this)`
610             });
611         });
612     }
613
614     fn resolve_lifetime_ref(&mut self, lifetime_ref: &hir::Lifetime) {
615         // Walk up the scope chain, tracking the number of fn scopes
616         // that we pass through, until we find a lifetime with the
617         // given name or we run out of scopes. If we encounter a code
618         // block, then the lifetime is not bound but free, so switch
619         // over to `resolve_free_lifetime_ref()` to complete the
620         // search.
621         let mut late_depth = 0;
622         let mut scope = self.scope;
623         loop {
624             match *scope {
625                 FnScope {fn_id, body_id, s } => {
626                     return self.resolve_free_lifetime_ref(
627                         region::CallSiteScopeData { fn_id: fn_id, body_id: body_id },
628                         lifetime_ref,
629                         s);
630                 }
631
632                 RootScope => {
633                     break;
634                 }
635
636                 EarlyScope(lifetimes, start, s) => {
637                     match search_lifetimes(lifetimes, lifetime_ref) {
638                         Some((index, lifetime_def)) => {
639                             let decl_id = lifetime_def.id;
640                             let def = DefEarlyBoundRegion(start + index, decl_id);
641                             self.insert_lifetime(lifetime_ref, def);
642                             return;
643                         }
644                         None => {
645                             scope = s;
646                         }
647                     }
648                 }
649
650                 LateScope(lifetimes, s) => {
651                     match search_lifetimes(lifetimes, lifetime_ref) {
652                         Some((_index, lifetime_def)) => {
653                             let decl_id = lifetime_def.id;
654                             let debruijn = ty::DebruijnIndex::new(late_depth + 1);
655                             let def = DefLateBoundRegion(debruijn, decl_id);
656                             self.insert_lifetime(lifetime_ref, def);
657                             return;
658                         }
659
660                         None => {
661                             late_depth += 1;
662                             scope = s;
663                         }
664                     }
665                 }
666             }
667         }
668
669         self.unresolved_lifetime_ref(lifetime_ref);
670     }
671
672     fn resolve_free_lifetime_ref(&mut self,
673                                  scope_data: region::CallSiteScopeData,
674                                  lifetime_ref: &hir::Lifetime,
675                                  scope: Scope) {
676         debug!("resolve_free_lifetime_ref \
677                 scope_data: {:?} lifetime_ref: {:?} scope: {:?}",
678                scope_data, lifetime_ref, scope);
679
680         // Walk up the scope chain, tracking the outermost free scope,
681         // until we encounter a scope that contains the named lifetime
682         // or we run out of scopes.
683         let mut scope_data = scope_data;
684         let mut scope = scope;
685         let mut search_result = None;
686         loop {
687             debug!("resolve_free_lifetime_ref \
688                     scope_data: {:?} scope: {:?} search_result: {:?}",
689                    scope_data, scope, search_result);
690             match *scope {
691                 FnScope { fn_id, body_id, s } => {
692                     scope_data = region::CallSiteScopeData {
693                         fn_id: fn_id, body_id: body_id
694                     };
695                     scope = s;
696                 }
697
698                 RootScope => {
699                     break;
700                 }
701
702                 EarlyScope(lifetimes, _, s) |
703                 LateScope(lifetimes, s) => {
704                     search_result = search_lifetimes(lifetimes, lifetime_ref);
705                     if search_result.is_some() {
706                         break;
707                     }
708                     scope = s;
709                 }
710             }
711         }
712
713         match search_result {
714             Some((_depth, lifetime)) => {
715                 let def = DefFreeRegion(scope_data, lifetime.id);
716                 self.insert_lifetime(lifetime_ref, def);
717             }
718
719             None => {
720                 self.unresolved_lifetime_ref(lifetime_ref);
721             }
722         }
723
724     }
725
726     fn unresolved_lifetime_ref(&self, lifetime_ref: &hir::Lifetime) {
727         struct_span_err!(self.sess, lifetime_ref.span, E0261,
728             "use of undeclared lifetime name `{}`", lifetime_ref.name)
729             .span_label(lifetime_ref.span, &format!("undeclared lifetime"))
730             .emit();
731     }
732
733     fn check_lifetime_defs(&mut self, old_scope: Scope, lifetimes: &[hir::LifetimeDef]) {
734         for i in 0..lifetimes.len() {
735             let lifetime_i = &lifetimes[i];
736
737             for lifetime in lifetimes {
738                 if lifetime.lifetime.name == keywords::StaticLifetime.name() {
739                     let lifetime = lifetime.lifetime;
740                     let mut err = struct_span_err!(self.sess, lifetime.span, E0262,
741                                   "invalid lifetime parameter name: `{}`", lifetime.name);
742                     err.span_label(lifetime.span,
743                                    &format!("{} is a reserved lifetime name", lifetime.name));
744                     err.emit();
745                 }
746             }
747
748             // It is a hard error to shadow a lifetime within the same scope.
749             for j in i + 1..lifetimes.len() {
750                 let lifetime_j = &lifetimes[j];
751
752                 if lifetime_i.lifetime.name == lifetime_j.lifetime.name {
753                     struct_span_err!(self.sess, lifetime_j.lifetime.span, E0263,
754                                      "lifetime name `{}` declared twice in the same scope",
755                                      lifetime_j.lifetime.name)
756                         .span_label(lifetime_j.lifetime.span,
757                                     &format!("declared twice"))
758                         .span_label(lifetime_i.lifetime.span,
759                                    &format!("previous declaration here"))
760                         .emit();
761                 }
762             }
763
764             // It is a soft error to shadow a lifetime within a parent scope.
765             self.check_lifetime_def_for_shadowing(old_scope, &lifetime_i.lifetime);
766
767             for bound in &lifetime_i.bounds {
768                 self.resolve_lifetime_ref(bound);
769             }
770         }
771     }
772
773     fn check_lifetime_def_for_shadowing(&self,
774                                         mut old_scope: Scope,
775                                         lifetime: &hir::Lifetime)
776     {
777         for &(label, label_span) in &self.labels_in_fn {
778             // FIXME (#24278): non-hygienic comparison
779             if lifetime.name == label {
780                 signal_shadowing_problem(self.sess,
781                                          lifetime.name,
782                                          original_label(label_span),
783                                          shadower_lifetime(&lifetime));
784                 return;
785             }
786         }
787
788         loop {
789             match *old_scope {
790                 FnScope { s, .. } => {
791                     old_scope = s;
792                 }
793
794                 RootScope => {
795                     return;
796                 }
797
798                 EarlyScope(lifetimes, _, s) |
799                 LateScope(lifetimes, s) => {
800                     if let Some((_, lifetime_def)) = search_lifetimes(lifetimes, lifetime) {
801                         signal_shadowing_problem(
802                             self.sess,
803                             lifetime.name,
804                             original_lifetime(&lifetime_def),
805                             shadower_lifetime(&lifetime));
806                         return;
807                     }
808
809                     old_scope = s;
810                 }
811             }
812         }
813     }
814
815     fn insert_lifetime(&mut self,
816                        lifetime_ref: &hir::Lifetime,
817                        def: DefRegion) {
818         if lifetime_ref.id == ast::DUMMY_NODE_ID {
819             span_bug!(lifetime_ref.span,
820                       "lifetime reference not renumbered, \
821                        probably a bug in syntax::fold");
822         }
823
824         debug!("lifetime_ref={:?} id={:?} resolved to {:?} span={:?}",
825                lifetime_to_string(lifetime_ref),
826                lifetime_ref.id,
827                def,
828                self.sess.codemap().span_to_string(lifetime_ref.span));
829         self.map.defs.insert(lifetime_ref.id, def);
830     }
831 }
832
833 fn search_lifetimes<'a>(lifetimes: &'a [hir::LifetimeDef],
834                     lifetime_ref: &hir::Lifetime)
835                     -> Option<(u32, &'a hir::Lifetime)> {
836     for (i, lifetime_decl) in lifetimes.iter().enumerate() {
837         if lifetime_decl.lifetime.name == lifetime_ref.name {
838             return Some((i as u32, &lifetime_decl.lifetime));
839         }
840     }
841     return None;
842 }
843
844 ///////////////////////////////////////////////////////////////////////////
845
846 /// Detects late-bound lifetimes and inserts them into
847 /// `map.late_bound`.
848 ///
849 /// A region declared on a fn is **late-bound** if:
850 /// - it is constrained by an argument type;
851 /// - it does not appear in a where-clause.
852 ///
853 /// "Constrained" basically means that it appears in any type but
854 /// not amongst the inputs to a projection.  In other words, `<&'a
855 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
856 fn insert_late_bound_lifetimes(map: &mut NamedRegionMap,
857                                fn_def_id: DefId,
858                                decl: &hir::FnDecl,
859                                generics: &hir::Generics) {
860     debug!("insert_late_bound_lifetimes(decl={:?}, generics={:?})", decl, generics);
861
862     let mut constrained_by_input = ConstrainedCollector { regions: FxHashSet() };
863     for arg in &decl.inputs {
864         constrained_by_input.visit_ty(&arg.ty);
865     }
866
867     let mut appears_in_output = AllCollector {
868         regions: FxHashSet(),
869         impl_trait: false
870     };
871     intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
872
873     debug!("insert_late_bound_lifetimes: constrained_by_input={:?}",
874            constrained_by_input.regions);
875
876     // Walk the lifetimes that appear in where clauses.
877     //
878     // Subtle point: because we disallow nested bindings, we can just
879     // ignore binders here and scrape up all names we see.
880     let mut appears_in_where_clause = AllCollector {
881         regions: FxHashSet(),
882         impl_trait: false
883     };
884     for ty_param in generics.ty_params.iter() {
885         walk_list!(&mut appears_in_where_clause,
886                    visit_ty_param_bound,
887                    &ty_param.bounds);
888     }
889     walk_list!(&mut appears_in_where_clause,
890                visit_where_predicate,
891                &generics.where_clause.predicates);
892     for lifetime_def in &generics.lifetimes {
893         if !lifetime_def.bounds.is_empty() {
894             // `'a: 'b` means both `'a` and `'b` are referenced
895             appears_in_where_clause.visit_lifetime_def(lifetime_def);
896         }
897     }
898
899     debug!("insert_late_bound_lifetimes: appears_in_where_clause={:?}",
900            appears_in_where_clause.regions);
901
902     // Late bound regions are those that:
903     // - appear in the inputs
904     // - do not appear in the where-clauses
905     // - are not implicitly captured by `impl Trait`
906     for lifetime in &generics.lifetimes {
907         let name = lifetime.lifetime.name;
908
909         // appears in the where clauses? early-bound.
910         if appears_in_where_clause.regions.contains(&name) { continue; }
911
912         // any `impl Trait` in the return type? early-bound.
913         if appears_in_output.impl_trait { continue; }
914
915         // does not appear in the inputs, but appears in the return
916         // type? eventually this will be early-bound, but for now we
917         // just mark it so we can issue warnings.
918         let constrained_by_input = constrained_by_input.regions.contains(&name);
919         let appears_in_output = appears_in_output.regions.contains(&name);
920         let will_change = !constrained_by_input && appears_in_output;
921         let issue_32330 = if will_change {
922             ty::Issue32330::WillChange {
923                 fn_def_id: fn_def_id,
924                 region_name: name,
925             }
926         } else {
927             ty::Issue32330::WontChange
928         };
929
930         debug!("insert_late_bound_lifetimes: \
931                 lifetime {:?} with id {:?} is late-bound ({:?}",
932                lifetime.lifetime.name, lifetime.lifetime.id, issue_32330);
933
934         let prev = map.late_bound.insert(lifetime.lifetime.id, issue_32330);
935         assert!(prev.is_none(), "visited lifetime {:?} twice", lifetime.lifetime.id);
936     }
937
938     return;
939
940     struct ConstrainedCollector {
941         regions: FxHashSet<ast::Name>,
942     }
943
944     impl<'v> Visitor<'v> for ConstrainedCollector {
945         fn visit_ty(&mut self, ty: &'v hir::Ty) {
946             match ty.node {
947                 hir::TyPath(hir::QPath::Resolved(Some(_), _)) |
948                 hir::TyPath(hir::QPath::TypeRelative(..)) => {
949                     // ignore lifetimes appearing in associated type
950                     // projections, as they are not *constrained*
951                     // (defined above)
952                 }
953
954                 hir::TyPath(hir::QPath::Resolved(None, ref path)) => {
955                     // consider only the lifetimes on the final
956                     // segment; I am not sure it's even currently
957                     // valid to have them elsewhere, but even if it
958                     // is, those would be potentially inputs to
959                     // projections
960                     if let Some(last_segment) = path.segments.last() {
961                         self.visit_path_segment(path.span, last_segment);
962                     }
963                 }
964
965                 _ => {
966                     intravisit::walk_ty(self, ty);
967                 }
968             }
969         }
970
971         fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
972             self.regions.insert(lifetime_ref.name);
973         }
974     }
975
976     struct AllCollector {
977         regions: FxHashSet<ast::Name>,
978         impl_trait: bool
979     }
980
981     impl<'v> Visitor<'v> for AllCollector {
982         fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
983             self.regions.insert(lifetime_ref.name);
984         }
985
986         fn visit_ty(&mut self, ty: &hir::Ty) {
987             if let hir::TyImplTrait(_) = ty.node {
988                 self.impl_trait = true;
989             }
990             intravisit::walk_ty(self, ty);
991         }
992     }
993 }