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