]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/error_reporting/mod.rs
da93156b0b0bd53c2acfd930d7346b08bbbca934
[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 catalog 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, RegionVariableOrigin, SubregionOrigin, TypeTrace, ValuePairs};
60 use super::region_constraints::GenericKind;
61 use super::lexical_region_resolve::RegionResolutionError;
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, Region, Ty, TyCtxt, TypeFoldable, TypeVariants};
70 use ty::error::TypeError;
71 use syntax::ast::DUMMY_NODE_ID;
72 use syntax_pos::{Pos, Span};
73 use errors::{DiagnosticBuilder, DiagnosticStyledString};
74
75 use rustc_data_structures::indexed_vec::Idx;
76
77 mod note;
78
79 mod need_type_info;
80
81 pub mod nice_region_error;
82
83 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
84     pub fn note_and_explain_region(
85         self,
86         region_scope_tree: &region::ScopeTree,
87         err: &mut DiagnosticBuilder,
88         prefix: &str,
89         region: ty::Region<'tcx>,
90         suffix: &str,
91     ) {
92         let (description, span) = match *region {
93             ty::ReScope(scope) => {
94                 let new_string;
95                 let unknown_scope = || {
96                     format!(
97                         "{}unknown scope: {:?}{}.  Please report a bug.",
98                         prefix, scope, suffix
99                     )
100                 };
101                 let span = scope.span(self, region_scope_tree);
102                 let tag = match self.hir.find(scope.node_id(self, region_scope_tree)) {
103                     Some(hir_map::NodeBlock(_)) => "block",
104                     Some(hir_map::NodeExpr(expr)) => match expr.node {
105                         hir::ExprCall(..) => "call",
106                         hir::ExprMethodCall(..) => "method call",
107                         hir::ExprMatch(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
108                         hir::ExprMatch(.., hir::MatchSource::WhileLetDesugar) => "while let",
109                         hir::ExprMatch(.., hir::MatchSource::ForLoopDesugar) => "for",
110                         hir::ExprMatch(..) => "match",
111                         _ => "expression",
112                     },
113                     Some(hir_map::NodeStmt(_)) => "statement",
114                     Some(hir_map::NodeItem(it)) => Self::item_scope_tag(&it),
115                     Some(hir_map::NodeTraitItem(it)) => Self::trait_item_scope_tag(&it),
116                     Some(hir_map::NodeImplItem(it)) => Self::impl_item_scope_tag(&it),
117                     Some(_) | None => {
118                         err.span_note(span, &unknown_scope());
119                         return;
120                     }
121                 };
122                 let scope_decorated_tag = match scope.data() {
123                     region::ScopeData::Node(_) => tag,
124                     region::ScopeData::CallSite(_) => "scope of call-site for function",
125                     region::ScopeData::Arguments(_) => "scope of function body",
126                     region::ScopeData::Destruction(_) => {
127                         new_string = format!("destruction scope surrounding {}", tag);
128                         &new_string[..]
129                     }
130                     region::ScopeData::Remainder(r) => {
131                         new_string = format!(
132                             "block suffix following statement {}",
133                             r.first_statement_index.index()
134                         );
135                         &new_string[..]
136                     }
137                 };
138                 self.explain_span(scope_decorated_tag, span)
139             }
140
141             ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
142                 self.msg_span_from_free_region(region)
143             }
144
145             ty::ReEmpty => ("the empty lifetime".to_owned(), None),
146
147             // FIXME(#13998) ReSkolemized should probably print like
148             // ReFree rather than dumping Debug output on the user.
149             //
150             // We shouldn't really be having unification failures with ReVar
151             // and ReLateBound though.
152             ty::ReSkolemized(..) | ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
153                 (format!("lifetime {:?}", region), None)
154             }
155
156             // We shouldn't encounter an error message with ReClosureBound.
157             ty::ReCanonical(..) |
158             ty::ReClosureBound(..) => {
159                 bug!("encountered unexpected ReClosureBound: {:?}", region,);
160             }
161         };
162
163         TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
164     }
165
166     pub fn note_and_explain_free_region(
167         self,
168         err: &mut DiagnosticBuilder,
169         prefix: &str,
170         region: ty::Region<'tcx>,
171         suffix: &str,
172     ) {
173         let (description, span) = self.msg_span_from_free_region(region);
174
175         TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
176     }
177
178     fn msg_span_from_free_region(self, region: ty::Region<'tcx>) -> (String, Option<Span>) {
179         match *region {
180             ty::ReEarlyBound(_) | ty::ReFree(_)  => {
181                 self.msg_span_from_early_bound_and_free_regions(region)
182             },
183             ty::ReStatic => ("the static lifetime".to_owned(), None),
184             _ => bug!("{:?}", region),
185         }
186     }
187
188     fn msg_span_from_early_bound_and_free_regions(
189         self,
190         region: ty::Region<'tcx>,
191     ) -> (String, Option<Span>) {
192         let scope = region.free_region_binding_scope(self);
193         let node = self.hir.as_local_node_id(scope).unwrap_or(DUMMY_NODE_ID);
194         let unknown;
195         let tag = match self.hir.find(node) {
196             Some(hir_map::NodeBlock(_)) | Some(hir_map::NodeExpr(_)) => "body",
197             Some(hir_map::NodeItem(it)) => Self::item_scope_tag(&it),
198             Some(hir_map::NodeTraitItem(it)) => Self::trait_item_scope_tag(&it),
199             Some(hir_map::NodeImplItem(it)) => Self::impl_item_scope_tag(&it),
200
201             // this really should not happen, but it does:
202             // FIXME(#27942)
203             Some(_) => {
204                 unknown = format!(
205                     "unexpected node ({}) for scope {:?}.  \
206                      Please report a bug.",
207                     self.hir.node_to_string(node),
208                     scope
209                 );
210                 &unknown
211             }
212             None => {
213                 unknown = format!(
214                     "unknown node for scope {:?}.  \
215                      Please report a bug.",
216                     scope
217                 );
218                 &unknown
219             }
220         };
221         let (prefix, span) = match *region {
222             ty::ReEarlyBound(ref br) => (
223                 format!("the lifetime {} as defined on", br.name),
224                 self.sess.codemap().def_span(self.hir.span(node)),
225             ),
226             ty::ReFree(ref fr) => match fr.bound_region {
227                 ty::BrAnon(idx) => (
228                     format!("the anonymous lifetime #{} defined on", idx + 1),
229                     self.hir.span(node),
230                 ),
231                 ty::BrFresh(_) => (
232                     "an anonymous lifetime defined on".to_owned(),
233                     self.hir.span(node),
234                 ),
235                 _ => (
236                     format!("the lifetime {} as defined on", fr.bound_region),
237                     self.sess.codemap().def_span(self.hir.span(node)),
238                 ),
239             },
240             _ => bug!(),
241         };
242         let (msg, opt_span) = self.explain_span(tag, span);
243         (format!("{} {}", prefix, msg), opt_span)
244     }
245
246     fn emit_msg_span(
247         err: &mut DiagnosticBuilder,
248         prefix: &str,
249         description: String,
250         span: Option<Span>,
251         suffix: &str,
252     ) {
253         let message = format!("{}{}{}", prefix, description, suffix);
254
255         if let Some(span) = span {
256             err.span_note(span, &message);
257         } else {
258             err.note(&message);
259         }
260     }
261
262     fn item_scope_tag(item: &hir::Item) -> &'static str {
263         match item.node {
264             hir::ItemImpl(..) => "impl",
265             hir::ItemStruct(..) => "struct",
266             hir::ItemUnion(..) => "union",
267             hir::ItemEnum(..) => "enum",
268             hir::ItemTrait(..) => "trait",
269             hir::ItemFn(..) => "function body",
270             _ => "item",
271         }
272     }
273
274     fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
275         match item.node {
276             hir::TraitItemKind::Method(..) => "method body",
277             hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => "associated item",
278         }
279     }
280
281     fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
282         match item.node {
283             hir::ImplItemKind::Method(..) => "method body",
284             hir::ImplItemKind::Const(..) | hir::ImplItemKind::Type(_) => "associated item",
285         }
286     }
287
288     fn explain_span(self, heading: &str, span: Span) -> (String, Option<Span>) {
289         let lo = self.sess.codemap().lookup_char_pos_adj(span.lo());
290         (
291             format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1),
292             Some(span),
293         )
294     }
295 }
296
297 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
298     pub fn report_region_errors(
299         &self,
300         region_scope_tree: &region::ScopeTree,
301         errors: &Vec<RegionResolutionError<'tcx>>,
302         will_later_be_reported_by_nll: bool,
303     ) {
304         debug!("report_region_errors(): {} errors to start", errors.len());
305
306         if will_later_be_reported_by_nll && self.tcx.use_mir_borrowck() {
307             // With `#![feature(nll)]`, we want to present a nice user
308             // experience, so don't even mention the errors from the
309             // AST checker.
310             if self.tcx.features().nll {
311                 return;
312             }
313
314             // But with nll, it's nice to have some note for later.
315             for error in errors {
316                 match *error {
317                     RegionResolutionError::ConcreteFailure(ref origin, ..)
318                     | RegionResolutionError::GenericBoundFailure(ref origin, ..) => {
319                         self.tcx
320                             .sess
321                             .span_warn(origin.span(), "not reporting region error due to nll");
322                     }
323
324                     RegionResolutionError::SubSupConflict(ref rvo, ..) => {
325                         self.tcx
326                             .sess
327                             .span_warn(rvo.span(), "not reporting region error due to nll");
328                     }
329                 }
330             }
331
332             return;
333         }
334
335         // try to pre-process the errors, which will group some of them
336         // together into a `ProcessedErrors` group:
337         let errors = self.process_errors(errors);
338
339         debug!(
340             "report_region_errors: {} errors after preprocessing",
341             errors.len()
342         );
343
344         for error in errors {
345             debug!("report_region_errors: error = {:?}", error);
346
347             if !self.try_report_nice_region_error(&error) {
348                 match error.clone() {
349                     // These errors could indicate all manner of different
350                     // problems with many different solutions. Rather
351                     // than generate a "one size fits all" error, what we
352                     // attempt to do is go through a number of specific
353                     // scenarios and try to find the best way to present
354                     // the error. If all of these fails, we fall back to a rather
355                     // general bit of code that displays the error information
356                     RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
357                         self.report_concrete_failure(region_scope_tree, origin, sub, sup)
358                             .emit();
359                     }
360
361                     RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
362                         self.report_generic_bound_failure(
363                             region_scope_tree,
364                             origin.span(),
365                             Some(origin),
366                             param_ty,
367                             sub,
368                         );
369                     }
370
371                     RegionResolutionError::SubSupConflict(
372                         var_origin,
373                         sub_origin,
374                         sub_r,
375                         sup_origin,
376                         sup_r,
377                     ) => {
378                         self.report_sub_sup_conflict(
379                             region_scope_tree,
380                             var_origin,
381                             sub_origin,
382                             sub_r,
383                             sup_origin,
384                             sup_r,
385                         );
386                     }
387                 }
388             }
389         }
390     }
391
392     // This method goes through all the errors and try to group certain types
393     // of error together, for the purpose of suggesting explicit lifetime
394     // parameters to the user. This is done so that we can have a more
395     // complete view of what lifetimes should be the same.
396     // If the return value is an empty vector, it means that processing
397     // failed (so the return value of this method should not be used).
398     //
399     // The method also attempts to weed out messages that seem like
400     // duplicates that will be unhelpful to the end-user. But
401     // obviously it never weeds out ALL errors.
402     fn process_errors(
403         &self,
404         errors: &Vec<RegionResolutionError<'tcx>>,
405     ) -> Vec<RegionResolutionError<'tcx>> {
406         debug!("process_errors()");
407
408         // We want to avoid reporting generic-bound failures if we can
409         // avoid it: these have a very high rate of being unhelpful in
410         // practice. This is because they are basically secondary
411         // checks that test the state of the region graph after the
412         // rest of inference is done, and the other kinds of errors
413         // indicate that the region constraint graph is internally
414         // inconsistent, so these test results are likely to be
415         // meaningless.
416         //
417         // Therefore, we filter them out of the list unless they are
418         // the only thing in the list.
419
420         let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
421             RegionResolutionError::GenericBoundFailure(..) => true,
422             RegionResolutionError::ConcreteFailure(..)
423             | RegionResolutionError::SubSupConflict(..) => false,
424         };
425
426         let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
427             errors.clone()
428         } else {
429             errors
430                 .iter()
431                 .filter(|&e| !is_bound_failure(e))
432                 .cloned()
433                 .collect()
434         };
435
436         // sort the errors by span, for better error message stability.
437         errors.sort_by_key(|u| match *u {
438             RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
439             RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
440             RegionResolutionError::SubSupConflict(ref rvo, _, _, _, _) => rvo.span(),
441         });
442         errors
443     }
444
445     /// Adds a note if the types come from similarly named crates
446     fn check_and_note_conflicting_crates(
447         &self,
448         err: &mut DiagnosticBuilder,
449         terr: &TypeError<'tcx>,
450         sp: Span,
451     ) {
452         let report_path_match = |err: &mut DiagnosticBuilder, did1: DefId, did2: DefId| {
453             // Only external crates, if either is from a local
454             // module we could have false positives
455             if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
456                 let exp_path = self.tcx.item_path_str(did1);
457                 let found_path = self.tcx.item_path_str(did2);
458                 let exp_abs_path = self.tcx.absolute_item_path_str(did1);
459                 let found_abs_path = self.tcx.absolute_item_path_str(did2);
460                 // We compare strings because DefPath can be different
461                 // for imported and non-imported crates
462                 if exp_path == found_path || exp_abs_path == found_abs_path {
463                     let crate_name = self.tcx.crate_name(did1.krate);
464                     err.span_note(
465                         sp,
466                         &format!(
467                             "Perhaps two different versions \
468                              of crate `{}` are being used?",
469                             crate_name
470                         ),
471                     );
472                 }
473             }
474         };
475         match *terr {
476             TypeError::Sorts(ref exp_found) => {
477                 // if they are both "path types", there's a chance of ambiguity
478                 // due to different versions of the same crate
479                 match (&exp_found.expected.sty, &exp_found.found.sty) {
480                     (&ty::TyAdt(exp_adt, _), &ty::TyAdt(found_adt, _)) => {
481                         report_path_match(err, exp_adt.did, found_adt.did);
482                     }
483                     _ => (),
484                 }
485             }
486             TypeError::Traits(ref exp_found) => {
487                 report_path_match(err, exp_found.expected, exp_found.found);
488             }
489             _ => (), // FIXME(#22750) handle traits and stuff
490         }
491     }
492
493     fn note_error_origin(&self, err: &mut DiagnosticBuilder<'tcx>, cause: &ObligationCause<'tcx>) {
494         match cause.code {
495             ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
496                 hir::MatchSource::IfLetDesugar { .. } => {
497                     let msg = "`if let` arm with an incompatible type";
498                     if self.tcx.sess.codemap().is_multiline(arm_span) {
499                         err.span_note(arm_span, msg);
500                     } else {
501                         err.span_label(arm_span, msg);
502                     }
503                 }
504                 _ => {
505                     let msg = "match arm with an incompatible type";
506                     if self.tcx.sess.codemap().is_multiline(arm_span) {
507                         err.span_note(arm_span, msg);
508                     } else {
509                         err.span_label(arm_span, msg);
510                     }
511                 }
512             },
513             _ => (),
514         }
515     }
516
517     /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
518     /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
519     /// populate `other_value` with `other_ty`.
520     ///
521     /// ```text
522     /// Foo<Bar<Qux>>
523     /// ^^^^--------^ this is highlighted
524     /// |   |
525     /// |   this type argument is exactly the same as the other type, not highlighted
526     /// this is highlighted
527     /// Bar<Qux>
528     /// -------- this type is the same as a type argument in the other type, not highlighted
529     /// ```
530     fn highlight_outer(
531         &self,
532         value: &mut DiagnosticStyledString,
533         other_value: &mut DiagnosticStyledString,
534         name: String,
535         sub: &ty::subst::Substs<'tcx>,
536         pos: usize,
537         other_ty: &Ty<'tcx>,
538     ) {
539         // `value` and `other_value` hold two incomplete type representation for display.
540         // `name` is the path of both types being compared. `sub`
541         value.push_highlighted(name);
542         let len = sub.len();
543         if len > 0 {
544             value.push_highlighted("<");
545         }
546
547         // Output the lifetimes fot the first type
548         let lifetimes = sub.regions()
549             .map(|lifetime| {
550                 let s = format!("{}", lifetime);
551                 if s.is_empty() {
552                     "'_".to_string()
553                 } else {
554                     s
555                 }
556             })
557             .collect::<Vec<_>>()
558             .join(", ");
559         if !lifetimes.is_empty() {
560             if sub.regions().count() < len {
561                 value.push_normal(lifetimes + &", ");
562             } else {
563                 value.push_normal(lifetimes);
564             }
565         }
566
567         // Highlight all the type arguments that aren't at `pos` and compare the type argument at
568         // `pos` and `other_ty`.
569         for (i, type_arg) in sub.types().enumerate() {
570             if i == pos {
571                 let values = self.cmp(type_arg, other_ty);
572                 value.0.extend((values.0).0);
573                 other_value.0.extend((values.1).0);
574             } else {
575                 value.push_highlighted(format!("{}", type_arg));
576             }
577
578             if len > 0 && i != len - 1 {
579                 value.push_normal(", ");
580             }
581             //self.push_comma(&mut value, &mut other_value, len, i);
582         }
583         if len > 0 {
584             value.push_highlighted(">");
585         }
586     }
587
588     /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
589     /// as that is the difference to the other type.
590     ///
591     /// For the following code:
592     ///
593     /// ```norun
594     /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
595     /// ```
596     ///
597     /// The type error output will behave in the following way:
598     ///
599     /// ```text
600     /// Foo<Bar<Qux>>
601     /// ^^^^--------^ this is highlighted
602     /// |   |
603     /// |   this type argument is exactly the same as the other type, not highlighted
604     /// this is highlighted
605     /// Bar<Qux>
606     /// -------- this type is the same as a type argument in the other type, not highlighted
607     /// ```
608     fn cmp_type_arg(
609         &self,
610         mut t1_out: &mut DiagnosticStyledString,
611         mut t2_out: &mut DiagnosticStyledString,
612         path: String,
613         sub: &ty::subst::Substs<'tcx>,
614         other_path: String,
615         other_ty: &Ty<'tcx>,
616     ) -> Option<()> {
617         for (i, ta) in sub.types().enumerate() {
618             if &ta == other_ty {
619                 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
620                 return Some(());
621             }
622             if let &ty::TyAdt(def, _) = &ta.sty {
623                 let path_ = self.tcx.item_path_str(def.did.clone());
624                 if path_ == other_path {
625                     self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
626                     return Some(());
627                 }
628             }
629         }
630         None
631     }
632
633     /// Add a `,` to the type representation only if it is appropriate.
634     fn push_comma(
635         &self,
636         value: &mut DiagnosticStyledString,
637         other_value: &mut DiagnosticStyledString,
638         len: usize,
639         pos: usize,
640     ) {
641         if len > 0 && pos != len - 1 {
642             value.push_normal(", ");
643             other_value.push_normal(", ");
644         }
645     }
646
647     /// Compare two given types, eliding parts that are the same between them and highlighting
648     /// relevant differences, and return two representation of those types for highlighted printing.
649     fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
650         fn equals<'tcx>(a: &Ty<'tcx>, b: &Ty<'tcx>) -> bool {
651             match (&a.sty, &b.sty) {
652                 (a, b) if *a == *b => true,
653                 (&ty::TyInt(_), &ty::TyInfer(ty::InferTy::IntVar(_)))
654                 | (&ty::TyInfer(ty::InferTy::IntVar(_)), &ty::TyInt(_))
655                 | (&ty::TyInfer(ty::InferTy::IntVar(_)), &ty::TyInfer(ty::InferTy::IntVar(_)))
656                 | (&ty::TyFloat(_), &ty::TyInfer(ty::InferTy::FloatVar(_)))
657                 | (&ty::TyInfer(ty::InferTy::FloatVar(_)), &ty::TyFloat(_))
658                 | (
659                     &ty::TyInfer(ty::InferTy::FloatVar(_)),
660                     &ty::TyInfer(ty::InferTy::FloatVar(_)),
661                 ) => true,
662                 _ => false,
663             }
664         }
665
666         fn push_ty_ref<'tcx>(
667             r: &ty::Region<'tcx>,
668             ty: Ty<'tcx>,
669             mutbl: hir::Mutability,
670             s: &mut DiagnosticStyledString,
671         ) {
672             let r = &format!("{}", r);
673             s.push_highlighted(format!(
674                 "&{}{}{}",
675                 r,
676                 if r == "" { "" } else { " " },
677                 if mutbl == hir::MutMutable {
678                     "mut "
679                 } else {
680                     ""
681                 }
682             ));
683             s.push_normal(format!("{}", ty));
684         }
685
686         match (&t1.sty, &t2.sty) {
687             (&ty::TyAdt(def1, sub1), &ty::TyAdt(def2, sub2)) => {
688                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
689                 let path1 = self.tcx.item_path_str(def1.did.clone());
690                 let path2 = self.tcx.item_path_str(def2.did.clone());
691                 if def1.did == def2.did {
692                     // Easy case. Replace same types with `_` to shorten the output and highlight
693                     // the differing ones.
694                     //     let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
695                     //     Foo<Bar, _>
696                     //     Foo<Quz, _>
697                     //         ---  ^ type argument elided
698                     //         |
699                     //         highlighted in output
700                     values.0.push_normal(path1);
701                     values.1.push_normal(path2);
702
703                     // Only draw `<...>` if there're lifetime/type arguments.
704                     let len = sub1.len();
705                     if len > 0 {
706                         values.0.push_normal("<");
707                         values.1.push_normal("<");
708                     }
709
710                     fn lifetime_display(lifetime: Region) -> String {
711                         let s = format!("{}", lifetime);
712                         if s.is_empty() {
713                             "'_".to_string()
714                         } else {
715                             s
716                         }
717                     }
718                     // At one point we'd like to elide all lifetimes here, they are irrelevant for
719                     // all diagnostics that use this output
720                     //
721                     //     Foo<'x, '_, Bar>
722                     //     Foo<'y, '_, Qux>
723                     //         ^^  ^^  --- type arguments are not elided
724                     //         |   |
725                     //         |   elided as they were the same
726                     //         not elided, they were different, but irrelevant
727                     let lifetimes = sub1.regions().zip(sub2.regions());
728                     for (i, lifetimes) in lifetimes.enumerate() {
729                         let l1 = lifetime_display(lifetimes.0);
730                         let l2 = lifetime_display(lifetimes.1);
731                         if l1 == l2 {
732                             values.0.push_normal("'_");
733                             values.1.push_normal("'_");
734                         } else {
735                             values.0.push_highlighted(l1);
736                             values.1.push_highlighted(l2);
737                         }
738                         self.push_comma(&mut values.0, &mut values.1, len, i);
739                     }
740
741                     // We're comparing two types with the same path, so we compare the type
742                     // arguments for both. If they are the same, do not highlight and elide from the
743                     // output.
744                     //     Foo<_, Bar>
745                     //     Foo<_, Qux>
746                     //         ^ elided type as this type argument was the same in both sides
747                     let type_arguments = sub1.types().zip(sub2.types());
748                     let regions_len = sub1.regions().collect::<Vec<_>>().len();
749                     for (i, (ta1, ta2)) in type_arguments.enumerate() {
750                         let i = i + regions_len;
751                         if ta1 == ta2 {
752                             values.0.push_normal("_");
753                             values.1.push_normal("_");
754                         } else {
755                             let (x1, x2) = self.cmp(ta1, ta2);
756                             (values.0).0.extend(x1.0);
757                             (values.1).0.extend(x2.0);
758                         }
759                         self.push_comma(&mut values.0, &mut values.1, len, i);
760                     }
761
762                     // Close the type argument bracket.
763                     // Only draw `<...>` if there're lifetime/type arguments.
764                     if len > 0 {
765                         values.0.push_normal(">");
766                         values.1.push_normal(">");
767                     }
768                     values
769                 } else {
770                     // Check for case:
771                     //     let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
772                     //     Foo<Bar<Qux>
773                     //         ------- this type argument is exactly the same as the other type
774                     //     Bar<Qux>
775                     if self.cmp_type_arg(
776                         &mut values.0,
777                         &mut values.1,
778                         path1.clone(),
779                         sub1,
780                         path2.clone(),
781                         &t2,
782                     ).is_some()
783                     {
784                         return values;
785                     }
786                     // Check for case:
787                     //     let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
788                     //     Bar<Qux>
789                     //     Foo<Bar<Qux>>
790                     //         ------- this type argument is exactly the same as the other type
791                     if self.cmp_type_arg(&mut values.1, &mut values.0, path2, sub2, path1, &t1)
792                         .is_some()
793                     {
794                         return values;
795                     }
796
797                     // We couldn't find anything in common, highlight everything.
798                     //     let x: Bar<Qux> = y::<Foo<Zar>>();
799                     (
800                         DiagnosticStyledString::highlighted(format!("{}", t1)),
801                         DiagnosticStyledString::highlighted(format!("{}", t2)),
802                     )
803                 }
804             }
805
806             // When finding T != &T, highlight only the borrow
807             (&ty::TyRef(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
808                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
809                 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
810                 values.1.push_normal(format!("{}", t2));
811                 values
812             }
813             (_, &ty::TyRef(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
814                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
815                 values.0.push_normal(format!("{}", t1));
816                 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
817                 values
818             }
819
820             // When encountering &T != &mut T, highlight only the borrow
821             (&ty::TyRef(r1, ref_ty1, mutbl1),
822              &ty::TyRef(r2, ref_ty2, mutbl2)) if equals(&ref_ty1, &ref_ty2) => {
823                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
824                 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
825                 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
826                 values
827             }
828
829             _ => {
830                 if t1 == t2 {
831                     // The two types are the same, elide and don't highlight.
832                     (
833                         DiagnosticStyledString::normal("_"),
834                         DiagnosticStyledString::normal("_"),
835                     )
836                 } else {
837                     // We couldn't find anything in common, highlight everything.
838                     (
839                         DiagnosticStyledString::highlighted(format!("{}", t1)),
840                         DiagnosticStyledString::highlighted(format!("{}", t2)),
841                     )
842                 }
843             }
844         }
845     }
846
847     pub fn note_type_err(
848         &self,
849         diag: &mut DiagnosticBuilder<'tcx>,
850         cause: &ObligationCause<'tcx>,
851         secondary_span: Option<(Span, String)>,
852         mut values: Option<ValuePairs<'tcx>>,
853         terr: &TypeError<'tcx>,
854     ) {
855         // For some types of errors, expected-found does not make
856         // sense, so just ignore the values we were given.
857         match terr {
858             TypeError::CyclicTy(_) => {
859                 values = None;
860             }
861             _ => {}
862         }
863
864         let (expected_found, exp_found, is_simple_error) = match values {
865             None => (None, None, false),
866             Some(values) => {
867                 let (is_simple_error, exp_found) = match values {
868                     ValuePairs::Types(exp_found) => {
869                         let is_simple_err =
870                             exp_found.expected.is_primitive() && exp_found.found.is_primitive();
871
872                         (is_simple_err, Some(exp_found))
873                     }
874                     _ => (false, None),
875                 };
876                 let vals = match self.values_str(&values) {
877                     Some((expected, found)) => Some((expected, found)),
878                     None => {
879                         // Derived error. Cancel the emitter.
880                         self.tcx.sess.diagnostic().cancel(diag);
881                         return;
882                     }
883                 };
884                 (vals, exp_found, is_simple_error)
885             }
886         };
887
888         let span = cause.span(&self.tcx);
889
890         diag.span_label(span, terr.to_string());
891         if let Some((sp, msg)) = secondary_span {
892             diag.span_label(sp, msg);
893         }
894
895         if let Some((expected, found)) = expected_found {
896             match (terr, is_simple_error, expected == found) {
897                 (&TypeError::Sorts(ref values), false, true) => {
898                     diag.note_expected_found_extra(
899                         &"type",
900                         expected,
901                         found,
902                         &format!(" ({})", values.expected.sort_string(self.tcx)),
903                         &format!(" ({})", values.found.sort_string(self.tcx)),
904                     );
905                 }
906                 (_, false, _) => {
907                     if let Some(exp_found) = exp_found {
908                         let (def_id, ret_ty) = match exp_found.found.sty {
909                             TypeVariants::TyFnDef(def, _) => {
910                                 (Some(def), Some(self.tcx.fn_sig(def).output()))
911                             }
912                             _ => (None, None),
913                         };
914
915                         let exp_is_struct = match exp_found.expected.sty {
916                             TypeVariants::TyAdt(def, _) => def.is_struct(),
917                             _ => false,
918                         };
919
920                         if let (Some(def_id), Some(ret_ty)) = (def_id, ret_ty) {
921                             if exp_is_struct && &exp_found.expected == ret_ty.skip_binder() {
922                                 let message = format!(
923                                     "did you mean `{}(/* fields */)`?",
924                                     self.tcx.item_path_str(def_id)
925                                 );
926                                 diag.span_label(span, message);
927                             }
928                         }
929                     }
930
931                     diag.note_expected_found(&"type", expected, found);
932                 }
933                 _ => (),
934             }
935         }
936
937         self.check_and_note_conflicting_crates(diag, terr, span);
938         self.tcx.note_and_explain_type_err(diag, terr, span);
939
940         // It reads better to have the error origin as the final
941         // thing.
942         self.note_error_origin(diag, &cause);
943     }
944
945     pub fn report_and_explain_type_error(
946         &self,
947         trace: TypeTrace<'tcx>,
948         terr: &TypeError<'tcx>,
949     ) -> DiagnosticBuilder<'tcx> {
950         debug!(
951             "report_and_explain_type_error(trace={:?}, terr={:?})",
952             trace, terr
953         );
954
955         let span = trace.cause.span(&self.tcx);
956         let failure_code = trace.cause.as_failure_code(terr);
957         let mut diag = match failure_code {
958             FailureCode::Error0317(failure_str) => {
959                 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
960             }
961             FailureCode::Error0580(failure_str) => {
962                 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
963             }
964             FailureCode::Error0308(failure_str) => {
965                 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
966             }
967             FailureCode::Error0644(failure_str) => {
968                 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
969             }
970         };
971         self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
972         diag
973     }
974
975     fn values_str(
976         &self,
977         values: &ValuePairs<'tcx>,
978     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
979         match *values {
980             infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
981             infer::Regions(ref exp_found) => self.expected_found_str(exp_found),
982             infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
983             infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
984         }
985     }
986
987     fn expected_found_str_ty(
988         &self,
989         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
990     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
991         let exp_found = self.resolve_type_vars_if_possible(exp_found);
992         if exp_found.references_error() {
993             return None;
994         }
995
996         Some(self.cmp(exp_found.expected, exp_found.found))
997     }
998
999     /// Returns a string of the form "expected `{}`, found `{}`".
1000     fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
1001         &self,
1002         exp_found: &ty::error::ExpectedFound<T>,
1003     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1004         let exp_found = self.resolve_type_vars_if_possible(exp_found);
1005         if exp_found.references_error() {
1006             return None;
1007         }
1008
1009         Some((
1010             DiagnosticStyledString::highlighted(format!("{}", exp_found.expected)),
1011             DiagnosticStyledString::highlighted(format!("{}", exp_found.found)),
1012         ))
1013     }
1014
1015     pub fn report_generic_bound_failure(
1016         &self,
1017         region_scope_tree: &region::ScopeTree,
1018         span: Span,
1019         origin: Option<SubregionOrigin<'tcx>>,
1020         bound_kind: GenericKind<'tcx>,
1021         sub: Region<'tcx>,
1022     ) {
1023         // Attempt to obtain the span of the parameter so we can
1024         // suggest adding an explicit lifetime bound to it.
1025         let type_param_span = match (self.in_progress_tables, bound_kind) {
1026             (Some(ref table), GenericKind::Param(ref param)) => {
1027                 let table = table.borrow();
1028                 table.local_id_root.and_then(|did| {
1029                     let generics = self.tcx.generics_of(did);
1030                     // Account for the case where `did` corresponds to `Self`, which doesn't have
1031                     // the expected type argument.
1032                     if !param.is_self() {
1033                         let type_param = generics.type_param(param, self.tcx);
1034                         let hir = &self.tcx.hir;
1035                         hir.as_local_node_id(type_param.def_id).map(|id| {
1036                             // Get the `hir::TyParam` to verify whether it already has any bounds.
1037                             // We do this to avoid suggesting code that ends up as `T: 'a'b`,
1038                             // instead we suggest `T: 'a + 'b` in that case.
1039                             let has_lifetimes = if let hir_map::NodeTyParam(ref p) = hir.get(id) {
1040                                 p.bounds.len() > 0
1041                             } else {
1042                                 false
1043                             };
1044                             let sp = hir.span(id);
1045                             // `sp` only covers `T`, change it so that it covers
1046                             // `T:` when appropriate
1047                             let sp = if has_lifetimes {
1048                                 sp.to(self.tcx
1049                                     .sess
1050                                     .codemap()
1051                                     .next_point(self.tcx.sess.codemap().next_point(sp)))
1052                             } else {
1053                                 sp
1054                             };
1055                             (sp, has_lifetimes)
1056                         })
1057                     } else {
1058                         None
1059                     }
1060                 })
1061             }
1062             _ => None,
1063         };
1064
1065         let labeled_user_string = match bound_kind {
1066             GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
1067             GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
1068         };
1069
1070         if let Some(SubregionOrigin::CompareImplMethodObligation {
1071             span,
1072             item_name,
1073             impl_item_def_id,
1074             trait_item_def_id,
1075         }) = origin
1076         {
1077             self.report_extra_impl_obligation(
1078                 span,
1079                 item_name,
1080                 impl_item_def_id,
1081                 trait_item_def_id,
1082                 &format!("`{}: {}`", bound_kind, sub),
1083             ).emit();
1084             return;
1085         }
1086
1087         fn binding_suggestion<'tcx, S: fmt::Display>(
1088             err: &mut DiagnosticBuilder<'tcx>,
1089             type_param_span: Option<(Span, bool)>,
1090             bound_kind: GenericKind<'tcx>,
1091             sub: S,
1092         ) {
1093             let consider = &format!(
1094                 "consider adding an explicit lifetime bound `{}: {}`...",
1095                 bound_kind, sub
1096             );
1097             if let Some((sp, has_lifetimes)) = type_param_span {
1098                 let tail = if has_lifetimes { " + " } else { "" };
1099                 let suggestion = format!("{}: {}{}", bound_kind, sub, tail);
1100                 err.span_suggestion_short(sp, consider, suggestion);
1101             } else {
1102                 err.help(consider);
1103             }
1104         }
1105
1106         let mut err = match *sub {
1107             ty::ReEarlyBound(_)
1108             | ty::ReFree(ty::FreeRegion {
1109                 bound_region: ty::BrNamed(..),
1110                 ..
1111             }) => {
1112                 // Does the required lifetime have a nice name we can print?
1113                 let mut err = struct_span_err!(
1114                     self.tcx.sess,
1115                     span,
1116                     E0309,
1117                     "{} may not live long enough",
1118                     labeled_user_string
1119                 );
1120                 binding_suggestion(&mut err, type_param_span, bound_kind, sub);
1121                 err
1122             }
1123
1124             ty::ReStatic => {
1125                 // Does the required lifetime have a nice name we can print?
1126                 let mut err = struct_span_err!(
1127                     self.tcx.sess,
1128                     span,
1129                     E0310,
1130                     "{} may not live long enough",
1131                     labeled_user_string
1132                 );
1133                 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
1134                 err
1135             }
1136
1137             _ => {
1138                 // If not, be less specific.
1139                 let mut err = struct_span_err!(
1140                     self.tcx.sess,
1141                     span,
1142                     E0311,
1143                     "{} may not live long enough",
1144                     labeled_user_string
1145                 );
1146                 err.help(&format!(
1147                     "consider adding an explicit lifetime bound for `{}`",
1148                     bound_kind
1149                 ));
1150                 self.tcx.note_and_explain_region(
1151                     region_scope_tree,
1152                     &mut err,
1153                     &format!("{} must be valid for ", labeled_user_string),
1154                     sub,
1155                     "...",
1156                 );
1157                 err
1158             }
1159         };
1160
1161         if let Some(origin) = origin {
1162             self.note_region_origin(&mut err, &origin);
1163         }
1164         err.emit();
1165     }
1166
1167     fn report_sub_sup_conflict(
1168         &self,
1169         region_scope_tree: &region::ScopeTree,
1170         var_origin: RegionVariableOrigin,
1171         sub_origin: SubregionOrigin<'tcx>,
1172         sub_region: Region<'tcx>,
1173         sup_origin: SubregionOrigin<'tcx>,
1174         sup_region: Region<'tcx>,
1175     ) {
1176         let mut err = self.report_inference_failure(var_origin);
1177
1178         self.tcx.note_and_explain_region(
1179             region_scope_tree,
1180             &mut err,
1181             "first, the lifetime cannot outlive ",
1182             sup_region,
1183             "...",
1184         );
1185
1186         match (&sup_origin, &sub_origin) {
1187             (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) => {
1188                 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) = (
1189                     self.values_str(&sup_trace.values),
1190                     self.values_str(&sub_trace.values),
1191                 ) {
1192                     if sub_expected == sup_expected && sub_found == sup_found {
1193                         self.tcx.note_and_explain_region(
1194                             region_scope_tree,
1195                             &mut err,
1196                             "...but the lifetime must also be valid for ",
1197                             sub_region,
1198                             "...",
1199                         );
1200                         err.note(&format!(
1201                             "...so that the {}:\nexpected {}\n   found {}",
1202                             sup_trace.cause.as_requirement_str(),
1203                             sup_expected.content(),
1204                             sup_found.content()
1205                         ));
1206                         err.emit();
1207                         return;
1208                     }
1209                 }
1210             }
1211             _ => {}
1212         }
1213
1214         self.note_region_origin(&mut err, &sup_origin);
1215
1216         self.tcx.note_and_explain_region(
1217             region_scope_tree,
1218             &mut err,
1219             "but, the lifetime must be valid for ",
1220             sub_region,
1221             "...",
1222         );
1223
1224         self.note_region_origin(&mut err, &sub_origin);
1225         err.emit();
1226     }
1227 }
1228
1229 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1230     fn report_inference_failure(
1231         &self,
1232         var_origin: RegionVariableOrigin,
1233     ) -> DiagnosticBuilder<'tcx> {
1234         let br_string = |br: ty::BoundRegion| {
1235             let mut s = br.to_string();
1236             if !s.is_empty() {
1237                 s.push_str(" ");
1238             }
1239             s
1240         };
1241         let var_description = match var_origin {
1242             infer::MiscVariable(_) => "".to_string(),
1243             infer::PatternRegion(_) => " for pattern".to_string(),
1244             infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1245             infer::Autoref(_) => " for autoref".to_string(),
1246             infer::Coercion(_) => " for automatic coercion".to_string(),
1247             infer::LateBoundRegion(_, br, infer::FnCall) => {
1248                 format!(" for lifetime parameter {}in function call", br_string(br))
1249             }
1250             infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1251                 format!(" for lifetime parameter {}in generic type", br_string(br))
1252             }
1253             infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
1254                 " for lifetime parameter {}in trait containing associated type `{}`",
1255                 br_string(br),
1256                 self.tcx.associated_item(def_id).name
1257             ),
1258             infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
1259             infer::BoundRegionInCoherence(name) => {
1260                 format!(" for lifetime parameter `{}` in coherence check", name)
1261             }
1262             infer::UpvarRegion(ref upvar_id, _) => {
1263                 let var_node_id = self.tcx.hir.hir_to_node_id(upvar_id.var_id);
1264                 let var_name = self.tcx.hir.name(var_node_id);
1265                 format!(" for capture of `{}` by closure", var_name)
1266             }
1267             infer::NLL(..) => bug!("NLL variable found in lexical phase"),
1268         };
1269
1270         struct_span_err!(
1271             self.tcx.sess,
1272             var_origin.span(),
1273             E0495,
1274             "cannot infer an appropriate lifetime{} \
1275              due to conflicting requirements",
1276             var_description
1277         )
1278     }
1279 }
1280
1281 enum FailureCode {
1282     Error0317(&'static str),
1283     Error0580(&'static str),
1284     Error0308(&'static str),
1285     Error0644(&'static str),
1286 }
1287
1288 impl<'tcx> ObligationCause<'tcx> {
1289     fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
1290         use self::FailureCode::*;
1291         use traits::ObligationCauseCode::*;
1292         match self.code {
1293             CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
1294             MatchExpressionArm { source, .. } => Error0308(match source {
1295                 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have incompatible types",
1296                 _ => "match arms have incompatible types",
1297             }),
1298             IfExpression => Error0308("if and else have incompatible types"),
1299             IfExpressionWithNoElse => Error0317("if may be missing an else clause"),
1300             MainFunctionType => Error0580("main function has wrong type"),
1301             StartFunctionType => Error0308("start function has wrong type"),
1302             IntrinsicType => Error0308("intrinsic has wrong type"),
1303             MethodReceiver => Error0308("mismatched method receiver"),
1304
1305             // In the case where we have no more specific thing to
1306             // say, also take a look at the error code, maybe we can
1307             // tailor to that.
1308             _ => match terr {
1309                 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
1310                     Error0644("closure/generator type that references itself")
1311                 }
1312                 _ => Error0308("mismatched types"),
1313             },
1314         }
1315     }
1316
1317     fn as_requirement_str(&self) -> &'static str {
1318         use traits::ObligationCauseCode::*;
1319         match self.code {
1320             CompareImplMethodObligation { .. } => "method type is compatible with trait",
1321             ExprAssignable => "expression is assignable",
1322             MatchExpressionArm { source, .. } => match source {
1323                 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
1324                 _ => "match arms have compatible types",
1325             },
1326             IfExpression => "if and else have compatible types",
1327             IfExpressionWithNoElse => "if missing an else returns ()",
1328             MainFunctionType => "`main` function has the correct type",
1329             StartFunctionType => "`start` function has the correct type",
1330             IntrinsicType => "intrinsic has the correct type",
1331             MethodReceiver => "method receiver has the correct type",
1332             _ => "types are compatible",
1333         }
1334     }
1335 }