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