]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/resolve_lifetime.rs
a8ba708cc2cd41427904d4fdb279b3a53efd2f8b
[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 use hir::map::Map;
19 use session::Session;
20 use hir::def::Def;
21 use hir::def_id::DefId;
22 use middle::region;
23 use ty;
24
25 use std::cell::Cell;
26 use std::mem::replace;
27 use syntax::ast;
28 use syntax::attr;
29 use syntax::ptr::P;
30 use syntax::symbol::keywords;
31 use syntax_pos::Span;
32 use errors::DiagnosticBuilder;
33 use util::nodemap::{NodeMap, NodeSet, FxHashSet, FxHashMap, DefIdMap};
34 use rustc_back::slice;
35
36 use hir;
37 use hir::intravisit::{self, Visitor, NestedVisitorMap};
38
39 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
40 pub enum Region {
41     Static,
42     EarlyBound(/* index */ u32, /* lifetime decl */ ast::NodeId),
43     LateBound(ty::DebruijnIndex, /* lifetime decl */ ast::NodeId),
44     LateBoundAnon(ty::DebruijnIndex, /* anon index */ u32),
45     Free(region::CallSiteScopeData, /* lifetime decl */ ast::NodeId),
46 }
47
48 impl Region {
49     fn early(index: &mut u32, def: &hir::LifetimeDef) -> (ast::Name, Region) {
50         let i = *index;
51         *index += 1;
52         (def.lifetime.name, Region::EarlyBound(i, def.lifetime.id))
53     }
54
55     fn late(def: &hir::LifetimeDef) -> (ast::Name, Region) {
56         let depth = ty::DebruijnIndex::new(1);
57         (def.lifetime.name, Region::LateBound(depth, def.lifetime.id))
58     }
59
60     fn late_anon(index: &Cell<u32>) -> Region {
61         let i = index.get();
62         index.set(i + 1);
63         let depth = ty::DebruijnIndex::new(1);
64         Region::LateBoundAnon(depth, i)
65     }
66
67     fn id(&self) -> Option<ast::NodeId> {
68         match *self {
69             Region::Static |
70             Region::LateBoundAnon(..) => None,
71
72             Region::EarlyBound(_, id) |
73             Region::LateBound(_, id) |
74             Region::Free(_, id) => Some(id)
75         }
76     }
77
78     fn shifted(self, amount: u32) -> Region {
79         match self {
80             Region::LateBound(depth, id) => {
81                 Region::LateBound(depth.shifted(amount), id)
82             }
83             Region::LateBoundAnon(depth, index) => {
84                 Region::LateBoundAnon(depth.shifted(amount), index)
85             }
86             _ => self
87         }
88     }
89
90     fn from_depth(self, depth: u32) -> Region {
91         match self {
92             Region::LateBound(debruijn, id) => {
93                 Region::LateBound(ty::DebruijnIndex {
94                     depth: debruijn.depth - (depth - 1)
95                 }, id)
96             }
97             Region::LateBoundAnon(debruijn, index) => {
98                 Region::LateBoundAnon(ty::DebruijnIndex {
99                     depth: debruijn.depth - (depth - 1)
100                 }, index)
101             }
102             _ => self
103         }
104     }
105
106     fn subst(self, params: &[hir::Lifetime], map: &NamedRegionMap)
107              -> Option<Region> {
108         if let Region::EarlyBound(index, _) = self {
109             params.get(index as usize).and_then(|lifetime| {
110                 map.defs.get(&lifetime.id).cloned()
111             })
112         } else {
113             Some(self)
114         }
115     }
116 }
117
118 /// A set containing, at most, one known element.
119 /// If two distinct values are inserted into a set, then it
120 /// becomes `Many`, which can be used to detect ambiguities.
121 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
122 pub enum Set1<T> {
123     Empty,
124     One(T),
125     Many
126 }
127
128 impl<T: PartialEq> Set1<T> {
129     pub fn insert(&mut self, value: T) {
130         if let Set1::Empty = *self {
131             *self = Set1::One(value);
132             return;
133         }
134         if let Set1::One(ref old) = *self {
135             if *old == value {
136                 return;
137             }
138         }
139         *self = Set1::Many;
140     }
141 }
142
143 pub type ObjectLifetimeDefault = Set1<Region>;
144
145 // Maps the id of each lifetime reference to the lifetime decl
146 // that it corresponds to.
147 pub struct NamedRegionMap {
148     // maps from every use of a named (not anonymous) lifetime to a
149     // `Region` describing how that region is bound
150     pub defs: NodeMap<Region>,
151
152     // the set of lifetime def ids that are late-bound; a region can
153     // be late-bound if (a) it does NOT appear in a where-clause and
154     // (b) it DOES appear in the arguments.
155     pub late_bound: NodeSet,
156
157     // Contains the node-ids for lifetimes that were (incorrectly) categorized
158     // as late-bound, until #32330 was fixed.
159     pub issue_32330: NodeMap<ty::Issue32330>,
160
161     // For each type and trait definition, maps type parameters
162     // to the trait object lifetime defaults computed from them.
163     pub object_lifetime_defaults: NodeMap<Vec<ObjectLifetimeDefault>>,
164 }
165
166 struct LifetimeContext<'a, 'tcx: 'a> {
167     sess: &'a Session,
168     hir_map: &'a Map<'tcx>,
169     map: &'a mut NamedRegionMap,
170     scope: ScopeRef<'a>,
171     // Deep breath. Our representation for poly trait refs contains a single
172     // binder and thus we only allow a single level of quantification. However,
173     // the syntax of Rust permits quantification in two places, e.g., `T: for <'a> Foo<'a>`
174     // and `for <'a, 'b> &'b T: Foo<'a>`. In order to get the de Bruijn indices
175     // correct when representing these constraints, we should only introduce one
176     // scope. However, we want to support both locations for the quantifier and
177     // during lifetime resolution we want precise information (so we can't
178     // desugar in an earlier phase).
179
180     // SO, if we encounter a quantifier at the outer scope, we set
181     // trait_ref_hack to true (and introduce a scope), and then if we encounter
182     // a quantifier at the inner scope, we error. If trait_ref_hack is false,
183     // then we introduce the scope at the inner quantifier.
184
185     // I'm sorry.
186     trait_ref_hack: bool,
187
188     // List of labels in the function/method currently under analysis.
189     labels_in_fn: Vec<(ast::Name, Span)>,
190
191     // Cache for cross-crate per-definition object lifetime defaults.
192     xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
193 }
194
195 #[derive(Debug)]
196 enum Scope<'a> {
197     /// Declares lifetimes, and each can be early-bound or late-bound.
198     /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
199     /// it should be shifted by the number of `Binder`s in between the
200     /// declaration `Binder` and the location it's referenced from.
201     Binder {
202         lifetimes: FxHashMap<ast::Name, Region>,
203         s: ScopeRef<'a>
204     },
205
206     /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
207     /// if this is a fn body, otherwise the original definitions are used.
208     /// Unspecified lifetimes are inferred, unless an elision scope is nested,
209     /// e.g. `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
210     Body {
211         id: hir::BodyId,
212         s: ScopeRef<'a>
213     },
214
215     /// A scope which either determines unspecified lifetimes or errors
216     /// on them (e.g. due to ambiguity). For more details, see `Elide`.
217     Elision {
218         elide: Elide,
219         s: ScopeRef<'a>
220     },
221
222     /// Use a specific lifetime (if `Some`) or leave it unset (to be
223     /// inferred in a function body or potentially error outside one),
224     /// for the default choice of lifetime in a trait object type.
225     ObjectLifetimeDefault {
226         lifetime: Option<Region>,
227         s: ScopeRef<'a>
228     },
229
230     Root
231 }
232
233 #[derive(Clone, Debug)]
234 enum Elide {
235     /// Use a fresh anonymous late-bound lifetime each time, by
236     /// incrementing the counter to generate sequential indices.
237     FreshLateAnon(Cell<u32>),
238     /// Always use this one lifetime.
239     Exact(Region),
240     /// Less or more than one lifetime were found, error on unspecified.
241     Error(Vec<ElisionFailureInfo>)
242 }
243
244 #[derive(Clone, Debug)]
245 struct ElisionFailureInfo {
246     /// Where we can find the argument pattern.
247     parent: Option<hir::BodyId>,
248     /// The index of the argument in the original definition.
249     index: usize,
250     lifetime_count: usize,
251     have_bound_regions: bool
252 }
253
254 type ScopeRef<'a> = &'a Scope<'a>;
255
256 const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
257
258 pub fn krate(sess: &Session,
259              hir_map: &Map)
260              -> Result<NamedRegionMap, usize> {
261     let krate = hir_map.krate();
262     let mut map = NamedRegionMap {
263         defs: NodeMap(),
264         late_bound: NodeSet(),
265         issue_32330: NodeMap(),
266         object_lifetime_defaults: compute_object_lifetime_defaults(sess, hir_map),
267     };
268     sess.track_errors(|| {
269         let mut visitor = LifetimeContext {
270             sess: sess,
271             hir_map: hir_map,
272             map: &mut map,
273             scope: ROOT_SCOPE,
274             trait_ref_hack: false,
275             labels_in_fn: vec![],
276             xcrate_object_lifetime_defaults: DefIdMap(),
277         };
278         for (_, item) in &krate.items {
279             visitor.visit_item(item);
280         }
281     })?;
282     Ok(map)
283 }
284
285 impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
286     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
287         NestedVisitorMap::All(self.hir_map)
288     }
289
290     // We want to nest trait/impl items in their parent, but nothing else.
291     fn visit_nested_item(&mut self, _: hir::ItemId) {}
292
293     fn visit_nested_body(&mut self, body: hir::BodyId) {
294         // Each body has their own set of labels, save labels.
295         let saved = replace(&mut self.labels_in_fn, vec![]);
296         let body = self.hir_map.body(body);
297         extract_labels(self, body);
298         self.with(Scope::Body { id: body.id(), s: self.scope }, |_, this| {
299             this.visit_body(body);
300         });
301         replace(&mut self.labels_in_fn, saved);
302     }
303
304     fn visit_item(&mut self, item: &'tcx hir::Item) {
305         match item.node {
306             hir::ItemFn(ref decl, _, _, _, ref generics, _) => {
307                 self.visit_early_late(item.id, None, decl, generics, |this| {
308                     intravisit::walk_item(this, item);
309                 });
310             }
311             hir::ItemExternCrate(_) |
312             hir::ItemUse(..) |
313             hir::ItemMod(..) |
314             hir::ItemDefaultImpl(..) |
315             hir::ItemForeignMod(..) |
316             hir::ItemGlobalAsm(..) => {
317                 // These sorts of items have no lifetime parameters at all.
318                 intravisit::walk_item(self, item);
319             }
320             hir::ItemStatic(..) |
321             hir::ItemConst(..) => {
322                 // No lifetime parameters, but implied 'static.
323                 let scope = Scope::Elision {
324                     elide: Elide::Exact(Region::Static),
325                     s: ROOT_SCOPE
326                 };
327                 self.with(scope, |_, this| intravisit::walk_item(this, item));
328             }
329             hir::ItemTy(_, ref generics) |
330             hir::ItemEnum(_, ref generics) |
331             hir::ItemStruct(_, ref generics) |
332             hir::ItemUnion(_, ref generics) |
333             hir::ItemTrait(_, ref generics, ..) |
334             hir::ItemImpl(_, _, _, ref generics, ..) => {
335                 // These kinds of items have only early bound lifetime parameters.
336                 let mut index = if let hir::ItemTrait(..) = item.node {
337                     1 // Self comes before lifetimes
338                 } else {
339                     0
340                 };
341                 let lifetimes = generics.lifetimes.iter().map(|def| {
342                     Region::early(&mut index, def)
343                 }).collect();
344                 let scope = Scope::Binder {
345                     lifetimes: lifetimes,
346                     s: ROOT_SCOPE
347                 };
348                 self.with(scope, |old_scope, this| {
349                     this.check_lifetime_defs(old_scope, &generics.lifetimes);
350                     intravisit::walk_item(this, item);
351                 });
352             }
353         }
354     }
355
356     fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
357         match item.node {
358             hir::ForeignItemFn(ref decl, _, ref generics) => {
359                 self.visit_early_late(item.id, None, decl, generics, |this| {
360                     intravisit::walk_foreign_item(this, item);
361                 })
362             }
363             hir::ForeignItemStatic(..) => {
364                 intravisit::walk_foreign_item(self, item);
365             }
366         }
367     }
368
369     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
370         match ty.node {
371             hir::TyBareFn(ref c) => {
372                 let scope = Scope::Binder {
373                     lifetimes: c.lifetimes.iter().map(Region::late).collect(),
374                     s: self.scope
375                 };
376                 self.with(scope, |old_scope, this| {
377                     // a bare fn has no bounds, so everything
378                     // contained within is scoped within its binder.
379                     this.check_lifetime_defs(old_scope, &c.lifetimes);
380                     intravisit::walk_ty(this, ty);
381                 });
382             }
383             hir::TyTraitObject(ref bounds, ref lifetime) => {
384                 for bound in bounds {
385                     self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
386                 }
387                 if lifetime.is_elided() {
388                     self.resolve_object_lifetime_default(lifetime)
389                 } else {
390                     self.visit_lifetime(lifetime);
391                 }
392             }
393             hir::TyRptr(ref lifetime_ref, ref mt) => {
394                 self.visit_lifetime(lifetime_ref);
395                 let scope = Scope::ObjectLifetimeDefault {
396                     lifetime: self.map.defs.get(&lifetime_ref.id).cloned(),
397                     s: self.scope
398                 };
399                 self.with(scope, |_, this| this.visit_ty(&mt.ty));
400             }
401             _ => {
402                 intravisit::walk_ty(self, ty)
403             }
404         }
405     }
406
407     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
408         if let hir::TraitItemKind::Method(ref sig, _) = trait_item.node {
409             self.visit_early_late(
410                 trait_item.id,
411                 Some(self.hir_map.get_parent(trait_item.id)),
412                 &sig.decl, &sig.generics,
413                 |this| intravisit::walk_trait_item(this, trait_item))
414         } else {
415             intravisit::walk_trait_item(self, trait_item);
416         }
417     }
418
419     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
420         if let hir::ImplItemKind::Method(ref sig, _) = impl_item.node {
421             self.visit_early_late(
422                 impl_item.id,
423                 Some(self.hir_map.get_parent(impl_item.id)),
424                 &sig.decl, &sig.generics,
425                 |this| intravisit::walk_impl_item(this, impl_item))
426         } else {
427             intravisit::walk_impl_item(self, impl_item);
428         }
429     }
430
431     fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
432         if lifetime_ref.is_elided() {
433             self.resolve_elided_lifetimes(slice::ref_slice(lifetime_ref));
434             return;
435         }
436         if lifetime_ref.is_static() {
437             self.insert_lifetime(lifetime_ref, Region::Static);
438             return;
439         }
440         self.resolve_lifetime_ref(lifetime_ref);
441     }
442
443     fn visit_path(&mut self, path: &'tcx hir::Path, _: ast::NodeId) {
444         for (i, segment) in path.segments.iter().enumerate() {
445             let depth = path.segments.len() - i - 1;
446             self.visit_segment_parameters(path.def, depth, &segment.parameters);
447         }
448     }
449
450     fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl) {
451         let output = match fd.output {
452             hir::DefaultReturn(_) => None,
453             hir::Return(ref ty) => Some(ty)
454         };
455         self.visit_fn_like_elision(&fd.inputs, output);
456     }
457
458     fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
459         for ty_param in generics.ty_params.iter() {
460             walk_list!(self, visit_ty_param_bound, &ty_param.bounds);
461             if let Some(ref ty) = ty_param.default {
462                 self.visit_ty(&ty);
463             }
464         }
465         for predicate in &generics.where_clause.predicates {
466             match predicate {
467                 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ ref bounded_ty,
468                                                                                ref bounds,
469                                                                                ref bound_lifetimes,
470                                                                                .. }) => {
471                     if !bound_lifetimes.is_empty() {
472                         self.trait_ref_hack = true;
473                         let scope = Scope::Binder {
474                             lifetimes: bound_lifetimes.iter().map(Region::late).collect(),
475                             s: self.scope
476                         };
477                         let result = self.with(scope, |old_scope, this| {
478                             this.check_lifetime_defs(old_scope, bound_lifetimes);
479                             this.visit_ty(&bounded_ty);
480                             walk_list!(this, visit_ty_param_bound, bounds);
481                         });
482                         self.trait_ref_hack = false;
483                         result
484                     } else {
485                         self.visit_ty(&bounded_ty);
486                         walk_list!(self, visit_ty_param_bound, bounds);
487                     }
488                 }
489                 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
490                                                                                 ref bounds,
491                                                                                 .. }) => {
492
493                     self.visit_lifetime(lifetime);
494                     for bound in bounds {
495                         self.visit_lifetime(bound);
496                     }
497                 }
498                 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
499                                                                         ref rhs_ty,
500                                                                         .. }) => {
501                     self.visit_ty(lhs_ty);
502                     self.visit_ty(rhs_ty);
503                 }
504             }
505         }
506     }
507
508     fn visit_poly_trait_ref(&mut self,
509                             trait_ref: &'tcx hir::PolyTraitRef,
510                             _modifier: hir::TraitBoundModifier) {
511         debug!("visit_poly_trait_ref trait_ref={:?}", trait_ref);
512
513         if !self.trait_ref_hack || !trait_ref.bound_lifetimes.is_empty() {
514             if self.trait_ref_hack {
515                 span_err!(self.sess, trait_ref.span, E0316,
516                           "nested quantification of lifetimes");
517             }
518             let scope = Scope::Binder {
519                 lifetimes: trait_ref.bound_lifetimes.iter().map(Region::late).collect(),
520                 s: self.scope
521             };
522             self.with(scope, |old_scope, this| {
523                 this.check_lifetime_defs(old_scope, &trait_ref.bound_lifetimes);
524                 for lifetime in &trait_ref.bound_lifetimes {
525                     this.visit_lifetime_def(lifetime);
526                 }
527                 this.visit_trait_ref(&trait_ref.trait_ref)
528             })
529         } else {
530             self.visit_trait_ref(&trait_ref.trait_ref)
531         }
532     }
533 }
534
535 #[derive(Copy, Clone, PartialEq)]
536 enum ShadowKind { Label, Lifetime }
537 struct Original { kind: ShadowKind, span: Span }
538 struct Shadower { kind: ShadowKind, span: Span }
539
540 fn original_label(span: Span) -> Original {
541     Original { kind: ShadowKind::Label, span: span }
542 }
543 fn shadower_label(span: Span) -> Shadower {
544     Shadower { kind: ShadowKind::Label, span: span }
545 }
546 fn original_lifetime(span: Span) -> Original {
547     Original { kind: ShadowKind::Lifetime, span: span }
548 }
549 fn shadower_lifetime(l: &hir::Lifetime) -> Shadower {
550     Shadower { kind: ShadowKind::Lifetime, span: l.span }
551 }
552
553 impl ShadowKind {
554     fn desc(&self) -> &'static str {
555         match *self {
556             ShadowKind::Label => "label",
557             ShadowKind::Lifetime => "lifetime",
558         }
559     }
560 }
561
562 fn signal_shadowing_problem(sess: &Session, name: ast::Name, orig: Original, shadower: Shadower) {
563     let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
564         // lifetime/lifetime shadowing is an error
565         struct_span_err!(sess, shadower.span, E0496,
566                          "{} name `{}` shadows a \
567                           {} name that is already in scope",
568                          shadower.kind.desc(), name, orig.kind.desc())
569     } else {
570         // shadowing involving a label is only a warning, due to issues with
571         // labels and lifetimes not being macro-hygienic.
572         sess.struct_span_warn(shadower.span,
573                               &format!("{} name `{}` shadows a \
574                                         {} name that is already in scope",
575                                        shadower.kind.desc(), name, orig.kind.desc()))
576     };
577     err.span_label(orig.span, &"first declared here");
578     err.span_label(shadower.span,
579                    &format!("lifetime {} already in scope", name));
580     err.emit();
581 }
582
583 // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
584 // if one of the label shadows a lifetime or another label.
585 fn extract_labels(ctxt: &mut LifetimeContext, body: &hir::Body) {
586     struct GatherLabels<'a, 'tcx: 'a> {
587         sess: &'a Session,
588         hir_map: &'a Map<'tcx>,
589         scope: ScopeRef<'a>,
590         labels_in_fn: &'a mut Vec<(ast::Name, Span)>,
591     }
592
593     let mut gather = GatherLabels {
594         sess: ctxt.sess,
595         hir_map: ctxt.hir_map,
596         scope: ctxt.scope,
597         labels_in_fn: &mut ctxt.labels_in_fn,
598     };
599     gather.visit_body(body);
600
601     impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
602         fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
603             NestedVisitorMap::None
604         }
605
606         fn visit_expr(&mut self, ex: &hir::Expr) {
607             if let Some((label, label_span)) = expression_label(ex) {
608                 for &(prior, prior_span) in &self.labels_in_fn[..] {
609                     // FIXME (#24278): non-hygienic comparison
610                     if label == prior {
611                         signal_shadowing_problem(self.sess,
612                                                  label,
613                                                  original_label(prior_span),
614                                                  shadower_label(label_span));
615                     }
616                 }
617
618                 check_if_label_shadows_lifetime(self.sess,
619                                                 self.hir_map,
620                                                 self.scope,
621                                                 label,
622                                                 label_span);
623
624                 self.labels_in_fn.push((label, label_span));
625             }
626             intravisit::walk_expr(self, ex)
627         }
628     }
629
630     fn expression_label(ex: &hir::Expr) -> Option<(ast::Name, Span)> {
631         match ex.node {
632             hir::ExprWhile(.., Some(label)) |
633             hir::ExprLoop(_, Some(label), _) => Some((label.node, label.span)),
634             _ => None,
635         }
636     }
637
638     fn check_if_label_shadows_lifetime<'a>(sess: &'a Session,
639                                            hir_map: &Map,
640                                            mut scope: ScopeRef<'a>,
641                                            label: ast::Name,
642                                            label_span: Span) {
643         loop {
644             match *scope {
645                 Scope::Body { s, .. } |
646                 Scope::Elision { s, .. } |
647                 Scope::ObjectLifetimeDefault { s, .. } => { scope = s; }
648
649                 Scope::Root => { return; }
650
651                 Scope::Binder { ref lifetimes, s } => {
652                     // FIXME (#24278): non-hygienic comparison
653                     if let Some(def) = lifetimes.get(&label) {
654                         signal_shadowing_problem(
655                             sess,
656                             label,
657                             original_lifetime(hir_map.span(def.id().unwrap())),
658                             shadower_label(label_span));
659                         return;
660                     }
661                     scope = s;
662                 }
663             }
664         }
665     }
666 }
667
668 fn compute_object_lifetime_defaults(sess: &Session, hir_map: &Map)
669                                     -> NodeMap<Vec<ObjectLifetimeDefault>> {
670     let mut map = NodeMap();
671     for item in hir_map.krate().items.values() {
672         match item.node {
673             hir::ItemStruct(_, ref generics) |
674             hir::ItemUnion(_, ref generics) |
675             hir::ItemEnum(_, ref generics) |
676             hir::ItemTy(_, ref generics) |
677             hir::ItemTrait(_, ref generics, ..) => {
678                 let result = object_lifetime_defaults_for_item(hir_map, generics);
679
680                 // Debugging aid.
681                 if attr::contains_name(&item.attrs, "rustc_object_lifetime_default") {
682                     let object_lifetime_default_reprs: String =
683                         result.iter().map(|set| {
684                             match *set {
685                                 Set1::Empty => "BaseDefault".to_string(),
686                                 Set1::One(Region::Static) => "'static".to_string(),
687                                 Set1::One(Region::EarlyBound(i, _)) => {
688                                     generics.lifetimes[i as usize].lifetime.name.to_string()
689                                 }
690                                 Set1::One(_) => bug!(),
691                                 Set1::Many => "Ambiguous".to_string(),
692                             }
693                         }).collect::<Vec<String>>().join(",");
694                     sess.span_err(item.span, &object_lifetime_default_reprs);
695                 }
696
697                 map.insert(item.id, result);
698             }
699             _ => {}
700         }
701     }
702     map
703 }
704
705 /// Scan the bounds and where-clauses on parameters to extract bounds
706 /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
707 /// for each type parameter.
708 fn object_lifetime_defaults_for_item(hir_map: &Map, generics: &hir::Generics)
709                                      -> Vec<ObjectLifetimeDefault> {
710     fn add_bounds(set: &mut Set1<ast::Name>, bounds: &[hir::TyParamBound]) {
711         for bound in bounds {
712             if let hir::RegionTyParamBound(ref lifetime) = *bound {
713                 set.insert(lifetime.name);
714             }
715         }
716     }
717
718     generics.ty_params.iter().map(|param| {
719         let mut set = Set1::Empty;
720
721         add_bounds(&mut set, &param.bounds);
722
723         let param_def_id = hir_map.local_def_id(param.id);
724         for predicate in &generics.where_clause.predicates {
725             // Look for `type: ...` where clauses.
726             let data = match *predicate {
727                 hir::WherePredicate::BoundPredicate(ref data) => data,
728                 _ => continue
729             };
730
731             // Ignore `for<'a> type: ...` as they can change what
732             // lifetimes mean (although we could "just" handle it).
733             if !data.bound_lifetimes.is_empty() {
734                 continue;
735             }
736
737             let def = match data.bounded_ty.node {
738                 hir::TyPath(hir::QPath::Resolved(None, ref path)) => path.def,
739                 _ => continue
740             };
741
742             if def == Def::TyParam(param_def_id) {
743                 add_bounds(&mut set, &data.bounds);
744             }
745         }
746
747         match set {
748             Set1::Empty => Set1::Empty,
749             Set1::One(name) => {
750                 if name == keywords::StaticLifetime.name() {
751                     Set1::One(Region::Static)
752                 } else {
753                     generics.lifetimes.iter().enumerate().find(|&(_, def)| {
754                         def.lifetime.name == name
755                     }).map_or(Set1::Many, |(i, def)| {
756                         Set1::One(Region::EarlyBound(i as u32, def.lifetime.id))
757                     })
758                 }
759             }
760             Set1::Many => Set1::Many
761         }
762     }).collect()
763 }
764
765 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
766     // FIXME(#37666) this works around a limitation in the region inferencer
767     fn hack<F>(&mut self, f: F) where
768         F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
769     {
770         f(self)
771     }
772
773     fn with<F>(&mut self, wrap_scope: Scope, f: F) where
774         F: for<'b> FnOnce(ScopeRef, &mut LifetimeContext<'b, 'tcx>),
775     {
776         let LifetimeContext {sess, hir_map, ref mut map, ..} = *self;
777         let labels_in_fn = replace(&mut self.labels_in_fn, vec![]);
778         let xcrate_object_lifetime_defaults =
779             replace(&mut self.xcrate_object_lifetime_defaults, DefIdMap());
780         let mut this = LifetimeContext {
781             sess: sess,
782             hir_map: hir_map,
783             map: *map,
784             scope: &wrap_scope,
785             trait_ref_hack: self.trait_ref_hack,
786             labels_in_fn: labels_in_fn,
787             xcrate_object_lifetime_defaults: xcrate_object_lifetime_defaults,
788         };
789         debug!("entering scope {:?}", this.scope);
790         f(self.scope, &mut this);
791         debug!("exiting scope {:?}", this.scope);
792         self.labels_in_fn = this.labels_in_fn;
793         self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
794     }
795
796     /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
797     ///
798     /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
799     /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
800     /// within type bounds; those are early bound lifetimes, and the rest are late bound.
801     ///
802     /// For example:
803     ///
804     ///    fn foo<'a,'b,'c,T:Trait<'b>>(...)
805     ///
806     /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
807     /// lifetimes may be interspersed together.
808     ///
809     /// If early bound lifetimes are present, we separate them into their own list (and likewise
810     /// for late bound). They will be numbered sequentially, starting from the lowest index that is
811     /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
812     /// bound lifetimes are resolved by name and associated with a binder id (`binder_id`), so the
813     /// ordering is not important there.
814     fn visit_early_late<F>(&mut self,
815                            fn_id: ast::NodeId,
816                            parent_id: Option<ast::NodeId>,
817                            decl: &'tcx hir::FnDecl,
818                            generics: &'tcx hir::Generics,
819                            walk: F) where
820         F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
821     {
822         let fn_def_id = self.hir_map.local_def_id(fn_id);
823         insert_late_bound_lifetimes(self.map,
824                                     fn_def_id,
825                                     decl,
826                                     generics);
827
828         // Find the start of nested early scopes, e.g. in methods.
829         let mut index = 0;
830         if let Some(parent_id) = parent_id {
831             let parent = self.hir_map.expect_item(parent_id);
832             if let hir::ItemTrait(..) = parent.node {
833                 index += 1; // Self comes first.
834             }
835             match parent.node {
836                 hir::ItemTrait(_, ref generics, ..) |
837                 hir::ItemImpl(_, _, _, ref generics, ..) => {
838                     index += (generics.lifetimes.len() + generics.ty_params.len()) as u32;
839                 }
840                 _ => {}
841             }
842         }
843
844         let lifetimes = generics.lifetimes.iter().map(|def| {
845             if self.map.late_bound.contains(&def.lifetime.id) {
846                 Region::late(def)
847             } else {
848                 Region::early(&mut index, def)
849             }
850         }).collect();
851
852         let scope = Scope::Binder {
853             lifetimes: lifetimes,
854             s: self.scope
855         };
856         self.with(scope, move |old_scope, this| {
857             this.check_lifetime_defs(old_scope, &generics.lifetimes);
858             this.hack(walk); // FIXME(#37666) workaround in place of `walk(this)`
859         });
860     }
861
862     fn resolve_lifetime_ref(&mut self, lifetime_ref: &hir::Lifetime) {
863         // Walk up the scope chain, tracking the number of fn scopes
864         // that we pass through, until we find a lifetime with the
865         // given name or we run out of scopes.
866         // search.
867         let mut late_depth = 0;
868         let mut scope = self.scope;
869         let mut outermost_body = None;
870         let result = loop {
871             match *scope {
872                 Scope::Body { id, s } => {
873                     outermost_body = Some(id);
874                     scope = s;
875                 }
876
877                 Scope::Root => {
878                     break None;
879                 }
880
881                 Scope::Binder { ref lifetimes, s } => {
882                     if let Some(&def) = lifetimes.get(&lifetime_ref.name) {
883                         break Some(def.shifted(late_depth));
884                     } else {
885                         late_depth += 1;
886                         scope = s;
887                     }
888                 }
889
890                 Scope::Elision { s, .. } |
891                 Scope::ObjectLifetimeDefault { s, .. } => {
892                     scope = s;
893                 }
894             }
895         };
896
897         if let Some(mut def) = result {
898             if let Some(body_id) = outermost_body {
899                 let fn_id = self.hir_map.body_owner(body_id);
900                 let scope_data = region::CallSiteScopeData {
901                     fn_id: fn_id, body_id: body_id.node_id
902                 };
903                 match self.hir_map.get(fn_id) {
904                     hir::map::NodeItem(&hir::Item {
905                         node: hir::ItemFn(..), ..
906                     }) |
907                     hir::map::NodeTraitItem(&hir::TraitItem {
908                         node: hir::TraitItemKind::Method(..), ..
909                     }) |
910                     hir::map::NodeImplItem(&hir::ImplItem {
911                         node: hir::ImplItemKind::Method(..), ..
912                     }) => {
913                         def = Region::Free(scope_data, def.id().unwrap());
914                     }
915                     _ => {}
916                 }
917             }
918             self.insert_lifetime(lifetime_ref, def);
919         } else {
920             struct_span_err!(self.sess, lifetime_ref.span, E0261,
921                 "use of undeclared lifetime name `{}`", lifetime_ref.name)
922                 .span_label(lifetime_ref.span, &format!("undeclared lifetime"))
923                 .emit();
924         }
925     }
926
927     fn visit_segment_parameters(&mut self,
928                                 def: Def,
929                                 depth: usize,
930                                 params: &'tcx hir::PathParameters) {
931         let data = match *params {
932             hir::ParenthesizedParameters(ref data) => {
933                 self.visit_fn_like_elision(&data.inputs, data.output.as_ref());
934                 return;
935             }
936             hir::AngleBracketedParameters(ref data) => data
937         };
938
939         if data.lifetimes.iter().all(|l| l.is_elided()) {
940             self.resolve_elided_lifetimes(&data.lifetimes);
941         } else {
942             for l in &data.lifetimes { self.visit_lifetime(l); }
943         }
944
945         // Figure out if this is a type/trait segment,
946         // which requires object lifetime defaults.
947         let parent_def_id = |this: &mut Self, def_id: DefId| {
948             let def_key = if def_id.is_local() {
949                 this.hir_map.def_key(def_id)
950             } else {
951                 this.sess.cstore.def_key(def_id)
952             };
953             DefId {
954                 krate: def_id.krate,
955                 index: def_key.parent.expect("missing parent")
956             }
957         };
958         let type_def_id = match def {
959             Def::AssociatedTy(def_id) if depth == 1 => {
960                 Some(parent_def_id(self, def_id))
961             }
962             Def::Variant(def_id) if depth == 0 => {
963                 Some(parent_def_id(self, def_id))
964             }
965             Def::Struct(def_id) |
966             Def::Union(def_id) |
967             Def::Enum(def_id) |
968             Def::TyAlias(def_id) |
969             Def::Trait(def_id) if depth == 0 => Some(def_id),
970             _ => None
971         };
972
973         let object_lifetime_defaults = type_def_id.map_or(vec![], |def_id| {
974             let in_body = {
975                 let mut scope = self.scope;
976                 loop {
977                     match *scope {
978                         Scope::Root => break false,
979
980                         Scope::Body { .. } => break true,
981
982                         Scope::Binder { s, .. } |
983                         Scope::Elision { s, .. } |
984                         Scope::ObjectLifetimeDefault { s, .. } => {
985                             scope = s;
986                         }
987                     }
988                 }
989             };
990
991             let map = &self.map;
992             let unsubst = if let Some(id) = self.hir_map.as_local_node_id(def_id) {
993                 &map.object_lifetime_defaults[&id]
994             } else {
995                 let cstore = &self.sess.cstore;
996                 self.xcrate_object_lifetime_defaults.entry(def_id).or_insert_with(|| {
997                     cstore.item_generics_cloned(def_id).types.into_iter().map(|def| {
998                         def.object_lifetime_default
999                     }).collect()
1000                 })
1001             };
1002             unsubst.iter().map(|set| {
1003                 match *set {
1004                     Set1::Empty => {
1005                         if in_body {
1006                             None
1007                         } else {
1008                             Some(Region::Static)
1009                         }
1010                     }
1011                     Set1::One(r) => r.subst(&data.lifetimes, map),
1012                     Set1::Many => None
1013                 }
1014             }).collect()
1015         });
1016
1017         for (i, ty) in data.types.iter().enumerate() {
1018             if let Some(&lt) = object_lifetime_defaults.get(i) {
1019                 let scope = Scope::ObjectLifetimeDefault {
1020                     lifetime: lt,
1021                     s: self.scope
1022                 };
1023                 self.with(scope, |_, this| this.visit_ty(ty));
1024             } else {
1025                 self.visit_ty(ty);
1026             }
1027         }
1028
1029         for b in &data.bindings { self.visit_assoc_type_binding(b); }
1030     }
1031
1032     fn visit_fn_like_elision(&mut self, inputs: &'tcx [P<hir::Ty>],
1033                              output: Option<&'tcx P<hir::Ty>>) {
1034         let mut arg_elide = Elide::FreshLateAnon(Cell::new(0));
1035         let arg_scope = Scope::Elision {
1036             elide: arg_elide.clone(),
1037             s: self.scope
1038         };
1039         self.with(arg_scope, |_, this| {
1040             for input in inputs {
1041                 this.visit_ty(input);
1042             }
1043             match *this.scope {
1044                 Scope::Elision { ref elide, .. } => {
1045                     arg_elide = elide.clone();
1046                 }
1047                 _ => bug!()
1048             }
1049         });
1050
1051         let output = match output {
1052             Some(ty) => ty,
1053             None => return
1054         };
1055
1056         // Figure out if there's a body we can get argument names from,
1057         // and whether there's a `self` argument (treated specially).
1058         let mut assoc_item_kind = None;
1059         let mut impl_self = None;
1060         let parent = self.hir_map.get_parent_node(output.id);
1061         let body = match self.hir_map.get(parent) {
1062             // `fn` definitions and methods.
1063             hir::map::NodeItem(&hir::Item {
1064                 node: hir::ItemFn(.., body), ..
1065             })  => Some(body),
1066
1067             hir::map::NodeTraitItem(&hir::TraitItem {
1068                 node: hir::TraitItemKind::Method(_, ref m), ..
1069             }) => {
1070                 match self.hir_map.expect_item(self.hir_map.get_parent(parent)).node {
1071                     hir::ItemTrait(.., ref trait_items) => {
1072                         assoc_item_kind = trait_items.iter().find(|ti| ti.id.node_id == parent)
1073                                                             .map(|ti| ti.kind);
1074                     }
1075                     _ => {}
1076                 }
1077                 match *m {
1078                     hir::TraitMethod::Required(_) => None,
1079                     hir::TraitMethod::Provided(body) => Some(body),
1080                 }
1081             }
1082
1083             hir::map::NodeImplItem(&hir::ImplItem {
1084                 node: hir::ImplItemKind::Method(_, body), ..
1085             }) => {
1086                 match self.hir_map.expect_item(self.hir_map.get_parent(parent)).node {
1087                     hir::ItemImpl(.., ref self_ty, ref impl_items) => {
1088                         impl_self = Some(self_ty);
1089                         assoc_item_kind = impl_items.iter().find(|ii| ii.id.node_id == parent)
1090                                                            .map(|ii| ii.kind);
1091                     }
1092                     _ => {}
1093                 }
1094                 Some(body)
1095             }
1096
1097             // `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
1098             hir::map::NodeTy(_) | hir::map::NodeTraitRef(_) => None,
1099
1100             // Foreign `fn` decls are terrible because we messed up,
1101             // and their return types get argument type elision.
1102             // And now too much code out there is abusing this rule.
1103             hir::map::NodeForeignItem(_) => {
1104                 let arg_scope = Scope::Elision {
1105                     elide: arg_elide,
1106                     s: self.scope
1107                 };
1108                 self.with(arg_scope, |_, this| this.visit_ty(output));
1109                 return;
1110             }
1111
1112             // Everything else (only closures?) doesn't
1113             // actually enjoy elision in return types.
1114             _ => {
1115                 self.visit_ty(output);
1116                 return;
1117             }
1118         };
1119
1120         let has_self = match assoc_item_kind {
1121             Some(hir::AssociatedItemKind::Method { has_self }) => has_self,
1122             _ => false
1123         };
1124
1125         // In accordance with the rules for lifetime elision, we can determine
1126         // what region to use for elision in the output type in two ways.
1127         // First (determined here), if `self` is by-reference, then the
1128         // implied output region is the region of the self parameter.
1129         if has_self {
1130             // Look for `self: &'a Self` - also desugared from `&'a self`,
1131             // and if that matches, use it for elision and return early.
1132             let is_self_ty = |def: Def| {
1133                 if let Def::SelfTy(..) = def {
1134                     return true;
1135                 }
1136
1137                 // Can't always rely on literal (or implied) `Self` due
1138                 // to the way elision rules were originally specified.
1139                 let impl_self = impl_self.map(|ty| &ty.node);
1140                 if let Some(&hir::TyPath(hir::QPath::Resolved(None, ref path))) = impl_self {
1141                     match path.def {
1142                         // Whitelist the types that unambiguously always
1143                         // result in the same type constructor being used
1144                         // (it can't differ between `Self` and `self`).
1145                         Def::Struct(_) |
1146                         Def::Union(_) |
1147                         Def::Enum(_) |
1148                         Def::PrimTy(_) => return def == path.def,
1149                         _ => {}
1150                     }
1151                 }
1152
1153                 false
1154             };
1155
1156             if let hir::TyRptr(lifetime_ref, ref mt) = inputs[0].node {
1157                 if let hir::TyPath(hir::QPath::Resolved(None, ref path)) = mt.ty.node {
1158                     if is_self_ty(path.def) {
1159                         if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.id) {
1160                             let scope = Scope::Elision {
1161                                 elide: Elide::Exact(lifetime),
1162                                 s: self.scope
1163                             };
1164                             self.with(scope, |_, this| this.visit_ty(output));
1165                             return;
1166                         }
1167                     }
1168                 }
1169             }
1170         }
1171
1172         // Second, if there was exactly one lifetime (either a substitution or a
1173         // reference) in the arguments, then any anonymous regions in the output
1174         // have that lifetime.
1175         let mut possible_implied_output_region = None;
1176         let mut lifetime_count = 0;
1177         let arg_lifetimes = inputs.iter().enumerate().skip(has_self as usize).map(|(i, input)| {
1178             let mut gather = GatherLifetimes {
1179                 map: self.map,
1180                 binder_depth: 1,
1181                 have_bound_regions: false,
1182                 lifetimes: FxHashSet()
1183             };
1184             gather.visit_ty(input);
1185
1186             lifetime_count += gather.lifetimes.len();
1187
1188             if lifetime_count == 1 && gather.lifetimes.len() == 1 {
1189                 // there's a chance that the unique lifetime of this
1190                 // iteration will be the appropriate lifetime for output
1191                 // parameters, so lets store it.
1192                 possible_implied_output_region = gather.lifetimes.iter().cloned().next();
1193             }
1194
1195             ElisionFailureInfo {
1196                 parent: body,
1197                 index: i,
1198                 lifetime_count: gather.lifetimes.len(),
1199                 have_bound_regions: gather.have_bound_regions
1200             }
1201         }).collect();
1202
1203         let elide = if lifetime_count == 1 {
1204             Elide::Exact(possible_implied_output_region.unwrap())
1205         } else {
1206             Elide::Error(arg_lifetimes)
1207         };
1208
1209         let scope = Scope::Elision {
1210             elide: elide,
1211             s: self.scope
1212         };
1213         self.with(scope, |_, this| this.visit_ty(output));
1214
1215         struct GatherLifetimes<'a> {
1216             map: &'a NamedRegionMap,
1217             binder_depth: u32,
1218             have_bound_regions: bool,
1219             lifetimes: FxHashSet<Region>,
1220         }
1221
1222         impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
1223             fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1224                 NestedVisitorMap::None
1225             }
1226
1227             fn visit_ty(&mut self, ty: &hir::Ty) {
1228                 if let hir::TyBareFn(_) = ty.node {
1229                     self.binder_depth += 1;
1230                 }
1231                 if let hir::TyTraitObject(ref bounds, ref lifetime) = ty.node {
1232                     for bound in bounds {
1233                         self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
1234                     }
1235
1236                     // Stay on the safe side and don't include the object
1237                     // lifetime default (which may not end up being used).
1238                     if !lifetime.is_elided() {
1239                         self.visit_lifetime(lifetime);
1240                     }
1241                 } else {
1242                     intravisit::walk_ty(self, ty);
1243                 }
1244                 if let hir::TyBareFn(_) = ty.node {
1245                     self.binder_depth -= 1;
1246                 }
1247             }
1248
1249             fn visit_poly_trait_ref(&mut self,
1250                                     trait_ref: &hir::PolyTraitRef,
1251                                     modifier: hir::TraitBoundModifier) {
1252                 self.binder_depth += 1;
1253                 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1254                 self.binder_depth -= 1;
1255             }
1256
1257             fn visit_lifetime_def(&mut self, lifetime_def: &hir::LifetimeDef) {
1258                 for l in &lifetime_def.bounds { self.visit_lifetime(l); }
1259             }
1260
1261             fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
1262                 if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.id) {
1263                     match lifetime {
1264                         Region::LateBound(debruijn, _) |
1265                         Region::LateBoundAnon(debruijn, _)
1266                                 if debruijn.depth < self.binder_depth => {
1267                             self.have_bound_regions = true;
1268                         }
1269                         _ => {
1270                             self.lifetimes.insert(lifetime.from_depth(self.binder_depth));
1271                         }
1272                     }
1273                 }
1274             }
1275         }
1276
1277     }
1278
1279     fn resolve_elided_lifetimes(&mut self, lifetime_refs: &[hir::Lifetime]) {
1280         if lifetime_refs.is_empty() {
1281             return;
1282         }
1283
1284         let span = lifetime_refs[0].span;
1285         let mut late_depth = 0;
1286         let mut scope = self.scope;
1287         let error = loop {
1288             match *scope {
1289                 // Do not assign any resolution, it will be inferred.
1290                 Scope::Body { .. } => return,
1291
1292                 Scope::Root => break None,
1293
1294                 Scope::Binder { s, .. } => {
1295                     late_depth += 1;
1296                     scope = s;
1297                 }
1298
1299                 Scope::Elision { ref elide, .. } => {
1300                     let lifetime = match *elide {
1301                         Elide::FreshLateAnon(ref counter) => {
1302                             for lifetime_ref in lifetime_refs {
1303                                 let lifetime = Region::late_anon(counter).shifted(late_depth);
1304                                 self.insert_lifetime(lifetime_ref, lifetime);
1305                             }
1306                             return;
1307                         }
1308                         Elide::Exact(l) => l.shifted(late_depth),
1309                         Elide::Error(ref e) => break Some(e)
1310                     };
1311                     for lifetime_ref in lifetime_refs {
1312                         self.insert_lifetime(lifetime_ref, lifetime);
1313                     }
1314                     return;
1315                 }
1316
1317                 Scope::ObjectLifetimeDefault { s, .. } => {
1318                     scope = s;
1319                 }
1320             }
1321         };
1322
1323         let mut err = struct_span_err!(self.sess, span, E0106,
1324             "missing lifetime specifier{}",
1325             if lifetime_refs.len() > 1 { "s" } else { "" });
1326         let msg = if lifetime_refs.len() > 1 {
1327             format!("expected {} lifetime parameters", lifetime_refs.len())
1328         } else {
1329             format!("expected lifetime parameter")
1330         };
1331         err.span_label(span, &msg);
1332
1333         if let Some(params) = error {
1334             if lifetime_refs.len() == 1 {
1335                 self.report_elision_failure(&mut err, params);
1336             }
1337         }
1338         err.emit();
1339     }
1340
1341     fn report_elision_failure(&mut self,
1342                               db: &mut DiagnosticBuilder,
1343                               params: &[ElisionFailureInfo]) {
1344         let mut m = String::new();
1345         let len = params.len();
1346
1347         let elided_params: Vec<_> = params.iter().cloned()
1348                                           .filter(|info| info.lifetime_count > 0)
1349                                           .collect();
1350
1351         let elided_len = elided_params.len();
1352
1353         for (i, info) in elided_params.into_iter().enumerate() {
1354             let ElisionFailureInfo {
1355                 parent, index, lifetime_count: n, have_bound_regions
1356             } = info;
1357
1358             let help_name = if let Some(body) = parent {
1359                 let arg = &self.hir_map.body(body).arguments[index];
1360                 format!("`{}`", self.hir_map.node_to_pretty_string(arg.pat.id))
1361             } else {
1362                 format!("argument {}", index + 1)
1363             };
1364
1365             m.push_str(&(if n == 1 {
1366                 help_name
1367             } else {
1368                 format!("one of {}'s {} elided {}lifetimes", help_name, n,
1369                         if have_bound_regions { "free " } else { "" } )
1370             })[..]);
1371
1372             if elided_len == 2 && i == 0 {
1373                 m.push_str(" or ");
1374             } else if i + 2 == elided_len {
1375                 m.push_str(", or ");
1376             } else if i != elided_len - 1 {
1377                 m.push_str(", ");
1378             }
1379
1380         }
1381
1382         if len == 0 {
1383             help!(db,
1384                   "this function's return type contains a borrowed value, but \
1385                    there is no value for it to be borrowed from");
1386             help!(db,
1387                   "consider giving it a 'static lifetime");
1388         } else if elided_len == 0 {
1389             help!(db,
1390                   "this function's return type contains a borrowed value with \
1391                    an elided lifetime, but the lifetime cannot be derived from \
1392                    the arguments");
1393             help!(db,
1394                   "consider giving it an explicit bounded or 'static \
1395                    lifetime");
1396         } else if elided_len == 1 {
1397             help!(db,
1398                   "this function's return type contains a borrowed value, but \
1399                    the signature does not say which {} it is borrowed from",
1400                   m);
1401         } else {
1402             help!(db,
1403                   "this function's return type contains a borrowed value, but \
1404                    the signature does not say whether it is borrowed from {}",
1405                   m);
1406         }
1407     }
1408
1409     fn resolve_object_lifetime_default(&mut self, lifetime_ref: &hir::Lifetime) {
1410         let mut late_depth = 0;
1411         let mut scope = self.scope;
1412         let lifetime = loop {
1413             match *scope {
1414                 Scope::Binder { s, .. } => {
1415                     late_depth += 1;
1416                     scope = s;
1417                 }
1418
1419                 Scope::Root |
1420                 Scope::Elision { .. } => break Region::Static,
1421
1422                 Scope::Body { .. } |
1423                 Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
1424
1425                 Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l
1426             }
1427         };
1428         self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
1429     }
1430
1431     fn check_lifetime_defs(&mut self, old_scope: ScopeRef, lifetimes: &[hir::LifetimeDef]) {
1432         for i in 0..lifetimes.len() {
1433             let lifetime_i = &lifetimes[i];
1434
1435             for lifetime in lifetimes {
1436                 if lifetime.lifetime.is_static() {
1437                     let lifetime = lifetime.lifetime;
1438                     let mut err = struct_span_err!(self.sess, lifetime.span, E0262,
1439                                   "invalid lifetime parameter name: `{}`", lifetime.name);
1440                     err.span_label(lifetime.span,
1441                                    &format!("{} is a reserved lifetime name", lifetime.name));
1442                     err.emit();
1443                 }
1444             }
1445
1446             // It is a hard error to shadow a lifetime within the same scope.
1447             for j in i + 1..lifetimes.len() {
1448                 let lifetime_j = &lifetimes[j];
1449
1450                 if lifetime_i.lifetime.name == lifetime_j.lifetime.name {
1451                     struct_span_err!(self.sess, lifetime_j.lifetime.span, E0263,
1452                                      "lifetime name `{}` declared twice in the same scope",
1453                                      lifetime_j.lifetime.name)
1454                         .span_label(lifetime_j.lifetime.span,
1455                                     &format!("declared twice"))
1456                         .span_label(lifetime_i.lifetime.span,
1457                                    &format!("previous declaration here"))
1458                         .emit();
1459                 }
1460             }
1461
1462             // It is a soft error to shadow a lifetime within a parent scope.
1463             self.check_lifetime_def_for_shadowing(old_scope, &lifetime_i.lifetime);
1464
1465             for bound in &lifetime_i.bounds {
1466                 if !bound.is_static() {
1467                     self.resolve_lifetime_ref(bound);
1468                 } else {
1469                     self.insert_lifetime(bound, Region::Static);
1470                     self.sess.struct_span_warn(lifetime_i.lifetime.span.to(bound.span),
1471                         &format!("unnecessary lifetime parameter `{}`", lifetime_i.lifetime.name))
1472                         .help(&format!("you can use the `'static` lifetime directly, in place \
1473                                         of `{}`", lifetime_i.lifetime.name))
1474                         .emit();
1475                 }
1476             }
1477         }
1478     }
1479
1480     fn check_lifetime_def_for_shadowing(&self,
1481                                         mut old_scope: ScopeRef,
1482                                         lifetime: &hir::Lifetime)
1483     {
1484         for &(label, label_span) in &self.labels_in_fn {
1485             // FIXME (#24278): non-hygienic comparison
1486             if lifetime.name == label {
1487                 signal_shadowing_problem(self.sess,
1488                                          lifetime.name,
1489                                          original_label(label_span),
1490                                          shadower_lifetime(&lifetime));
1491                 return;
1492             }
1493         }
1494
1495         loop {
1496             match *old_scope {
1497                 Scope::Body { s, .. } |
1498                 Scope::Elision { s, .. } |
1499                 Scope::ObjectLifetimeDefault { s, .. } => {
1500                     old_scope = s;
1501                 }
1502
1503                 Scope::Root => {
1504                     return;
1505                 }
1506
1507                 Scope::Binder { ref lifetimes, s } => {
1508                     if let Some(&def) = lifetimes.get(&lifetime.name) {
1509                         signal_shadowing_problem(
1510                             self.sess,
1511                             lifetime.name,
1512                             original_lifetime(self.hir_map.span(def.id().unwrap())),
1513                             shadower_lifetime(&lifetime));
1514                         return;
1515                     }
1516
1517                     old_scope = s;
1518                 }
1519             }
1520         }
1521     }
1522
1523     fn insert_lifetime(&mut self,
1524                        lifetime_ref: &hir::Lifetime,
1525                        def: Region) {
1526         if lifetime_ref.id == ast::DUMMY_NODE_ID {
1527             span_bug!(lifetime_ref.span,
1528                       "lifetime reference not renumbered, \
1529                        probably a bug in syntax::fold");
1530         }
1531
1532         debug!("{} resolved to {:?} span={:?}",
1533                self.hir_map.node_to_string(lifetime_ref.id),
1534                def,
1535                self.sess.codemap().span_to_string(lifetime_ref.span));
1536         self.map.defs.insert(lifetime_ref.id, def);
1537     }
1538 }
1539
1540 ///////////////////////////////////////////////////////////////////////////
1541
1542 /// Detects late-bound lifetimes and inserts them into
1543 /// `map.late_bound`.
1544 ///
1545 /// A region declared on a fn is **late-bound** if:
1546 /// - it is constrained by an argument type;
1547 /// - it does not appear in a where-clause.
1548 ///
1549 /// "Constrained" basically means that it appears in any type but
1550 /// not amongst the inputs to a projection.  In other words, `<&'a
1551 /// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
1552 fn insert_late_bound_lifetimes(map: &mut NamedRegionMap,
1553                                fn_def_id: DefId,
1554                                decl: &hir::FnDecl,
1555                                generics: &hir::Generics) {
1556     debug!("insert_late_bound_lifetimes(decl={:?}, generics={:?})", decl, generics);
1557
1558     let mut constrained_by_input = ConstrainedCollector { regions: FxHashSet() };
1559     for arg_ty in &decl.inputs {
1560         constrained_by_input.visit_ty(arg_ty);
1561     }
1562
1563     let mut appears_in_output = AllCollector {
1564         regions: FxHashSet(),
1565         impl_trait: false
1566     };
1567     intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
1568
1569     debug!("insert_late_bound_lifetimes: constrained_by_input={:?}",
1570            constrained_by_input.regions);
1571
1572     // Walk the lifetimes that appear in where clauses.
1573     //
1574     // Subtle point: because we disallow nested bindings, we can just
1575     // ignore binders here and scrape up all names we see.
1576     let mut appears_in_where_clause = AllCollector {
1577         regions: FxHashSet(),
1578         impl_trait: false
1579     };
1580     for ty_param in generics.ty_params.iter() {
1581         walk_list!(&mut appears_in_where_clause,
1582                    visit_ty_param_bound,
1583                    &ty_param.bounds);
1584     }
1585     walk_list!(&mut appears_in_where_clause,
1586                visit_where_predicate,
1587                &generics.where_clause.predicates);
1588     for lifetime_def in &generics.lifetimes {
1589         if !lifetime_def.bounds.is_empty() {
1590             // `'a: 'b` means both `'a` and `'b` are referenced
1591             appears_in_where_clause.visit_lifetime_def(lifetime_def);
1592         }
1593     }
1594
1595     debug!("insert_late_bound_lifetimes: appears_in_where_clause={:?}",
1596            appears_in_where_clause.regions);
1597
1598     // Late bound regions are those that:
1599     // - appear in the inputs
1600     // - do not appear in the where-clauses
1601     // - are not implicitly captured by `impl Trait`
1602     for lifetime in &generics.lifetimes {
1603         let name = lifetime.lifetime.name;
1604
1605         // appears in the where clauses? early-bound.
1606         if appears_in_where_clause.regions.contains(&name) { continue; }
1607
1608         // any `impl Trait` in the return type? early-bound.
1609         if appears_in_output.impl_trait { continue; }
1610
1611         // does not appear in the inputs, but appears in the return
1612         // type? eventually this will be early-bound, but for now we
1613         // just mark it so we can issue warnings.
1614         let constrained_by_input = constrained_by_input.regions.contains(&name);
1615         let appears_in_output = appears_in_output.regions.contains(&name);
1616         if !constrained_by_input && appears_in_output {
1617             debug!("inserting issue_32330 entry for {:?}, {:?} on {:?}",
1618                    lifetime.lifetime.id,
1619                    name,
1620                    fn_def_id);
1621             map.issue_32330.insert(
1622                 lifetime.lifetime.id,
1623                 ty::Issue32330 {
1624                     fn_def_id: fn_def_id,
1625                     region_name: name,
1626                 });
1627             continue;
1628         }
1629
1630         debug!("insert_late_bound_lifetimes: \
1631                 lifetime {:?} with id {:?} is late-bound",
1632                lifetime.lifetime.name, lifetime.lifetime.id);
1633
1634         let inserted = map.late_bound.insert(lifetime.lifetime.id);
1635         assert!(inserted, "visited lifetime {:?} twice", lifetime.lifetime.id);
1636     }
1637
1638     return;
1639
1640     struct ConstrainedCollector {
1641         regions: FxHashSet<ast::Name>,
1642     }
1643
1644     impl<'v> Visitor<'v> for ConstrainedCollector {
1645         fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1646             NestedVisitorMap::None
1647         }
1648
1649         fn visit_ty(&mut self, ty: &'v hir::Ty) {
1650             match ty.node {
1651                 hir::TyPath(hir::QPath::Resolved(Some(_), _)) |
1652                 hir::TyPath(hir::QPath::TypeRelative(..)) => {
1653                     // ignore lifetimes appearing in associated type
1654                     // projections, as they are not *constrained*
1655                     // (defined above)
1656                 }
1657
1658                 hir::TyPath(hir::QPath::Resolved(None, ref path)) => {
1659                     // consider only the lifetimes on the final
1660                     // segment; I am not sure it's even currently
1661                     // valid to have them elsewhere, but even if it
1662                     // is, those would be potentially inputs to
1663                     // projections
1664                     if let Some(last_segment) = path.segments.last() {
1665                         self.visit_path_segment(path.span, last_segment);
1666                     }
1667                 }
1668
1669                 _ => {
1670                     intravisit::walk_ty(self, ty);
1671                 }
1672             }
1673         }
1674
1675         fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
1676             self.regions.insert(lifetime_ref.name);
1677         }
1678     }
1679
1680     struct AllCollector {
1681         regions: FxHashSet<ast::Name>,
1682         impl_trait: bool
1683     }
1684
1685     impl<'v> Visitor<'v> for AllCollector {
1686         fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1687             NestedVisitorMap::None
1688         }
1689
1690         fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
1691             self.regions.insert(lifetime_ref.name);
1692         }
1693
1694         fn visit_ty(&mut self, ty: &hir::Ty) {
1695             if let hir::TyImplTrait(_) = ty.node {
1696                 self.impl_trait = true;
1697             }
1698             intravisit::walk_ty(self, ty);
1699         }
1700     }
1701 }