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