]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/infer/error_reporting.rs
Rollup merge of #30511 - defyrlt:issue_30507, r=steveklabnik
[rust.git] / src / librustc / middle / infer / error_reporting.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 //! Error Reporting Code for the inference engine
12 //!
13 //! Because of the way inference, and in particular region inference,
14 //! works, it often happens that errors are not detected until far after
15 //! the relevant line of code has been type-checked. Therefore, there is
16 //! an elaborate system to track why a particular constraint in the
17 //! inference graph arose so that we can explain to the user what gave
18 //! rise to a particular error.
19 //!
20 //! The basis of the system are the "origin" types. An "origin" is the
21 //! reason that a constraint or inference variable arose. There are
22 //! different "origin" enums for different kinds of constraints/variables
23 //! (e.g., `TypeOrigin`, `RegionVariableOrigin`). An origin always has
24 //! a span, but also more information so that we can generate a meaningful
25 //! error message.
26 //!
27 //! Having a catalogue of all the different reasons an error can arise is
28 //! also useful for other reasons, like cross-referencing FAQs etc, though
29 //! we are not really taking advantage of this yet.
30 //!
31 //! # Region Inference
32 //!
33 //! Region inference is particularly tricky because it always succeeds "in
34 //! the moment" and simply registers a constraint. Then, at the end, we
35 //! can compute the full graph and report errors, so we need to be able to
36 //! store and later report what gave rise to the conflicting constraints.
37 //!
38 //! # Subtype Trace
39 //!
40 //! Determining whether `T1 <: T2` often involves a number of subtypes and
41 //! subconstraints along the way. A "TypeTrace" is an extended version
42 //! of an origin that traces the types and other values that were being
43 //! compared. It is not necessarily comprehensive (in fact, at the time of
44 //! this writing it only tracks the root values being compared) but I'd
45 //! like to extend it to include significant "waypoints". For example, if
46 //! you are comparing `(T1, T2) <: (T3, T4)`, and the problem is that `T2
47 //! <: T4` fails, I'd like the trace to include enough information to say
48 //! "in the 2nd element of the tuple". Similarly, failures when comparing
49 //! arguments or return types in fn types should be able to cite the
50 //! specific position, etc.
51 //!
52 //! # Reality vs plan
53 //!
54 //! Of course, there is still a LOT of code in typeck that has yet to be
55 //! ported to this system, and which relies on string concatenation at the
56 //! time of error detection.
57
58 use self::FreshOrKept::*;
59
60 use super::InferCtxt;
61 use super::TypeTrace;
62 use super::SubregionOrigin;
63 use super::RegionVariableOrigin;
64 use super::ValuePairs;
65 use super::region_inference::RegionResolutionError;
66 use super::region_inference::ConcreteFailure;
67 use super::region_inference::SubSupConflict;
68 use super::region_inference::GenericBoundFailure;
69 use super::region_inference::GenericKind;
70 use super::region_inference::ProcessedErrors;
71 use super::region_inference::SameRegions;
72
73 use std::collections::HashSet;
74
75 use front::map as ast_map;
76 use rustc_front::hir;
77 use rustc_front::print::pprust;
78
79 use middle::cstore::CrateStore;
80 use middle::def;
81 use middle::def_id::DefId;
82 use middle::infer::{self, TypeOrigin};
83 use middle::region;
84 use middle::subst;
85 use middle::ty::{self, Ty, HasTypeFlags};
86 use middle::ty::{Region, ReFree};
87 use middle::ty::error::TypeError;
88
89 use std::cell::{Cell, RefCell};
90 use std::char::from_u32;
91 use std::fmt;
92 use syntax::ast;
93 use syntax::errors::DiagnosticBuilder;
94 use syntax::codemap::{self, Pos, Span};
95 use syntax::parse::token;
96 use syntax::ptr::P;
97
98 impl<'tcx> ty::ctxt<'tcx> {
99     pub fn note_and_explain_region(&self,
100                                    err: &mut DiagnosticBuilder,
101                                    prefix: &str,
102                                    region: ty::Region,
103                                    suffix: &str) {
104         fn item_scope_tag(item: &hir::Item) -> &'static str {
105             match item.node {
106                 hir::ItemImpl(..) => "impl",
107                 hir::ItemStruct(..) => "struct",
108                 hir::ItemEnum(..) => "enum",
109                 hir::ItemTrait(..) => "trait",
110                 hir::ItemFn(..) => "function body",
111                 _ => "item"
112             }
113         }
114
115         fn explain_span(tcx: &ty::ctxt, heading: &str, span: Span)
116                         -> (String, Option<Span>) {
117             let lo = tcx.sess.codemap().lookup_char_pos_adj(span.lo);
118             (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize()),
119              Some(span))
120         }
121
122         let (description, span) = match region {
123             ty::ReScope(scope) => {
124                 let new_string;
125                 let unknown_scope = || {
126                     format!("{}unknown scope: {:?}{}.  Please report a bug.",
127                             prefix, scope, suffix)
128                 };
129                 let span = match scope.span(&self.region_maps, &self.map) {
130                     Some(s) => s,
131                     None => {
132                         err.note(&unknown_scope());
133                         return;
134                     }
135                 };
136                 let tag = match self.map.find(scope.node_id(&self.region_maps)) {
137                     Some(ast_map::NodeBlock(_)) => "block",
138                     Some(ast_map::NodeExpr(expr)) => match expr.node {
139                         hir::ExprCall(..) => "call",
140                         hir::ExprMethodCall(..) => "method call",
141                         hir::ExprMatch(_, _, hir::MatchSource::IfLetDesugar { .. }) => "if let",
142                         hir::ExprMatch(_, _, hir::MatchSource::WhileLetDesugar) =>  "while let",
143                         hir::ExprMatch(_, _, hir::MatchSource::ForLoopDesugar) =>  "for",
144                         hir::ExprMatch(..) => "match",
145                         _ => "expression",
146                     },
147                     Some(ast_map::NodeStmt(_)) => "statement",
148                     Some(ast_map::NodeItem(it)) => item_scope_tag(&*it),
149                     Some(_) | None => {
150                         err.span_note(span, &unknown_scope());
151                         return;
152                     }
153                 };
154                 let scope_decorated_tag = match self.region_maps.code_extent_data(scope) {
155                     region::CodeExtentData::Misc(_) => tag,
156                     region::CodeExtentData::CallSiteScope { .. } => {
157                         "scope of call-site for function"
158                     }
159                     region::CodeExtentData::ParameterScope { .. } => {
160                         "scope of parameters for function"
161                     }
162                     region::CodeExtentData::DestructionScope(_) => {
163                         new_string = format!("destruction scope surrounding {}", tag);
164                         &new_string[..]
165                     }
166                     region::CodeExtentData::Remainder(r) => {
167                         new_string = format!("block suffix following statement {}",
168                                              r.first_statement_index);
169                         &new_string[..]
170                     }
171                 };
172                 explain_span(self, scope_decorated_tag, span)
173             }
174
175             ty::ReFree(ref fr) => {
176                 let prefix = match fr.bound_region {
177                     ty::BrAnon(idx) => {
178                         format!("the anonymous lifetime #{} defined on", idx + 1)
179                     }
180                     ty::BrFresh(_) => "an anonymous lifetime defined on".to_owned(),
181                     _ => {
182                         format!("the lifetime {} as defined on",
183                                 fr.bound_region)
184                     }
185                 };
186
187                 match self.map.find(fr.scope.node_id(&self.region_maps)) {
188                     Some(ast_map::NodeBlock(ref blk)) => {
189                         let (msg, opt_span) = explain_span(self, "block", blk.span);
190                         (format!("{} {}", prefix, msg), opt_span)
191                     }
192                     Some(ast_map::NodeItem(it)) => {
193                         let tag = item_scope_tag(&*it);
194                         let (msg, opt_span) = explain_span(self, tag, it.span);
195                         (format!("{} {}", prefix, msg), opt_span)
196                     }
197                     Some(_) | None => {
198                         // this really should not happen, but it does:
199                         // FIXME(#27942)
200                         (format!("{} unknown free region bounded by scope {:?}",
201                                  prefix, fr.scope), None)
202                     }
203                 }
204             }
205
206             ty::ReStatic => ("the static lifetime".to_owned(), None),
207
208             ty::ReEmpty => ("the empty lifetime".to_owned(), None),
209
210             ty::ReEarlyBound(ref data) => (data.name.to_string(), None),
211
212             // FIXME(#13998) ReSkolemized should probably print like
213             // ReFree rather than dumping Debug output on the user.
214             //
215             // We shouldn't really be having unification failures with ReVar
216             // and ReLateBound though.
217             ty::ReSkolemized(..) | ty::ReVar(_) | ty::ReLateBound(..) => {
218                 (format!("lifetime {:?}", region), None)
219             }
220         };
221         let message = format!("{}{}{}", prefix, description, suffix);
222         if let Some(span) = span {
223             err.span_note(span, &message);
224         } else {
225             err.note(&message);
226         }
227     }
228 }
229
230 pub trait ErrorReporting<'tcx> {
231     fn report_region_errors(&self,
232                             errors: &Vec<RegionResolutionError<'tcx>>);
233
234     fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
235                       -> Vec<RegionResolutionError<'tcx>>;
236
237     fn report_type_error(&self,
238                          trace: TypeTrace<'tcx>,
239                          terr: &TypeError<'tcx>)
240                          -> DiagnosticBuilder<'tcx>;
241
242     fn check_and_note_conflicting_crates(&self,
243                                          err: &mut DiagnosticBuilder,
244                                          terr: &TypeError<'tcx>,
245                                          sp: Span);
246
247     fn report_and_explain_type_error(&self,
248                                      trace: TypeTrace<'tcx>,
249                                      terr: &TypeError<'tcx>);
250
251     fn values_str(&self, values: &ValuePairs<'tcx>) -> Option<String>;
252
253     fn expected_found_str<T: fmt::Display + Resolvable<'tcx> + HasTypeFlags>(
254         &self,
255         exp_found: &ty::error::ExpectedFound<T>)
256         -> Option<String>;
257
258     fn report_concrete_failure(&self,
259                                origin: SubregionOrigin<'tcx>,
260                                sub: Region,
261                                sup: Region);
262
263     fn report_generic_bound_failure(&self,
264                                     origin: SubregionOrigin<'tcx>,
265                                     kind: GenericKind<'tcx>,
266                                     sub: Region);
267
268     fn report_sub_sup_conflict(&self,
269                                var_origin: RegionVariableOrigin,
270                                sub_origin: SubregionOrigin<'tcx>,
271                                sub_region: Region,
272                                sup_origin: SubregionOrigin<'tcx>,
273                                sup_region: Region);
274
275     fn report_processed_errors(&self,
276                                var_origin: &[RegionVariableOrigin],
277                                trace_origin: &[(TypeTrace<'tcx>, TypeError<'tcx>)],
278                                same_regions: &[SameRegions]);
279
280     fn give_suggestion(&self, err: &mut DiagnosticBuilder, same_regions: &[SameRegions]);
281 }
282
283 trait ErrorReportingHelpers<'tcx> {
284     fn report_inference_failure(&self,
285                                 var_origin: RegionVariableOrigin)
286                                 -> DiagnosticBuilder<'tcx>;
287
288     fn note_region_origin(&self,
289                           err: &mut DiagnosticBuilder,
290                           origin: &SubregionOrigin<'tcx>);
291
292     fn give_expl_lifetime_param(&self,
293                                 err: &mut DiagnosticBuilder,
294                                 decl: &hir::FnDecl,
295                                 unsafety: hir::Unsafety,
296                                 constness: hir::Constness,
297                                 name: ast::Name,
298                                 opt_explicit_self: Option<&hir::ExplicitSelf_>,
299                                 generics: &hir::Generics,
300                                 span: Span);
301 }
302
303 impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> {
304     fn report_region_errors(&self,
305                             errors: &Vec<RegionResolutionError<'tcx>>) {
306         let p_errors = self.process_errors(errors);
307         let errors = if p_errors.is_empty() { errors } else { &p_errors };
308         for error in errors {
309             match error.clone() {
310                 ConcreteFailure(origin, sub, sup) => {
311                     self.report_concrete_failure(origin, sub, sup);
312                 }
313
314                 GenericBoundFailure(kind, param_ty, sub) => {
315                     self.report_generic_bound_failure(kind, param_ty, sub);
316                 }
317
318                 SubSupConflict(var_origin,
319                                sub_origin, sub_r,
320                                sup_origin, sup_r) => {
321                     self.report_sub_sup_conflict(var_origin,
322                                                  sub_origin, sub_r,
323                                                  sup_origin, sup_r);
324                 }
325
326                 ProcessedErrors(ref var_origins,
327                                 ref trace_origins,
328                                 ref same_regions) => {
329                     if !same_regions.is_empty() {
330                         self.report_processed_errors(&var_origins[..],
331                                                      &trace_origins[..],
332                                                      &same_regions[..]);
333                     }
334                 }
335             }
336         }
337     }
338
339     // This method goes through all the errors and try to group certain types
340     // of error together, for the purpose of suggesting explicit lifetime
341     // parameters to the user. This is done so that we can have a more
342     // complete view of what lifetimes should be the same.
343     // If the return value is an empty vector, it means that processing
344     // failed (so the return value of this method should not be used)
345     fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
346                       -> Vec<RegionResolutionError<'tcx>> {
347         debug!("process_errors()");
348         let mut var_origins = Vec::new();
349         let mut trace_origins = Vec::new();
350         let mut same_regions = Vec::new();
351         let mut processed_errors = Vec::new();
352         for error in errors {
353             match error.clone() {
354                 ConcreteFailure(origin, sub, sup) => {
355                     debug!("processing ConcreteFailure");
356                     let trace = match origin {
357                         infer::Subtype(trace) => Some(trace),
358                         _ => None,
359                     };
360                     match free_regions_from_same_fn(self.tcx, sub, sup) {
361                         Some(ref same_frs) if trace.is_some() => {
362                             let trace = trace.unwrap();
363                             let terr = TypeError::RegionsDoesNotOutlive(sup,
364                                                                         sub);
365                             trace_origins.push((trace, terr));
366                             append_to_same_regions(&mut same_regions, same_frs);
367                         }
368                         _ => processed_errors.push((*error).clone()),
369                     }
370                 }
371                 SubSupConflict(var_origin, _, sub_r, _, sup_r) => {
372                     debug!("processing SubSupConflict sub: {:?} sup: {:?}", sub_r, sup_r);
373                     match free_regions_from_same_fn(self.tcx, sub_r, sup_r) {
374                         Some(ref same_frs) => {
375                             var_origins.push(var_origin);
376                             append_to_same_regions(&mut same_regions, same_frs);
377                         }
378                         None => processed_errors.push((*error).clone()),
379                     }
380                 }
381                 _ => ()  // This shouldn't happen
382             }
383         }
384         if !same_regions.is_empty() {
385             let common_scope_id = same_regions[0].scope_id;
386             for sr in &same_regions {
387                 // Since ProcessedErrors is used to reconstruct the function
388                 // declaration, we want to make sure that they are, in fact,
389                 // from the same scope
390                 if sr.scope_id != common_scope_id {
391                     debug!("returning empty result from process_errors because
392                             {} != {}", sr.scope_id, common_scope_id);
393                     return vec!();
394                 }
395             }
396             let pe = ProcessedErrors(var_origins, trace_origins, same_regions);
397             debug!("errors processed: {:?}", pe);
398             processed_errors.push(pe);
399         }
400         return processed_errors;
401
402
403         struct FreeRegionsFromSameFn {
404             sub_fr: ty::FreeRegion,
405             sup_fr: ty::FreeRegion,
406             scope_id: ast::NodeId
407         }
408
409         impl FreeRegionsFromSameFn {
410             fn new(sub_fr: ty::FreeRegion,
411                    sup_fr: ty::FreeRegion,
412                    scope_id: ast::NodeId)
413                    -> FreeRegionsFromSameFn {
414                 FreeRegionsFromSameFn {
415                     sub_fr: sub_fr,
416                     sup_fr: sup_fr,
417                     scope_id: scope_id
418                 }
419             }
420         }
421
422         fn free_regions_from_same_fn(tcx: &ty::ctxt,
423                                      sub: Region,
424                                      sup: Region)
425                                      -> Option<FreeRegionsFromSameFn> {
426             debug!("free_regions_from_same_fn(sub={:?}, sup={:?})", sub, sup);
427             let (scope_id, fr1, fr2) = match (sub, sup) {
428                 (ReFree(fr1), ReFree(fr2)) => {
429                     if fr1.scope != fr2.scope {
430                         return None
431                     }
432                     assert!(fr1.scope == fr2.scope);
433                     (fr1.scope.node_id(&tcx.region_maps), fr1, fr2)
434                 },
435                 _ => return None
436             };
437             let parent = tcx.map.get_parent(scope_id);
438             let parent_node = tcx.map.find(parent);
439             match parent_node {
440                 Some(node) => match node {
441                     ast_map::NodeItem(item) => match item.node {
442                         hir::ItemFn(..) => {
443                             Some(FreeRegionsFromSameFn::new(fr1, fr2, scope_id))
444                         },
445                         _ => None
446                     },
447                     ast_map::NodeImplItem(..) |
448                     ast_map::NodeTraitItem(..) => {
449                         Some(FreeRegionsFromSameFn::new(fr1, fr2, scope_id))
450                     },
451                     _ => None
452                 },
453                 None => {
454                     debug!("no parent node of scope_id {}", scope_id);
455                     None
456                 }
457             }
458         }
459
460         fn append_to_same_regions(same_regions: &mut Vec<SameRegions>,
461                                   same_frs: &FreeRegionsFromSameFn) {
462             let scope_id = same_frs.scope_id;
463             let (sub_fr, sup_fr) = (same_frs.sub_fr, same_frs.sup_fr);
464             for sr in &mut *same_regions {
465                 if sr.contains(&sup_fr.bound_region)
466                    && scope_id == sr.scope_id {
467                     sr.push(sub_fr.bound_region);
468                     return
469                 }
470             }
471             same_regions.push(SameRegions {
472                 scope_id: scope_id,
473                 regions: vec!(sub_fr.bound_region, sup_fr.bound_region)
474             })
475         }
476     }
477
478     fn report_type_error(&self,
479                          trace: TypeTrace<'tcx>,
480                          terr: &TypeError<'tcx>)
481                          -> DiagnosticBuilder<'tcx> {
482         let expected_found_str = match self.values_str(&trace.values) {
483             Some(v) => v,
484             None => {
485                 return self.tcx.sess.diagnostic().struct_dummy(); /* derived error */
486             }
487         };
488
489         let mut err = struct_span_err!(self.tcx.sess,
490                                        trace.origin.span(),
491                                        E0308,
492                                        "{}: {} ({})",
493                                        trace.origin,
494                                        expected_found_str,
495                                        terr);
496
497         self.check_and_note_conflicting_crates(&mut err, terr, trace.origin.span());
498
499         match trace.origin {
500             TypeOrigin::MatchExpressionArm(_, arm_span, source) => match source {
501                 hir::MatchSource::IfLetDesugar{..} => {
502                     err.span_note(arm_span, "`if let` arm with an incompatible type");
503                 }
504                 _ => {
505                     err.span_note(arm_span, "match arm with an incompatible type");
506                 }
507             },
508             _ => ()
509         }
510         err
511     }
512
513     /// Adds a note if the types come from similarly named crates
514     fn check_and_note_conflicting_crates(&self,
515                                          err: &mut DiagnosticBuilder,
516                                          terr: &TypeError<'tcx>,
517                                          sp: Span) {
518         let report_path_match = |err: &mut DiagnosticBuilder, did1: DefId, did2: DefId| {
519             // Only external crates, if either is from a local
520             // module we could have false positives
521             if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
522                 let exp_path = self.tcx.with_path(did1,
523                                                   |p| p.map(|x| x.to_string())
524                                                        .collect::<Vec<_>>());
525                 let found_path = self.tcx.with_path(did2,
526                                                     |p| p.map(|x| x.to_string())
527                                                          .collect::<Vec<_>>());
528                 // We compare strings because PathMod and PathName can be different
529                 // for imported and non-imported crates
530                 if exp_path == found_path {
531                     let crate_name = self.tcx.sess.cstore.crate_name(did1.krate);
532                     err.span_note(sp, &format!("Perhaps two different versions \
533                                                 of crate `{}` are being used?",
534                                                crate_name));
535                 }
536             }
537         };
538         match *terr {
539             TypeError::Sorts(ref exp_found) => {
540                 // if they are both "path types", there's a chance of ambiguity
541                 // due to different versions of the same crate
542                 match (&exp_found.expected.sty, &exp_found.found.sty) {
543                     (&ty::TyEnum(ref exp_adt, _), &ty::TyEnum(ref found_adt, _)) |
544                     (&ty::TyStruct(ref exp_adt, _), &ty::TyStruct(ref found_adt, _)) |
545                     (&ty::TyEnum(ref exp_adt, _), &ty::TyStruct(ref found_adt, _)) |
546                     (&ty::TyStruct(ref exp_adt, _), &ty::TyEnum(ref found_adt, _)) => {
547                         report_path_match(err, exp_adt.did, found_adt.did);
548                     },
549                     _ => ()
550                 }
551             },
552             TypeError::Traits(ref exp_found) => {
553                 report_path_match(err, exp_found.expected, exp_found.found);
554             },
555             _ => () // FIXME(#22750) handle traits and stuff
556         }
557     }
558
559     fn report_and_explain_type_error(&self,
560                                      trace: TypeTrace<'tcx>,
561                                      terr: &TypeError<'tcx>) {
562         let span = trace.origin.span();
563         let mut err = self.report_type_error(trace, terr);
564         self.tcx.note_and_explain_type_err(&mut err, terr, span);
565         err.emit();
566     }
567
568     /// Returns a string of the form "expected `{}`, found `{}`", or None if this is a derived
569     /// error.
570     fn values_str(&self, values: &ValuePairs<'tcx>) -> Option<String> {
571         match *values {
572             infer::Types(ref exp_found) => self.expected_found_str(exp_found),
573             infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
574             infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found)
575         }
576     }
577
578     fn expected_found_str<T: fmt::Display + Resolvable<'tcx> + HasTypeFlags>(
579         &self,
580         exp_found: &ty::error::ExpectedFound<T>)
581         -> Option<String>
582     {
583         let expected = exp_found.expected.resolve(self);
584         if expected.references_error() {
585             return None;
586         }
587
588         let found = exp_found.found.resolve(self);
589         if found.references_error() {
590             return None;
591         }
592
593         Some(format!("expected `{}`, found `{}`",
594                      expected,
595                      found))
596     }
597
598     fn report_generic_bound_failure(&self,
599                                     origin: SubregionOrigin<'tcx>,
600                                     bound_kind: GenericKind<'tcx>,
601                                     sub: Region)
602     {
603         // FIXME: it would be better to report the first error message
604         // with the span of the parameter itself, rather than the span
605         // where the error was detected. But that span is not readily
606         // accessible.
607
608         let labeled_user_string = match bound_kind {
609             GenericKind::Param(ref p) =>
610                 format!("the parameter type `{}`", p),
611             GenericKind::Projection(ref p) =>
612                 format!("the associated type `{}`", p),
613         };
614
615         let mut err = match sub {
616             ty::ReFree(ty::FreeRegion {bound_region: ty::BrNamed(..), ..}) => {
617                 // Does the required lifetime have a nice name we can print?
618                 let mut err = struct_span_err!(self.tcx.sess,
619                                                origin.span(),
620                                                E0309,
621                                                "{} may not live long enough",
622                                                labeled_user_string);
623                 err.fileline_help(origin.span(),
624                                   &format!("consider adding an explicit lifetime bound `{}: {}`...",
625                                            bound_kind,
626                                            sub));
627                 err
628             }
629
630             ty::ReStatic => {
631                 // Does the required lifetime have a nice name we can print?
632                 let mut err = struct_span_err!(self.tcx.sess,
633                                                origin.span(),
634                                                E0310,
635                                                "{} may not live long enough",
636                                                labeled_user_string);
637                 err.fileline_help(origin.span(),
638                                   &format!("consider adding an explicit lifetime \
639                                             bound `{}: 'static`...",
640                                            bound_kind));
641                 err
642             }
643
644             _ => {
645                 // If not, be less specific.
646                 let mut err = struct_span_err!(self.tcx.sess,
647                                                origin.span(),
648                                                E0311,
649                                                "{} may not live long enough",
650                                                labeled_user_string);
651                 err.fileline_help(origin.span(),
652                                   &format!("consider adding an explicit lifetime bound for `{}`",
653                                            bound_kind));
654                 self.tcx.note_and_explain_region(
655                     &mut err,
656                     &format!("{} must be valid for ", labeled_user_string),
657                     sub,
658                     "...");
659                 err
660             }
661         };
662
663         self.note_region_origin(&mut err, &origin);
664         err.emit();
665     }
666
667     fn report_concrete_failure(&self,
668                                origin: SubregionOrigin<'tcx>,
669                                sub: Region,
670                                sup: Region) {
671         match origin {
672             infer::Subtype(trace) => {
673                 let terr = TypeError::RegionsDoesNotOutlive(sup, sub);
674                 self.report_and_explain_type_error(trace, &terr);
675             }
676             infer::Reborrow(span) => {
677                 let mut err = struct_span_err!(self.tcx.sess, span, E0312,
678                     "lifetime of reference outlines \
679                      lifetime of borrowed content...");
680                 self.tcx.note_and_explain_region(&mut err,
681                     "...the reference is valid for ",
682                     sub,
683                     "...");
684                 self.tcx.note_and_explain_region(&mut err,
685                     "...but the borrowed content is only valid for ",
686                     sup,
687                     "");
688                 err.emit();
689             }
690             infer::ReborrowUpvar(span, ref upvar_id) => {
691                 let mut err = struct_span_err!(self.tcx.sess, span, E0313,
692                     "lifetime of borrowed pointer outlives \
693                             lifetime of captured variable `{}`...",
694                             self.tcx.local_var_name_str(upvar_id.var_id));
695                 self.tcx.note_and_explain_region(&mut err,
696                     "...the borrowed pointer is valid for ",
697                     sub,
698                     "...");
699                 self.tcx.note_and_explain_region(&mut err,
700                     &format!("...but `{}` is only valid for ",
701                              self.tcx.local_var_name_str(upvar_id.var_id)),
702                     sup,
703                     "");
704                 err.emit();
705             }
706             infer::InfStackClosure(span) => {
707                 let mut err = struct_span_err!(self.tcx.sess, span, E0314,
708                     "closure outlives stack frame");
709                 self.tcx.note_and_explain_region(&mut err,
710                     "...the closure must be valid for ",
711                     sub,
712                     "...");
713                 self.tcx.note_and_explain_region(&mut err,
714                     "...but the closure's stack frame is only valid for ",
715                     sup,
716                     "");
717                 err.emit();
718             }
719             infer::InvokeClosure(span) => {
720                 let mut err = struct_span_err!(self.tcx.sess, span, E0315,
721                     "cannot invoke closure outside of its lifetime");
722                 self.tcx.note_and_explain_region(&mut err,
723                     "the closure is only valid for ",
724                     sup,
725                     "");
726                 err.emit();
727             }
728             infer::DerefPointer(span) => {
729                 let mut err = struct_span_err!(self.tcx.sess, span, E0473,
730                           "dereference of reference outside its lifetime");
731                 self.tcx.note_and_explain_region(&mut err,
732                     "the reference is only valid for ",
733                     sup,
734                     "");
735                 err.emit();
736             }
737             infer::FreeVariable(span, id) => {
738                 let mut err = struct_span_err!(self.tcx.sess, span, E0474,
739                           "captured variable `{}` does not outlive the enclosing closure",
740                           self.tcx.local_var_name_str(id));
741                 self.tcx.note_and_explain_region(&mut err,
742                     "captured variable is valid for ",
743                     sup,
744                     "");
745                 self.tcx.note_and_explain_region(&mut err,
746                     "closure is valid for ",
747                     sub,
748                     "");
749                 err.emit();
750             }
751             infer::IndexSlice(span) => {
752                 let mut err = struct_span_err!(self.tcx.sess, span, E0475,
753                           "index of slice outside its lifetime");
754                 self.tcx.note_and_explain_region(&mut err,
755                     "the slice is only valid for ",
756                     sup,
757                     "");
758                 err.emit();
759             }
760             infer::RelateObjectBound(span) => {
761                 let mut err = struct_span_err!(self.tcx.sess, span, E0476,
762                           "lifetime of the source pointer does not outlive \
763                            lifetime bound of the object type");
764                 self.tcx.note_and_explain_region(&mut err,
765                     "object type is valid for ",
766                     sub,
767                     "");
768                 self.tcx.note_and_explain_region(&mut err,
769                     "source pointer is only valid for ",
770                     sup,
771                     "");
772                 err.emit();
773             }
774             infer::RelateParamBound(span, ty) => {
775                 let mut err = struct_span_err!(self.tcx.sess, span, E0477,
776                           "the type `{}` does not fulfill the required lifetime",
777                           self.ty_to_string(ty));
778                 self.tcx.note_and_explain_region(&mut err,
779                                         "type must outlive ",
780                                         sub,
781                                         "");
782                 err.emit();
783             }
784             infer::RelateRegionParamBound(span) => {
785                 let mut err = struct_span_err!(self.tcx.sess, span, E0478,
786                           "lifetime bound not satisfied");
787                 self.tcx.note_and_explain_region(&mut err,
788                     "lifetime parameter instantiated with ",
789                     sup,
790                     "");
791                 self.tcx.note_and_explain_region(&mut err,
792                     "but lifetime parameter must outlive ",
793                     sub,
794                     "");
795                 err.emit();
796             }
797             infer::RelateDefaultParamBound(span, ty) => {
798                 let mut err = struct_span_err!(self.tcx.sess, span, E0479,
799                           "the type `{}` (provided as the value of \
800                            a type parameter) is not valid at this point",
801                           self.ty_to_string(ty));
802                 self.tcx.note_and_explain_region(&mut err,
803                                         "type must outlive ",
804                                         sub,
805                                         "");
806                 err.emit();
807             }
808             infer::CallRcvr(span) => {
809                 let mut err = struct_span_err!(self.tcx.sess, span, E0480,
810                           "lifetime of method receiver does not outlive \
811                            the method call");
812                 self.tcx.note_and_explain_region(&mut err,
813                     "the receiver is only valid for ",
814                     sup,
815                     "");
816                 err.emit();
817             }
818             infer::CallArg(span) => {
819                 let mut err = struct_span_err!(self.tcx.sess, span, E0481,
820                           "lifetime of function argument does not outlive \
821                            the function call");
822                 self.tcx.note_and_explain_region(&mut err,
823                     "the function argument is only valid for ",
824                     sup,
825                     "");
826                 err.emit();
827             }
828             infer::CallReturn(span) => {
829                 let mut err = struct_span_err!(self.tcx.sess, span, E0482,
830                           "lifetime of return value does not outlive \
831                            the function call");
832                 self.tcx.note_and_explain_region(&mut err,
833                     "the return value is only valid for ",
834                     sup,
835                     "");
836                 err.emit();
837             }
838             infer::Operand(span) => {
839                 let mut err = struct_span_err!(self.tcx.sess, span, E0483,
840                           "lifetime of operand does not outlive \
841                            the operation");
842                 self.tcx.note_and_explain_region(&mut err,
843                     "the operand is only valid for ",
844                     sup,
845                     "");
846                 err.emit();
847             }
848             infer::AddrOf(span) => {
849                 let mut err = struct_span_err!(self.tcx.sess, span, E0484,
850                           "reference is not valid at the time of borrow");
851                 self.tcx.note_and_explain_region(&mut err,
852                     "the borrow is only valid for ",
853                     sup,
854                     "");
855                 err.emit();
856             }
857             infer::AutoBorrow(span) => {
858                 let mut err = struct_span_err!(self.tcx.sess, span, E0485,
859                           "automatically reference is not valid \
860                            at the time of borrow");
861                 self.tcx.note_and_explain_region(&mut err,
862                     "the automatic borrow is only valid for ",
863                     sup,
864                     "");
865                 err.emit();
866             }
867             infer::ExprTypeIsNotInScope(t, span) => {
868                 let mut err = struct_span_err!(self.tcx.sess, span, E0486,
869                           "type of expression contains references \
870                            that are not valid during the expression: `{}`",
871                           self.ty_to_string(t));
872                 self.tcx.note_and_explain_region(&mut err,
873                     "type is only valid for ",
874                     sup,
875                     "");
876                 err.emit();
877             }
878             infer::SafeDestructor(span) => {
879                 let mut err = struct_span_err!(self.tcx.sess, span, E0487,
880                           "unsafe use of destructor: destructor might be called \
881                            while references are dead");
882                 // FIXME (22171): terms "super/subregion" are suboptimal
883                 self.tcx.note_and_explain_region(&mut err,
884                     "superregion: ",
885                     sup,
886                     "");
887                 self.tcx.note_and_explain_region(&mut err,
888                     "subregion: ",
889                     sub,
890                     "");
891                 err.emit();
892             }
893             infer::BindingTypeIsNotValidAtDecl(span) => {
894                 let mut err = struct_span_err!(self.tcx.sess, span, E0488,
895                           "lifetime of variable does not enclose its declaration");
896                 self.tcx.note_and_explain_region(&mut err,
897                     "the variable is only valid for ",
898                     sup,
899                     "");
900                 err.emit();
901             }
902             infer::ParameterInScope(_, span) => {
903                 let mut err = struct_span_err!(self.tcx.sess, span, E0489,
904                           "type/lifetime parameter not in scope here");
905                 self.tcx.note_and_explain_region(&mut err,
906                     "the parameter is only valid for ",
907                     sub,
908                     "");
909                 err.emit();
910             }
911             infer::DataBorrowed(ty, span) => {
912                 let mut err = struct_span_err!(self.tcx.sess, span, E0490,
913                           "a value of type `{}` is borrowed for too long",
914                           self.ty_to_string(ty));
915                 self.tcx.note_and_explain_region(&mut err, "the type is valid for ", sub, "");
916                 self.tcx.note_and_explain_region(&mut err, "but the borrow lasts for ", sup, "");
917                 err.emit();
918             }
919             infer::ReferenceOutlivesReferent(ty, span) => {
920                 let mut err = struct_span_err!(self.tcx.sess, span, E0491,
921                           "in type `{}`, reference has a longer lifetime \
922                            than the data it references",
923                           self.ty_to_string(ty));
924                 self.tcx.note_and_explain_region(&mut err,
925                     "the pointer is valid for ",
926                     sub,
927                     "");
928                 self.tcx.note_and_explain_region(&mut err,
929                     "but the referenced data is only valid for ",
930                     sup,
931                     "");
932                 err.emit();
933             }
934         }
935     }
936
937     fn report_sub_sup_conflict(&self,
938                                var_origin: RegionVariableOrigin,
939                                sub_origin: SubregionOrigin<'tcx>,
940                                sub_region: Region,
941                                sup_origin: SubregionOrigin<'tcx>,
942                                sup_region: Region) {
943         let mut err = self.report_inference_failure(var_origin);
944
945         self.tcx.note_and_explain_region(&mut err,
946             "first, the lifetime cannot outlive ",
947             sup_region,
948             "...");
949
950         self.note_region_origin(&mut err, &sup_origin);
951
952         self.tcx.note_and_explain_region(&mut err,
953             "but, the lifetime must be valid for ",
954             sub_region,
955             "...");
956
957         self.note_region_origin(&mut err, &sub_origin);
958         err.emit();
959     }
960
961     fn report_processed_errors(&self,
962                                var_origins: &[RegionVariableOrigin],
963                                trace_origins: &[(TypeTrace<'tcx>, TypeError<'tcx>)],
964                                same_regions: &[SameRegions]) {
965         for (i, vo) in var_origins.iter().enumerate() {
966             let mut err = self.report_inference_failure(vo.clone());
967             if i == var_origins.len() - 1 {
968                 self.give_suggestion(&mut err, same_regions);
969             }
970             err.emit();
971         }
972
973         for &(ref trace, ref terr) in trace_origins {
974             self.report_and_explain_type_error(trace.clone(), terr);
975         }
976     }
977
978     fn give_suggestion(&self, err: &mut DiagnosticBuilder, same_regions: &[SameRegions]) {
979         let scope_id = same_regions[0].scope_id;
980         let parent = self.tcx.map.get_parent(scope_id);
981         let parent_node = self.tcx.map.find(parent);
982         let taken = lifetimes_in_scope(self.tcx, scope_id);
983         let life_giver = LifeGiver::with_taken(&taken[..]);
984         let node_inner = match parent_node {
985             Some(ref node) => match *node {
986                 ast_map::NodeItem(ref item) => {
987                     match item.node {
988                         hir::ItemFn(ref fn_decl, unsafety, constness, _, ref gen, _) => {
989                             Some((fn_decl, gen, unsafety, constness,
990                                   item.name, None, item.span))
991                         },
992                         _ => None
993                     }
994                 }
995                 ast_map::NodeImplItem(item) => {
996                     match item.node {
997                         hir::ImplItemKind::Method(ref sig, _) => {
998                             Some((&sig.decl,
999                                   &sig.generics,
1000                                   sig.unsafety,
1001                                   sig.constness,
1002                                   item.name,
1003                                   Some(&sig.explicit_self.node),
1004                                   item.span))
1005                         }
1006                         _ => None,
1007                     }
1008                 },
1009                 ast_map::NodeTraitItem(item) => {
1010                     match item.node {
1011                         hir::MethodTraitItem(ref sig, Some(_)) => {
1012                             Some((&sig.decl,
1013                                   &sig.generics,
1014                                   sig.unsafety,
1015                                   sig.constness,
1016                                   item.name,
1017                                   Some(&sig.explicit_self.node),
1018                                   item.span))
1019                         }
1020                         _ => None
1021                     }
1022                 }
1023                 _ => None
1024             },
1025             None => None
1026         };
1027         let (fn_decl, generics, unsafety, constness, name, expl_self, span)
1028                                     = node_inner.expect("expect item fn");
1029         let rebuilder = Rebuilder::new(self.tcx, fn_decl, expl_self,
1030                                        generics, same_regions, &life_giver);
1031         let (fn_decl, expl_self, generics) = rebuilder.rebuild();
1032         self.give_expl_lifetime_param(err, &fn_decl, unsafety, constness, name,
1033                                       expl_self.as_ref(), &generics, span);
1034     }
1035 }
1036
1037 struct RebuildPathInfo<'a> {
1038     path: &'a hir::Path,
1039     // indexes to insert lifetime on path.lifetimes
1040     indexes: Vec<u32>,
1041     // number of lifetimes we expect to see on the type referred by `path`
1042     // (e.g., expected=1 for struct Foo<'a>)
1043     expected: u32,
1044     anon_nums: &'a HashSet<u32>,
1045     region_names: &'a HashSet<ast::Name>
1046 }
1047
1048 struct Rebuilder<'a, 'tcx: 'a> {
1049     tcx: &'a ty::ctxt<'tcx>,
1050     fn_decl: &'a hir::FnDecl,
1051     expl_self_opt: Option<&'a hir::ExplicitSelf_>,
1052     generics: &'a hir::Generics,
1053     same_regions: &'a [SameRegions],
1054     life_giver: &'a LifeGiver,
1055     cur_anon: Cell<u32>,
1056     inserted_anons: RefCell<HashSet<u32>>,
1057 }
1058
1059 enum FreshOrKept {
1060     Fresh,
1061     Kept
1062 }
1063
1064 impl<'a, 'tcx> Rebuilder<'a, 'tcx> {
1065     fn new(tcx: &'a ty::ctxt<'tcx>,
1066            fn_decl: &'a hir::FnDecl,
1067            expl_self_opt: Option<&'a hir::ExplicitSelf_>,
1068            generics: &'a hir::Generics,
1069            same_regions: &'a [SameRegions],
1070            life_giver: &'a LifeGiver)
1071            -> Rebuilder<'a, 'tcx> {
1072         Rebuilder {
1073             tcx: tcx,
1074             fn_decl: fn_decl,
1075             expl_self_opt: expl_self_opt,
1076             generics: generics,
1077             same_regions: same_regions,
1078             life_giver: life_giver,
1079             cur_anon: Cell::new(0),
1080             inserted_anons: RefCell::new(HashSet::new()),
1081         }
1082     }
1083
1084     fn rebuild(&self)
1085                -> (hir::FnDecl, Option<hir::ExplicitSelf_>, hir::Generics) {
1086         let mut expl_self_opt = self.expl_self_opt.cloned();
1087         let mut inputs = self.fn_decl.inputs.clone();
1088         let mut output = self.fn_decl.output.clone();
1089         let mut ty_params = self.generics.ty_params.clone();
1090         let where_clause = self.generics.where_clause.clone();
1091         let mut kept_lifetimes = HashSet::new();
1092         for sr in self.same_regions {
1093             self.cur_anon.set(0);
1094             self.offset_cur_anon();
1095             let (anon_nums, region_names) =
1096                                 self.extract_anon_nums_and_names(sr);
1097             let (lifetime, fresh_or_kept) = self.pick_lifetime(&region_names);
1098             match fresh_or_kept {
1099                 Kept => { kept_lifetimes.insert(lifetime.name); }
1100                 _ => ()
1101             }
1102             expl_self_opt = self.rebuild_expl_self(expl_self_opt, lifetime,
1103                                                    &anon_nums, &region_names);
1104             inputs = self.rebuild_args_ty(&inputs[..], lifetime,
1105                                           &anon_nums, &region_names);
1106             output = self.rebuild_output(&output, lifetime, &anon_nums, &region_names);
1107             ty_params = self.rebuild_ty_params(ty_params, lifetime,
1108                                                &region_names);
1109         }
1110         let fresh_lifetimes = self.life_giver.get_generated_lifetimes();
1111         let all_region_names = self.extract_all_region_names();
1112         let generics = self.rebuild_generics(self.generics,
1113                                              &fresh_lifetimes,
1114                                              &kept_lifetimes,
1115                                              &all_region_names,
1116                                              ty_params,
1117                                              where_clause);
1118         let new_fn_decl = hir::FnDecl {
1119             inputs: inputs,
1120             output: output,
1121             variadic: self.fn_decl.variadic
1122         };
1123         (new_fn_decl, expl_self_opt, generics)
1124     }
1125
1126     fn pick_lifetime(&self,
1127                      region_names: &HashSet<ast::Name>)
1128                      -> (hir::Lifetime, FreshOrKept) {
1129         if !region_names.is_empty() {
1130             // It's not necessary to convert the set of region names to a
1131             // vector of string and then sort them. However, it makes the
1132             // choice of lifetime name deterministic and thus easier to test.
1133             let mut names = Vec::new();
1134             for rn in region_names {
1135                 let lt_name = rn.to_string();
1136                 names.push(lt_name);
1137             }
1138             names.sort();
1139             let name = token::intern(&names[0]);
1140             return (name_to_dummy_lifetime(name), Kept);
1141         }
1142         return (self.life_giver.give_lifetime(), Fresh);
1143     }
1144
1145     fn extract_anon_nums_and_names(&self, same_regions: &SameRegions)
1146                                    -> (HashSet<u32>, HashSet<ast::Name>) {
1147         let mut anon_nums = HashSet::new();
1148         let mut region_names = HashSet::new();
1149         for br in &same_regions.regions {
1150             match *br {
1151                 ty::BrAnon(i) => {
1152                     anon_nums.insert(i);
1153                 }
1154                 ty::BrNamed(_, name) => {
1155                     region_names.insert(name);
1156                 }
1157                 _ => ()
1158             }
1159         }
1160         (anon_nums, region_names)
1161     }
1162
1163     fn extract_all_region_names(&self) -> HashSet<ast::Name> {
1164         let mut all_region_names = HashSet::new();
1165         for sr in self.same_regions {
1166             for br in &sr.regions {
1167                 match *br {
1168                     ty::BrNamed(_, name) => {
1169                         all_region_names.insert(name);
1170                     }
1171                     _ => ()
1172                 }
1173             }
1174         }
1175         all_region_names
1176     }
1177
1178     fn inc_cur_anon(&self, n: u32) {
1179         let anon = self.cur_anon.get();
1180         self.cur_anon.set(anon+n);
1181     }
1182
1183     fn offset_cur_anon(&self) {
1184         let mut anon = self.cur_anon.get();
1185         while self.inserted_anons.borrow().contains(&anon) {
1186             anon += 1;
1187         }
1188         self.cur_anon.set(anon);
1189     }
1190
1191     fn inc_and_offset_cur_anon(&self, n: u32) {
1192         self.inc_cur_anon(n);
1193         self.offset_cur_anon();
1194     }
1195
1196     fn track_anon(&self, anon: u32) {
1197         self.inserted_anons.borrow_mut().insert(anon);
1198     }
1199
1200     fn rebuild_ty_params(&self,
1201                          ty_params: hir::HirVec<hir::TyParam>,
1202                          lifetime: hir::Lifetime,
1203                          region_names: &HashSet<ast::Name>)
1204                          -> hir::HirVec<hir::TyParam> {
1205         ty_params.iter().map(|ty_param| {
1206             let bounds = self.rebuild_ty_param_bounds(ty_param.bounds.clone(),
1207                                                       lifetime,
1208                                                       region_names);
1209             hir::TyParam {
1210                 name: ty_param.name,
1211                 id: ty_param.id,
1212                 bounds: bounds,
1213                 default: ty_param.default.clone(),
1214                 span: ty_param.span,
1215             }
1216         }).collect()
1217     }
1218
1219     fn rebuild_ty_param_bounds(&self,
1220                                ty_param_bounds: hir::TyParamBounds,
1221                                lifetime: hir::Lifetime,
1222                                region_names: &HashSet<ast::Name>)
1223                                -> hir::TyParamBounds {
1224         ty_param_bounds.iter().map(|tpb| {
1225             match tpb {
1226                 &hir::RegionTyParamBound(lt) => {
1227                     // FIXME -- it's unclear whether I'm supposed to
1228                     // substitute lifetime here. I suspect we need to
1229                     // be passing down a map.
1230                     hir::RegionTyParamBound(lt)
1231                 }
1232                 &hir::TraitTyParamBound(ref poly_tr, modifier) => {
1233                     let tr = &poly_tr.trait_ref;
1234                     let last_seg = tr.path.segments.last().unwrap();
1235                     let mut insert = Vec::new();
1236                     let lifetimes = last_seg.parameters.lifetimes();
1237                     for (i, lt) in lifetimes.iter().enumerate() {
1238                         if region_names.contains(&lt.name) {
1239                             insert.push(i as u32);
1240                         }
1241                     }
1242                     let rebuild_info = RebuildPathInfo {
1243                         path: &tr.path,
1244                         indexes: insert,
1245                         expected: lifetimes.len() as u32,
1246                         anon_nums: &HashSet::new(),
1247                         region_names: region_names
1248                     };
1249                     let new_path = self.rebuild_path(rebuild_info, lifetime);
1250                     hir::TraitTyParamBound(hir::PolyTraitRef {
1251                         bound_lifetimes: poly_tr.bound_lifetimes.clone(),
1252                         trait_ref: hir::TraitRef {
1253                             path: new_path,
1254                             ref_id: tr.ref_id,
1255                         },
1256                         span: poly_tr.span,
1257                     }, modifier)
1258                 }
1259             }
1260         }).collect()
1261     }
1262
1263     fn rebuild_expl_self(&self,
1264                          expl_self_opt: Option<hir::ExplicitSelf_>,
1265                          lifetime: hir::Lifetime,
1266                          anon_nums: &HashSet<u32>,
1267                          region_names: &HashSet<ast::Name>)
1268                          -> Option<hir::ExplicitSelf_> {
1269         match expl_self_opt {
1270             Some(ref expl_self) => match *expl_self {
1271                 hir::SelfRegion(lt_opt, muta, id) => match lt_opt {
1272                     Some(lt) => if region_names.contains(&lt.name) {
1273                         return Some(hir::SelfRegion(Some(lifetime), muta, id));
1274                     },
1275                     None => {
1276                         let anon = self.cur_anon.get();
1277                         self.inc_and_offset_cur_anon(1);
1278                         if anon_nums.contains(&anon) {
1279                             self.track_anon(anon);
1280                             return Some(hir::SelfRegion(Some(lifetime), muta, id));
1281                         }
1282                     }
1283                 },
1284                 _ => ()
1285             },
1286             None => ()
1287         }
1288         expl_self_opt
1289     }
1290
1291     fn rebuild_generics(&self,
1292                         generics: &hir::Generics,
1293                         add: &Vec<hir::Lifetime>,
1294                         keep: &HashSet<ast::Name>,
1295                         remove: &HashSet<ast::Name>,
1296                         ty_params: hir::HirVec<hir::TyParam>,
1297                         where_clause: hir::WhereClause)
1298                         -> hir::Generics {
1299         let mut lifetimes = Vec::new();
1300         for lt in add {
1301             lifetimes.push(hir::LifetimeDef { lifetime: *lt,
1302                                               bounds: hir::HirVec::new() });
1303         }
1304         for lt in &generics.lifetimes {
1305             if keep.contains(&lt.lifetime.name) ||
1306                 !remove.contains(&lt.lifetime.name) {
1307                 lifetimes.push((*lt).clone());
1308             }
1309         }
1310         hir::Generics {
1311             lifetimes: lifetimes.into(),
1312             ty_params: ty_params,
1313             where_clause: where_clause,
1314         }
1315     }
1316
1317     fn rebuild_args_ty(&self,
1318                        inputs: &[hir::Arg],
1319                        lifetime: hir::Lifetime,
1320                        anon_nums: &HashSet<u32>,
1321                        region_names: &HashSet<ast::Name>)
1322                        -> hir::HirVec<hir::Arg> {
1323         let mut new_inputs = Vec::new();
1324         for arg in inputs {
1325             let new_ty = self.rebuild_arg_ty_or_output(&*arg.ty, lifetime,
1326                                                        anon_nums, region_names);
1327             let possibly_new_arg = hir::Arg {
1328                 ty: new_ty,
1329                 pat: arg.pat.clone(),
1330                 id: arg.id
1331             };
1332             new_inputs.push(possibly_new_arg);
1333         }
1334         new_inputs.into()
1335     }
1336
1337     fn rebuild_output(&self, ty: &hir::FunctionRetTy,
1338                       lifetime: hir::Lifetime,
1339                       anon_nums: &HashSet<u32>,
1340                       region_names: &HashSet<ast::Name>) -> hir::FunctionRetTy {
1341         match *ty {
1342             hir::Return(ref ret_ty) => hir::Return(
1343                 self.rebuild_arg_ty_or_output(&**ret_ty, lifetime, anon_nums, region_names)
1344             ),
1345             hir::DefaultReturn(span) => hir::DefaultReturn(span),
1346             hir::NoReturn(span) => hir::NoReturn(span)
1347         }
1348     }
1349
1350     fn rebuild_arg_ty_or_output(&self,
1351                                 ty: &hir::Ty,
1352                                 lifetime: hir::Lifetime,
1353                                 anon_nums: &HashSet<u32>,
1354                                 region_names: &HashSet<ast::Name>)
1355                                 -> P<hir::Ty> {
1356         let mut new_ty = P(ty.clone());
1357         let mut ty_queue = vec!(ty);
1358         while !ty_queue.is_empty() {
1359             let cur_ty = ty_queue.remove(0);
1360             match cur_ty.node {
1361                 hir::TyRptr(lt_opt, ref mut_ty) => {
1362                     let rebuild = match lt_opt {
1363                         Some(lt) => region_names.contains(&lt.name),
1364                         None => {
1365                             let anon = self.cur_anon.get();
1366                             let rebuild = anon_nums.contains(&anon);
1367                             if rebuild {
1368                                 self.track_anon(anon);
1369                             }
1370                             self.inc_and_offset_cur_anon(1);
1371                             rebuild
1372                         }
1373                     };
1374                     if rebuild {
1375                         let to = hir::Ty {
1376                             id: cur_ty.id,
1377                             node: hir::TyRptr(Some(lifetime), mut_ty.clone()),
1378                             span: cur_ty.span
1379                         };
1380                         new_ty = self.rebuild_ty(new_ty, P(to));
1381                     }
1382                     ty_queue.push(&*mut_ty.ty);
1383                 }
1384                 hir::TyPath(ref maybe_qself, ref path) => {
1385                     let a_def = match self.tcx.def_map.borrow().get(&cur_ty.id) {
1386                         None => {
1387                             self.tcx
1388                                 .sess
1389                                 .fatal(&format!(
1390                                         "unbound path {}",
1391                                         pprust::path_to_string(path)))
1392                         }
1393                         Some(d) => d.full_def()
1394                     };
1395                     match a_def {
1396                         def::DefTy(did, _) | def::DefStruct(did) => {
1397                             let generics = self.tcx.lookup_item_type(did).generics;
1398
1399                             let expected =
1400                                 generics.regions.len(subst::TypeSpace) as u32;
1401                             let lifetimes =
1402                                 path.segments.last().unwrap().parameters.lifetimes();
1403                             let mut insert = Vec::new();
1404                             if lifetimes.is_empty() {
1405                                 let anon = self.cur_anon.get();
1406                                 for (i, a) in (anon..anon+expected).enumerate() {
1407                                     if anon_nums.contains(&a) {
1408                                         insert.push(i as u32);
1409                                     }
1410                                     self.track_anon(a);
1411                                 }
1412                                 self.inc_and_offset_cur_anon(expected);
1413                             } else {
1414                                 for (i, lt) in lifetimes.iter().enumerate() {
1415                                     if region_names.contains(&lt.name) {
1416                                         insert.push(i as u32);
1417                                     }
1418                                 }
1419                             }
1420                             let rebuild_info = RebuildPathInfo {
1421                                 path: path,
1422                                 indexes: insert,
1423                                 expected: expected,
1424                                 anon_nums: anon_nums,
1425                                 region_names: region_names
1426                             };
1427                             let new_path = self.rebuild_path(rebuild_info, lifetime);
1428                             let qself = maybe_qself.as_ref().map(|qself| {
1429                                 hir::QSelf {
1430                                     ty: self.rebuild_arg_ty_or_output(&qself.ty, lifetime,
1431                                                                       anon_nums, region_names),
1432                                     position: qself.position
1433                                 }
1434                             });
1435                             let to = hir::Ty {
1436                                 id: cur_ty.id,
1437                                 node: hir::TyPath(qself, new_path),
1438                                 span: cur_ty.span
1439                             };
1440                             new_ty = self.rebuild_ty(new_ty, P(to));
1441                         }
1442                         _ => ()
1443                     }
1444
1445                 }
1446
1447                 hir::TyPtr(ref mut_ty) => {
1448                     ty_queue.push(&*mut_ty.ty);
1449                 }
1450                 hir::TyVec(ref ty) |
1451                 hir::TyFixedLengthVec(ref ty, _) => {
1452                     ty_queue.push(&**ty);
1453                 }
1454                 hir::TyTup(ref tys) => ty_queue.extend(tys.iter().map(|ty| &**ty)),
1455                 _ => {}
1456             }
1457         }
1458         new_ty
1459     }
1460
1461     fn rebuild_ty(&self,
1462                   from: P<hir::Ty>,
1463                   to: P<hir::Ty>)
1464                   -> P<hir::Ty> {
1465
1466         fn build_to(from: P<hir::Ty>,
1467                     to: &mut Option<P<hir::Ty>>)
1468                     -> P<hir::Ty> {
1469             if Some(from.id) == to.as_ref().map(|ty| ty.id) {
1470                 return to.take().expect("`to` type found more than once during rebuild");
1471             }
1472             from.map(|hir::Ty {id, node, span}| {
1473                 let new_node = match node {
1474                     hir::TyRptr(lifetime, mut_ty) => {
1475                         hir::TyRptr(lifetime, hir::MutTy {
1476                             mutbl: mut_ty.mutbl,
1477                             ty: build_to(mut_ty.ty, to),
1478                         })
1479                     }
1480                     hir::TyPtr(mut_ty) => {
1481                         hir::TyPtr(hir::MutTy {
1482                             mutbl: mut_ty.mutbl,
1483                             ty: build_to(mut_ty.ty, to),
1484                         })
1485                     }
1486                     hir::TyVec(ty) => hir::TyVec(build_to(ty, to)),
1487                     hir::TyFixedLengthVec(ty, e) => {
1488                         hir::TyFixedLengthVec(build_to(ty, to), e)
1489                     }
1490                     hir::TyTup(tys) => {
1491                         hir::TyTup(tys.into_iter().map(|ty| build_to(ty, to)).collect())
1492                     }
1493                     other => other
1494                 };
1495                 hir::Ty { id: id, node: new_node, span: span }
1496             })
1497         }
1498
1499         build_to(from, &mut Some(to))
1500     }
1501
1502     fn rebuild_path(&self,
1503                     rebuild_info: RebuildPathInfo,
1504                     lifetime: hir::Lifetime)
1505                     -> hir::Path
1506     {
1507         let RebuildPathInfo {
1508             path,
1509             indexes,
1510             expected,
1511             anon_nums,
1512             region_names,
1513         } = rebuild_info;
1514
1515         let last_seg = path.segments.last().unwrap();
1516         let new_parameters = match last_seg.parameters {
1517             hir::ParenthesizedParameters(..) => {
1518                 last_seg.parameters.clone()
1519             }
1520
1521             hir::AngleBracketedParameters(ref data) => {
1522                 let mut new_lts = Vec::new();
1523                 if data.lifetimes.is_empty() {
1524                     // traverse once to see if there's a need to insert lifetime
1525                     let need_insert = (0..expected).any(|i| {
1526                         indexes.contains(&i)
1527                     });
1528                     if need_insert {
1529                         for i in 0..expected {
1530                             if indexes.contains(&i) {
1531                                 new_lts.push(lifetime);
1532                             } else {
1533                                 new_lts.push(self.life_giver.give_lifetime());
1534                             }
1535                         }
1536                     }
1537                 } else {
1538                     for (i, lt) in data.lifetimes.iter().enumerate() {
1539                         if indexes.contains(&(i as u32)) {
1540                             new_lts.push(lifetime);
1541                         } else {
1542                             new_lts.push(*lt);
1543                         }
1544                     }
1545                 }
1546                 let new_types = data.types.iter().map(|t| {
1547                     self.rebuild_arg_ty_or_output(&**t, lifetime, anon_nums, region_names)
1548                 }).collect();
1549                 let new_bindings = data.bindings.iter().map(|b| {
1550                     hir::TypeBinding {
1551                         id: b.id,
1552                         name: b.name,
1553                         ty: self.rebuild_arg_ty_or_output(&*b.ty,
1554                                                           lifetime,
1555                                                           anon_nums,
1556                                                           region_names),
1557                         span: b.span
1558                     }
1559                 }).collect();
1560                 hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
1561                     lifetimes: new_lts.into(),
1562                     types: new_types,
1563                     bindings: new_bindings,
1564                })
1565             }
1566         };
1567         let new_seg = hir::PathSegment {
1568             identifier: last_seg.identifier,
1569             parameters: new_parameters
1570         };
1571         let mut new_segs = Vec::new();
1572         new_segs.extend_from_slice(path.segments.split_last().unwrap().1);
1573         new_segs.push(new_seg);
1574         hir::Path {
1575             span: path.span,
1576             global: path.global,
1577             segments: new_segs.into()
1578         }
1579     }
1580 }
1581
1582 impl<'a, 'tcx> ErrorReportingHelpers<'tcx> for InferCtxt<'a, 'tcx> {
1583     fn give_expl_lifetime_param(&self,
1584                                 err: &mut DiagnosticBuilder,
1585                                 decl: &hir::FnDecl,
1586                                 unsafety: hir::Unsafety,
1587                                 constness: hir::Constness,
1588                                 name: ast::Name,
1589                                 opt_explicit_self: Option<&hir::ExplicitSelf_>,
1590                                 generics: &hir::Generics,
1591                                 span: Span) {
1592         let suggested_fn = pprust::fun_to_string(decl, unsafety, constness, name,
1593                                                  opt_explicit_self, generics);
1594         let msg = format!("consider using an explicit lifetime \
1595                            parameter as shown: {}", suggested_fn);
1596         err.span_help(span, &msg[..]);
1597     }
1598
1599     fn report_inference_failure(&self,
1600                                 var_origin: RegionVariableOrigin)
1601                                 -> DiagnosticBuilder<'tcx> {
1602         let br_string = |br: ty::BoundRegion| {
1603             let mut s = br.to_string();
1604             if !s.is_empty() {
1605                 s.push_str(" ");
1606             }
1607             s
1608         };
1609         let var_description = match var_origin {
1610             infer::MiscVariable(_) => "".to_string(),
1611             infer::PatternRegion(_) => " for pattern".to_string(),
1612             infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1613             infer::Autoref(_) => " for autoref".to_string(),
1614             infer::Coercion(_) => " for automatic coercion".to_string(),
1615             infer::LateBoundRegion(_, br, infer::FnCall) => {
1616                 format!(" for lifetime parameter {}in function call",
1617                         br_string(br))
1618             }
1619             infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1620                 format!(" for lifetime parameter {}in generic type", br_string(br))
1621             }
1622             infer::LateBoundRegion(_, br, infer::AssocTypeProjection(type_name)) => {
1623                 format!(" for lifetime parameter {}in trait containing associated type `{}`",
1624                         br_string(br), type_name)
1625             }
1626             infer::EarlyBoundRegion(_, name) => {
1627                 format!(" for lifetime parameter `{}`",
1628                         name)
1629             }
1630             infer::BoundRegionInCoherence(name) => {
1631                 format!(" for lifetime parameter `{}` in coherence check",
1632                         name)
1633             }
1634             infer::UpvarRegion(ref upvar_id, _) => {
1635                 format!(" for capture of `{}` by closure",
1636                         self.tcx.local_var_name_str(upvar_id.var_id).to_string())
1637             }
1638         };
1639
1640         struct_span_err!(self.tcx.sess, var_origin.span(), E0495,
1641                   "cannot infer an appropriate lifetime{} \
1642                    due to conflicting requirements",
1643                   var_description)
1644     }
1645
1646     fn note_region_origin(&self, err: &mut DiagnosticBuilder, origin: &SubregionOrigin<'tcx>) {
1647         match *origin {
1648             infer::Subtype(ref trace) => {
1649                 let desc = match trace.origin {
1650                     TypeOrigin::Misc(_) => {
1651                         "types are compatible"
1652                     }
1653                     TypeOrigin::MethodCompatCheck(_) => {
1654                         "method type is compatible with trait"
1655                     }
1656                     TypeOrigin::ExprAssignable(_) => {
1657                         "expression is assignable"
1658                     }
1659                     TypeOrigin::RelateTraitRefs(_) => {
1660                         "traits are compatible"
1661                     }
1662                     TypeOrigin::RelateSelfType(_) => {
1663                         "self type matches impl self type"
1664                     }
1665                     TypeOrigin::RelateOutputImplTypes(_) => {
1666                         "trait type parameters matches those \
1667                                  specified on the impl"
1668                     }
1669                     TypeOrigin::MatchExpressionArm(_, _, _) => {
1670                         "match arms have compatible types"
1671                     }
1672                     TypeOrigin::IfExpression(_) => {
1673                         "if and else have compatible types"
1674                     }
1675                     TypeOrigin::IfExpressionWithNoElse(_) => {
1676                         "if may be missing an else clause"
1677                     }
1678                     TypeOrigin::RangeExpression(_) => {
1679                         "start and end of range have compatible types"
1680                     }
1681                     TypeOrigin::EquatePredicate(_) => {
1682                         "equality where clause is satisfied"
1683                     }
1684                 };
1685
1686                 match self.values_str(&trace.values) {
1687                     Some(values_str) => {
1688                         err.span_note(
1689                             trace.origin.span(),
1690                             &format!("...so that {} ({})",
1691                                     desc, values_str));
1692                     }
1693                     None => {
1694                         // Really should avoid printing this error at
1695                         // all, since it is derived, but that would
1696                         // require more refactoring than I feel like
1697                         // doing right now. - nmatsakis
1698                         err.span_note(
1699                             trace.origin.span(),
1700                             &format!("...so that {}", desc));
1701                     }
1702                 }
1703             }
1704             infer::Reborrow(span) => {
1705                 err.span_note(
1706                     span,
1707                     "...so that reference does not outlive \
1708                     borrowed content");
1709             }
1710             infer::ReborrowUpvar(span, ref upvar_id) => {
1711                 err.span_note(
1712                     span,
1713                     &format!(
1714                         "...so that closure can access `{}`",
1715                         self.tcx.local_var_name_str(upvar_id.var_id)
1716                             .to_string()));
1717             }
1718             infer::InfStackClosure(span) => {
1719                 err.span_note(
1720                     span,
1721                     "...so that closure does not outlive its stack frame");
1722             }
1723             infer::InvokeClosure(span) => {
1724                 err.span_note(
1725                     span,
1726                     "...so that closure is not invoked outside its lifetime");
1727             }
1728             infer::DerefPointer(span) => {
1729                 err.span_note(
1730                     span,
1731                     "...so that pointer is not dereferenced \
1732                     outside its lifetime");
1733             }
1734             infer::FreeVariable(span, id) => {
1735                 err.span_note(
1736                     span,
1737                     &format!("...so that captured variable `{}` \
1738                             does not outlive the enclosing closure",
1739                             self.tcx.local_var_name_str(id)));
1740             }
1741             infer::IndexSlice(span) => {
1742                 err.span_note(
1743                     span,
1744                     "...so that slice is not indexed outside the lifetime");
1745             }
1746             infer::RelateObjectBound(span) => {
1747                 err.span_note(
1748                     span,
1749                     "...so that it can be closed over into an object");
1750             }
1751             infer::CallRcvr(span) => {
1752                 err.span_note(
1753                     span,
1754                     "...so that method receiver is valid for the method call");
1755             }
1756             infer::CallArg(span) => {
1757                 err.span_note(
1758                     span,
1759                     "...so that argument is valid for the call");
1760             }
1761             infer::CallReturn(span) => {
1762                 err.span_note(
1763                     span,
1764                     "...so that return value is valid for the call");
1765             }
1766             infer::Operand(span) => {
1767                 err.span_note(
1768                     span,
1769                     "...so that operand is valid for operation");
1770             }
1771             infer::AddrOf(span) => {
1772                 err.span_note(
1773                     span,
1774                     "...so that reference is valid \
1775                      at the time of borrow");
1776             }
1777             infer::AutoBorrow(span) => {
1778                 err.span_note(
1779                     span,
1780                     "...so that auto-reference is valid \
1781                      at the time of borrow");
1782             }
1783             infer::ExprTypeIsNotInScope(t, span) => {
1784                 err.span_note(
1785                     span,
1786                     &format!("...so type `{}` of expression is valid during the \
1787                              expression",
1788                             self.ty_to_string(t)));
1789             }
1790             infer::BindingTypeIsNotValidAtDecl(span) => {
1791                 err.span_note(
1792                     span,
1793                     "...so that variable is valid at time of its declaration");
1794             }
1795             infer::ParameterInScope(_, span) => {
1796                 err.span_note(
1797                     span,
1798                     "...so that a type/lifetime parameter is in scope here");
1799             }
1800             infer::DataBorrowed(ty, span) => {
1801                 err.span_note(
1802                     span,
1803                     &format!("...so that the type `{}` is not borrowed for too long",
1804                              self.ty_to_string(ty)));
1805             }
1806             infer::ReferenceOutlivesReferent(ty, span) => {
1807                 err.span_note(
1808                     span,
1809                     &format!("...so that the reference type `{}` \
1810                              does not outlive the data it points at",
1811                             self.ty_to_string(ty)));
1812             }
1813             infer::RelateParamBound(span, t) => {
1814                 err.span_note(
1815                     span,
1816                     &format!("...so that the type `{}` \
1817                              will meet its required lifetime bounds",
1818                             self.ty_to_string(t)));
1819             }
1820             infer::RelateDefaultParamBound(span, t) => {
1821                 err.span_note(
1822                     span,
1823                     &format!("...so that type parameter \
1824                              instantiated with `{}`, \
1825                              will meet its declared lifetime bounds",
1826                             self.ty_to_string(t)));
1827             }
1828             infer::RelateRegionParamBound(span) => {
1829                 err.span_note(
1830                     span,
1831                     "...so that the declared lifetime parameter bounds \
1832                                 are satisfied");
1833             }
1834             infer::SafeDestructor(span) => {
1835                 err.span_note(
1836                     span,
1837                     "...so that references are valid when the destructor \
1838                      runs");
1839             }
1840         }
1841     }
1842 }
1843
1844 pub trait Resolvable<'tcx> {
1845     fn resolve<'a>(&self, infcx: &InferCtxt<'a, 'tcx>) -> Self;
1846 }
1847
1848 impl<'tcx> Resolvable<'tcx> for Ty<'tcx> {
1849     fn resolve<'a>(&self, infcx: &InferCtxt<'a, 'tcx>) -> Ty<'tcx> {
1850         infcx.resolve_type_vars_if_possible(self)
1851     }
1852 }
1853
1854 impl<'tcx> Resolvable<'tcx> for ty::TraitRef<'tcx> {
1855     fn resolve<'a>(&self, infcx: &InferCtxt<'a, 'tcx>)
1856                    -> ty::TraitRef<'tcx> {
1857         infcx.resolve_type_vars_if_possible(self)
1858     }
1859 }
1860
1861 impl<'tcx> Resolvable<'tcx> for ty::PolyTraitRef<'tcx> {
1862     fn resolve<'a>(&self,
1863                    infcx: &InferCtxt<'a, 'tcx>)
1864                    -> ty::PolyTraitRef<'tcx>
1865     {
1866         infcx.resolve_type_vars_if_possible(self)
1867     }
1868 }
1869
1870 fn lifetimes_in_scope(tcx: &ty::ctxt,
1871                       scope_id: ast::NodeId)
1872                       -> Vec<hir::LifetimeDef> {
1873     let mut taken = Vec::new();
1874     let parent = tcx.map.get_parent(scope_id);
1875     let method_id_opt = match tcx.map.find(parent) {
1876         Some(node) => match node {
1877             ast_map::NodeItem(item) => match item.node {
1878                 hir::ItemFn(_, _, _, _, ref gen, _) => {
1879                     taken.extend_from_slice(&gen.lifetimes);
1880                     None
1881                 },
1882                 _ => None
1883             },
1884             ast_map::NodeImplItem(ii) => {
1885                 match ii.node {
1886                     hir::ImplItemKind::Method(ref sig, _) => {
1887                         taken.extend_from_slice(&sig.generics.lifetimes);
1888                         Some(ii.id)
1889                     }
1890                     _ => None,
1891                 }
1892             }
1893             _ => None
1894         },
1895         None => None
1896     };
1897     if method_id_opt.is_some() {
1898         let method_id = method_id_opt.unwrap();
1899         let parent = tcx.map.get_parent(method_id);
1900         match tcx.map.find(parent) {
1901             Some(node) => match node {
1902                 ast_map::NodeItem(item) => match item.node {
1903                     hir::ItemImpl(_, _, ref gen, _, _, _) => {
1904                         taken.extend_from_slice(&gen.lifetimes);
1905                     }
1906                     _ => ()
1907                 },
1908                 _ => ()
1909             },
1910             None => ()
1911         }
1912     }
1913     return taken;
1914 }
1915
1916 // LifeGiver is responsible for generating fresh lifetime names
1917 struct LifeGiver {
1918     taken: HashSet<String>,
1919     counter: Cell<usize>,
1920     generated: RefCell<Vec<hir::Lifetime>>,
1921 }
1922
1923 impl LifeGiver {
1924     fn with_taken(taken: &[hir::LifetimeDef]) -> LifeGiver {
1925         let mut taken_ = HashSet::new();
1926         for lt in taken {
1927             let lt_name = lt.lifetime.name.to_string();
1928             taken_.insert(lt_name);
1929         }
1930         LifeGiver {
1931             taken: taken_,
1932             counter: Cell::new(0),
1933             generated: RefCell::new(Vec::new()),
1934         }
1935     }
1936
1937     fn inc_counter(&self) {
1938         let c = self.counter.get();
1939         self.counter.set(c+1);
1940     }
1941
1942     fn give_lifetime(&self) -> hir::Lifetime {
1943         let lifetime;
1944         loop {
1945             let mut s = String::from("'");
1946             s.push_str(&num_to_string(self.counter.get()));
1947             if !self.taken.contains(&s) {
1948                 lifetime = name_to_dummy_lifetime(token::intern(&s[..]));
1949                 self.generated.borrow_mut().push(lifetime);
1950                 break;
1951             }
1952             self.inc_counter();
1953         }
1954         self.inc_counter();
1955         return lifetime;
1956
1957         // 0 .. 25 generates a .. z, 26 .. 51 generates aa .. zz, and so on
1958         fn num_to_string(counter: usize) -> String {
1959             let mut s = String::new();
1960             let (n, r) = (counter/26 + 1, counter % 26);
1961             let letter: char = from_u32((r+97) as u32).unwrap();
1962             for _ in 0..n {
1963                 s.push(letter);
1964             }
1965             s
1966         }
1967     }
1968
1969     fn get_generated_lifetimes(&self) -> Vec<hir::Lifetime> {
1970         self.generated.borrow().clone()
1971     }
1972 }
1973
1974 fn name_to_dummy_lifetime(name: ast::Name) -> hir::Lifetime {
1975     hir::Lifetime { id: ast::DUMMY_NODE_ID,
1976                     span: codemap::DUMMY_SP,
1977                     name: name }
1978 }