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