]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/infer/error_reporting.rs
Rollup merge of #30370 - zachreizner:patch-1, r=apasel422
[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 is_warning = match origin {
582             infer::RFC1214Subregion(_) => true,
583             _ => false,
584         };
585
586         let labeled_user_string = match bound_kind {
587             GenericKind::Param(ref p) =>
588                 format!("the parameter type `{}`", p),
589             GenericKind::Projection(ref p) =>
590                 format!("the associated type `{}`", p),
591         };
592
593         match sub {
594             ty::ReFree(ty::FreeRegion {bound_region: ty::BrNamed(..), ..}) => {
595                 // Does the required lifetime have a nice name we can print?
596                 span_err_or_warn!(
597                     is_warning, self.tcx.sess, origin.span(), E0309,
598                     "{} may not live long enough", labeled_user_string);
599                 self.tcx.sess.fileline_help(
600                     origin.span(),
601                     &format!(
602                         "consider adding an explicit lifetime bound `{}: {}`...",
603                         bound_kind,
604                         sub));
605             }
606
607             ty::ReStatic => {
608                 // Does the required lifetime have a nice name we can print?
609                 span_err_or_warn!(
610                     is_warning, self.tcx.sess, origin.span(), E0310,
611                     "{} may not live long enough", labeled_user_string);
612                 self.tcx.sess.fileline_help(
613                     origin.span(),
614                     &format!(
615                         "consider adding an explicit lifetime bound `{}: 'static`...",
616                         bound_kind));
617             }
618
619             _ => {
620                 // If not, be less specific.
621                 span_err_or_warn!(
622                     is_warning, self.tcx.sess, origin.span(), E0311,
623                     "{} may not live long enough",
624                     labeled_user_string);
625                 self.tcx.sess.fileline_help(
626                     origin.span(),
627                     &format!(
628                         "consider adding an explicit lifetime bound for `{}`",
629                         bound_kind));
630                 self.tcx.note_and_explain_region(
631                     &format!("{} must be valid for ", labeled_user_string),
632                     sub,
633                     "...");
634             }
635         }
636
637         if is_warning {
638             self.tcx.sess.note_rfc_1214(origin.span());
639         }
640
641         self.note_region_origin(&origin);
642     }
643
644     fn report_concrete_failure(&self,
645                                origin: SubregionOrigin<'tcx>,
646                                sub: Region,
647                                sup: Region) {
648         match origin {
649             infer::RFC1214Subregion(ref suborigin) => {
650                 // Ideally, this would be a warning, but it doesn't
651                 // seem to come up in practice, since the changes from
652                 // RFC1214 mostly trigger errors in type definitions
653                 // that don't wind up coming down this path.
654                 self.report_concrete_failure((**suborigin).clone(), sub, sup);
655             }
656             infer::Subtype(trace) => {
657                 let terr = TypeError::RegionsDoesNotOutlive(sup, sub);
658                 self.report_and_explain_type_error(trace, &terr);
659             }
660             infer::Reborrow(span) => {
661                 span_err!(self.tcx.sess, span, E0312,
662                     "lifetime of reference outlines \
663                      lifetime of borrowed content...");
664                 self.tcx.note_and_explain_region(
665                     "...the reference is valid for ",
666                     sub,
667                     "...");
668                 self.tcx.note_and_explain_region(
669                     "...but the borrowed content is only valid for ",
670                     sup,
671                     "");
672             }
673             infer::ReborrowUpvar(span, ref upvar_id) => {
674                 span_err!(self.tcx.sess, span, E0313,
675                     "lifetime of borrowed pointer outlives \
676                             lifetime of captured variable `{}`...",
677                             self.tcx.local_var_name_str(upvar_id.var_id));
678                 self.tcx.note_and_explain_region(
679                     "...the borrowed pointer is valid for ",
680                     sub,
681                     "...");
682                 self.tcx.note_and_explain_region(
683                     &format!("...but `{}` is only valid for ",
684                              self.tcx.local_var_name_str(upvar_id.var_id)),
685                     sup,
686                     "");
687             }
688             infer::InfStackClosure(span) => {
689                 span_err!(self.tcx.sess, span, E0314,
690                     "closure outlives stack frame");
691                 self.tcx.note_and_explain_region(
692                     "...the closure must be valid for ",
693                     sub,
694                     "...");
695                 self.tcx.note_and_explain_region(
696                     "...but the closure's stack frame is only valid for ",
697                     sup,
698                     "");
699             }
700             infer::InvokeClosure(span) => {
701                 span_err!(self.tcx.sess, span, E0315,
702                     "cannot invoke closure outside of its lifetime");
703                 self.tcx.note_and_explain_region(
704                     "the closure is only valid for ",
705                     sup,
706                     "");
707             }
708             infer::DerefPointer(span) => {
709                 span_err!(self.tcx.sess, span, E0473,
710                           "dereference of reference outside its lifetime");
711                 self.tcx.note_and_explain_region(
712                     "the reference is only valid for ",
713                     sup,
714                     "");
715             }
716             infer::FreeVariable(span, id) => {
717                 span_err!(self.tcx.sess, span, E0474,
718                           "captured variable `{}` does not outlive the enclosing closure",
719                           self.tcx.local_var_name_str(id));
720                 self.tcx.note_and_explain_region(
721                     "captured variable is valid for ",
722                     sup,
723                     "");
724                 self.tcx.note_and_explain_region(
725                     "closure is valid for ",
726                     sub,
727                     "");
728             }
729             infer::IndexSlice(span) => {
730                 span_err!(self.tcx.sess, span, E0475,
731                           "index of slice outside its lifetime");
732                 self.tcx.note_and_explain_region(
733                     "the slice is only valid for ",
734                     sup,
735                     "");
736             }
737             infer::RelateObjectBound(span) => {
738                 span_err!(self.tcx.sess, span, E0476,
739                           "lifetime of the source pointer does not outlive \
740                            lifetime bound of the object type");
741                 self.tcx.note_and_explain_region(
742                     "object type is valid for ",
743                     sub,
744                     "");
745                 self.tcx.note_and_explain_region(
746                     "source pointer is only valid for ",
747                     sup,
748                     "");
749             }
750             infer::RelateParamBound(span, ty) => {
751                 span_err!(self.tcx.sess, span, E0477,
752                           "the type `{}` does not fulfill the required lifetime",
753                           self.ty_to_string(ty));
754                 self.tcx.note_and_explain_region(
755                                         "type must outlive ",
756                                         sub,
757                                         "");
758             }
759             infer::RelateRegionParamBound(span) => {
760                 span_err!(self.tcx.sess, span, E0478,
761                           "lifetime bound not satisfied");
762                 self.tcx.note_and_explain_region(
763                     "lifetime parameter instantiated with ",
764                     sup,
765                     "");
766                 self.tcx.note_and_explain_region(
767                     "but lifetime parameter must outlive ",
768                     sub,
769                     "");
770             }
771             infer::RelateDefaultParamBound(span, ty) => {
772                 span_err!(self.tcx.sess, span, E0479,
773                           "the type `{}` (provided as the value of \
774                            a type parameter) is not valid at this point",
775                           self.ty_to_string(ty));
776                 self.tcx.note_and_explain_region(
777                                         "type must outlive ",
778                                         sub,
779                                         "");
780             }
781             infer::CallRcvr(span) => {
782                 span_err!(self.tcx.sess, span, E0480,
783                           "lifetime of method receiver does not outlive \
784                            the method call");
785                 self.tcx.note_and_explain_region(
786                     "the receiver is only valid for ",
787                     sup,
788                     "");
789             }
790             infer::CallArg(span) => {
791                 span_err!(self.tcx.sess, span, E0481,
792                           "lifetime of function argument does not outlive \
793                            the function call");
794                 self.tcx.note_and_explain_region(
795                     "the function argument is only valid for ",
796                     sup,
797                     "");
798             }
799             infer::CallReturn(span) => {
800                 span_err!(self.tcx.sess, span, E0482,
801                           "lifetime of return value does not outlive \
802                            the function call");
803                 self.tcx.note_and_explain_region(
804                     "the return value is only valid for ",
805                     sup,
806                     "");
807             }
808             infer::Operand(span) => {
809                 span_err!(self.tcx.sess, span, E0483,
810                           "lifetime of operand does not outlive \
811                            the operation");
812                 self.tcx.note_and_explain_region(
813                     "the operand is only valid for ",
814                     sup,
815                     "");
816             }
817             infer::AddrOf(span) => {
818                 span_err!(self.tcx.sess, span, E0484,
819                           "reference is not valid at the time of borrow");
820                 self.tcx.note_and_explain_region(
821                     "the borrow is only valid for ",
822                     sup,
823                     "");
824             }
825             infer::AutoBorrow(span) => {
826                 span_err!(self.tcx.sess, span, E0485,
827                           "automatically reference is not valid \
828                            at the time of borrow");
829                 self.tcx.note_and_explain_region(
830                     "the automatic borrow is only valid for ",
831                     sup,
832                     "");
833             }
834             infer::ExprTypeIsNotInScope(t, span) => {
835                 span_err!(self.tcx.sess, span, E0486,
836                           "type of expression contains references \
837                            that are not valid during the expression: `{}`",
838                           self.ty_to_string(t));
839                 self.tcx.note_and_explain_region(
840                     "type is only valid for ",
841                     sup,
842                     "");
843             }
844             infer::SafeDestructor(span) => {
845                 span_err!(self.tcx.sess, span, E0487,
846                           "unsafe use of destructor: destructor might be called \
847                            while references are dead");
848                 // FIXME (22171): terms "super/subregion" are suboptimal
849                 self.tcx.note_and_explain_region(
850                     "superregion: ",
851                     sup,
852                     "");
853                 self.tcx.note_and_explain_region(
854                     "subregion: ",
855                     sub,
856                     "");
857             }
858             infer::BindingTypeIsNotValidAtDecl(span) => {
859                 span_err!(self.tcx.sess, span, E0488,
860                           "lifetime of variable does not enclose its declaration");
861                 self.tcx.note_and_explain_region(
862                     "the variable is only valid for ",
863                     sup,
864                     "");
865             }
866             infer::ParameterInScope(_, span) => {
867                 span_err!(self.tcx.sess, span, E0489,
868                           "type/lifetime parameter not in scope here");
869                 self.tcx.note_and_explain_region(
870                     "the parameter is only valid for ",
871                     sub,
872                     "");
873             }
874             infer::DataBorrowed(ty, span) => {
875                 span_err!(self.tcx.sess, span, E0490,
876                           "a value of type `{}` is borrowed for too long",
877                           self.ty_to_string(ty));
878                 self.tcx.note_and_explain_region("the type is valid for ", sub, "");
879                 self.tcx.note_and_explain_region("but the borrow lasts for ", sup, "");
880             }
881             infer::ReferenceOutlivesReferent(ty, span) => {
882                 span_err!(self.tcx.sess, span, E0491,
883                           "in type `{}`, reference has a longer lifetime \
884                            than the data it references",
885                           self.ty_to_string(ty));
886                 self.tcx.note_and_explain_region(
887                     "the pointer is valid for ",
888                     sub,
889                     "");
890                 self.tcx.note_and_explain_region(
891                     "but the referenced data is only valid for ",
892                     sup,
893                     "");
894             }
895         }
896     }
897
898     fn report_sub_sup_conflict(&self,
899                                var_origin: RegionVariableOrigin,
900                                sub_origin: SubregionOrigin<'tcx>,
901                                sub_region: Region,
902                                sup_origin: SubregionOrigin<'tcx>,
903                                sup_region: Region) {
904         self.report_inference_failure(var_origin);
905
906         self.tcx.note_and_explain_region(
907             "first, the lifetime cannot outlive ",
908             sup_region,
909             "...");
910
911         self.note_region_origin(&sup_origin);
912
913         self.tcx.note_and_explain_region(
914             "but, the lifetime must be valid for ",
915             sub_region,
916             "...");
917
918         self.note_region_origin(&sub_origin);
919     }
920
921     fn report_processed_errors(&self,
922                                var_origins: &[RegionVariableOrigin],
923                                trace_origins: &[(TypeTrace<'tcx>, TypeError<'tcx>)],
924                                same_regions: &[SameRegions]) {
925         for vo in var_origins {
926             self.report_inference_failure(vo.clone());
927         }
928         self.give_suggestion(same_regions);
929         for &(ref trace, ref terr) in trace_origins {
930             self.report_and_explain_type_error(trace.clone(), terr);
931         }
932     }
933
934     fn give_suggestion(&self, same_regions: &[SameRegions]) {
935         let scope_id = same_regions[0].scope_id;
936         let parent = self.tcx.map.get_parent(scope_id);
937         let parent_node = self.tcx.map.find(parent);
938         let taken = lifetimes_in_scope(self.tcx, scope_id);
939         let life_giver = LifeGiver::with_taken(&taken[..]);
940         let node_inner = match parent_node {
941             Some(ref node) => match *node {
942                 ast_map::NodeItem(ref item) => {
943                     match item.node {
944                         hir::ItemFn(ref fn_decl, unsafety, constness, _, ref gen, _) => {
945                             Some((fn_decl, gen, unsafety, constness,
946                                   item.name, None, item.span))
947                         },
948                         _ => None
949                     }
950                 }
951                 ast_map::NodeImplItem(item) => {
952                     match item.node {
953                         hir::ImplItemKind::Method(ref sig, _) => {
954                             Some((&sig.decl,
955                                   &sig.generics,
956                                   sig.unsafety,
957                                   sig.constness,
958                                   item.name,
959                                   Some(&sig.explicit_self.node),
960                                   item.span))
961                         }
962                         _ => None,
963                     }
964                 },
965                 ast_map::NodeTraitItem(item) => {
966                     match item.node {
967                         hir::MethodTraitItem(ref sig, Some(_)) => {
968                             Some((&sig.decl,
969                                   &sig.generics,
970                                   sig.unsafety,
971                                   sig.constness,
972                                   item.name,
973                                   Some(&sig.explicit_self.node),
974                                   item.span))
975                         }
976                         _ => None
977                     }
978                 }
979                 _ => None
980             },
981             None => None
982         };
983         let (fn_decl, generics, unsafety, constness, name, expl_self, span)
984                                     = node_inner.expect("expect item fn");
985         let rebuilder = Rebuilder::new(self.tcx, fn_decl, expl_self,
986                                        generics, same_regions, &life_giver);
987         let (fn_decl, expl_self, generics) = rebuilder.rebuild();
988         self.give_expl_lifetime_param(&fn_decl, unsafety, constness, name,
989                                       expl_self.as_ref(), &generics, span);
990     }
991 }
992
993 struct RebuildPathInfo<'a> {
994     path: &'a hir::Path,
995     // indexes to insert lifetime on path.lifetimes
996     indexes: Vec<u32>,
997     // number of lifetimes we expect to see on the type referred by `path`
998     // (e.g., expected=1 for struct Foo<'a>)
999     expected: u32,
1000     anon_nums: &'a HashSet<u32>,
1001     region_names: &'a HashSet<ast::Name>
1002 }
1003
1004 struct Rebuilder<'a, 'tcx: 'a> {
1005     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     cur_anon: Cell<u32>,
1012     inserted_anons: RefCell<HashSet<u32>>,
1013 }
1014
1015 enum FreshOrKept {
1016     Fresh,
1017     Kept
1018 }
1019
1020 impl<'a, 'tcx> Rebuilder<'a, 'tcx> {
1021     fn new(tcx: &'a ty::ctxt<'tcx>,
1022            fn_decl: &'a hir::FnDecl,
1023            expl_self_opt: Option<&'a hir::ExplicitSelf_>,
1024            generics: &'a hir::Generics,
1025            same_regions: &'a [SameRegions],
1026            life_giver: &'a LifeGiver)
1027            -> Rebuilder<'a, 'tcx> {
1028         Rebuilder {
1029             tcx: tcx,
1030             fn_decl: fn_decl,
1031             expl_self_opt: expl_self_opt,
1032             generics: generics,
1033             same_regions: same_regions,
1034             life_giver: life_giver,
1035             cur_anon: Cell::new(0),
1036             inserted_anons: RefCell::new(HashSet::new()),
1037         }
1038     }
1039
1040     fn rebuild(&self)
1041                -> (hir::FnDecl, Option<hir::ExplicitSelf_>, hir::Generics) {
1042         let mut expl_self_opt = self.expl_self_opt.cloned();
1043         let mut inputs = self.fn_decl.inputs.clone();
1044         let mut output = self.fn_decl.output.clone();
1045         let mut ty_params = self.generics.ty_params.clone();
1046         let where_clause = self.generics.where_clause.clone();
1047         let mut kept_lifetimes = HashSet::new();
1048         for sr in self.same_regions {
1049             self.cur_anon.set(0);
1050             self.offset_cur_anon();
1051             let (anon_nums, region_names) =
1052                                 self.extract_anon_nums_and_names(sr);
1053             let (lifetime, fresh_or_kept) = self.pick_lifetime(&region_names);
1054             match fresh_or_kept {
1055                 Kept => { kept_lifetimes.insert(lifetime.name); }
1056                 _ => ()
1057             }
1058             expl_self_opt = self.rebuild_expl_self(expl_self_opt, lifetime,
1059                                                    &anon_nums, &region_names);
1060             inputs = self.rebuild_args_ty(&inputs[..], lifetime,
1061                                           &anon_nums, &region_names);
1062             output = self.rebuild_output(&output, lifetime, &anon_nums, &region_names);
1063             ty_params = self.rebuild_ty_params(ty_params, lifetime,
1064                                                &region_names);
1065         }
1066         let fresh_lifetimes = self.life_giver.get_generated_lifetimes();
1067         let all_region_names = self.extract_all_region_names();
1068         let generics = self.rebuild_generics(self.generics,
1069                                              &fresh_lifetimes,
1070                                              &kept_lifetimes,
1071                                              &all_region_names,
1072                                              ty_params,
1073                                              where_clause);
1074         let new_fn_decl = hir::FnDecl {
1075             inputs: inputs,
1076             output: output,
1077             variadic: self.fn_decl.variadic
1078         };
1079         (new_fn_decl, expl_self_opt, generics)
1080     }
1081
1082     fn pick_lifetime(&self,
1083                      region_names: &HashSet<ast::Name>)
1084                      -> (hir::Lifetime, FreshOrKept) {
1085         if !region_names.is_empty() {
1086             // It's not necessary to convert the set of region names to a
1087             // vector of string and then sort them. However, it makes the
1088             // choice of lifetime name deterministic and thus easier to test.
1089             let mut names = Vec::new();
1090             for rn in region_names {
1091                 let lt_name = rn.to_string();
1092                 names.push(lt_name);
1093             }
1094             names.sort();
1095             let name = token::intern(&names[0]);
1096             return (name_to_dummy_lifetime(name), Kept);
1097         }
1098         return (self.life_giver.give_lifetime(), Fresh);
1099     }
1100
1101     fn extract_anon_nums_and_names(&self, same_regions: &SameRegions)
1102                                    -> (HashSet<u32>, HashSet<ast::Name>) {
1103         let mut anon_nums = HashSet::new();
1104         let mut region_names = HashSet::new();
1105         for br in &same_regions.regions {
1106             match *br {
1107                 ty::BrAnon(i) => {
1108                     anon_nums.insert(i);
1109                 }
1110                 ty::BrNamed(_, name) => {
1111                     region_names.insert(name);
1112                 }
1113                 _ => ()
1114             }
1115         }
1116         (anon_nums, region_names)
1117     }
1118
1119     fn extract_all_region_names(&self) -> HashSet<ast::Name> {
1120         let mut all_region_names = HashSet::new();
1121         for sr in self.same_regions {
1122             for br in &sr.regions {
1123                 match *br {
1124                     ty::BrNamed(_, name) => {
1125                         all_region_names.insert(name);
1126                     }
1127                     _ => ()
1128                 }
1129             }
1130         }
1131         all_region_names
1132     }
1133
1134     fn inc_cur_anon(&self, n: u32) {
1135         let anon = self.cur_anon.get();
1136         self.cur_anon.set(anon+n);
1137     }
1138
1139     fn offset_cur_anon(&self) {
1140         let mut anon = self.cur_anon.get();
1141         while self.inserted_anons.borrow().contains(&anon) {
1142             anon += 1;
1143         }
1144         self.cur_anon.set(anon);
1145     }
1146
1147     fn inc_and_offset_cur_anon(&self, n: u32) {
1148         self.inc_cur_anon(n);
1149         self.offset_cur_anon();
1150     }
1151
1152     fn track_anon(&self, anon: u32) {
1153         self.inserted_anons.borrow_mut().insert(anon);
1154     }
1155
1156     fn rebuild_ty_params(&self,
1157                          ty_params: OwnedSlice<hir::TyParam>,
1158                          lifetime: hir::Lifetime,
1159                          region_names: &HashSet<ast::Name>)
1160                          -> OwnedSlice<hir::TyParam> {
1161         ty_params.map(|ty_param| {
1162             let bounds = self.rebuild_ty_param_bounds(ty_param.bounds.clone(),
1163                                                       lifetime,
1164                                                       region_names);
1165             hir::TyParam {
1166                 name: ty_param.name,
1167                 id: ty_param.id,
1168                 bounds: bounds,
1169                 default: ty_param.default.clone(),
1170                 span: ty_param.span,
1171             }
1172         })
1173     }
1174
1175     fn rebuild_ty_param_bounds(&self,
1176                                ty_param_bounds: OwnedSlice<hir::TyParamBound>,
1177                                lifetime: hir::Lifetime,
1178                                region_names: &HashSet<ast::Name>)
1179                                -> OwnedSlice<hir::TyParamBound> {
1180         ty_param_bounds.map(|tpb| {
1181             match tpb {
1182                 &hir::RegionTyParamBound(lt) => {
1183                     // FIXME -- it's unclear whether I'm supposed to
1184                     // substitute lifetime here. I suspect we need to
1185                     // be passing down a map.
1186                     hir::RegionTyParamBound(lt)
1187                 }
1188                 &hir::TraitTyParamBound(ref poly_tr, modifier) => {
1189                     let tr = &poly_tr.trait_ref;
1190                     let last_seg = tr.path.segments.last().unwrap();
1191                     let mut insert = Vec::new();
1192                     let lifetimes = last_seg.parameters.lifetimes();
1193                     for (i, lt) in lifetimes.iter().enumerate() {
1194                         if region_names.contains(&lt.name) {
1195                             insert.push(i as u32);
1196                         }
1197                     }
1198                     let rebuild_info = RebuildPathInfo {
1199                         path: &tr.path,
1200                         indexes: insert,
1201                         expected: lifetimes.len() as u32,
1202                         anon_nums: &HashSet::new(),
1203                         region_names: region_names
1204                     };
1205                     let new_path = self.rebuild_path(rebuild_info, lifetime);
1206                     hir::TraitTyParamBound(hir::PolyTraitRef {
1207                         bound_lifetimes: poly_tr.bound_lifetimes.clone(),
1208                         trait_ref: hir::TraitRef {
1209                             path: new_path,
1210                             ref_id: tr.ref_id,
1211                         },
1212                         span: poly_tr.span,
1213                     }, modifier)
1214                 }
1215             }
1216         })
1217     }
1218
1219     fn rebuild_expl_self(&self,
1220                          expl_self_opt: Option<hir::ExplicitSelf_>,
1221                          lifetime: hir::Lifetime,
1222                          anon_nums: &HashSet<u32>,
1223                          region_names: &HashSet<ast::Name>)
1224                          -> Option<hir::ExplicitSelf_> {
1225         match expl_self_opt {
1226             Some(ref expl_self) => match *expl_self {
1227                 hir::SelfRegion(lt_opt, muta, id) => match lt_opt {
1228                     Some(lt) => if region_names.contains(&lt.name) {
1229                         return Some(hir::SelfRegion(Some(lifetime), muta, id));
1230                     },
1231                     None => {
1232                         let anon = self.cur_anon.get();
1233                         self.inc_and_offset_cur_anon(1);
1234                         if anon_nums.contains(&anon) {
1235                             self.track_anon(anon);
1236                             return Some(hir::SelfRegion(Some(lifetime), muta, id));
1237                         }
1238                     }
1239                 },
1240                 _ => ()
1241             },
1242             None => ()
1243         }
1244         expl_self_opt
1245     }
1246
1247     fn rebuild_generics(&self,
1248                         generics: &hir::Generics,
1249                         add: &Vec<hir::Lifetime>,
1250                         keep: &HashSet<ast::Name>,
1251                         remove: &HashSet<ast::Name>,
1252                         ty_params: OwnedSlice<hir::TyParam>,
1253                         where_clause: hir::WhereClause)
1254                         -> hir::Generics {
1255         let mut lifetimes = Vec::new();
1256         for lt in add {
1257             lifetimes.push(hir::LifetimeDef { lifetime: *lt,
1258                                               bounds: Vec::new() });
1259         }
1260         for lt in &generics.lifetimes {
1261             if keep.contains(&lt.lifetime.name) ||
1262                 !remove.contains(&lt.lifetime.name) {
1263                 lifetimes.push((*lt).clone());
1264             }
1265         }
1266         hir::Generics {
1267             lifetimes: lifetimes,
1268             ty_params: ty_params,
1269             where_clause: where_clause,
1270         }
1271     }
1272
1273     fn rebuild_args_ty(&self,
1274                        inputs: &[hir::Arg],
1275                        lifetime: hir::Lifetime,
1276                        anon_nums: &HashSet<u32>,
1277                        region_names: &HashSet<ast::Name>)
1278                        -> Vec<hir::Arg> {
1279         let mut new_inputs = Vec::new();
1280         for arg in inputs {
1281             let new_ty = self.rebuild_arg_ty_or_output(&*arg.ty, lifetime,
1282                                                        anon_nums, region_names);
1283             let possibly_new_arg = hir::Arg {
1284                 ty: new_ty,
1285                 pat: arg.pat.clone(),
1286                 id: arg.id
1287             };
1288             new_inputs.push(possibly_new_arg);
1289         }
1290         new_inputs
1291     }
1292
1293     fn rebuild_output(&self, ty: &hir::FunctionRetTy,
1294                       lifetime: hir::Lifetime,
1295                       anon_nums: &HashSet<u32>,
1296                       region_names: &HashSet<ast::Name>) -> hir::FunctionRetTy {
1297         match *ty {
1298             hir::Return(ref ret_ty) => hir::Return(
1299                 self.rebuild_arg_ty_or_output(&**ret_ty, lifetime, anon_nums, region_names)
1300             ),
1301             hir::DefaultReturn(span) => hir::DefaultReturn(span),
1302             hir::NoReturn(span) => hir::NoReturn(span)
1303         }
1304     }
1305
1306     fn rebuild_arg_ty_or_output(&self,
1307                                 ty: &hir::Ty,
1308                                 lifetime: hir::Lifetime,
1309                                 anon_nums: &HashSet<u32>,
1310                                 region_names: &HashSet<ast::Name>)
1311                                 -> P<hir::Ty> {
1312         let mut new_ty = P(ty.clone());
1313         let mut ty_queue = vec!(ty);
1314         while !ty_queue.is_empty() {
1315             let cur_ty = ty_queue.remove(0);
1316             match cur_ty.node {
1317                 hir::TyRptr(lt_opt, ref mut_ty) => {
1318                     let rebuild = match lt_opt {
1319                         Some(lt) => region_names.contains(&lt.name),
1320                         None => {
1321                             let anon = self.cur_anon.get();
1322                             let rebuild = anon_nums.contains(&anon);
1323                             if rebuild {
1324                                 self.track_anon(anon);
1325                             }
1326                             self.inc_and_offset_cur_anon(1);
1327                             rebuild
1328                         }
1329                     };
1330                     if rebuild {
1331                         let to = hir::Ty {
1332                             id: cur_ty.id,
1333                             node: hir::TyRptr(Some(lifetime), mut_ty.clone()),
1334                             span: cur_ty.span
1335                         };
1336                         new_ty = self.rebuild_ty(new_ty, P(to));
1337                     }
1338                     ty_queue.push(&*mut_ty.ty);
1339                 }
1340                 hir::TyPath(ref maybe_qself, ref path) => {
1341                     let a_def = match self.tcx.def_map.borrow().get(&cur_ty.id) {
1342                         None => {
1343                             self.tcx
1344                                 .sess
1345                                 .fatal(&format!(
1346                                         "unbound path {}",
1347                                         pprust::path_to_string(path)))
1348                         }
1349                         Some(d) => d.full_def()
1350                     };
1351                     match a_def {
1352                         def::DefTy(did, _) | def::DefStruct(did) => {
1353                             let generics = self.tcx.lookup_item_type(did).generics;
1354
1355                             let expected =
1356                                 generics.regions.len(subst::TypeSpace) as u32;
1357                             let lifetimes =
1358                                 path.segments.last().unwrap().parameters.lifetimes();
1359                             let mut insert = Vec::new();
1360                             if lifetimes.is_empty() {
1361                                 let anon = self.cur_anon.get();
1362                                 for (i, a) in (anon..anon+expected).enumerate() {
1363                                     if anon_nums.contains(&a) {
1364                                         insert.push(i as u32);
1365                                     }
1366                                     self.track_anon(a);
1367                                 }
1368                                 self.inc_and_offset_cur_anon(expected);
1369                             } else {
1370                                 for (i, lt) in lifetimes.iter().enumerate() {
1371                                     if region_names.contains(&lt.name) {
1372                                         insert.push(i as u32);
1373                                     }
1374                                 }
1375                             }
1376                             let rebuild_info = RebuildPathInfo {
1377                                 path: path,
1378                                 indexes: insert,
1379                                 expected: expected,
1380                                 anon_nums: anon_nums,
1381                                 region_names: region_names
1382                             };
1383                             let new_path = self.rebuild_path(rebuild_info, lifetime);
1384                             let qself = maybe_qself.as_ref().map(|qself| {
1385                                 hir::QSelf {
1386                                     ty: self.rebuild_arg_ty_or_output(&qself.ty, lifetime,
1387                                                                       anon_nums, region_names),
1388                                     position: qself.position
1389                                 }
1390                             });
1391                             let to = hir::Ty {
1392                                 id: cur_ty.id,
1393                                 node: hir::TyPath(qself, new_path),
1394                                 span: cur_ty.span
1395                             };
1396                             new_ty = self.rebuild_ty(new_ty, P(to));
1397                         }
1398                         _ => ()
1399                     }
1400
1401                 }
1402
1403                 hir::TyPtr(ref mut_ty) => {
1404                     ty_queue.push(&*mut_ty.ty);
1405                 }
1406                 hir::TyVec(ref ty) |
1407                 hir::TyFixedLengthVec(ref ty, _) => {
1408                     ty_queue.push(&**ty);
1409                 }
1410                 hir::TyTup(ref tys) => ty_queue.extend(tys.iter().map(|ty| &**ty)),
1411                 _ => {}
1412             }
1413         }
1414         new_ty
1415     }
1416
1417     fn rebuild_ty(&self,
1418                   from: P<hir::Ty>,
1419                   to: P<hir::Ty>)
1420                   -> P<hir::Ty> {
1421
1422         fn build_to(from: P<hir::Ty>,
1423                     to: &mut Option<P<hir::Ty>>)
1424                     -> P<hir::Ty> {
1425             if Some(from.id) == to.as_ref().map(|ty| ty.id) {
1426                 return to.take().expect("`to` type found more than once during rebuild");
1427             }
1428             from.map(|hir::Ty {id, node, span}| {
1429                 let new_node = match node {
1430                     hir::TyRptr(lifetime, mut_ty) => {
1431                         hir::TyRptr(lifetime, hir::MutTy {
1432                             mutbl: mut_ty.mutbl,
1433                             ty: build_to(mut_ty.ty, to),
1434                         })
1435                     }
1436                     hir::TyPtr(mut_ty) => {
1437                         hir::TyPtr(hir::MutTy {
1438                             mutbl: mut_ty.mutbl,
1439                             ty: build_to(mut_ty.ty, to),
1440                         })
1441                     }
1442                     hir::TyVec(ty) => hir::TyVec(build_to(ty, to)),
1443                     hir::TyFixedLengthVec(ty, e) => {
1444                         hir::TyFixedLengthVec(build_to(ty, to), e)
1445                     }
1446                     hir::TyTup(tys) => {
1447                         hir::TyTup(tys.into_iter().map(|ty| build_to(ty, to)).collect())
1448                     }
1449                     other => other
1450                 };
1451                 hir::Ty { id: id, node: new_node, span: span }
1452             })
1453         }
1454
1455         build_to(from, &mut Some(to))
1456     }
1457
1458     fn rebuild_path(&self,
1459                     rebuild_info: RebuildPathInfo,
1460                     lifetime: hir::Lifetime)
1461                     -> hir::Path
1462     {
1463         let RebuildPathInfo {
1464             path,
1465             indexes,
1466             expected,
1467             anon_nums,
1468             region_names,
1469         } = rebuild_info;
1470
1471         let last_seg = path.segments.last().unwrap();
1472         let new_parameters = match last_seg.parameters {
1473             hir::ParenthesizedParameters(..) => {
1474                 last_seg.parameters.clone()
1475             }
1476
1477             hir::AngleBracketedParameters(ref data) => {
1478                 let mut new_lts = Vec::new();
1479                 if data.lifetimes.is_empty() {
1480                     // traverse once to see if there's a need to insert lifetime
1481                     let need_insert = (0..expected).any(|i| {
1482                         indexes.contains(&i)
1483                     });
1484                     if need_insert {
1485                         for i in 0..expected {
1486                             if indexes.contains(&i) {
1487                                 new_lts.push(lifetime);
1488                             } else {
1489                                 new_lts.push(self.life_giver.give_lifetime());
1490                             }
1491                         }
1492                     }
1493                 } else {
1494                     for (i, lt) in data.lifetimes.iter().enumerate() {
1495                         if indexes.contains(&(i as u32)) {
1496                             new_lts.push(lifetime);
1497                         } else {
1498                             new_lts.push(*lt);
1499                         }
1500                     }
1501                 }
1502                 let new_types = data.types.map(|t| {
1503                     self.rebuild_arg_ty_or_output(&**t, lifetime, anon_nums, region_names)
1504                 });
1505                 let new_bindings = data.bindings.map(|b| {
1506                     hir::TypeBinding {
1507                         id: b.id,
1508                         name: b.name,
1509                         ty: self.rebuild_arg_ty_or_output(&*b.ty,
1510                                                           lifetime,
1511                                                           anon_nums,
1512                                                           region_names),
1513                         span: b.span
1514                     }
1515                 });
1516                 hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
1517                     lifetimes: new_lts,
1518                     types: new_types,
1519                     bindings: new_bindings,
1520                })
1521             }
1522         };
1523         let new_seg = hir::PathSegment {
1524             identifier: last_seg.identifier,
1525             parameters: new_parameters
1526         };
1527         let mut new_segs = Vec::new();
1528         new_segs.extend_from_slice(path.segments.split_last().unwrap().1);
1529         new_segs.push(new_seg);
1530         hir::Path {
1531             span: path.span,
1532             global: path.global,
1533             segments: new_segs
1534         }
1535     }
1536 }
1537
1538 impl<'a, 'tcx> ErrorReportingHelpers<'tcx> for InferCtxt<'a, 'tcx> {
1539     fn give_expl_lifetime_param(&self,
1540                                 decl: &hir::FnDecl,
1541                                 unsafety: hir::Unsafety,
1542                                 constness: hir::Constness,
1543                                 name: ast::Name,
1544                                 opt_explicit_self: Option<&hir::ExplicitSelf_>,
1545                                 generics: &hir::Generics,
1546                                 span: Span) {
1547         let suggested_fn = pprust::fun_to_string(decl, unsafety, constness, name,
1548                                                  opt_explicit_self, generics);
1549         let msg = format!("consider using an explicit lifetime \
1550                            parameter as shown: {}", suggested_fn);
1551         self.tcx.sess.span_help(span, &msg[..]);
1552     }
1553
1554     fn report_inference_failure(&self,
1555                                 var_origin: RegionVariableOrigin) {
1556         let br_string = |br: ty::BoundRegion| {
1557             let mut s = br.to_string();
1558             if !s.is_empty() {
1559                 s.push_str(" ");
1560             }
1561             s
1562         };
1563         let var_description = match var_origin {
1564             infer::MiscVariable(_) => "".to_string(),
1565             infer::PatternRegion(_) => " for pattern".to_string(),
1566             infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1567             infer::Autoref(_) => " for autoref".to_string(),
1568             infer::Coercion(_) => " for automatic coercion".to_string(),
1569             infer::LateBoundRegion(_, br, infer::FnCall) => {
1570                 format!(" for lifetime parameter {}in function call",
1571                         br_string(br))
1572             }
1573             infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1574                 format!(" for lifetime parameter {}in generic type", br_string(br))
1575             }
1576             infer::LateBoundRegion(_, br, infer::AssocTypeProjection(type_name)) => {
1577                 format!(" for lifetime parameter {}in trait containing associated type `{}`",
1578                         br_string(br), type_name)
1579             }
1580             infer::EarlyBoundRegion(_, name) => {
1581                 format!(" for lifetime parameter `{}`",
1582                         name)
1583             }
1584             infer::BoundRegionInCoherence(name) => {
1585                 format!(" for lifetime parameter `{}` in coherence check",
1586                         name)
1587             }
1588             infer::UpvarRegion(ref upvar_id, _) => {
1589                 format!(" for capture of `{}` by closure",
1590                         self.tcx.local_var_name_str(upvar_id.var_id).to_string())
1591             }
1592         };
1593
1594         span_err!(self.tcx.sess, var_origin.span(), E0495,
1595                   "cannot infer an appropriate lifetime{} \
1596                    due to conflicting requirements",
1597                   var_description);
1598     }
1599
1600     fn note_region_origin(&self, origin: &SubregionOrigin<'tcx>) {
1601         match *origin {
1602             infer::RFC1214Subregion(ref suborigin) => {
1603                 self.note_region_origin(suborigin);
1604             }
1605             infer::Subtype(ref trace) => {
1606                 let desc = match trace.origin {
1607                     TypeOrigin::Misc(_) => {
1608                         "types are compatible"
1609                     }
1610                     TypeOrigin::MethodCompatCheck(_) => {
1611                         "method type is compatible with trait"
1612                     }
1613                     TypeOrigin::ExprAssignable(_) => {
1614                         "expression is assignable"
1615                     }
1616                     TypeOrigin::RelateTraitRefs(_) => {
1617                         "traits are compatible"
1618                     }
1619                     TypeOrigin::RelateSelfType(_) => {
1620                         "self type matches impl self type"
1621                     }
1622                     TypeOrigin::RelateOutputImplTypes(_) => {
1623                         "trait type parameters matches those \
1624                                  specified on the impl"
1625                     }
1626                     TypeOrigin::MatchExpressionArm(_, _, _) => {
1627                         "match arms have compatible types"
1628                     }
1629                     TypeOrigin::IfExpression(_) => {
1630                         "if and else have compatible types"
1631                     }
1632                     TypeOrigin::IfExpressionWithNoElse(_) => {
1633                         "if may be missing an else clause"
1634                     }
1635                     TypeOrigin::RangeExpression(_) => {
1636                         "start and end of range have compatible types"
1637                     }
1638                     TypeOrigin::EquatePredicate(_) => {
1639                         "equality where clause is satisfied"
1640                     }
1641                 };
1642
1643                 match self.values_str(&trace.values) {
1644                     Some(values_str) => {
1645                         self.tcx.sess.span_note(
1646                             trace.origin.span(),
1647                             &format!("...so that {} ({})",
1648                                     desc, values_str));
1649                     }
1650                     None => {
1651                         // Really should avoid printing this error at
1652                         // all, since it is derived, but that would
1653                         // require more refactoring than I feel like
1654                         // doing right now. - nmatsakis
1655                         self.tcx.sess.span_note(
1656                             trace.origin.span(),
1657                             &format!("...so that {}", desc));
1658                     }
1659                 }
1660             }
1661             infer::Reborrow(span) => {
1662                 self.tcx.sess.span_note(
1663                     span,
1664                     "...so that reference does not outlive \
1665                     borrowed content");
1666             }
1667             infer::ReborrowUpvar(span, ref upvar_id) => {
1668                 self.tcx.sess.span_note(
1669                     span,
1670                     &format!(
1671                         "...so that closure can access `{}`",
1672                         self.tcx.local_var_name_str(upvar_id.var_id)
1673                             .to_string()))
1674             }
1675             infer::InfStackClosure(span) => {
1676                 self.tcx.sess.span_note(
1677                     span,
1678                     "...so that closure does not outlive its stack frame");
1679             }
1680             infer::InvokeClosure(span) => {
1681                 self.tcx.sess.span_note(
1682                     span,
1683                     "...so that closure is not invoked outside its lifetime");
1684             }
1685             infer::DerefPointer(span) => {
1686                 self.tcx.sess.span_note(
1687                     span,
1688                     "...so that pointer is not dereferenced \
1689                     outside its lifetime");
1690             }
1691             infer::FreeVariable(span, id) => {
1692                 self.tcx.sess.span_note(
1693                     span,
1694                     &format!("...so that captured variable `{}` \
1695                             does not outlive the enclosing closure",
1696                             self.tcx.local_var_name_str(id)));
1697             }
1698             infer::IndexSlice(span) => {
1699                 self.tcx.sess.span_note(
1700                     span,
1701                     "...so that slice is not indexed outside the lifetime");
1702             }
1703             infer::RelateObjectBound(span) => {
1704                 self.tcx.sess.span_note(
1705                     span,
1706                     "...so that it can be closed over into an object");
1707             }
1708             infer::CallRcvr(span) => {
1709                 self.tcx.sess.span_note(
1710                     span,
1711                     "...so that method receiver is valid for the method call");
1712             }
1713             infer::CallArg(span) => {
1714                 self.tcx.sess.span_note(
1715                     span,
1716                     "...so that argument is valid for the call");
1717             }
1718             infer::CallReturn(span) => {
1719                 self.tcx.sess.span_note(
1720                     span,
1721                     "...so that return value is valid for the call");
1722             }
1723             infer::Operand(span) => {
1724                 self.tcx.sess.span_note(
1725                     span,
1726                     "...so that operand is valid for operation");
1727             }
1728             infer::AddrOf(span) => {
1729                 self.tcx.sess.span_note(
1730                     span,
1731                     "...so that reference is valid \
1732                      at the time of borrow");
1733             }
1734             infer::AutoBorrow(span) => {
1735                 self.tcx.sess.span_note(
1736                     span,
1737                     "...so that auto-reference is valid \
1738                      at the time of borrow");
1739             }
1740             infer::ExprTypeIsNotInScope(t, span) => {
1741                 self.tcx.sess.span_note(
1742                     span,
1743                     &format!("...so type `{}` of expression is valid during the \
1744                              expression",
1745                             self.ty_to_string(t)));
1746             }
1747             infer::BindingTypeIsNotValidAtDecl(span) => {
1748                 self.tcx.sess.span_note(
1749                     span,
1750                     "...so that variable is valid at time of its declaration");
1751             }
1752             infer::ParameterInScope(_, span) => {
1753                 self.tcx.sess.span_note(
1754                     span,
1755                     "...so that a type/lifetime parameter is in scope here");
1756             }
1757             infer::DataBorrowed(ty, span) => {
1758                 self.tcx.sess.span_note(
1759                     span,
1760                     &format!("...so that the type `{}` is not borrowed for too long",
1761                              self.ty_to_string(ty)));
1762             }
1763             infer::ReferenceOutlivesReferent(ty, span) => {
1764                 self.tcx.sess.span_note(
1765                     span,
1766                     &format!("...so that the reference type `{}` \
1767                              does not outlive the data it points at",
1768                             self.ty_to_string(ty)));
1769             }
1770             infer::RelateParamBound(span, t) => {
1771                 self.tcx.sess.span_note(
1772                     span,
1773                     &format!("...so that the type `{}` \
1774                              will meet its required lifetime bounds",
1775                             self.ty_to_string(t)));
1776             }
1777             infer::RelateDefaultParamBound(span, t) => {
1778                 self.tcx.sess.span_note(
1779                     span,
1780                     &format!("...so that type parameter \
1781                              instantiated with `{}`, \
1782                              will meet its declared lifetime bounds",
1783                             self.ty_to_string(t)));
1784             }
1785             infer::RelateRegionParamBound(span) => {
1786                 self.tcx.sess.span_note(
1787                     span,
1788                     "...so that the declared lifetime parameter bounds \
1789                                 are satisfied");
1790             }
1791             infer::SafeDestructor(span) => {
1792                 self.tcx.sess.span_note(
1793                     span,
1794                     "...so that references are valid when the destructor \
1795                      runs")
1796             }
1797         }
1798     }
1799 }
1800
1801 pub trait Resolvable<'tcx> {
1802     fn resolve<'a>(&self, infcx: &InferCtxt<'a, 'tcx>) -> Self;
1803 }
1804
1805 impl<'tcx> Resolvable<'tcx> for Ty<'tcx> {
1806     fn resolve<'a>(&self, infcx: &InferCtxt<'a, 'tcx>) -> Ty<'tcx> {
1807         infcx.resolve_type_vars_if_possible(self)
1808     }
1809 }
1810
1811 impl<'tcx> Resolvable<'tcx> for ty::TraitRef<'tcx> {
1812     fn resolve<'a>(&self, infcx: &InferCtxt<'a, 'tcx>)
1813                    -> ty::TraitRef<'tcx> {
1814         infcx.resolve_type_vars_if_possible(self)
1815     }
1816 }
1817
1818 impl<'tcx> Resolvable<'tcx> for ty::PolyTraitRef<'tcx> {
1819     fn resolve<'a>(&self,
1820                    infcx: &InferCtxt<'a, 'tcx>)
1821                    -> ty::PolyTraitRef<'tcx>
1822     {
1823         infcx.resolve_type_vars_if_possible(self)
1824     }
1825 }
1826
1827 fn lifetimes_in_scope(tcx: &ty::ctxt,
1828                       scope_id: ast::NodeId)
1829                       -> Vec<hir::LifetimeDef> {
1830     let mut taken = Vec::new();
1831     let parent = tcx.map.get_parent(scope_id);
1832     let method_id_opt = match tcx.map.find(parent) {
1833         Some(node) => match node {
1834             ast_map::NodeItem(item) => match item.node {
1835                 hir::ItemFn(_, _, _, _, ref gen, _) => {
1836                     taken.extend_from_slice(&gen.lifetimes);
1837                     None
1838                 },
1839                 _ => None
1840             },
1841             ast_map::NodeImplItem(ii) => {
1842                 match ii.node {
1843                     hir::ImplItemKind::Method(ref sig, _) => {
1844                         taken.extend_from_slice(&sig.generics.lifetimes);
1845                         Some(ii.id)
1846                     }
1847                     _ => None,
1848                 }
1849             }
1850             _ => None
1851         },
1852         None => None
1853     };
1854     if method_id_opt.is_some() {
1855         let method_id = method_id_opt.unwrap();
1856         let parent = tcx.map.get_parent(method_id);
1857         match tcx.map.find(parent) {
1858             Some(node) => match node {
1859                 ast_map::NodeItem(item) => match item.node {
1860                     hir::ItemImpl(_, _, ref gen, _, _, _) => {
1861                         taken.extend_from_slice(&gen.lifetimes);
1862                     }
1863                     _ => ()
1864                 },
1865                 _ => ()
1866             },
1867             None => ()
1868         }
1869     }
1870     return taken;
1871 }
1872
1873 // LifeGiver is responsible for generating fresh lifetime names
1874 struct LifeGiver {
1875     taken: HashSet<String>,
1876     counter: Cell<usize>,
1877     generated: RefCell<Vec<hir::Lifetime>>,
1878 }
1879
1880 impl LifeGiver {
1881     fn with_taken(taken: &[hir::LifetimeDef]) -> LifeGiver {
1882         let mut taken_ = HashSet::new();
1883         for lt in taken {
1884             let lt_name = lt.lifetime.name.to_string();
1885             taken_.insert(lt_name);
1886         }
1887         LifeGiver {
1888             taken: taken_,
1889             counter: Cell::new(0),
1890             generated: RefCell::new(Vec::new()),
1891         }
1892     }
1893
1894     fn inc_counter(&self) {
1895         let c = self.counter.get();
1896         self.counter.set(c+1);
1897     }
1898
1899     fn give_lifetime(&self) -> hir::Lifetime {
1900         let lifetime;
1901         loop {
1902             let mut s = String::from("'");
1903             s.push_str(&num_to_string(self.counter.get()));
1904             if !self.taken.contains(&s) {
1905                 lifetime = name_to_dummy_lifetime(token::intern(&s[..]));
1906                 self.generated.borrow_mut().push(lifetime);
1907                 break;
1908             }
1909             self.inc_counter();
1910         }
1911         self.inc_counter();
1912         return lifetime;
1913
1914         // 0 .. 25 generates a .. z, 26 .. 51 generates aa .. zz, and so on
1915         fn num_to_string(counter: usize) -> String {
1916             let mut s = String::new();
1917             let (n, r) = (counter/26 + 1, counter % 26);
1918             let letter: char = from_u32((r+97) as u32).unwrap();
1919             for _ in 0..n {
1920                 s.push(letter);
1921             }
1922             s
1923         }
1924     }
1925
1926     fn get_generated_lifetimes(&self) -> Vec<hir::Lifetime> {
1927         self.generated.borrow().clone()
1928     }
1929 }
1930
1931 fn name_to_dummy_lifetime(name: ast::Name) -> hir::Lifetime {
1932     hir::Lifetime { id: ast::DUMMY_NODE_ID,
1933                     span: codemap::DUMMY_SP,
1934                     name: name }
1935 }