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