]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/error_reporting.rs
Rollup merge of #39604 - est31:i128_tests, r=alexcrichton
[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 super::InferCtxt;
59 use super::TypeTrace;
60 use super::SubregionOrigin;
61 use super::RegionVariableOrigin;
62 use super::ValuePairs;
63 use super::region_inference::RegionResolutionError;
64 use super::region_inference::ConcreteFailure;
65 use super::region_inference::SubSupConflict;
66 use super::region_inference::GenericBoundFailure;
67 use super::region_inference::GenericKind;
68 use super::region_inference::ProcessedErrors;
69 use super::region_inference::ProcessedErrorOrigin;
70 use super::region_inference::SameRegions;
71
72 use hir::map as hir_map;
73 use hir;
74
75 use hir::def_id::DefId;
76 use infer;
77 use middle::region;
78 use traits::{ObligationCause, ObligationCauseCode};
79 use ty::{self, TyCtxt, TypeFoldable};
80 use ty::{Region, ReFree, Issue32330};
81 use ty::error::TypeError;
82
83 use std::fmt;
84 use syntax::ast;
85 use syntax_pos::{Pos, Span};
86 use errors::DiagnosticBuilder;
87
88 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
89     pub fn note_and_explain_region(self,
90                                    err: &mut DiagnosticBuilder,
91                                    prefix: &str,
92                                    region: &'tcx ty::Region,
93                                    suffix: &str) {
94         fn item_scope_tag(item: &hir::Item) -> &'static str {
95             match item.node {
96                 hir::ItemImpl(..) => "impl",
97                 hir::ItemStruct(..) => "struct",
98                 hir::ItemUnion(..) => "union",
99                 hir::ItemEnum(..) => "enum",
100                 hir::ItemTrait(..) => "trait",
101                 hir::ItemFn(..) => "function body",
102                 _ => "item"
103             }
104         }
105
106         fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
107             match item.node {
108                 hir::TraitItemKind::Method(..) => "method body",
109                 hir::TraitItemKind::Const(..) |
110                 hir::TraitItemKind::Type(..) => "associated item"
111             }
112         }
113
114         fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
115             match item.node {
116                 hir::ImplItemKind::Method(..) => "method body",
117                 hir::ImplItemKind::Const(..) |
118                 hir::ImplItemKind::Type(_) => "associated item"
119             }
120         }
121
122         fn explain_span<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
123                                         heading: &str, span: Span)
124                                         -> (String, Option<Span>) {
125             let lo = tcx.sess.codemap().lookup_char_pos_adj(span.lo);
126             (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize()),
127              Some(span))
128         }
129
130         let (description, span) = match *region {
131             ty::ReScope(scope) => {
132                 let new_string;
133                 let unknown_scope = || {
134                     format!("{}unknown scope: {:?}{}.  Please report a bug.",
135                             prefix, scope, suffix)
136                 };
137                 let span = match scope.span(&self.region_maps, &self.hir) {
138                     Some(s) => s,
139                     None => {
140                         err.note(&unknown_scope());
141                         return;
142                     }
143                 };
144                 let tag = match self.hir.find(scope.node_id(&self.region_maps)) {
145                     Some(hir_map::NodeBlock(_)) => "block",
146                     Some(hir_map::NodeExpr(expr)) => match expr.node {
147                         hir::ExprCall(..) => "call",
148                         hir::ExprMethodCall(..) => "method call",
149                         hir::ExprMatch(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
150                         hir::ExprMatch(.., hir::MatchSource::WhileLetDesugar) =>  "while let",
151                         hir::ExprMatch(.., hir::MatchSource::ForLoopDesugar) =>  "for",
152                         hir::ExprMatch(..) => "match",
153                         _ => "expression",
154                     },
155                     Some(hir_map::NodeStmt(_)) => "statement",
156                     Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
157                     Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
158                     Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
159                     Some(_) | None => {
160                         err.span_note(span, &unknown_scope());
161                         return;
162                     }
163                 };
164                 let scope_decorated_tag = match self.region_maps.code_extent_data(scope) {
165                     region::CodeExtentData::Misc(_) => tag,
166                     region::CodeExtentData::CallSiteScope { .. } => {
167                         "scope of call-site for function"
168                     }
169                     region::CodeExtentData::ParameterScope { .. } => {
170                         "scope of function body"
171                     }
172                     region::CodeExtentData::DestructionScope(_) => {
173                         new_string = format!("destruction scope surrounding {}", tag);
174                         &new_string[..]
175                     }
176                     region::CodeExtentData::Remainder(r) => {
177                         new_string = format!("block suffix following statement {}",
178                                              r.first_statement_index);
179                         &new_string[..]
180                     }
181                 };
182                 explain_span(self, scope_decorated_tag, span)
183             }
184
185             ty::ReFree(ref fr) => {
186                 let prefix = match fr.bound_region {
187                     ty::BrAnon(idx) => {
188                         format!("the anonymous lifetime #{} defined on", idx + 1)
189                     }
190                     ty::BrFresh(_) => "an anonymous lifetime defined on".to_owned(),
191                     _ => {
192                         format!("the lifetime {} as defined on",
193                                 fr.bound_region)
194                     }
195                 };
196
197                 let node = fr.scope.node_id(&self.region_maps);
198                 let unknown;
199                 let tag = match self.hir.find(node) {
200                     Some(hir_map::NodeBlock(_)) |
201                     Some(hir_map::NodeExpr(_)) => "body",
202                     Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
203                     Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
204                     Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
205
206                     // this really should not happen, but it does:
207                     // FIXME(#27942)
208                     Some(_) => {
209                         unknown = format!("unexpected node ({}) for scope {:?}.  \
210                                            Please report a bug.",
211                                           self.hir.node_to_string(node), fr.scope);
212                         &unknown
213                     }
214                     None => {
215                         unknown = format!("unknown node for scope {:?}.  \
216                                            Please report a bug.", fr.scope);
217                         &unknown
218                     }
219                 };
220                 let (msg, opt_span) = explain_span(self, tag, self.hir.span(node));
221                 (format!("{} {}", prefix, msg), opt_span)
222             }
223
224             ty::ReStatic => ("the static lifetime".to_owned(), None),
225
226             ty::ReEmpty => ("the empty lifetime".to_owned(), None),
227
228             ty::ReEarlyBound(ref data) => (data.name.to_string(), None),
229
230             // FIXME(#13998) ReSkolemized should probably print like
231             // ReFree rather than dumping Debug output on the user.
232             //
233             // We shouldn't really be having unification failures with ReVar
234             // and ReLateBound though.
235             ty::ReSkolemized(..) |
236             ty::ReVar(_) |
237             ty::ReLateBound(..) |
238             ty::ReErased => {
239                 (format!("lifetime {:?}", region), None)
240             }
241         };
242         let message = format!("{}{}{}", prefix, description, suffix);
243         if let Some(span) = span {
244             err.span_note(span, &message);
245         } else {
246             err.note(&message);
247         }
248     }
249 }
250
251 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
252     pub fn report_region_errors(&self,
253                                 errors: &Vec<RegionResolutionError<'tcx>>) {
254         debug!("report_region_errors(): {} errors to start", errors.len());
255
256         // try to pre-process the errors, which will group some of them
257         // together into a `ProcessedErrors` group:
258         let processed_errors = self.process_errors(errors);
259         let errors = processed_errors.as_ref().unwrap_or(errors);
260
261         debug!("report_region_errors: {} errors after preprocessing", errors.len());
262
263         for error in errors {
264             debug!("report_region_errors: error = {:?}", error);
265             match error.clone() {
266                 ConcreteFailure(origin, sub, sup) => {
267                     self.report_concrete_failure(origin, sub, sup).emit();
268                 }
269
270                 GenericBoundFailure(kind, param_ty, sub) => {
271                     self.report_generic_bound_failure(kind, param_ty, sub);
272                 }
273
274                 SubSupConflict(var_origin,
275                                sub_origin, sub_r,
276                                sup_origin, sup_r) => {
277                     self.report_sub_sup_conflict(var_origin,
278                                                  sub_origin, sub_r,
279                                                  sup_origin, sup_r);
280                 }
281
282                 ProcessedErrors(ref origins,
283                                 ref same_regions) => {
284                     if !same_regions.is_empty() {
285                         self.report_processed_errors(origins);
286                     }
287                 }
288             }
289         }
290     }
291
292     // This method goes through all the errors and try to group certain types
293     // of error together, for the purpose of suggesting explicit lifetime
294     // parameters to the user. This is done so that we can have a more
295     // complete view of what lifetimes should be the same.
296     // If the return value is an empty vector, it means that processing
297     // failed (so the return value of this method should not be used).
298     //
299     // The method also attempts to weed out messages that seem like
300     // duplicates that will be unhelpful to the end-user. But
301     // obviously it never weeds out ALL errors.
302     fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
303                       -> Option<Vec<RegionResolutionError<'tcx>>> {
304         debug!("process_errors()");
305         let mut origins = Vec::new();
306
307         // we collect up ConcreteFailures and SubSupConflicts that are
308         // relating free-regions bound on the fn-header and group them
309         // together into this vector
310         let mut same_regions = Vec::new();
311
312         // here we put errors that we will not be able to process nicely
313         let mut other_errors = Vec::new();
314
315         // we collect up GenericBoundFailures in here.
316         let mut bound_failures = Vec::new();
317
318         for error in errors {
319             // Check whether we can process this error into some other
320             // form; if not, fall through.
321             match *error {
322                 ConcreteFailure(ref origin, sub, sup) => {
323                     debug!("processing ConcreteFailure");
324                     if let SubregionOrigin::CompareImplMethodObligation { .. } = *origin {
325                         // When comparing an impl method against a
326                         // trait method, it is not helpful to suggest
327                         // changes to the impl method.  This is
328                         // because the impl method signature is being
329                         // checked using the trait's environment, so
330                         // usually the changes we suggest would
331                         // actually have to be applied to the *trait*
332                         // method (and it's not clear that the trait
333                         // method is even under the user's control).
334                     } else if let Some(same_frs) = free_regions_from_same_fn(self.tcx, sub, sup) {
335                         origins.push(
336                             ProcessedErrorOrigin::ConcreteFailure(
337                                 origin.clone(),
338                                 sub,
339                                 sup));
340                         append_to_same_regions(&mut same_regions, &same_frs);
341                         continue;
342                     }
343                 }
344                 SubSupConflict(ref var_origin, ref sub_origin, sub, ref sup_origin, sup) => {
345                     debug!("processing SubSupConflict sub: {:?} sup: {:?}", sub, sup);
346                     match (sub_origin, sup_origin) {
347                         (&SubregionOrigin::CompareImplMethodObligation { .. }, _) => {
348                             // As above, when comparing an impl method
349                             // against a trait method, it is not helpful
350                             // to suggest changes to the impl method.
351                         }
352                         (_, &SubregionOrigin::CompareImplMethodObligation { .. }) => {
353                             // See above.
354                         }
355                         _ => {
356                             if let Some(same_frs) = free_regions_from_same_fn(self.tcx, sub, sup) {
357                                 origins.push(
358                                     ProcessedErrorOrigin::VariableFailure(
359                                         var_origin.clone()));
360                                 append_to_same_regions(&mut same_regions, &same_frs);
361                                 continue;
362                             }
363                         }
364                     }
365                 }
366                 GenericBoundFailure(ref origin, ref kind, region) => {
367                     bound_failures.push((origin.clone(), kind.clone(), region));
368                     continue;
369                 }
370                 ProcessedErrors(..) => {
371                     bug!("should not encounter a `ProcessedErrors` yet: {:?}", error)
372                 }
373             }
374
375             // No changes to this error.
376             other_errors.push(error.clone());
377         }
378
379         // ok, let's pull together the errors, sorted in an order that
380         // we think will help user the best
381         let mut processed_errors = vec![];
382
383         // first, put the processed errors, if any
384         if !same_regions.is_empty() {
385             let common_scope_id = same_regions[0].scope_id;
386             for sr in &same_regions {
387                 // Since ProcessedErrors is used to reconstruct the function
388                 // declaration, we want to make sure that they are, in fact,
389                 // from the same scope
390                 if sr.scope_id != common_scope_id {
391                     debug!("returning empty result from process_errors because
392                             {} != {}", sr.scope_id, common_scope_id);
393                     return None;
394                 }
395             }
396             assert!(origins.len() > 0);
397             let pe = ProcessedErrors(origins, same_regions);
398             debug!("errors processed: {:?}", pe);
399             processed_errors.push(pe);
400         }
401
402         // next, put the other misc errors
403         processed_errors.extend(other_errors);
404
405         // finally, put the `T: 'a` errors, but only if there were no
406         // other errors. otherwise, these have a very high rate of
407         // being unhelpful in practice. This is because they are
408         // basically secondary checks that test the state of the
409         // region graph after the rest of inference is done, and the
410         // other kinds of errors indicate that the region constraint
411         // graph is internally inconsistent, so these test results are
412         // likely to be meaningless.
413         if processed_errors.is_empty() {
414             for (origin, kind, region) in bound_failures {
415                 processed_errors.push(GenericBoundFailure(origin, kind, region));
416             }
417         }
418
419         // we should always wind up with SOME errors, unless there were no
420         // errors to start
421         assert!(if errors.len() > 0 {processed_errors.len() > 0} else {true});
422
423         return Some(processed_errors);
424
425         #[derive(Debug)]
426         struct FreeRegionsFromSameFn {
427             sub_fr: ty::FreeRegion,
428             sup_fr: ty::FreeRegion,
429             scope_id: ast::NodeId
430         }
431
432         impl FreeRegionsFromSameFn {
433             fn new(sub_fr: ty::FreeRegion,
434                    sup_fr: ty::FreeRegion,
435                    scope_id: ast::NodeId)
436                    -> FreeRegionsFromSameFn {
437                 FreeRegionsFromSameFn {
438                     sub_fr: sub_fr,
439                     sup_fr: sup_fr,
440                     scope_id: scope_id
441                 }
442             }
443         }
444
445         fn free_regions_from_same_fn<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
446                                                      sub: &'tcx Region,
447                                                      sup: &'tcx Region)
448                                                      -> Option<FreeRegionsFromSameFn> {
449             debug!("free_regions_from_same_fn(sub={:?}, sup={:?})", sub, sup);
450             let (scope_id, fr1, fr2) = match (sub, sup) {
451                 (&ReFree(fr1), &ReFree(fr2)) => {
452                     if fr1.scope != fr2.scope {
453                         return None
454                     }
455                     assert!(fr1.scope == fr2.scope);
456                     (fr1.scope.node_id(&tcx.region_maps), fr1, fr2)
457                 },
458                 _ => return None
459             };
460             let parent = tcx.hir.get_parent(scope_id);
461             let parent_node = tcx.hir.find(parent);
462             match parent_node {
463                 Some(node) => match node {
464                     hir_map::NodeItem(item) => match item.node {
465                         hir::ItemFn(..) => {
466                             Some(FreeRegionsFromSameFn::new(fr1, fr2, scope_id))
467                         },
468                         _ => None
469                     },
470                     hir_map::NodeImplItem(..) |
471                     hir_map::NodeTraitItem(..) => {
472                         Some(FreeRegionsFromSameFn::new(fr1, fr2, scope_id))
473                     },
474                     _ => None
475                 },
476                 None => {
477                     debug!("no parent node of scope_id {}", scope_id);
478                     None
479                 }
480             }
481         }
482
483         fn append_to_same_regions(same_regions: &mut Vec<SameRegions>,
484                                   same_frs: &FreeRegionsFromSameFn) {
485             debug!("append_to_same_regions(same_regions={:?}, same_frs={:?})",
486                    same_regions, same_frs);
487             let scope_id = same_frs.scope_id;
488             let (sub_fr, sup_fr) = (same_frs.sub_fr, same_frs.sup_fr);
489             for sr in same_regions.iter_mut() {
490                 if sr.contains(&sup_fr.bound_region) && scope_id == sr.scope_id {
491                     sr.push(sub_fr.bound_region);
492                     return
493                 }
494             }
495             same_regions.push(SameRegions {
496                 scope_id: scope_id,
497                 regions: vec![sub_fr.bound_region, sup_fr.bound_region]
498             })
499         }
500     }
501
502     /// Adds a note if the types come from similarly named crates
503     fn check_and_note_conflicting_crates(&self,
504                                          err: &mut DiagnosticBuilder,
505                                          terr: &TypeError<'tcx>,
506                                          sp: Span) {
507         let report_path_match = |err: &mut DiagnosticBuilder, did1: DefId, did2: DefId| {
508             // Only external crates, if either is from a local
509             // module we could have false positives
510             if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
511                 let exp_path = self.tcx.item_path_str(did1);
512                 let found_path = self.tcx.item_path_str(did2);
513                 // We compare strings because DefPath can be different
514                 // for imported and non-imported crates
515                 if exp_path == found_path {
516                     let crate_name = self.tcx.sess.cstore.crate_name(did1.krate);
517                     err.span_note(sp, &format!("Perhaps two different versions \
518                                                 of crate `{}` are being used?",
519                                                crate_name));
520                 }
521             }
522         };
523         match *terr {
524             TypeError::Sorts(ref exp_found) => {
525                 // if they are both "path types", there's a chance of ambiguity
526                 // due to different versions of the same crate
527                 match (&exp_found.expected.sty, &exp_found.found.sty) {
528                     (&ty::TyAdt(exp_adt, _), &ty::TyAdt(found_adt, _)) => {
529                         report_path_match(err, exp_adt.did, found_adt.did);
530                     },
531                     _ => ()
532                 }
533             },
534             TypeError::Traits(ref exp_found) => {
535                 report_path_match(err, exp_found.expected, exp_found.found);
536             },
537             _ => () // FIXME(#22750) handle traits and stuff
538         }
539     }
540
541     fn note_error_origin(&self,
542                          err: &mut DiagnosticBuilder<'tcx>,
543                          cause: &ObligationCause<'tcx>)
544     {
545         match cause.code {
546             ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
547                 hir::MatchSource::IfLetDesugar {..} => {
548                     err.span_note(arm_span, "`if let` arm with an incompatible type");
549                 }
550                 _ => {
551                     err.span_note(arm_span, "match arm with an incompatible type");
552                 }
553             },
554             _ => ()
555         }
556     }
557
558     pub fn note_type_err(&self,
559                          diag: &mut DiagnosticBuilder<'tcx>,
560                          cause: &ObligationCause<'tcx>,
561                          secondary_span: Option<(Span, String)>,
562                          values: Option<ValuePairs<'tcx>>,
563                          terr: &TypeError<'tcx>)
564     {
565         let expected_found = match values {
566             None => None,
567             Some(values) => match self.values_str(&values) {
568                 Some((expected, found)) => Some((expected, found)),
569                 None => {
570                     // Derived error. Cancel the emitter.
571                     self.tcx.sess.diagnostic().cancel(diag);
572                     return
573                 }
574             }
575         };
576
577         let span = cause.span;
578
579         if let Some((expected, found)) = expected_found {
580             let is_simple_error = if let &TypeError::Sorts(ref values) = terr {
581                 values.expected.is_primitive() && values.found.is_primitive()
582             } else {
583                 false
584             };
585
586             if !is_simple_error {
587                 if expected == found {
588                     if let &TypeError::Sorts(ref values) = terr {
589                         diag.note_expected_found_extra(
590                             &"type", &expected, &found,
591                             &format!(" ({})", values.expected.sort_string(self.tcx)),
592                             &format!(" ({})", values.found.sort_string(self.tcx)));
593                     } else {
594                         diag.note_expected_found(&"type", &expected, &found);
595                     }
596                 } else {
597                     diag.note_expected_found(&"type", &expected, &found);
598                 }
599             }
600         }
601
602         diag.span_label(span, &terr);
603         if let Some((sp, msg)) = secondary_span {
604             diag.span_label(sp, &msg);
605         }
606
607         self.note_error_origin(diag, &cause);
608         self.check_and_note_conflicting_crates(diag, terr, span);
609         self.tcx.note_and_explain_type_err(diag, terr, span);
610     }
611
612     pub fn note_issue_32330(&self,
613                             diag: &mut DiagnosticBuilder<'tcx>,
614                             terr: &TypeError<'tcx>)
615     {
616         debug!("note_issue_32330: terr={:?}", terr);
617         match *terr {
618             TypeError::RegionsInsufficientlyPolymorphic(_, &Region::ReVar(vid)) |
619             TypeError::RegionsOverlyPolymorphic(_, &Region::ReVar(vid)) => {
620                 match self.region_vars.var_origin(vid) {
621                     RegionVariableOrigin::EarlyBoundRegion(_, _, Some(Issue32330 {
622                         fn_def_id,
623                         region_name
624                     })) => {
625                         diag.note(
626                             &format!("lifetime parameter `{0}` declared on fn `{1}` \
627                                       appears only in the return type, \
628                                       but here is required to be higher-ranked, \
629                                       which means that `{0}` must appear in both \
630                                       argument and return types",
631                                      region_name,
632                                      self.tcx.item_path_str(fn_def_id)));
633                         diag.note(
634                             &format!("this error is the result of a recent bug fix; \
635                                       for more information, see issue #33685 \
636                                       <https://github.com/rust-lang/rust/issues/33685>"));
637                     }
638                     _ => { }
639                 }
640             }
641             _ => { }
642         }
643     }
644
645     pub fn report_and_explain_type_error(&self,
646                                          trace: TypeTrace<'tcx>,
647                                          terr: &TypeError<'tcx>)
648                                          -> DiagnosticBuilder<'tcx>
649     {
650         let span = trace.cause.span;
651         let failure_str = trace.cause.as_failure_str();
652         let mut diag = match trace.cause.code {
653             ObligationCauseCode::IfExpressionWithNoElse => {
654                 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
655             }
656             ObligationCauseCode::MainFunctionType => {
657                 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
658             }
659             _ => {
660                 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
661             }
662         };
663         self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
664         self.note_issue_32330(&mut diag, terr);
665         diag
666     }
667
668     /// Returns a string of the form "expected `{}`, found `{}`".
669     fn values_str(&self, values: &ValuePairs<'tcx>) -> Option<(String, String)> {
670         match *values {
671             infer::Types(ref exp_found) => self.expected_found_str(exp_found),
672             infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
673             infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
674         }
675     }
676
677     fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
678         &self,
679         exp_found: &ty::error::ExpectedFound<T>)
680         -> Option<(String, String)>
681     {
682         let exp_found = self.resolve_type_vars_if_possible(exp_found);
683         if exp_found.references_error() {
684             return None;
685         }
686
687         Some((format!("{}", exp_found.expected), format!("{}", exp_found.found)))
688     }
689
690     fn report_generic_bound_failure(&self,
691                                     origin: SubregionOrigin<'tcx>,
692                                     bound_kind: GenericKind<'tcx>,
693                                     sub: &'tcx Region)
694     {
695         // FIXME: it would be better to report the first error message
696         // with the span of the parameter itself, rather than the span
697         // where the error was detected. But that span is not readily
698         // accessible.
699
700         let labeled_user_string = match bound_kind {
701             GenericKind::Param(ref p) =>
702                 format!("the parameter type `{}`", p),
703             GenericKind::Projection(ref p) =>
704                 format!("the associated type `{}`", p),
705         };
706
707         if let SubregionOrigin::CompareImplMethodObligation {
708             span, item_name, impl_item_def_id, trait_item_def_id, lint_id
709         } = origin {
710             self.report_extra_impl_obligation(span,
711                                               item_name,
712                                               impl_item_def_id,
713                                               trait_item_def_id,
714                                               &format!("`{}: {}`", bound_kind, sub),
715                                               lint_id)
716                 .emit();
717             return;
718         }
719
720         let mut err = match *sub {
721             ty::ReFree(ty::FreeRegion {bound_region: ty::BrNamed(..), ..}) => {
722                 // Does the required lifetime have a nice name we can print?
723                 let mut err = struct_span_err!(self.tcx.sess,
724                                                origin.span(),
725                                                E0309,
726                                                "{} may not live long enough",
727                                                labeled_user_string);
728                 err.help(&format!("consider adding an explicit lifetime bound `{}: {}`...",
729                          bound_kind,
730                          sub));
731                 err
732             }
733
734             ty::ReStatic => {
735                 // Does the required lifetime have a nice name we can print?
736                 let mut err = struct_span_err!(self.tcx.sess,
737                                                origin.span(),
738                                                E0310,
739                                                "{} may not live long enough",
740                                                labeled_user_string);
741                 err.help(&format!("consider adding an explicit lifetime \
742                                    bound `{}: 'static`...",
743                                   bound_kind));
744                 err
745             }
746
747             _ => {
748                 // If not, be less specific.
749                 let mut err = struct_span_err!(self.tcx.sess,
750                                                origin.span(),
751                                                E0311,
752                                                "{} may not live long enough",
753                                                labeled_user_string);
754                 err.help(&format!("consider adding an explicit lifetime bound for `{}`",
755                                   bound_kind));
756                 self.tcx.note_and_explain_region(
757                     &mut err,
758                     &format!("{} must be valid for ", labeled_user_string),
759                     sub,
760                     "...");
761                 err
762             }
763         };
764
765         self.note_region_origin(&mut err, &origin);
766         err.emit();
767     }
768
769     fn report_concrete_failure(&self,
770                                origin: SubregionOrigin<'tcx>,
771                                sub: &'tcx Region,
772                                sup: &'tcx Region)
773                                 -> DiagnosticBuilder<'tcx> {
774         match origin {
775             infer::Subtype(trace) => {
776                 let terr = TypeError::RegionsDoesNotOutlive(sup, sub);
777                 self.report_and_explain_type_error(trace, &terr)
778             }
779             infer::Reborrow(span) => {
780                 let mut err = struct_span_err!(self.tcx.sess, span, E0312,
781                     "lifetime of reference outlives \
782                      lifetime of borrowed content...");
783                 self.tcx.note_and_explain_region(&mut err,
784                     "...the reference is valid for ",
785                     sub,
786                     "...");
787                 self.tcx.note_and_explain_region(&mut err,
788                     "...but the borrowed content is only valid for ",
789                     sup,
790                     "");
791                 err
792             }
793             infer::ReborrowUpvar(span, ref upvar_id) => {
794                 let mut err = struct_span_err!(self.tcx.sess, span, E0313,
795                     "lifetime of borrowed pointer outlives \
796                             lifetime of captured variable `{}`...",
797                             self.tcx.local_var_name_str(upvar_id.var_id));
798                 self.tcx.note_and_explain_region(&mut err,
799                     "...the borrowed pointer is valid for ",
800                     sub,
801                     "...");
802                 self.tcx.note_and_explain_region(&mut err,
803                     &format!("...but `{}` is only valid for ",
804                              self.tcx.local_var_name_str(upvar_id.var_id)),
805                     sup,
806                     "");
807                 err
808             }
809             infer::InfStackClosure(span) => {
810                 let mut err = struct_span_err!(self.tcx.sess, span, E0314,
811                     "closure outlives stack frame");
812                 self.tcx.note_and_explain_region(&mut err,
813                     "...the closure must be valid for ",
814                     sub,
815                     "...");
816                 self.tcx.note_and_explain_region(&mut err,
817                     "...but the closure's stack frame is only valid for ",
818                     sup,
819                     "");
820                 err
821             }
822             infer::InvokeClosure(span) => {
823                 let mut err = struct_span_err!(self.tcx.sess, span, E0315,
824                     "cannot invoke closure outside of its lifetime");
825                 self.tcx.note_and_explain_region(&mut err,
826                     "the closure is only valid for ",
827                     sup,
828                     "");
829                 err
830             }
831             infer::DerefPointer(span) => {
832                 let mut err = struct_span_err!(self.tcx.sess, span, E0473,
833                           "dereference of reference outside its lifetime");
834                 self.tcx.note_and_explain_region(&mut err,
835                     "the reference is only valid for ",
836                     sup,
837                     "");
838                 err
839             }
840             infer::FreeVariable(span, id) => {
841                 let mut err = struct_span_err!(self.tcx.sess, span, E0474,
842                           "captured variable `{}` does not outlive the enclosing closure",
843                           self.tcx.local_var_name_str(id));
844                 self.tcx.note_and_explain_region(&mut err,
845                     "captured variable is valid for ",
846                     sup,
847                     "");
848                 self.tcx.note_and_explain_region(&mut err,
849                     "closure is valid for ",
850                     sub,
851                     "");
852                 err
853             }
854             infer::IndexSlice(span) => {
855                 let mut err = struct_span_err!(self.tcx.sess, span, E0475,
856                           "index of slice outside its lifetime");
857                 self.tcx.note_and_explain_region(&mut err,
858                     "the slice is only valid for ",
859                     sup,
860                     "");
861                 err
862             }
863             infer::RelateObjectBound(span) => {
864                 let mut err = struct_span_err!(self.tcx.sess, span, E0476,
865                           "lifetime of the source pointer does not outlive \
866                            lifetime bound of the object type");
867                 self.tcx.note_and_explain_region(&mut err,
868                     "object type is valid for ",
869                     sub,
870                     "");
871                 self.tcx.note_and_explain_region(&mut err,
872                     "source pointer is only valid for ",
873                     sup,
874                     "");
875                 err
876             }
877             infer::RelateParamBound(span, ty) => {
878                 let mut err = struct_span_err!(self.tcx.sess, span, E0477,
879                           "the type `{}` does not fulfill the required lifetime",
880                           self.ty_to_string(ty));
881                 self.tcx.note_and_explain_region(&mut err,
882                                         "type must outlive ",
883                                         sub,
884                                         "");
885                 err
886             }
887             infer::RelateRegionParamBound(span) => {
888                 let mut err = struct_span_err!(self.tcx.sess, span, E0478,
889                           "lifetime bound not satisfied");
890                 self.tcx.note_and_explain_region(&mut err,
891                     "lifetime parameter instantiated with ",
892                     sup,
893                     "");
894                 self.tcx.note_and_explain_region(&mut err,
895                     "but lifetime parameter must outlive ",
896                     sub,
897                     "");
898                 err
899             }
900             infer::RelateDefaultParamBound(span, ty) => {
901                 let mut err = struct_span_err!(self.tcx.sess, span, E0479,
902                           "the type `{}` (provided as the value of \
903                            a type parameter) is not valid at this point",
904                           self.ty_to_string(ty));
905                 self.tcx.note_and_explain_region(&mut err,
906                                         "type must outlive ",
907                                         sub,
908                                         "");
909                 err
910             }
911             infer::CallRcvr(span) => {
912                 let mut err = struct_span_err!(self.tcx.sess, span, E0480,
913                           "lifetime of method receiver does not outlive \
914                            the method call");
915                 self.tcx.note_and_explain_region(&mut err,
916                     "the receiver is only valid for ",
917                     sup,
918                     "");
919                 err
920             }
921             infer::CallArg(span) => {
922                 let mut err = struct_span_err!(self.tcx.sess, span, E0481,
923                           "lifetime of function argument does not outlive \
924                            the function call");
925                 self.tcx.note_and_explain_region(&mut err,
926                     "the function argument is only valid for ",
927                     sup,
928                     "");
929                 err
930             }
931             infer::CallReturn(span) => {
932                 let mut err = struct_span_err!(self.tcx.sess, span, E0482,
933                           "lifetime of return value does not outlive \
934                            the function call");
935                 self.tcx.note_and_explain_region(&mut err,
936                     "the return value is only valid for ",
937                     sup,
938                     "");
939                 err
940             }
941             infer::Operand(span) => {
942                 let mut err = struct_span_err!(self.tcx.sess, span, E0483,
943                           "lifetime of operand does not outlive \
944                            the operation");
945                 self.tcx.note_and_explain_region(&mut err,
946                     "the operand is only valid for ",
947                     sup,
948                     "");
949                 err
950             }
951             infer::AddrOf(span) => {
952                 let mut err = struct_span_err!(self.tcx.sess, span, E0484,
953                           "reference is not valid at the time of borrow");
954                 self.tcx.note_and_explain_region(&mut err,
955                     "the borrow is only valid for ",
956                     sup,
957                     "");
958                 err
959             }
960             infer::AutoBorrow(span) => {
961                 let mut err = struct_span_err!(self.tcx.sess, span, E0485,
962                           "automatically reference is not valid \
963                            at the time of borrow");
964                 self.tcx.note_and_explain_region(&mut err,
965                     "the automatic borrow is only valid for ",
966                     sup,
967                     "");
968                 err
969             }
970             infer::ExprTypeIsNotInScope(t, span) => {
971                 let mut err = struct_span_err!(self.tcx.sess, span, E0486,
972                           "type of expression contains references \
973                            that are not valid during the expression: `{}`",
974                           self.ty_to_string(t));
975                 self.tcx.note_and_explain_region(&mut err,
976                     "type is only valid for ",
977                     sup,
978                     "");
979                 err
980             }
981             infer::SafeDestructor(span) => {
982                 let mut err = struct_span_err!(self.tcx.sess, span, E0487,
983                           "unsafe use of destructor: destructor might be called \
984                            while references are dead");
985                 // FIXME (22171): terms "super/subregion" are suboptimal
986                 self.tcx.note_and_explain_region(&mut err,
987                     "superregion: ",
988                     sup,
989                     "");
990                 self.tcx.note_and_explain_region(&mut err,
991                     "subregion: ",
992                     sub,
993                     "");
994                 err
995             }
996             infer::BindingTypeIsNotValidAtDecl(span) => {
997                 let mut err = struct_span_err!(self.tcx.sess, span, E0488,
998                           "lifetime of variable does not enclose its declaration");
999                 self.tcx.note_and_explain_region(&mut err,
1000                     "the variable is only valid for ",
1001                     sup,
1002                     "");
1003                 err
1004             }
1005             infer::ParameterInScope(_, span) => {
1006                 let mut err = struct_span_err!(self.tcx.sess, span, E0489,
1007                           "type/lifetime parameter not in scope here");
1008                 self.tcx.note_and_explain_region(&mut err,
1009                     "the parameter is only valid for ",
1010                     sub,
1011                     "");
1012                 err
1013             }
1014             infer::DataBorrowed(ty, span) => {
1015                 let mut err = struct_span_err!(self.tcx.sess, span, E0490,
1016                           "a value of type `{}` is borrowed for too long",
1017                           self.ty_to_string(ty));
1018                 self.tcx.note_and_explain_region(&mut err, "the type is valid for ", sub, "");
1019                 self.tcx.note_and_explain_region(&mut err, "but the borrow lasts for ", sup, "");
1020                 err
1021             }
1022             infer::ReferenceOutlivesReferent(ty, span) => {
1023                 let mut err = struct_span_err!(self.tcx.sess, span, E0491,
1024                           "in type `{}`, reference has a longer lifetime \
1025                            than the data it references",
1026                           self.ty_to_string(ty));
1027                 self.tcx.note_and_explain_region(&mut err,
1028                     "the pointer is valid for ",
1029                     sub,
1030                     "");
1031                 self.tcx.note_and_explain_region(&mut err,
1032                     "but the referenced data is only valid for ",
1033                     sup,
1034                     "");
1035                 err
1036             }
1037             infer::CompareImplMethodObligation { span,
1038                                                  item_name,
1039                                                  impl_item_def_id,
1040                                                  trait_item_def_id,
1041                                                  lint_id } => {
1042                 self.report_extra_impl_obligation(span,
1043                                                   item_name,
1044                                                   impl_item_def_id,
1045                                                   trait_item_def_id,
1046                                                   &format!("`{}: {}`", sup, sub),
1047                                                   lint_id)
1048             }
1049         }
1050     }
1051
1052     fn report_sub_sup_conflict(&self,
1053                                var_origin: RegionVariableOrigin,
1054                                sub_origin: SubregionOrigin<'tcx>,
1055                                sub_region: &'tcx Region,
1056                                sup_origin: SubregionOrigin<'tcx>,
1057                                sup_region: &'tcx Region) {
1058         let mut err = self.report_inference_failure(var_origin);
1059
1060         self.tcx.note_and_explain_region(&mut err,
1061             "first, the lifetime cannot outlive ",
1062             sup_region,
1063             "...");
1064
1065         self.note_region_origin(&mut err, &sup_origin);
1066
1067         self.tcx.note_and_explain_region(&mut err,
1068             "but, the lifetime must be valid for ",
1069             sub_region,
1070             "...");
1071
1072         self.note_region_origin(&mut err, &sub_origin);
1073         err.emit();
1074     }
1075
1076     fn report_processed_errors(&self,
1077                                origins: &[ProcessedErrorOrigin<'tcx>]) {
1078         for origin in origins.iter() {
1079             let mut err = match *origin {
1080                 ProcessedErrorOrigin::VariableFailure(ref var_origin) =>
1081                     self.report_inference_failure(var_origin.clone()),
1082                 ProcessedErrorOrigin::ConcreteFailure(ref sr_origin, sub, sup) =>
1083                     self.report_concrete_failure(sr_origin.clone(), sub, sup),
1084             };
1085
1086             err.emit();
1087         }
1088     }
1089 }
1090
1091 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1092     fn report_inference_failure(&self,
1093                                 var_origin: RegionVariableOrigin)
1094                                 -> DiagnosticBuilder<'tcx> {
1095         let br_string = |br: ty::BoundRegion| {
1096             let mut s = br.to_string();
1097             if !s.is_empty() {
1098                 s.push_str(" ");
1099             }
1100             s
1101         };
1102         let var_description = match var_origin {
1103             infer::MiscVariable(_) => "".to_string(),
1104             infer::PatternRegion(_) => " for pattern".to_string(),
1105             infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1106             infer::Autoref(_) => " for autoref".to_string(),
1107             infer::Coercion(_) => " for automatic coercion".to_string(),
1108             infer::LateBoundRegion(_, br, infer::FnCall) => {
1109                 format!(" for lifetime parameter {}in function call",
1110                         br_string(br))
1111             }
1112             infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1113                 format!(" for lifetime parameter {}in generic type", br_string(br))
1114             }
1115             infer::LateBoundRegion(_, br, infer::AssocTypeProjection(type_name)) => {
1116                 format!(" for lifetime parameter {}in trait containing associated type `{}`",
1117                         br_string(br), type_name)
1118             }
1119             infer::EarlyBoundRegion(_, name, _) => {
1120                 format!(" for lifetime parameter `{}`",
1121                         name)
1122             }
1123             infer::BoundRegionInCoherence(name) => {
1124                 format!(" for lifetime parameter `{}` in coherence check",
1125                         name)
1126             }
1127             infer::UpvarRegion(ref upvar_id, _) => {
1128                 format!(" for capture of `{}` by closure",
1129                         self.tcx.local_var_name_str(upvar_id.var_id).to_string())
1130             }
1131         };
1132
1133         struct_span_err!(self.tcx.sess, var_origin.span(), E0495,
1134                   "cannot infer an appropriate lifetime{} \
1135                    due to conflicting requirements",
1136                   var_description)
1137     }
1138
1139     fn note_region_origin(&self, err: &mut DiagnosticBuilder, origin: &SubregionOrigin<'tcx>) {
1140         match *origin {
1141             infer::Subtype(ref trace) => {
1142                 if let Some((expected, found)) = self.values_str(&trace.values) {
1143                     // FIXME: do we want a "the" here?
1144                     err.span_note(
1145                         trace.cause.span,
1146                         &format!("...so that {} (expected {}, found {})",
1147                                  trace.cause.as_requirement_str(), expected, found));
1148                 } else {
1149                     // FIXME: this really should be handled at some earlier stage. Our
1150                     // handling of region checking when type errors are present is
1151                     // *terrible*.
1152
1153                     err.span_note(
1154                         trace.cause.span,
1155                         &format!("...so that {}",
1156                                  trace.cause.as_requirement_str()));
1157                 }
1158             }
1159             infer::Reborrow(span) => {
1160                 err.span_note(
1161                     span,
1162                     "...so that reference does not outlive \
1163                     borrowed content");
1164             }
1165             infer::ReborrowUpvar(span, ref upvar_id) => {
1166                 err.span_note(
1167                     span,
1168                     &format!(
1169                         "...so that closure can access `{}`",
1170                         self.tcx.local_var_name_str(upvar_id.var_id)
1171                             .to_string()));
1172             }
1173             infer::InfStackClosure(span) => {
1174                 err.span_note(
1175                     span,
1176                     "...so that closure does not outlive its stack frame");
1177             }
1178             infer::InvokeClosure(span) => {
1179                 err.span_note(
1180                     span,
1181                     "...so that closure is not invoked outside its lifetime");
1182             }
1183             infer::DerefPointer(span) => {
1184                 err.span_note(
1185                     span,
1186                     "...so that pointer is not dereferenced \
1187                     outside its lifetime");
1188             }
1189             infer::FreeVariable(span, id) => {
1190                 err.span_note(
1191                     span,
1192                     &format!("...so that captured variable `{}` \
1193                             does not outlive the enclosing closure",
1194                             self.tcx.local_var_name_str(id)));
1195             }
1196             infer::IndexSlice(span) => {
1197                 err.span_note(
1198                     span,
1199                     "...so that slice is not indexed outside the lifetime");
1200             }
1201             infer::RelateObjectBound(span) => {
1202                 err.span_note(
1203                     span,
1204                     "...so that it can be closed over into an object");
1205             }
1206             infer::CallRcvr(span) => {
1207                 err.span_note(
1208                     span,
1209                     "...so that method receiver is valid for the method call");
1210             }
1211             infer::CallArg(span) => {
1212                 err.span_note(
1213                     span,
1214                     "...so that argument is valid for the call");
1215             }
1216             infer::CallReturn(span) => {
1217                 err.span_note(
1218                     span,
1219                     "...so that return value is valid for the call");
1220             }
1221             infer::Operand(span) => {
1222                 err.span_note(
1223                     span,
1224                     "...so that operand is valid for operation");
1225             }
1226             infer::AddrOf(span) => {
1227                 err.span_note(
1228                     span,
1229                     "...so that reference is valid \
1230                      at the time of borrow");
1231             }
1232             infer::AutoBorrow(span) => {
1233                 err.span_note(
1234                     span,
1235                     "...so that auto-reference is valid \
1236                      at the time of borrow");
1237             }
1238             infer::ExprTypeIsNotInScope(t, span) => {
1239                 err.span_note(
1240                     span,
1241                     &format!("...so type `{}` of expression is valid during the \
1242                              expression",
1243                             self.ty_to_string(t)));
1244             }
1245             infer::BindingTypeIsNotValidAtDecl(span) => {
1246                 err.span_note(
1247                     span,
1248                     "...so that variable is valid at time of its declaration");
1249             }
1250             infer::ParameterInScope(_, span) => {
1251                 err.span_note(
1252                     span,
1253                     "...so that a type/lifetime parameter is in scope here");
1254             }
1255             infer::DataBorrowed(ty, span) => {
1256                 err.span_note(
1257                     span,
1258                     &format!("...so that the type `{}` is not borrowed for too long",
1259                              self.ty_to_string(ty)));
1260             }
1261             infer::ReferenceOutlivesReferent(ty, span) => {
1262                 err.span_note(
1263                     span,
1264                     &format!("...so that the reference type `{}` \
1265                              does not outlive the data it points at",
1266                             self.ty_to_string(ty)));
1267             }
1268             infer::RelateParamBound(span, t) => {
1269                 err.span_note(
1270                     span,
1271                     &format!("...so that the type `{}` \
1272                              will meet its required lifetime bounds",
1273                             self.ty_to_string(t)));
1274             }
1275             infer::RelateDefaultParamBound(span, t) => {
1276                 err.span_note(
1277                     span,
1278                     &format!("...so that type parameter \
1279                              instantiated with `{}`, \
1280                              will meet its declared lifetime bounds",
1281                             self.ty_to_string(t)));
1282             }
1283             infer::RelateRegionParamBound(span) => {
1284                 err.span_note(
1285                     span,
1286                     "...so that the declared lifetime parameter bounds \
1287                                 are satisfied");
1288             }
1289             infer::SafeDestructor(span) => {
1290                 err.span_note(
1291                     span,
1292                     "...so that references are valid when the destructor \
1293                      runs");
1294             }
1295             infer::CompareImplMethodObligation { span, .. } => {
1296                 err.span_note(
1297                     span,
1298                     "...so that the definition in impl matches the definition from the trait");
1299             }
1300         }
1301     }
1302 }
1303
1304 impl<'tcx> ObligationCause<'tcx> {
1305     fn as_failure_str(&self) -> &'static str {
1306         use traits::ObligationCauseCode::*;
1307         match self.code {
1308             CompareImplMethodObligation { .. } => "method not compatible with trait",
1309             MatchExpressionArm { source, .. } => match source {
1310                 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have incompatible types",
1311                 _ => "match arms have incompatible types",
1312             },
1313             IfExpression => "if and else have incompatible types",
1314             IfExpressionWithNoElse => "if may be missing an else clause",
1315             EquatePredicate => "equality predicate not satisfied",
1316             MainFunctionType => "main function has wrong type",
1317             StartFunctionType => "start function has wrong type",
1318             IntrinsicType => "intrinsic has wrong type",
1319             MethodReceiver => "mismatched method receiver",
1320             _ => "mismatched types",
1321         }
1322     }
1323
1324     fn as_requirement_str(&self) -> &'static str {
1325         use traits::ObligationCauseCode::*;
1326         match self.code {
1327             CompareImplMethodObligation { .. } => "method type is compatible with trait",
1328             ExprAssignable => "expression is assignable",
1329             MatchExpressionArm { source, .. } => match source {
1330                 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have compatible types",
1331                 _ => "match arms have compatible types",
1332             },
1333             IfExpression => "if and else have compatible types",
1334             IfExpressionWithNoElse => "if missing an else returns ()",
1335             EquatePredicate => "equality where clause is satisfied",
1336             MainFunctionType => "`main` function has the correct type",
1337             StartFunctionType => "`start` function has the correct type",
1338             IntrinsicType => "intrinsic has the correct type",
1339             MethodReceiver => "method receiver has the correct type",
1340             _ => "types are compatible",
1341         }
1342     }
1343 }