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