]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/error_reporting/mod.rs
Fix invalid associated type rendering in rustdoc
[rust.git] / src / librustc / infer / error_reporting / mod.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 infer;
59 use super::{InferCtxt, TypeTrace, SubregionOrigin, RegionVariableOrigin, ValuePairs};
60 use super::region_inference::{RegionResolutionError, ConcreteFailure, SubSupConflict,
61                               GenericBoundFailure, GenericKind};
62
63 use std::fmt;
64 use hir;
65 use hir::map as hir_map;
66 use hir::def_id::DefId;
67 use middle::region;
68 use traits::{ObligationCause, ObligationCauseCode};
69 use ty::{self, TyCtxt, TypeFoldable};
70 use ty::{Region, Issue32330};
71 use ty::error::TypeError;
72 use syntax_pos::{Pos, Span};
73 use errors::DiagnosticBuilder;
74
75 mod note;
76
77 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
78     pub fn note_and_explain_region(self,
79                                    err: &mut DiagnosticBuilder,
80                                    prefix: &str,
81                                    region: &'tcx ty::Region,
82                                    suffix: &str) {
83         fn item_scope_tag(item: &hir::Item) -> &'static str {
84             match item.node {
85                 hir::ItemImpl(..) => "impl",
86                 hir::ItemStruct(..) => "struct",
87                 hir::ItemUnion(..) => "union",
88                 hir::ItemEnum(..) => "enum",
89                 hir::ItemTrait(..) => "trait",
90                 hir::ItemFn(..) => "function body",
91                 _ => "item"
92             }
93         }
94
95         fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
96             match item.node {
97                 hir::TraitItemKind::Method(..) => "method body",
98                 hir::TraitItemKind::Const(..) |
99                 hir::TraitItemKind::Type(..) => "associated item"
100             }
101         }
102
103         fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
104             match item.node {
105                 hir::ImplItemKind::Method(..) => "method body",
106                 hir::ImplItemKind::Const(..) |
107                 hir::ImplItemKind::Type(_) => "associated item"
108             }
109         }
110
111         fn explain_span<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
112                                         heading: &str, span: Span)
113                                         -> (String, Option<Span>) {
114             let lo = tcx.sess.codemap().lookup_char_pos_adj(span.lo);
115             (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize()),
116              Some(span))
117         }
118
119         let (description, span) = match *region {
120             ty::ReScope(scope) => {
121                 let new_string;
122                 let unknown_scope = || {
123                     format!("{}unknown scope: {:?}{}.  Please report a bug.",
124                             prefix, scope, suffix)
125                 };
126                 let span = match scope.span(&self.region_maps, &self.hir) {
127                     Some(s) => s,
128                     None => {
129                         err.note(&unknown_scope());
130                         return;
131                     }
132                 };
133                 let tag = match self.hir.find(scope.node_id(&self.region_maps)) {
134                     Some(hir_map::NodeBlock(_)) => "block",
135                     Some(hir_map::NodeExpr(expr)) => match expr.node {
136                         hir::ExprCall(..) => "call",
137                         hir::ExprMethodCall(..) => "method call",
138                         hir::ExprMatch(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
139                         hir::ExprMatch(.., hir::MatchSource::WhileLetDesugar) =>  "while let",
140                         hir::ExprMatch(.., hir::MatchSource::ForLoopDesugar) =>  "for",
141                         hir::ExprMatch(..) => "match",
142                         _ => "expression",
143                     },
144                     Some(hir_map::NodeStmt(_)) => "statement",
145                     Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
146                     Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
147                     Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
148                     Some(_) | None => {
149                         err.span_note(span, &unknown_scope());
150                         return;
151                     }
152                 };
153                 let scope_decorated_tag = match self.region_maps.code_extent_data(scope) {
154                     region::CodeExtentData::Misc(_) => tag,
155                     region::CodeExtentData::CallSiteScope { .. } => {
156                         "scope of call-site for function"
157                     }
158                     region::CodeExtentData::ParameterScope { .. } => {
159                         "scope of function body"
160                     }
161                     region::CodeExtentData::DestructionScope(_) => {
162                         new_string = format!("destruction scope surrounding {}", tag);
163                         &new_string[..]
164                     }
165                     region::CodeExtentData::Remainder(r) => {
166                         new_string = format!("block suffix following statement {}",
167                                              r.first_statement_index);
168                         &new_string[..]
169                     }
170                 };
171                 explain_span(self, scope_decorated_tag, span)
172             }
173
174             ty::ReFree(ref fr) => {
175                 let prefix = match fr.bound_region {
176                     ty::BrAnon(idx) => {
177                         format!("the anonymous lifetime #{} defined on", idx + 1)
178                     }
179                     ty::BrFresh(_) => "an anonymous lifetime defined on".to_owned(),
180                     _ => {
181                         format!("the lifetime {} as defined on",
182                                 fr.bound_region)
183                     }
184                 };
185
186                 let node = fr.scope.node_id(&self.region_maps);
187                 let unknown;
188                 let tag = match self.hir.find(node) {
189                     Some(hir_map::NodeBlock(_)) |
190                     Some(hir_map::NodeExpr(_)) => "body",
191                     Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
192                     Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
193                     Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
194
195                     // this really should not happen, but it does:
196                     // FIXME(#27942)
197                     Some(_) => {
198                         unknown = format!("unexpected node ({}) for scope {:?}.  \
199                                            Please report a bug.",
200                                           self.hir.node_to_string(node), fr.scope);
201                         &unknown
202                     }
203                     None => {
204                         unknown = format!("unknown node for scope {:?}.  \
205                                            Please report a bug.", fr.scope);
206                         &unknown
207                     }
208                 };
209                 let (msg, opt_span) = explain_span(self, tag, self.hir.span(node));
210                 (format!("{} {}", prefix, msg), opt_span)
211             }
212
213             ty::ReStatic => ("the static lifetime".to_owned(), None),
214
215             ty::ReEmpty => ("the empty lifetime".to_owned(), None),
216
217             ty::ReEarlyBound(ref data) => (data.name.to_string(), None),
218
219             // FIXME(#13998) ReSkolemized should probably print like
220             // ReFree rather than dumping Debug output on the user.
221             //
222             // We shouldn't really be having unification failures with ReVar
223             // and ReLateBound though.
224             ty::ReSkolemized(..) |
225             ty::ReVar(_) |
226             ty::ReLateBound(..) |
227             ty::ReErased => {
228                 (format!("lifetime {:?}", region), None)
229             }
230         };
231         let message = format!("{}{}{}", prefix, description, suffix);
232         if let Some(span) = span {
233             err.span_note(span, &message);
234         } else {
235             err.note(&message);
236         }
237     }
238 }
239
240 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
241     pub fn report_region_errors(&self,
242                                 errors: &Vec<RegionResolutionError<'tcx>>) {
243         debug!("report_region_errors(): {} errors to start", errors.len());
244
245         // try to pre-process the errors, which will group some of them
246         // together into a `ProcessedErrors` group:
247         let errors = self.process_errors(errors);
248
249         debug!("report_region_errors: {} errors after preprocessing", errors.len());
250
251         for error in errors {
252             debug!("report_region_errors: error = {:?}", error);
253             match error.clone() {
254                 ConcreteFailure(origin, sub, sup) => {
255                     self.report_concrete_failure(origin, sub, sup).emit();
256                 }
257
258                 GenericBoundFailure(kind, param_ty, sub) => {
259                     self.report_generic_bound_failure(kind, param_ty, sub);
260                 }
261
262                 SubSupConflict(var_origin,
263                                sub_origin, sub_r,
264                                sup_origin, sup_r) => {
265                     self.report_sub_sup_conflict(var_origin,
266                                                  sub_origin, sub_r,
267                                                  sup_origin, sup_r);
268                 }
269             }
270         }
271     }
272
273     // This method goes through all the errors and try to group certain types
274     // of error together, for the purpose of suggesting explicit lifetime
275     // parameters to the user. This is done so that we can have a more
276     // complete view of what lifetimes should be the same.
277     // If the return value is an empty vector, it means that processing
278     // failed (so the return value of this method should not be used).
279     //
280     // The method also attempts to weed out messages that seem like
281     // duplicates that will be unhelpful to the end-user. But
282     // obviously it never weeds out ALL errors.
283     fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
284                       -> Vec<RegionResolutionError<'tcx>> {
285         debug!("process_errors()");
286
287         // We want to avoid reporting generic-bound failures if we can
288         // avoid it: these have a very high rate of being unhelpful in
289         // practice. This is because they are basically secondary
290         // checks that test the state of the region graph after the
291         // rest of inference is done, and the other kinds of errors
292         // indicate that the region constraint graph is internally
293         // inconsistent, so these test results are likely to be
294         // meaningless.
295         //
296         // Therefore, we filter them out of the list unless they are
297         // the only thing in the list.
298
299         let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
300             ConcreteFailure(..) => false,
301             SubSupConflict(..) => false,
302             GenericBoundFailure(..) => true,
303         };
304
305         if errors.iter().all(|e| is_bound_failure(e)) {
306             errors.clone()
307         } else {
308             errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
309         }
310     }
311
312     /// Adds a note if the types come from similarly named crates
313     fn check_and_note_conflicting_crates(&self,
314                                          err: &mut DiagnosticBuilder,
315                                          terr: &TypeError<'tcx>,
316                                          sp: Span) {
317         let report_path_match = |err: &mut DiagnosticBuilder, did1: DefId, did2: DefId| {
318             // Only external crates, if either is from a local
319             // module we could have false positives
320             if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
321                 let exp_path = self.tcx.item_path_str(did1);
322                 let found_path = self.tcx.item_path_str(did2);
323                 // We compare strings because DefPath can be different
324                 // for imported and non-imported crates
325                 if exp_path == found_path {
326                     let crate_name = self.tcx.sess.cstore.crate_name(did1.krate);
327                     err.span_note(sp, &format!("Perhaps two different versions \
328                                                 of crate `{}` are being used?",
329                                                crate_name));
330                 }
331             }
332         };
333         match *terr {
334             TypeError::Sorts(ref exp_found) => {
335                 // if they are both "path types", there's a chance of ambiguity
336                 // due to different versions of the same crate
337                 match (&exp_found.expected.sty, &exp_found.found.sty) {
338                     (&ty::TyAdt(exp_adt, _), &ty::TyAdt(found_adt, _)) => {
339                         report_path_match(err, exp_adt.did, found_adt.did);
340                     },
341                     _ => ()
342                 }
343             },
344             TypeError::Traits(ref exp_found) => {
345                 report_path_match(err, exp_found.expected, exp_found.found);
346             },
347             _ => () // FIXME(#22750) handle traits and stuff
348         }
349     }
350
351     fn note_error_origin(&self,
352                          err: &mut DiagnosticBuilder<'tcx>,
353                          cause: &ObligationCause<'tcx>)
354     {
355         match cause.code {
356             ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
357                 hir::MatchSource::IfLetDesugar {..} => {
358                     err.span_note(arm_span, "`if let` arm with an incompatible type");
359                 }
360                 _ => {
361                     err.span_note(arm_span, "match arm with an incompatible type");
362                 }
363             },
364             _ => ()
365         }
366     }
367
368     pub fn note_type_err(&self,
369                          diag: &mut DiagnosticBuilder<'tcx>,
370                          cause: &ObligationCause<'tcx>,
371                          secondary_span: Option<(Span, String)>,
372                          values: Option<ValuePairs<'tcx>>,
373                          terr: &TypeError<'tcx>)
374     {
375         let (expected_found, is_simple_error) = match values {
376             None => (None, false),
377             Some(values) => {
378                 let is_simple_error = match values {
379                     ValuePairs::Types(exp_found) => {
380                         exp_found.expected.is_primitive() && exp_found.found.is_primitive()
381                     }
382                     _ => false,
383                 };
384                 let vals = match self.values_str(&values) {
385                     Some((expected, found)) => Some((expected, found)),
386                     None => {
387                         // Derived error. Cancel the emitter.
388                         self.tcx.sess.diagnostic().cancel(diag);
389                         return
390                     }
391                 };
392                 (vals, is_simple_error)
393             }
394         };
395
396         let span = cause.span;
397
398         if let Some((expected, found)) = expected_found {
399             match (terr, is_simple_error, expected == found) {
400                 (&TypeError::Sorts(ref values), false,  true) => {
401                     diag.note_expected_found_extra(
402                         &"type", &expected, &found,
403                         &format!(" ({})", values.expected.sort_string(self.tcx)),
404                         &format!(" ({})", values.found.sort_string(self.tcx)));
405                 }
406                 (_, false,  _) => {
407                     diag.note_expected_found(&"type", &expected, &found);
408                 }
409                 _ => (),
410             }
411         }
412
413         diag.span_label(span, &terr);
414         if let Some((sp, msg)) = secondary_span {
415             diag.span_label(sp, &msg);
416         }
417
418         self.note_error_origin(diag, &cause);
419         self.check_and_note_conflicting_crates(diag, terr, span);
420         self.tcx.note_and_explain_type_err(diag, terr, span);
421     }
422
423     pub fn note_issue_32330(&self,
424                             diag: &mut DiagnosticBuilder<'tcx>,
425                             terr: &TypeError<'tcx>)
426     {
427         debug!("note_issue_32330: terr={:?}", terr);
428         match *terr {
429             TypeError::RegionsInsufficientlyPolymorphic(_, _, Some(box Issue32330 {
430                 fn_def_id, region_name
431             })) |
432             TypeError::RegionsOverlyPolymorphic(_, _, Some(box Issue32330 {
433                 fn_def_id, region_name
434             })) => {
435                 diag.note(
436                     &format!("lifetime parameter `{0}` declared on fn `{1}` \
437                               appears only in the return type, \
438                               but here is required to be higher-ranked, \
439                               which means that `{0}` must appear in both \
440                               argument and return types",
441                              region_name,
442                              self.tcx.item_path_str(fn_def_id)));
443                 diag.note(
444                     &format!("this error is the result of a recent bug fix; \
445                               for more information, see issue #33685 \
446                               <https://github.com/rust-lang/rust/issues/33685>"));
447             }
448             _ => {}
449         }
450     }
451
452     pub fn report_and_explain_type_error(&self,
453                                          trace: TypeTrace<'tcx>,
454                                          terr: &TypeError<'tcx>)
455                                          -> DiagnosticBuilder<'tcx>
456     {
457         let span = trace.cause.span;
458         let failure_str = trace.cause.as_failure_str();
459         let mut diag = match trace.cause.code {
460             ObligationCauseCode::IfExpressionWithNoElse => {
461                 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
462             }
463             ObligationCauseCode::MainFunctionType => {
464                 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
465             }
466             _ => {
467                 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
468             }
469         };
470         self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
471         self.note_issue_32330(&mut diag, terr);
472         diag
473     }
474
475     /// Returns a string of the form "expected `{}`, found `{}`".
476     fn values_str(&self, values: &ValuePairs<'tcx>) -> Option<(String, String)> {
477         match *values {
478             infer::Types(ref exp_found) => self.expected_found_str(exp_found),
479             infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
480             infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
481         }
482     }
483
484     fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
485         &self,
486         exp_found: &ty::error::ExpectedFound<T>)
487         -> Option<(String, String)>
488     {
489         let exp_found = self.resolve_type_vars_if_possible(exp_found);
490         if exp_found.references_error() {
491             return None;
492         }
493
494         Some((format!("{}", exp_found.expected), format!("{}", exp_found.found)))
495     }
496
497     fn report_generic_bound_failure(&self,
498                                     origin: SubregionOrigin<'tcx>,
499                                     bound_kind: GenericKind<'tcx>,
500                                     sub: &'tcx Region)
501     {
502         // FIXME: it would be better to report the first error message
503         // with the span of the parameter itself, rather than the span
504         // where the error was detected. But that span is not readily
505         // accessible.
506
507         let labeled_user_string = match bound_kind {
508             GenericKind::Param(ref p) =>
509                 format!("the parameter type `{}`", p),
510             GenericKind::Projection(ref p) =>
511                 format!("the associated type `{}`", p),
512         };
513
514         if let SubregionOrigin::CompareImplMethodObligation {
515             span, item_name, impl_item_def_id, trait_item_def_id, lint_id
516         } = origin {
517             self.report_extra_impl_obligation(span,
518                                               item_name,
519                                               impl_item_def_id,
520                                               trait_item_def_id,
521                                               &format!("`{}: {}`", bound_kind, sub),
522                                               lint_id)
523                 .emit();
524             return;
525         }
526
527         let mut err = match *sub {
528             ty::ReFree(ty::FreeRegion {bound_region: ty::BrNamed(..), ..}) => {
529                 // Does the required lifetime have a nice name we can print?
530                 let mut err = struct_span_err!(self.tcx.sess,
531                                                origin.span(),
532                                                E0309,
533                                                "{} may not live long enough",
534                                                labeled_user_string);
535                 err.help(&format!("consider adding an explicit lifetime bound `{}: {}`...",
536                          bound_kind,
537                          sub));
538                 err
539             }
540
541             ty::ReStatic => {
542                 // Does the required lifetime have a nice name we can print?
543                 let mut err = struct_span_err!(self.tcx.sess,
544                                                origin.span(),
545                                                E0310,
546                                                "{} may not live long enough",
547                                                labeled_user_string);
548                 err.help(&format!("consider adding an explicit lifetime \
549                                    bound `{}: 'static`...",
550                                   bound_kind));
551                 err
552             }
553
554             _ => {
555                 // If not, be less specific.
556                 let mut err = struct_span_err!(self.tcx.sess,
557                                                origin.span(),
558                                                E0311,
559                                                "{} may not live long enough",
560                                                labeled_user_string);
561                 err.help(&format!("consider adding an explicit lifetime bound for `{}`",
562                                   bound_kind));
563                 self.tcx.note_and_explain_region(
564                     &mut err,
565                     &format!("{} must be valid for ", labeled_user_string),
566                     sub,
567                     "...");
568                 err
569             }
570         };
571
572         self.note_region_origin(&mut err, &origin);
573         err.emit();
574     }
575
576     fn report_sub_sup_conflict(&self,
577                                var_origin: RegionVariableOrigin,
578                                sub_origin: SubregionOrigin<'tcx>,
579                                sub_region: &'tcx Region,
580                                sup_origin: SubregionOrigin<'tcx>,
581                                sup_region: &'tcx Region) {
582         let mut err = self.report_inference_failure(var_origin);
583
584         self.tcx.note_and_explain_region(&mut err,
585             "first, the lifetime cannot outlive ",
586             sup_region,
587             "...");
588
589         self.note_region_origin(&mut err, &sup_origin);
590
591         self.tcx.note_and_explain_region(&mut err,
592             "but, the lifetime must be valid for ",
593             sub_region,
594             "...");
595
596         self.note_region_origin(&mut err, &sub_origin);
597         err.emit();
598     }
599 }
600
601 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
602     fn report_inference_failure(&self,
603                                 var_origin: RegionVariableOrigin)
604                                 -> DiagnosticBuilder<'tcx> {
605         let br_string = |br: ty::BoundRegion| {
606             let mut s = br.to_string();
607             if !s.is_empty() {
608                 s.push_str(" ");
609             }
610             s
611         };
612         let var_description = match var_origin {
613             infer::MiscVariable(_) => "".to_string(),
614             infer::PatternRegion(_) => " for pattern".to_string(),
615             infer::AddrOfRegion(_) => " for borrow expression".to_string(),
616             infer::Autoref(_) => " for autoref".to_string(),
617             infer::Coercion(_) => " for automatic coercion".to_string(),
618             infer::LateBoundRegion(_, br, infer::FnCall) => {
619                 format!(" for lifetime parameter {}in function call",
620                         br_string(br))
621             }
622             infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
623                 format!(" for lifetime parameter {}in generic type", br_string(br))
624             }
625             infer::LateBoundRegion(_, br, infer::AssocTypeProjection(type_name)) => {
626                 format!(" for lifetime parameter {}in trait containing associated type `{}`",
627                         br_string(br), type_name)
628             }
629             infer::EarlyBoundRegion(_, name, _) => {
630                 format!(" for lifetime parameter `{}`",
631                         name)
632             }
633             infer::BoundRegionInCoherence(name) => {
634                 format!(" for lifetime parameter `{}` in coherence check",
635                         name)
636             }
637             infer::UpvarRegion(ref upvar_id, _) => {
638                 format!(" for capture of `{}` by closure",
639                         self.tcx.local_var_name_str(upvar_id.var_id).to_string())
640             }
641         };
642
643         struct_span_err!(self.tcx.sess, var_origin.span(), E0495,
644                   "cannot infer an appropriate lifetime{} \
645                    due to conflicting requirements",
646                   var_description)
647     }
648 }
649
650 impl<'tcx> ObligationCause<'tcx> {
651     fn as_failure_str(&self) -> &'static str {
652         use traits::ObligationCauseCode::*;
653         match self.code {
654             CompareImplMethodObligation { .. } => "method not compatible with trait",
655             MatchExpressionArm { source, .. } => match source {
656                 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have incompatible types",
657                 _ => "match arms have incompatible types",
658             },
659             IfExpression => "if and else have incompatible types",
660             IfExpressionWithNoElse => "if may be missing an else clause",
661             EquatePredicate => "equality predicate not satisfied",
662             MainFunctionType => "main function has wrong type",
663             StartFunctionType => "start function has wrong type",
664             IntrinsicType => "intrinsic has wrong type",
665             MethodReceiver => "mismatched method receiver",
666             _ => "mismatched types",
667         }
668     }
669
670     fn as_requirement_str(&self) -> &'static str {
671         use traits::ObligationCauseCode::*;
672         match self.code {
673             CompareImplMethodObligation { .. } => "method type is compatible with trait",
674             ExprAssignable => "expression is assignable",
675             MatchExpressionArm { source, .. } => match source {
676                 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have compatible types",
677                 _ => "match arms have compatible types",
678             },
679             IfExpression => "if and else have compatible types",
680             IfExpressionWithNoElse => "if missing an else returns ()",
681             EquatePredicate => "equality where clause is satisfied",
682             MainFunctionType => "`main` function has the correct type",
683             StartFunctionType => "`start` function has the correct type",
684             IntrinsicType => "intrinsic has the correct type",
685             MethodReceiver => "method receiver has the correct type",
686             _ => "types are compatible",
687         }
688     }
689 }