]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/error_reporting/mod.rs
update comment to explain the importance of this check more clearly
[rust.git] / src / librustc / infer / error_reporting / mod.rs
1 //! Error Reporting Code for the inference engine
2 //!
3 //! Because of the way inference, and in particular region inference,
4 //! works, it often happens that errors are not detected until far after
5 //! the relevant line of code has been type-checked. Therefore, there is
6 //! an elaborate system to track why a particular constraint in the
7 //! inference graph arose so that we can explain to the user what gave
8 //! rise to a particular error.
9 //!
10 //! The basis of the system are the "origin" types. An "origin" is the
11 //! reason that a constraint or inference variable arose. There are
12 //! different "origin" enums for different kinds of constraints/variables
13 //! (e.g., `TypeOrigin`, `RegionVariableOrigin`). An origin always has
14 //! a span, but also more information so that we can generate a meaningful
15 //! error message.
16 //!
17 //! Having a catalog of all the different reasons an error can arise is
18 //! also useful for other reasons, like cross-referencing FAQs etc, though
19 //! we are not really taking advantage of this yet.
20 //!
21 //! # Region Inference
22 //!
23 //! Region inference is particularly tricky because it always succeeds "in
24 //! the moment" and simply registers a constraint. Then, at the end, we
25 //! can compute the full graph and report errors, so we need to be able to
26 //! store and later report what gave rise to the conflicting constraints.
27 //!
28 //! # Subtype Trace
29 //!
30 //! Determining whether `T1 <: T2` often involves a number of subtypes and
31 //! subconstraints along the way. A "TypeTrace" is an extended version
32 //! of an origin that traces the types and other values that were being
33 //! compared. It is not necessarily comprehensive (in fact, at the time of
34 //! this writing it only tracks the root values being compared) but I'd
35 //! like to extend it to include significant "waypoints". For example, if
36 //! you are comparing `(T1, T2) <: (T3, T4)`, and the problem is that `T2
37 //! <: T4` fails, I'd like the trace to include enough information to say
38 //! "in the 2nd element of the tuple". Similarly, failures when comparing
39 //! arguments or return types in fn types should be able to cite the
40 //! specific position, etc.
41 //!
42 //! # Reality vs plan
43 //!
44 //! Of course, there is still a LOT of code in typeck that has yet to be
45 //! ported to this system, and which relies on string concatenation at the
46 //! time of error detection.
47
48 use super::lexical_region_resolve::RegionResolutionError;
49 use super::region_constraints::GenericKind;
50 use super::{InferCtxt, RegionVariableOrigin, SubregionOrigin, TypeTrace, ValuePairs};
51
52 use crate::hir;
53 use crate::hir::def_id::DefId;
54 use crate::hir::Node;
55 use crate::infer::{self, SuppressRegionErrors};
56 use crate::infer::opaque_types;
57 use crate::middle::region;
58 use crate::traits::{
59     IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
60 };
61 use crate::ty::error::TypeError;
62 use crate::ty::{self, subst::{Subst, SubstsRef}, Region, Ty, TyCtxt, TypeFoldable};
63
64 use errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString};
65 use rustc_error_codes::*;
66 use rustc_target::spec::abi;
67 use syntax_pos::{Pos, Span};
68 use std::{cmp, fmt};
69
70 mod note;
71
72 mod need_type_info;
73
74 pub mod nice_region_error;
75
76 impl<'tcx> TyCtxt<'tcx> {
77     pub fn note_and_explain_region(
78         self,
79         region_scope_tree: &region::ScopeTree,
80         err: &mut DiagnosticBuilder<'_>,
81         prefix: &str,
82         region: ty::Region<'tcx>,
83         suffix: &str,
84     ) {
85         let (description, span) = match *region {
86             ty::ReScope(scope) => {
87                 let new_string;
88                 let unknown_scope = || {
89                     format!(
90                         "{}unknown scope: {:?}{}.  Please report a bug.",
91                         prefix, scope, suffix
92                     )
93                 };
94                 let span = scope.span(self, region_scope_tree);
95                 let tag = match self.hir().find(scope.hir_id(region_scope_tree)) {
96                     Some(Node::Block(_)) => "block",
97                     Some(Node::Expr(expr)) => match expr.kind {
98                         hir::ExprKind::Call(..) => "call",
99                         hir::ExprKind::MethodCall(..) => "method call",
100                         hir::ExprKind::Match(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
101                         hir::ExprKind::Match(.., hir::MatchSource::WhileLetDesugar) => "while let",
102                         hir::ExprKind::Match(.., hir::MatchSource::ForLoopDesugar) => "for",
103                         hir::ExprKind::Match(..) => "match",
104                         _ => "expression",
105                     },
106                     Some(Node::Stmt(_)) => "statement",
107                     Some(Node::Item(it)) => Self::item_scope_tag(&it),
108                     Some(Node::TraitItem(it)) => Self::trait_item_scope_tag(&it),
109                     Some(Node::ImplItem(it)) => Self::impl_item_scope_tag(&it),
110                     Some(_) | None => {
111                         err.span_note(span, &unknown_scope());
112                         return;
113                     }
114                 };
115                 let scope_decorated_tag = match scope.data {
116                     region::ScopeData::Node => tag,
117                     region::ScopeData::CallSite => "scope of call-site for function",
118                     region::ScopeData::Arguments => "scope of function body",
119                     region::ScopeData::Destruction => {
120                         new_string = format!("destruction scope surrounding {}", tag);
121                         &new_string[..]
122                     }
123                     region::ScopeData::Remainder(first_statement_index) => {
124                         new_string = format!(
125                             "block suffix following statement {}",
126                             first_statement_index.index()
127                         );
128                         &new_string[..]
129                     }
130                 };
131                 self.explain_span(scope_decorated_tag, span)
132             }
133
134             ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
135                 self.msg_span_from_free_region(region)
136             }
137
138             ty::ReEmpty => ("the empty lifetime".to_owned(), None),
139
140             ty::RePlaceholder(_) => (format!("any other region"), None),
141
142             // FIXME(#13998) RePlaceholder should probably print like
143             // ReFree rather than dumping Debug output on the user.
144             //
145             // We shouldn't really be having unification failures with ReVar
146             // and ReLateBound though.
147             ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
148                 (format!("lifetime {:?}", region), None)
149             }
150
151             // We shouldn't encounter an error message with ReClosureBound.
152             ty::ReClosureBound(..) => {
153                 bug!("encountered unexpected ReClosureBound: {:?}", region,);
154             }
155         };
156
157         TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
158     }
159
160     pub fn note_and_explain_free_region(
161         self,
162         err: &mut DiagnosticBuilder<'_>,
163         prefix: &str,
164         region: ty::Region<'tcx>,
165         suffix: &str,
166     ) {
167         let (description, span) = self.msg_span_from_free_region(region);
168
169         TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
170     }
171
172     fn msg_span_from_free_region(self, region: ty::Region<'tcx>) -> (String, Option<Span>) {
173         match *region {
174             ty::ReEarlyBound(_) | ty::ReFree(_) => {
175                 self.msg_span_from_early_bound_and_free_regions(region)
176             }
177             ty::ReStatic => ("the static lifetime".to_owned(), None),
178             ty::ReEmpty => ("an empty lifetime".to_owned(), None),
179             _ => bug!("{:?}", region),
180         }
181     }
182
183     fn msg_span_from_early_bound_and_free_regions(
184         self,
185         region: ty::Region<'tcx>,
186     ) -> (String, Option<Span>) {
187         let cm = self.sess.source_map();
188
189         let scope = region.free_region_binding_scope(self);
190         let node = self.hir().as_local_hir_id(scope).unwrap_or(hir::DUMMY_HIR_ID);
191         let tag = match self.hir().find(node) {
192             Some(Node::Block(_)) | Some(Node::Expr(_)) => "body",
193             Some(Node::Item(it)) => Self::item_scope_tag(&it),
194             Some(Node::TraitItem(it)) => Self::trait_item_scope_tag(&it),
195             Some(Node::ImplItem(it)) => Self::impl_item_scope_tag(&it),
196             _ => unreachable!(),
197         };
198         let (prefix, span) = match *region {
199             ty::ReEarlyBound(ref br) => {
200                 let mut sp = cm.def_span(self.hir().span(node));
201                 if let Some(param) = self.hir()
202                     .get_generics(scope)
203                     .and_then(|generics| generics.get_named(br.name))
204                 {
205                     sp = param.span;
206                 }
207                 (format!("the lifetime `{}` as defined on", br.name), sp)
208             }
209             ty::ReFree(ty::FreeRegion {
210                 bound_region: ty::BoundRegion::BrNamed(_, name),
211                 ..
212             }) => {
213                 let mut sp = cm.def_span(self.hir().span(node));
214                 if let Some(param) = self.hir()
215                     .get_generics(scope)
216                     .and_then(|generics| generics.get_named(name))
217                 {
218                     sp = param.span;
219                 }
220                 (format!("the lifetime `{}` as defined on", name), sp)
221             }
222             ty::ReFree(ref fr) => match fr.bound_region {
223                 ty::BrAnon(idx) => (
224                     format!("the anonymous lifetime #{} defined on", idx + 1),
225                     self.hir().span(node),
226                 ),
227                 _ => (
228                     format!("the lifetime `{}` as defined on", region),
229                     cm.def_span(self.hir().span(node)),
230                 ),
231             },
232             _ => bug!(),
233         };
234         let (msg, opt_span) = self.explain_span(tag, span);
235         (format!("{} {}", prefix, msg), opt_span)
236     }
237
238     fn emit_msg_span(
239         err: &mut DiagnosticBuilder<'_>,
240         prefix: &str,
241         description: String,
242         span: Option<Span>,
243         suffix: &str,
244     ) {
245         let message = format!("{}{}{}", prefix, description, suffix);
246
247         if let Some(span) = span {
248             err.span_note(span, &message);
249         } else {
250             err.note(&message);
251         }
252     }
253
254     fn item_scope_tag(item: &hir::Item) -> &'static str {
255         match item.kind {
256             hir::ItemKind::Impl(..) => "impl",
257             hir::ItemKind::Struct(..) => "struct",
258             hir::ItemKind::Union(..) => "union",
259             hir::ItemKind::Enum(..) => "enum",
260             hir::ItemKind::Trait(..) => "trait",
261             hir::ItemKind::Fn(..) => "function body",
262             _ => "item",
263         }
264     }
265
266     fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
267         match item.kind {
268             hir::TraitItemKind::Method(..) => "method body",
269             hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => "associated item",
270         }
271     }
272
273     fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
274         match item.kind {
275             hir::ImplItemKind::Method(..) => "method body",
276             hir::ImplItemKind::Const(..)
277             | hir::ImplItemKind::OpaqueTy(..)
278             | hir::ImplItemKind::TyAlias(..) => "associated item",
279         }
280     }
281
282     fn explain_span(self, heading: &str, span: Span) -> (String, Option<Span>) {
283         let lo = self.sess.source_map().lookup_char_pos(span.lo());
284         (
285             format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1),
286             Some(span),
287         )
288     }
289 }
290
291 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
292     pub fn report_region_errors(
293         &self,
294         region_scope_tree: &region::ScopeTree,
295         errors: &Vec<RegionResolutionError<'tcx>>,
296         suppress: SuppressRegionErrors,
297     ) {
298         debug!(
299             "report_region_errors(): {} errors to start, suppress = {:?}",
300             errors.len(),
301             suppress
302         );
303
304         if suppress.suppressed() {
305             return;
306         }
307
308         // try to pre-process the errors, which will group some of them
309         // together into a `ProcessedErrors` group:
310         let errors = self.process_errors(errors);
311
312         debug!(
313             "report_region_errors: {} errors after preprocessing",
314             errors.len()
315         );
316
317         for error in errors {
318             debug!("report_region_errors: error = {:?}", error);
319
320             if !self.try_report_nice_region_error(&error) {
321                 match error.clone() {
322                     // These errors could indicate all manner of different
323                     // problems with many different solutions. Rather
324                     // than generate a "one size fits all" error, what we
325                     // attempt to do is go through a number of specific
326                     // scenarios and try to find the best way to present
327                     // the error. If all of these fails, we fall back to a rather
328                     // general bit of code that displays the error information
329                     RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
330                         if sub.is_placeholder() || sup.is_placeholder() {
331                             self.report_placeholder_failure(region_scope_tree, origin, sub, sup)
332                                 .emit();
333                         } else {
334                             self.report_concrete_failure(region_scope_tree, origin, sub, sup)
335                                 .emit();
336                         }
337                     }
338
339                     RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
340                         self.report_generic_bound_failure(
341                             region_scope_tree,
342                             origin.span(),
343                             Some(origin),
344                             param_ty,
345                             sub,
346                         );
347                     }
348
349                     RegionResolutionError::SubSupConflict(
350                         _,
351                         var_origin,
352                         sub_origin,
353                         sub_r,
354                         sup_origin,
355                         sup_r,
356                     ) => {
357                         if sub_r.is_placeholder() {
358                             self.report_placeholder_failure(
359                                 region_scope_tree,
360                                 sub_origin,
361                                 sub_r,
362                                 sup_r,
363                             )
364                                 .emit();
365                         } else if sup_r.is_placeholder() {
366                             self.report_placeholder_failure(
367                                 region_scope_tree,
368                                 sup_origin,
369                                 sub_r,
370                                 sup_r,
371                             )
372                                 .emit();
373                         } else {
374                             self.report_sub_sup_conflict(
375                                 region_scope_tree,
376                                 var_origin,
377                                 sub_origin,
378                                 sub_r,
379                                 sup_origin,
380                                 sup_r,
381                             );
382                         }
383                     }
384
385                     RegionResolutionError::MemberConstraintFailure {
386                         opaque_type_def_id,
387                         hidden_ty,
388                         member_region,
389                         span: _,
390                         choice_regions: _,
391                     } => {
392                         let hidden_ty = self.resolve_vars_if_possible(&hidden_ty);
393                         opaque_types::unexpected_hidden_region_diagnostic(
394                             self.tcx,
395                             Some(region_scope_tree),
396                             opaque_type_def_id,
397                             hidden_ty,
398                             member_region,
399                         ).emit();
400                     }
401                 }
402             }
403         }
404     }
405
406     // This method goes through all the errors and try to group certain types
407     // of error together, for the purpose of suggesting explicit lifetime
408     // parameters to the user. This is done so that we can have a more
409     // complete view of what lifetimes should be the same.
410     // If the return value is an empty vector, it means that processing
411     // failed (so the return value of this method should not be used).
412     //
413     // The method also attempts to weed out messages that seem like
414     // duplicates that will be unhelpful to the end-user. But
415     // obviously it never weeds out ALL errors.
416     fn process_errors(
417         &self,
418         errors: &Vec<RegionResolutionError<'tcx>>,
419     ) -> Vec<RegionResolutionError<'tcx>> {
420         debug!("process_errors()");
421
422         // We want to avoid reporting generic-bound failures if we can
423         // avoid it: these have a very high rate of being unhelpful in
424         // practice. This is because they are basically secondary
425         // checks that test the state of the region graph after the
426         // rest of inference is done, and the other kinds of errors
427         // indicate that the region constraint graph is internally
428         // inconsistent, so these test results are likely to be
429         // meaningless.
430         //
431         // Therefore, we filter them out of the list unless they are
432         // the only thing in the list.
433
434         let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
435             RegionResolutionError::GenericBoundFailure(..) => true,
436             RegionResolutionError::ConcreteFailure(..)
437                 | RegionResolutionError::SubSupConflict(..)
438                 | RegionResolutionError::MemberConstraintFailure { .. } => false,
439         };
440
441         let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
442             errors.clone()
443         } else {
444             errors
445             .iter()
446             .filter(|&e| !is_bound_failure(e))
447             .cloned()
448             .collect()
449         };
450
451         // sort the errors by span, for better error message stability.
452         errors.sort_by_key(|u| match *u {
453             RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
454             RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
455             RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _) => rvo.span(),
456             RegionResolutionError::MemberConstraintFailure { span, .. } => span,
457         });
458         errors
459     }
460
461     /// Adds a note if the types come from similarly named crates
462     fn check_and_note_conflicting_crates(
463         &self,
464         err: &mut DiagnosticBuilder<'_>,
465         terr: &TypeError<'tcx>,
466     ) {
467         use hir::def_id::CrateNum;
468         use hir::map::DisambiguatedDefPathData;
469         use ty::print::Printer;
470         use ty::subst::GenericArg;
471
472         struct AbsolutePathPrinter<'tcx> {
473             tcx: TyCtxt<'tcx>,
474         }
475
476         struct NonTrivialPath;
477
478         impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
479             type Error = NonTrivialPath;
480
481             type Path = Vec<String>;
482             type Region = !;
483             type Type = !;
484             type DynExistential = !;
485             type Const = !;
486
487             fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
488                 self.tcx
489             }
490
491             fn print_region(
492                 self,
493                 _region: ty::Region<'_>,
494             ) -> Result<Self::Region, Self::Error> {
495                 Err(NonTrivialPath)
496             }
497
498             fn print_type(
499                 self,
500                 _ty: Ty<'tcx>,
501             ) -> Result<Self::Type, Self::Error> {
502                 Err(NonTrivialPath)
503             }
504
505             fn print_dyn_existential(
506                 self,
507                 _predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
508             ) -> Result<Self::DynExistential, Self::Error> {
509                 Err(NonTrivialPath)
510             }
511
512             fn print_const(
513                 self,
514                 _ct: &'tcx ty::Const<'tcx>,
515             ) -> Result<Self::Const, Self::Error> {
516                 Err(NonTrivialPath)
517             }
518
519             fn path_crate(
520                 self,
521                 cnum: CrateNum,
522             ) -> Result<Self::Path, Self::Error> {
523                 Ok(vec![self.tcx.original_crate_name(cnum).to_string()])
524             }
525             fn path_qualified(
526                 self,
527                 _self_ty: Ty<'tcx>,
528                 _trait_ref: Option<ty::TraitRef<'tcx>>,
529             ) -> Result<Self::Path, Self::Error> {
530                 Err(NonTrivialPath)
531             }
532
533             fn path_append_impl(
534                 self,
535                 _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
536                 _disambiguated_data: &DisambiguatedDefPathData,
537                 _self_ty: Ty<'tcx>,
538                 _trait_ref: Option<ty::TraitRef<'tcx>>,
539             ) -> Result<Self::Path, Self::Error> {
540                 Err(NonTrivialPath)
541             }
542             fn path_append(
543                 self,
544                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
545                 disambiguated_data: &DisambiguatedDefPathData,
546             ) -> Result<Self::Path, Self::Error> {
547                 let mut path = print_prefix(self)?;
548                 path.push(disambiguated_data.data.as_symbol().to_string());
549                 Ok(path)
550             }
551             fn path_generic_args(
552                 self,
553                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
554                 _args: &[GenericArg<'tcx>],
555             ) -> Result<Self::Path, Self::Error> {
556                 print_prefix(self)
557             }
558         }
559
560         let report_path_match = |err: &mut DiagnosticBuilder<'_>, did1: DefId, did2: DefId| {
561             // Only external crates, if either is from a local
562             // module we could have false positives
563             if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
564                 let abs_path = |def_id| {
565                     AbsolutePathPrinter { tcx: self.tcx }
566                         .print_def_path(def_id, &[])
567                 };
568
569                 // We compare strings because DefPath can be different
570                 // for imported and non-imported crates
571                 let same_path = || -> Result<_, NonTrivialPath> {
572                     Ok(
573                         self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2) ||
574                         abs_path(did1)? == abs_path(did2)?
575                     )
576                 };
577                 if same_path().unwrap_or(false) {
578                     let crate_name = self.tcx.crate_name(did1.krate);
579                     err.note(&format!(
580                         "perhaps two different versions of crate `{}` are being used?",
581                         crate_name
582                     ));
583                 }
584             }
585         };
586         match *terr {
587             TypeError::Sorts(ref exp_found) => {
588                 // if they are both "path types", there's a chance of ambiguity
589                 // due to different versions of the same crate
590                 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _))
591                      = (&exp_found.expected.kind, &exp_found.found.kind)
592                 {
593                     report_path_match(err, exp_adt.did, found_adt.did);
594                 }
595             }
596             TypeError::Traits(ref exp_found) => {
597                 report_path_match(err, exp_found.expected, exp_found.found);
598             }
599             _ => (), // FIXME(#22750) handle traits and stuff
600         }
601     }
602
603     fn note_error_origin(
604         &self,
605         err: &mut DiagnosticBuilder<'tcx>,
606         cause: &ObligationCause<'tcx>,
607         exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
608     ) {
609         match cause.code {
610             ObligationCauseCode::MatchExpressionArmPattern { span, ty } => {
611                 if ty.is_suggestable() {  // don't show type `_`
612                     err.span_label(span, format!("this match expression has type `{}`", ty));
613                 }
614                 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found {
615                     if ty.is_box() && ty.boxed_ty() == found {
616                         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
617                             err.span_suggestion(
618                                 span,
619                                 "consider dereferencing the boxed value",
620                                 format!("*{}", snippet),
621                                 Applicability::MachineApplicable,
622                             );
623                         }
624                     }
625                 }
626             }
627             ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
628                 source,
629                 ref prior_arms,
630                 last_ty,
631                 discrim_hir_id,
632                 ..
633             }) => match source {
634                 hir::MatchSource::IfLetDesugar { .. } => {
635                     let msg = "`if let` arms have incompatible types";
636                     err.span_label(cause.span, msg);
637                 }
638                 hir::MatchSource::TryDesugar => {
639                     if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
640                         let discrim_expr = self.tcx.hir().expect_expr(discrim_hir_id);
641                         let discrim_ty = if let hir::ExprKind::Call(_, args) = &discrim_expr.kind {
642                             let arg_expr = args.first().expect("try desugaring call w/out arg");
643                             self.in_progress_tables.and_then(|tables| {
644                                 tables.borrow().expr_ty_opt(arg_expr)
645                             })
646                         } else {
647                             bug!("try desugaring w/out call expr as discriminant");
648                         };
649
650                         match discrim_ty {
651                             Some(ty) if expected == ty => {
652                                 let source_map = self.tcx.sess.source_map();
653                                 err.span_suggestion(
654                                     source_map.end_point(cause.span),
655                                     "try removing this `?`",
656                                     "".to_string(),
657                                     Applicability::MachineApplicable,
658                                 );
659                             },
660                             _ => {},
661                         }
662                     }
663                 }
664                 _ => {
665                     // `last_ty` can be `!`, `expected` will have better info when present.
666                     let t = self.resolve_vars_if_possible(&match exp_found {
667                         Some(ty::error::ExpectedFound { expected, .. }) => expected,
668                         _ => last_ty,
669                     });
670                     let msg = "`match` arms have incompatible types";
671                     err.span_label(cause.span, msg);
672                     if prior_arms.len() <= 4 {
673                         for sp in prior_arms {
674                             err.span_label( *sp, format!("this is found to be of type `{}`", t));
675                         }
676                     } else if let Some(sp) = prior_arms.last() {
677                         err.span_label(
678                             *sp,
679                             format!("this and all prior arms are found to be of type `{}`", t),
680                         );
681                     }
682                 }
683             },
684             ObligationCauseCode::IfExpression(box IfExpressionCause { then, outer, semicolon }) => {
685                 err.span_label(then, "expected because of this");
686                 outer.map(|sp| err.span_label(sp, "if and else have incompatible types"));
687                 if let Some(sp) = semicolon {
688                     err.span_suggestion_short(
689                         sp,
690                         "consider removing this semicolon",
691                         String::new(),
692                         Applicability::MachineApplicable,
693                     );
694                 }
695             }
696             _ => (),
697         }
698     }
699
700     /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
701     /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
702     /// populate `other_value` with `other_ty`.
703     ///
704     /// ```text
705     /// Foo<Bar<Qux>>
706     /// ^^^^--------^ this is highlighted
707     /// |   |
708     /// |   this type argument is exactly the same as the other type, not highlighted
709     /// this is highlighted
710     /// Bar<Qux>
711     /// -------- this type is the same as a type argument in the other type, not highlighted
712     /// ```
713     fn highlight_outer(
714         &self,
715         value: &mut DiagnosticStyledString,
716         other_value: &mut DiagnosticStyledString,
717         name: String,
718         sub: ty::subst::SubstsRef<'tcx>,
719         pos: usize,
720         other_ty: Ty<'tcx>,
721     ) {
722         // `value` and `other_value` hold two incomplete type representation for display.
723         // `name` is the path of both types being compared. `sub`
724         value.push_highlighted(name);
725         let len = sub.len();
726         if len > 0 {
727             value.push_highlighted("<");
728         }
729
730         // Output the lifetimes for the first type
731         let lifetimes = sub.regions()
732             .map(|lifetime| {
733                 let s = lifetime.to_string();
734                 if s.is_empty() {
735                     "'_".to_string()
736                 } else {
737                     s
738                 }
739             })
740             .collect::<Vec<_>>()
741             .join(", ");
742         if !lifetimes.is_empty() {
743             if sub.regions().count() < len {
744                 value.push_normal(lifetimes + &", ");
745             } else {
746                 value.push_normal(lifetimes);
747             }
748         }
749
750         // Highlight all the type arguments that aren't at `pos` and compare the type argument at
751         // `pos` and `other_ty`.
752         for (i, type_arg) in sub.types().enumerate() {
753             if i == pos {
754                 let values = self.cmp(type_arg, other_ty);
755                 value.0.extend((values.0).0);
756                 other_value.0.extend((values.1).0);
757             } else {
758                 value.push_highlighted(type_arg.to_string());
759             }
760
761             if len > 0 && i != len - 1 {
762                 value.push_normal(", ");
763             }
764         }
765         if len > 0 {
766             value.push_highlighted(">");
767         }
768     }
769
770     /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
771     /// as that is the difference to the other type.
772     ///
773     /// For the following code:
774     ///
775     /// ```norun
776     /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
777     /// ```
778     ///
779     /// The type error output will behave in the following way:
780     ///
781     /// ```text
782     /// Foo<Bar<Qux>>
783     /// ^^^^--------^ this is highlighted
784     /// |   |
785     /// |   this type argument is exactly the same as the other type, not highlighted
786     /// this is highlighted
787     /// Bar<Qux>
788     /// -------- this type is the same as a type argument in the other type, not highlighted
789     /// ```
790     fn cmp_type_arg(
791         &self,
792         mut t1_out: &mut DiagnosticStyledString,
793         mut t2_out: &mut DiagnosticStyledString,
794         path: String,
795         sub: ty::subst::SubstsRef<'tcx>,
796         other_path: String,
797         other_ty: Ty<'tcx>,
798     ) -> Option<()> {
799         for (i, ta) in sub.types().enumerate() {
800             if ta == other_ty {
801                 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
802                 return Some(());
803             }
804             if let &ty::Adt(def, _) = &ta.kind {
805                 let path_ = self.tcx.def_path_str(def.did.clone());
806                 if path_ == other_path {
807                     self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
808                     return Some(());
809                 }
810             }
811         }
812         None
813     }
814
815     /// Adds a `,` to the type representation only if it is appropriate.
816     fn push_comma(
817         &self,
818         value: &mut DiagnosticStyledString,
819         other_value: &mut DiagnosticStyledString,
820         len: usize,
821         pos: usize,
822     ) {
823         if len > 0 && pos != len - 1 {
824             value.push_normal(", ");
825             other_value.push_normal(", ");
826         }
827     }
828
829     /// For generic types with parameters with defaults, remove the parameters corresponding to
830     /// the defaults. This repeats a lot of the logic found in `ty::print::pretty`.
831     fn strip_generic_default_params(
832         &self,
833         def_id: DefId,
834         substs: ty::subst::SubstsRef<'tcx>,
835     ) -> SubstsRef<'tcx> {
836         let generics = self.tcx.generics_of(def_id);
837         let mut num_supplied_defaults = 0;
838         let mut type_params = generics.params.iter().rev().filter_map(|param| match param.kind {
839             ty::GenericParamDefKind::Lifetime => None,
840             ty::GenericParamDefKind::Type { has_default, .. } => Some((param.def_id, has_default)),
841             ty::GenericParamDefKind::Const => None, // FIXME(const_generics:defaults)
842         }).peekable();
843         let has_default = {
844             let has_default = type_params.peek().map(|(_, has_default)| has_default);
845             *has_default.unwrap_or(&false)
846         };
847         if has_default {
848             let types = substs.types().rev();
849             for ((def_id, has_default), actual) in type_params.zip(types) {
850                 if !has_default {
851                     break;
852                 }
853                 if self.tcx.type_of(def_id).subst(self.tcx, substs) != actual {
854                     break;
855                 }
856                 num_supplied_defaults += 1;
857             }
858         }
859         let len = generics.params.len();
860         let mut generics = generics.clone();
861         generics.params.truncate(len - num_supplied_defaults);
862         substs.truncate_to(self.tcx, &generics)
863     }
864
865     /// Given two `fn` signatures highlight only sub-parts that are different.
866     fn cmp_fn_sig(
867         &self,
868         sig1: &ty::PolyFnSig<'tcx>,
869         sig2: &ty::PolyFnSig<'tcx>,
870     ) -> (DiagnosticStyledString, DiagnosticStyledString) {
871         let get_lifetimes = |sig| {
872             use crate::hir::def::Namespace;
873             let mut s = String::new();
874             let (_, (sig, reg)) = ty::print::FmtPrinter::new(self.tcx, &mut s, Namespace::TypeNS)
875                 .name_all_regions(sig)
876                 .unwrap();
877             let lts: Vec<String> = reg.into_iter().map(|(_, kind)| kind.to_string()).collect();
878             (if lts.is_empty() {
879                 String::new()
880             } else {
881                 format!("for<{}> ", lts.join(", "))
882             }, sig)
883         };
884
885         let (lt1, sig1) = get_lifetimes(sig1);
886         let (lt2, sig2) = get_lifetimes(sig2);
887
888         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
889         let mut values = (
890             DiagnosticStyledString::normal("".to_string()),
891             DiagnosticStyledString::normal("".to_string()),
892         );
893
894         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
895         // ^^^^^^
896         values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
897         values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
898
899         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
900         //        ^^^^^^^^^^
901         if sig1.abi != abi::Abi::Rust {
902             values.0.push(format!("extern {} ", sig1.abi), sig1.abi != sig2.abi);
903         }
904         if sig2.abi != abi::Abi::Rust {
905             values.1.push(format!("extern {} ", sig2.abi), sig1.abi != sig2.abi);
906         }
907
908         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
909         //                   ^^^^^^^^
910         let lifetime_diff = lt1 != lt2;
911         values.0.push(lt1, lifetime_diff);
912         values.1.push(lt2, lifetime_diff);
913
914         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
915         //                           ^^^
916         values.0.push_normal("fn(");
917         values.1.push_normal("fn(");
918
919         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
920         //                              ^^^^^
921         let len1 = sig1.inputs().len();
922         let len2 = sig2.inputs().len();
923         if len1 == len2 {
924             for (i, (l, r)) in sig1.inputs().iter().zip(sig2.inputs().iter()).enumerate() {
925                 let (x1, x2) = self.cmp(l, r);
926                 (values.0).0.extend(x1.0);
927                 (values.1).0.extend(x2.0);
928                 self.push_comma(&mut values.0, &mut values.1, len1, i);
929             }
930         } else {
931             for (i, l) in sig1.inputs().iter().enumerate() {
932                 values.0.push_highlighted(l.to_string());
933                 if i != len1 - 1 {
934                     values.0.push_highlighted(", ");
935                 }
936             }
937             for (i, r) in sig2.inputs().iter().enumerate() {
938                 values.1.push_highlighted(r.to_string());
939                 if i != len2 - 1 {
940                     values.1.push_highlighted(", ");
941                 }
942             }
943         }
944
945         if sig1.c_variadic {
946             if len1 > 0 {
947                 values.0.push_normal(", ");
948             }
949             values.0.push("...", !sig2.c_variadic);
950         }
951         if sig2.c_variadic {
952             if len2 > 0 {
953                 values.1.push_normal(", ");
954             }
955             values.1.push("...", !sig1.c_variadic);
956         }
957
958         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
959         //                                   ^
960         values.0.push_normal(")");
961         values.1.push_normal(")");
962
963         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
964         //                                     ^^^^^^^^
965         let output1 = sig1.output();
966         let output2 = sig2.output();
967         let (x1, x2) = self.cmp(output1, output2);
968         if !output1.is_unit() {
969             values.0.push_normal(" -> ");
970             (values.0).0.extend(x1.0);
971         }
972         if !output2.is_unit() {
973             values.1.push_normal(" -> ");
974             (values.1).0.extend(x2.0);
975         }
976         values
977     }
978
979     /// Compares two given types, eliding parts that are the same between them and highlighting
980     /// relevant differences, and return two representation of those types for highlighted printing.
981     fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
982         debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind, t2, t2.kind);
983
984         // helper functions
985         fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
986             match (&a.kind, &b.kind) {
987                 (a, b) if *a == *b => true,
988                 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
989                 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Int(_))
990                 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Infer(ty::InferTy::IntVar(_)))
991                 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
992                 | (&ty::Infer(ty::InferTy::FloatVar(_)), &ty::Float(_))
993                 | (&ty::Infer(ty::InferTy::FloatVar(_)), &ty::Infer(ty::InferTy::FloatVar(_))) => {
994                     true
995                 }
996                 _ => false,
997             }
998         }
999
1000         fn push_ty_ref<'tcx>(
1001             r: &ty::Region<'tcx>,
1002             ty: Ty<'tcx>,
1003             mutbl: hir::Mutability,
1004             s: &mut DiagnosticStyledString,
1005         ) {
1006             let mut r = r.to_string();
1007             if r == "'_" {
1008                 r.clear();
1009             } else {
1010                 r.push(' ');
1011             }
1012             s.push_highlighted(format!("&{}{}", r, mutbl.prefix_str()));
1013             s.push_normal(ty.to_string());
1014         }
1015
1016         // process starts here
1017         match (&t1.kind, &t2.kind) {
1018             (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1019                 let sub_no_defaults_1 = self.strip_generic_default_params(def1.did, sub1);
1020                 let sub_no_defaults_2 = self.strip_generic_default_params(def2.did, sub2);
1021                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1022                 let path1 = self.tcx.def_path_str(def1.did.clone());
1023                 let path2 = self.tcx.def_path_str(def2.did.clone());
1024                 if def1.did == def2.did {
1025                     // Easy case. Replace same types with `_` to shorten the output and highlight
1026                     // the differing ones.
1027                     //     let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1028                     //     Foo<Bar, _>
1029                     //     Foo<Quz, _>
1030                     //         ---  ^ type argument elided
1031                     //         |
1032                     //         highlighted in output
1033                     values.0.push_normal(path1);
1034                     values.1.push_normal(path2);
1035
1036                     // Avoid printing out default generic parameters that are common to both
1037                     // types.
1038                     let len1 = sub_no_defaults_1.len();
1039                     let len2 = sub_no_defaults_2.len();
1040                     let common_len = cmp::min(len1, len2);
1041                     let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
1042                     let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
1043                     let common_default_params = remainder1
1044                         .iter()
1045                         .rev()
1046                         .zip(remainder2.iter().rev())
1047                         .filter(|(a, b)| a == b)
1048                         .count();
1049                     let len = sub1.len() - common_default_params;
1050                     let consts_offset = len - sub1.consts().count();
1051
1052                     // Only draw `<...>` if there're lifetime/type arguments.
1053                     if len > 0 {
1054                         values.0.push_normal("<");
1055                         values.1.push_normal("<");
1056                     }
1057
1058                     fn lifetime_display(lifetime: Region<'_>) -> String {
1059                         let s = lifetime.to_string();
1060                         if s.is_empty() {
1061                             "'_".to_string()
1062                         } else {
1063                             s
1064                         }
1065                     }
1066                     // At one point we'd like to elide all lifetimes here, they are irrelevant for
1067                     // all diagnostics that use this output
1068                     //
1069                     //     Foo<'x, '_, Bar>
1070                     //     Foo<'y, '_, Qux>
1071                     //         ^^  ^^  --- type arguments are not elided
1072                     //         |   |
1073                     //         |   elided as they were the same
1074                     //         not elided, they were different, but irrelevant
1075                     let lifetimes = sub1.regions().zip(sub2.regions());
1076                     for (i, lifetimes) in lifetimes.enumerate() {
1077                         let l1 = lifetime_display(lifetimes.0);
1078                         let l2 = lifetime_display(lifetimes.1);
1079                         if lifetimes.0 == lifetimes.1 {
1080                             values.0.push_normal("'_");
1081                             values.1.push_normal("'_");
1082                         } else {
1083                             values.0.push_highlighted(l1);
1084                             values.1.push_highlighted(l2);
1085                         }
1086                         self.push_comma(&mut values.0, &mut values.1, len, i);
1087                     }
1088
1089                     // We're comparing two types with the same path, so we compare the type
1090                     // arguments for both. If they are the same, do not highlight and elide from the
1091                     // output.
1092                     //     Foo<_, Bar>
1093                     //     Foo<_, Qux>
1094                     //         ^ elided type as this type argument was the same in both sides
1095                     let type_arguments = sub1.types().zip(sub2.types());
1096                     let regions_len = sub1.regions().count();
1097                     let num_display_types = consts_offset - regions_len;
1098                     for (i, (ta1, ta2)) in type_arguments.take(num_display_types).enumerate() {
1099                         let i = i + regions_len;
1100                         if ta1 == ta2 {
1101                             values.0.push_normal("_");
1102                             values.1.push_normal("_");
1103                         } else {
1104                             let (x1, x2) = self.cmp(ta1, ta2);
1105                             (values.0).0.extend(x1.0);
1106                             (values.1).0.extend(x2.0);
1107                         }
1108                         self.push_comma(&mut values.0, &mut values.1, len, i);
1109                     }
1110
1111                     // Do the same for const arguments, if they are equal, do not highlight and
1112                     // elide them from the output.
1113                     let const_arguments = sub1.consts().zip(sub2.consts());
1114                     for (i, (ca1, ca2)) in const_arguments.enumerate() {
1115                         let i = i + consts_offset;
1116                         if ca1 == ca2 {
1117                             values.0.push_normal("_");
1118                             values.1.push_normal("_");
1119                         } else {
1120                             values.0.push_highlighted(ca1.to_string());
1121                             values.1.push_highlighted(ca2.to_string());
1122                         }
1123                         self.push_comma(&mut values.0, &mut values.1, len, i);
1124                     }
1125
1126                     // Close the type argument bracket.
1127                     // Only draw `<...>` if there're lifetime/type arguments.
1128                     if len > 0 {
1129                         values.0.push_normal(">");
1130                         values.1.push_normal(">");
1131                     }
1132                     values
1133                 } else {
1134                     // Check for case:
1135                     //     let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1136                     //     Foo<Bar<Qux>
1137                     //         ------- this type argument is exactly the same as the other type
1138                     //     Bar<Qux>
1139                     if self.cmp_type_arg(
1140                         &mut values.0,
1141                         &mut values.1,
1142                         path1.clone(),
1143                         sub_no_defaults_1,
1144                         path2.clone(),
1145                         &t2,
1146                     ).is_some()
1147                     {
1148                         return values;
1149                     }
1150                     // Check for case:
1151                     //     let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1152                     //     Bar<Qux>
1153                     //     Foo<Bar<Qux>>
1154                     //         ------- this type argument is exactly the same as the other type
1155                     if self.cmp_type_arg(
1156                         &mut values.1,
1157                         &mut values.0,
1158                         path2,
1159                         sub_no_defaults_2,
1160                         path1,
1161                         &t1,
1162                     ).is_some()
1163                     {
1164                         return values;
1165                     }
1166
1167                     // We can't find anything in common, highlight relevant part of type path.
1168                     //     let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1169                     //     foo::bar::Baz<Qux>
1170                     //     foo::bar::Bar<Zar>
1171                     //               -------- this part of the path is different
1172
1173                     let t1_str = t1.to_string();
1174                     let t2_str = t2.to_string();
1175                     let min_len = t1_str.len().min(t2_str.len());
1176
1177                     const SEPARATOR: &str = "::";
1178                     let separator_len = SEPARATOR.len();
1179                     let split_idx: usize =
1180                         t1_str.split(SEPARATOR)
1181                             .zip(t2_str.split(SEPARATOR))
1182                             .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1183                             .map(|(mod_str, _)| mod_str.len() + separator_len)
1184                             .sum();
1185
1186                     debug!("cmp: separator_len={}, split_idx={}, min_len={}",
1187                         separator_len, split_idx, min_len
1188                     );
1189
1190                     if split_idx >= min_len {
1191                         // paths are identical, highlight everything
1192                         (
1193                             DiagnosticStyledString::highlighted(t1_str),
1194                             DiagnosticStyledString::highlighted(t2_str)
1195                         )
1196                     } else {
1197                         let (common, uniq1) = t1_str.split_at(split_idx);
1198                         let (_, uniq2) = t2_str.split_at(split_idx);
1199                         debug!("cmp: common={}, uniq1={}, uniq2={}", common, uniq1, uniq2);
1200
1201                         values.0.push_normal(common);
1202                         values.0.push_highlighted(uniq1);
1203                         values.1.push_normal(common);
1204                         values.1.push_highlighted(uniq2);
1205
1206                         values
1207                     }
1208                 }
1209             }
1210
1211             // When finding T != &T, highlight only the borrow
1212             (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
1213                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1214                 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1215                 values.1.push_normal(t2.to_string());
1216                 values
1217             }
1218             (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
1219                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1220                 values.0.push_normal(t1.to_string());
1221                 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1222                 values
1223             }
1224
1225             // When encountering &T != &mut T, highlight only the borrow
1226             (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1227                 if equals(&ref_ty1, &ref_ty2) =>
1228             {
1229                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1230                 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1231                 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1232                 values
1233             }
1234
1235             // When encountering tuples of the same size, highlight only the differing types
1236             (&ty::Tuple(substs1), &ty::Tuple(substs2)) if substs1.len() == substs2.len() => {
1237                 let mut values = (
1238                     DiagnosticStyledString::normal("("),
1239                     DiagnosticStyledString::normal("("),
1240                 );
1241                 let len = substs1.len();
1242                 for (i, (left, right)) in substs1.types().zip(substs2.types()).enumerate() {
1243                     let (x1, x2) = self.cmp(left, right);
1244                     (values.0).0.extend(x1.0);
1245                     (values.1).0.extend(x2.0);
1246                     self.push_comma(&mut values.0, &mut values.1, len, i);
1247                 }
1248                 if len == 1 { // Keep the output for single element tuples as `(ty,)`.
1249                     values.0.push_normal(",");
1250                     values.1.push_normal(",");
1251                 }
1252                 values.0.push_normal(")");
1253                 values.1.push_normal(")");
1254                 values
1255             }
1256
1257             (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1258                 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1259                 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1260                 let mut values = self.cmp_fn_sig(&sig1, &sig2);
1261                 let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did1, substs1));
1262                 let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did2, substs2));
1263                 let same_path = path1 == path2;
1264                 values.0.push(path1, !same_path);
1265                 values.1.push(path2, !same_path);
1266                 values
1267             }
1268
1269             (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => {
1270                 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1271                 let mut values = self.cmp_fn_sig(&sig1, sig2);
1272                 values.0.push_normal(format!(
1273                     " {{{}}}",
1274                     self.tcx.def_path_str_with_substs(*did1, substs1)),
1275                 );
1276                 values
1277             }
1278
1279             (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => {
1280                 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1281                 let mut values = self.cmp_fn_sig(sig1, &sig2);
1282                 values.1.push_normal(format!(
1283                     " {{{}}}",
1284                     self.tcx.def_path_str_with_substs(*did2, substs2)),
1285                 );
1286                 values
1287             }
1288
1289             (ty::FnPtr(sig1), ty::FnPtr(sig2)) => {
1290                 self.cmp_fn_sig(sig1, sig2)
1291             }
1292
1293             _ => {
1294                 if t1 == t2 {
1295                     // The two types are the same, elide and don't highlight.
1296                     (
1297                         DiagnosticStyledString::normal("_"),
1298                         DiagnosticStyledString::normal("_"),
1299                     )
1300                 } else {
1301                     // We couldn't find anything in common, highlight everything.
1302                     (
1303                         DiagnosticStyledString::highlighted(t1.to_string()),
1304                         DiagnosticStyledString::highlighted(t2.to_string()),
1305                     )
1306                 }
1307             }
1308         }
1309     }
1310
1311     pub fn note_type_err(
1312         &self,
1313         diag: &mut DiagnosticBuilder<'tcx>,
1314         cause: &ObligationCause<'tcx>,
1315         secondary_span: Option<(Span, String)>,
1316         mut values: Option<ValuePairs<'tcx>>,
1317         terr: &TypeError<'tcx>,
1318     ) {
1319         // For some types of errors, expected-found does not make
1320         // sense, so just ignore the values we were given.
1321         match terr {
1322             TypeError::CyclicTy(_) => {
1323                 values = None;
1324             }
1325             _ => {}
1326         }
1327
1328         debug!("note_type_err(diag={:?})", diag);
1329         let (expected_found, exp_found, is_simple_error) = match values {
1330             None => (None, None, false),
1331             Some(values) => {
1332                 let (is_simple_error, exp_found) = match values {
1333                     ValuePairs::Types(exp_found) => {
1334                         let is_simple_err = exp_found.expected.is_simple_text()
1335                             && exp_found.found.is_simple_text();
1336
1337                         (is_simple_err, Some(exp_found))
1338                     }
1339                     _ => (false, None),
1340                 };
1341                 let vals = match self.values_str(&values) {
1342                     Some((expected, found)) => Some((expected, found)),
1343                     None => {
1344                         // Derived error. Cancel the emitter.
1345                         diag.cancel();
1346                         return;
1347                     }
1348                 };
1349                 (vals, exp_found, is_simple_error)
1350             }
1351         };
1352
1353         let span = cause.span(self.tcx);
1354
1355         // Ignore msg for object safe coercion
1356         // since E0038 message will be printed
1357         match terr {
1358             TypeError::ObjectUnsafeCoercion(_) => {}
1359             _ => {
1360                 diag.span_label(span, terr.to_string());
1361                 if let Some((sp, msg)) = secondary_span {
1362                     diag.span_label(sp, msg);
1363                 }
1364             }
1365         };
1366
1367         if let Some((expected, found)) = expected_found {
1368             let expected_label = exp_found.map_or("type".into(), |ef| ef.expected.prefix_string());
1369             let found_label = exp_found.map_or("type".into(), |ef| ef.found.prefix_string());
1370             match (&terr, expected == found) {
1371                 (TypeError::Sorts(values), extra) => {
1372                     let sort_string = |ty: Ty<'tcx>| match (extra, &ty.kind) {
1373                         (true, ty::Opaque(def_id, _)) => format!(
1374                             " (opaque type at {})",
1375                             self.tcx.sess.source_map()
1376                                 .mk_substr_filename(self.tcx.def_span(*def_id)),
1377                         ),
1378                         (true, _) => format!(" ({})", ty.sort_string(self.tcx)),
1379                         (false, _) => "".to_string(),
1380                     };
1381                     if !(values.expected.is_simple_text() && values.found.is_simple_text()) || (
1382                         exp_found.map_or(false, |ef| {
1383                             // This happens when the type error is a subset of the expectation,
1384                             // like when you have two references but one is `usize` and the other
1385                             // is `f32`. In those cases we still want to show the `note`. If the
1386                             // value from `ef` is `Infer(_)`, then we ignore it.
1387                             if !ef.expected.is_ty_infer() {
1388                                 ef.expected != values.expected
1389                             } else if !ef.found.is_ty_infer() {
1390                                 ef.found != values.found
1391                             } else {
1392                                 false
1393                             }
1394                         })
1395                     ) {
1396                         diag.note_expected_found_extra(
1397                             &expected_label,
1398                             expected,
1399                             &found_label,
1400                             found,
1401                             &sort_string(values.expected),
1402                             &sort_string(values.found),
1403                         );
1404                     }
1405                 }
1406                 (TypeError::ObjectUnsafeCoercion(_), _) => {
1407                     diag.note_unsuccessfull_coercion(found, expected);
1408                 }
1409                 (_, _) => {
1410                     debug!(
1411                         "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1412                         exp_found, expected, found
1413                     );
1414                     if !is_simple_error || terr.must_include_note() {
1415                         diag.note_expected_found(&expected_label, expected, &found_label, found);
1416                     }
1417                 }
1418             }
1419         }
1420         if let Some(exp_found) = exp_found {
1421             self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1422         }
1423
1424         // In some (most?) cases cause.body_id points to actual body, but in some cases
1425         // it's a actual definition. According to the comments (e.g. in
1426         // librustc_typeck/check/compare_method.rs:compare_predicate_entailment) the latter
1427         // is relied upon by some other code. This might (or might not) need cleanup.
1428         let body_owner_def_id = self.tcx.hir().opt_local_def_id(cause.body_id)
1429             .unwrap_or_else(|| {
1430                 self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id })
1431             });
1432         self.check_and_note_conflicting_crates(diag, terr);
1433         self.tcx.note_and_explain_type_err(diag, terr, span, body_owner_def_id);
1434
1435         // It reads better to have the error origin as the final
1436         // thing.
1437         self.note_error_origin(diag, &cause, exp_found);
1438     }
1439
1440     /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
1441     /// suggests it.
1442     fn suggest_as_ref_where_appropriate(
1443         &self,
1444         span: Span,
1445         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1446         diag: &mut DiagnosticBuilder<'tcx>,
1447     ) {
1448         match (&exp_found.expected.kind, &exp_found.found.kind) {
1449             (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) => {
1450                 if let ty::Adt(found_def, found_substs) = found_ty.kind {
1451                     let path_str = format!("{:?}", exp_def);
1452                     if exp_def == &found_def {
1453                         let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
1454                                        `.as_ref()`";
1455                         let result_msg = "you can convert from `&Result<T, E>` to \
1456                                           `Result<&T, &E>` using `.as_ref()`";
1457                         let have_as_ref = &[
1458                             ("std::option::Option", opt_msg),
1459                             ("core::option::Option", opt_msg),
1460                             ("std::result::Result", result_msg),
1461                             ("core::result::Result", result_msg),
1462                         ];
1463                         if let Some(msg) = have_as_ref.iter()
1464                             .filter_map(|(path, msg)| if &path_str == path {
1465                                 Some(msg)
1466                             } else {
1467                                 None
1468                             }).next()
1469                         {
1470                             let mut show_suggestion = true;
1471                             for (exp_ty, found_ty) in exp_substs.types().zip(found_substs.types()) {
1472                                 match exp_ty.kind {
1473                                     ty::Ref(_, exp_ty, _) => {
1474                                         match (&exp_ty.kind, &found_ty.kind) {
1475                                             (_, ty::Param(_)) |
1476                                             (_, ty::Infer(_)) |
1477                                             (ty::Param(_), _) |
1478                                             (ty::Infer(_), _) => {}
1479                                             _ if ty::TyS::same_type(exp_ty, found_ty) => {}
1480                                             _ => show_suggestion = false,
1481                                         };
1482                                     }
1483                                     ty::Param(_) | ty::Infer(_) => {}
1484                                     _ => show_suggestion = false,
1485                                 }
1486                             }
1487                             if let (Ok(snippet), true) = (
1488                                 self.tcx.sess.source_map().span_to_snippet(span),
1489                                 show_suggestion,
1490                             ) {
1491                                 diag.span_suggestion(
1492                                     span,
1493                                     msg,
1494                                     format!("{}.as_ref()", snippet),
1495                                     Applicability::MachineApplicable,
1496                                 );
1497                             }
1498                         }
1499                     }
1500                 }
1501             }
1502             _ => {}
1503         }
1504     }
1505
1506     pub fn report_and_explain_type_error(
1507         &self,
1508         trace: TypeTrace<'tcx>,
1509         terr: &TypeError<'tcx>,
1510     ) -> DiagnosticBuilder<'tcx> {
1511         debug!(
1512             "report_and_explain_type_error(trace={:?}, terr={:?})",
1513             trace, terr
1514         );
1515
1516         let span = trace.cause.span(self.tcx);
1517         let failure_code = trace.cause.as_failure_code(terr);
1518         let mut diag = match failure_code {
1519             FailureCode::Error0038(did) => {
1520                 let violations = self.tcx.object_safety_violations(did);
1521                 self.tcx.report_object_safety_error(span, did, violations)
1522             }
1523             FailureCode::Error0317(failure_str) => {
1524                 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
1525             }
1526             FailureCode::Error0580(failure_str) => {
1527                 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
1528             }
1529             FailureCode::Error0308(failure_str) => {
1530                 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
1531             }
1532             FailureCode::Error0644(failure_str) => {
1533                 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
1534             }
1535         };
1536         self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
1537         diag
1538     }
1539
1540     fn values_str(
1541         &self,
1542         values: &ValuePairs<'tcx>,
1543     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1544         match *values {
1545             infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
1546             infer::Regions(ref exp_found) => self.expected_found_str(exp_found),
1547             infer::Consts(ref exp_found) => self.expected_found_str(exp_found),
1548             infer::TraitRefs(ref exp_found) => {
1549                 let pretty_exp_found = ty::error::ExpectedFound {
1550                     expected: exp_found.expected.print_only_trait_path(),
1551                     found: exp_found.found.print_only_trait_path()
1552                 };
1553                 self.expected_found_str(&pretty_exp_found)
1554             },
1555             infer::PolyTraitRefs(ref exp_found) => {
1556                 let pretty_exp_found = ty::error::ExpectedFound {
1557                     expected: exp_found.expected.print_only_trait_path(),
1558                     found: exp_found.found.print_only_trait_path()
1559                 };
1560                 self.expected_found_str(&pretty_exp_found)
1561             },
1562         }
1563     }
1564
1565     fn expected_found_str_ty(
1566         &self,
1567         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1568     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1569         let exp_found = self.resolve_vars_if_possible(exp_found);
1570         if exp_found.references_error() {
1571             return None;
1572         }
1573
1574         Some(self.cmp(exp_found.expected, exp_found.found))
1575     }
1576
1577     /// Returns a string of the form "expected `{}`, found `{}`".
1578     fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
1579         &self,
1580         exp_found: &ty::error::ExpectedFound<T>,
1581     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1582         let exp_found = self.resolve_vars_if_possible(exp_found);
1583         if exp_found.references_error() {
1584             return None;
1585         }
1586
1587         Some((
1588             DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
1589             DiagnosticStyledString::highlighted(exp_found.found.to_string()),
1590         ))
1591     }
1592
1593     pub fn report_generic_bound_failure(
1594         &self,
1595         region_scope_tree: &region::ScopeTree,
1596         span: Span,
1597         origin: Option<SubregionOrigin<'tcx>>,
1598         bound_kind: GenericKind<'tcx>,
1599         sub: Region<'tcx>,
1600     ) {
1601         self.construct_generic_bound_failure(region_scope_tree, span, origin, bound_kind, sub)
1602             .emit()
1603     }
1604
1605     pub fn construct_generic_bound_failure(
1606         &self,
1607         region_scope_tree: &region::ScopeTree,
1608         span: Span,
1609         origin: Option<SubregionOrigin<'tcx>>,
1610         bound_kind: GenericKind<'tcx>,
1611         sub: Region<'tcx>,
1612     ) -> DiagnosticBuilder<'a> {
1613         // Attempt to obtain the span of the parameter so we can
1614         // suggest adding an explicit lifetime bound to it.
1615         let type_param_span = match (self.in_progress_tables, bound_kind) {
1616             (Some(ref table), GenericKind::Param(ref param)) => {
1617                 let table = table.borrow();
1618                 table.local_id_root.and_then(|did| {
1619                     let generics = self.tcx.generics_of(did);
1620                     // Account for the case where `did` corresponds to `Self`, which doesn't have
1621                     // the expected type argument.
1622                     if !(generics.has_self && param.index == 0) {
1623                         let type_param = generics.type_param(param, self.tcx);
1624                         let hir = &self.tcx.hir();
1625                         hir.as_local_hir_id(type_param.def_id).map(|id| {
1626                             // Get the `hir::Param` to verify whether it already has any bounds.
1627                             // We do this to avoid suggesting code that ends up as `T: 'a'b`,
1628                             // instead we suggest `T: 'a + 'b` in that case.
1629                             let mut has_bounds = false;
1630                             if let Node::GenericParam(param) = hir.get(id) {
1631                                 has_bounds = !param.bounds.is_empty();
1632                             }
1633                             let sp = hir.span(id);
1634                             // `sp` only covers `T`, change it so that it covers
1635                             // `T:` when appropriate
1636                             let is_impl_trait = bound_kind.to_string().starts_with("impl ");
1637                             let sp = if has_bounds && !is_impl_trait {
1638                                 sp.to(self.tcx
1639                                     .sess
1640                                     .source_map()
1641                                     .next_point(self.tcx.sess.source_map().next_point(sp)))
1642                             } else {
1643                                 sp
1644                             };
1645                             (sp, has_bounds, is_impl_trait)
1646                         })
1647                     } else {
1648                         None
1649                     }
1650                 })
1651             }
1652             _ => None,
1653         };
1654
1655         let labeled_user_string = match bound_kind {
1656             GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
1657             GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
1658         };
1659
1660         if let Some(SubregionOrigin::CompareImplMethodObligation {
1661             span,
1662             item_name,
1663             impl_item_def_id,
1664             trait_item_def_id,
1665         }) = origin
1666         {
1667             return self.report_extra_impl_obligation(
1668                 span,
1669                 item_name,
1670                 impl_item_def_id,
1671                 trait_item_def_id,
1672                 &format!("`{}: {}`", bound_kind, sub),
1673             );
1674         }
1675
1676         fn binding_suggestion<'tcx, S: fmt::Display>(
1677             err: &mut DiagnosticBuilder<'tcx>,
1678             type_param_span: Option<(Span, bool, bool)>,
1679             bound_kind: GenericKind<'tcx>,
1680             sub: S,
1681         ) {
1682             let consider = format!(
1683                 "consider adding an explicit lifetime bound {}",
1684                 if type_param_span.map(|(_, _, is_impl_trait)| is_impl_trait).unwrap_or(false) {
1685                     format!(" `{}` to `{}`...", sub, bound_kind)
1686                 } else {
1687                     format!("`{}: {}`...", bound_kind, sub)
1688                 },
1689             );
1690             if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
1691                 let suggestion = if is_impl_trait {
1692                     format!("{} + {}", bound_kind, sub)
1693                 } else {
1694                     let tail = if has_lifetimes { " + " } else { "" };
1695                     format!("{}: {}{}", bound_kind, sub, tail)
1696                 };
1697                 err.span_suggestion_short(
1698                     sp,
1699                     &consider,
1700                     suggestion,
1701                     Applicability::MaybeIncorrect, // Issue #41966
1702                 );
1703             } else {
1704                 err.help(&consider);
1705             }
1706         }
1707
1708         let mut err = match *sub {
1709             ty::ReEarlyBound(_)
1710             | ty::ReFree(ty::FreeRegion {
1711                 bound_region: ty::BrNamed(..),
1712                 ..
1713             }) => {
1714                 // Does the required lifetime have a nice name we can print?
1715                 let mut err = struct_span_err!(
1716                     self.tcx.sess,
1717                     span,
1718                     E0309,
1719                     "{} may not live long enough",
1720                     labeled_user_string
1721                 );
1722                 binding_suggestion(&mut err, type_param_span, bound_kind, sub);
1723                 err
1724             }
1725
1726             ty::ReStatic => {
1727                 // Does the required lifetime have a nice name we can print?
1728                 let mut err = struct_span_err!(
1729                     self.tcx.sess,
1730                     span,
1731                     E0310,
1732                     "{} may not live long enough",
1733                     labeled_user_string
1734                 );
1735                 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
1736                 err
1737             }
1738
1739             _ => {
1740                 // If not, be less specific.
1741                 let mut err = struct_span_err!(
1742                     self.tcx.sess,
1743                     span,
1744                     E0311,
1745                     "{} may not live long enough",
1746                     labeled_user_string
1747                 );
1748                 err.help(&format!(
1749                     "consider adding an explicit lifetime bound for `{}`",
1750                     bound_kind
1751                 ));
1752                 self.tcx.note_and_explain_region(
1753                     region_scope_tree,
1754                     &mut err,
1755                     &format!("{} must be valid for ", labeled_user_string),
1756                     sub,
1757                     "...",
1758                 );
1759                 err
1760             }
1761         };
1762
1763         if let Some(origin) = origin {
1764             self.note_region_origin(&mut err, &origin);
1765         }
1766         err
1767     }
1768
1769     fn report_sub_sup_conflict(
1770         &self,
1771         region_scope_tree: &region::ScopeTree,
1772         var_origin: RegionVariableOrigin,
1773         sub_origin: SubregionOrigin<'tcx>,
1774         sub_region: Region<'tcx>,
1775         sup_origin: SubregionOrigin<'tcx>,
1776         sup_region: Region<'tcx>,
1777     ) {
1778         let mut err = self.report_inference_failure(var_origin);
1779
1780         self.tcx.note_and_explain_region(
1781             region_scope_tree,
1782             &mut err,
1783             "first, the lifetime cannot outlive ",
1784             sup_region,
1785             "...",
1786         );
1787
1788         match (&sup_origin, &sub_origin) {
1789             (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) => {
1790                 debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
1791                 debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
1792                 debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
1793                 debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
1794                 debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
1795                 debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
1796                 debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
1797                 debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
1798                 debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
1799
1800                 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) = (
1801                     self.values_str(&sup_trace.values),
1802                     self.values_str(&sub_trace.values),
1803                 ) {
1804                     if sub_expected == sup_expected && sub_found == sup_found {
1805                         self.tcx.note_and_explain_region(
1806                             region_scope_tree,
1807                             &mut err,
1808                             "...but the lifetime must also be valid for ",
1809                             sub_region,
1810                             "...",
1811                         );
1812                         err.note(&format!(
1813                             "...so that the {}:\nexpected {}\n   found {}",
1814                             sup_trace.cause.as_requirement_str(),
1815                             sup_expected.content(),
1816                             sup_found.content()
1817                         ));
1818                         err.emit();
1819                         return;
1820                     }
1821                 }
1822             }
1823             _ => {}
1824         }
1825
1826         self.note_region_origin(&mut err, &sup_origin);
1827
1828         self.tcx.note_and_explain_region(
1829             region_scope_tree,
1830             &mut err,
1831             "but, the lifetime must be valid for ",
1832             sub_region,
1833             "...",
1834         );
1835
1836         self.note_region_origin(&mut err, &sub_origin);
1837         err.emit();
1838     }
1839 }
1840
1841 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
1842     fn report_inference_failure(
1843         &self,
1844         var_origin: RegionVariableOrigin,
1845     ) -> DiagnosticBuilder<'tcx> {
1846         let br_string = |br: ty::BoundRegion| {
1847             let mut s = match br {
1848                 ty::BrNamed(_, name) => name.to_string(),
1849                 _ => String::new(),
1850             };
1851             if !s.is_empty() {
1852                 s.push_str(" ");
1853             }
1854             s
1855         };
1856         let var_description = match var_origin {
1857             infer::MiscVariable(_) => String::new(),
1858             infer::PatternRegion(_) => " for pattern".to_string(),
1859             infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1860             infer::Autoref(_) => " for autoref".to_string(),
1861             infer::Coercion(_) => " for automatic coercion".to_string(),
1862             infer::LateBoundRegion(_, br, infer::FnCall) => {
1863                 format!(" for lifetime parameter {}in function call", br_string(br))
1864             }
1865             infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1866                 format!(" for lifetime parameter {}in generic type", br_string(br))
1867             }
1868             infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
1869                 " for lifetime parameter {}in trait containing associated type `{}`",
1870                 br_string(br),
1871                 self.tcx.associated_item(def_id).ident
1872             ),
1873             infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
1874             infer::BoundRegionInCoherence(name) => {
1875                 format!(" for lifetime parameter `{}` in coherence check", name)
1876             }
1877             infer::UpvarRegion(ref upvar_id, _) => {
1878                 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
1879                 format!(" for capture of `{}` by closure", var_name)
1880             }
1881             infer::NLL(..) => bug!("NLL variable found in lexical phase"),
1882         };
1883
1884         struct_span_err!(
1885             self.tcx.sess,
1886             var_origin.span(),
1887             E0495,
1888             "cannot infer an appropriate lifetime{} \
1889              due to conflicting requirements",
1890             var_description
1891         )
1892     }
1893 }
1894
1895 enum FailureCode {
1896     Error0038(DefId),
1897     Error0317(&'static str),
1898     Error0580(&'static str),
1899     Error0308(&'static str),
1900     Error0644(&'static str),
1901 }
1902
1903 impl<'tcx> ObligationCause<'tcx> {
1904     fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
1905         use self::FailureCode::*;
1906         use crate::traits::ObligationCauseCode::*;
1907         match self.code {
1908             CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
1909             MatchExpressionArm(box MatchExpressionArmCause { source, .. }) =>
1910                 Error0308(match source {
1911                     hir::MatchSource::IfLetDesugar { .. } =>
1912                         "`if let` arms have incompatible types",
1913                     hir::MatchSource::TryDesugar => {
1914                         "try expression alternatives have incompatible types"
1915                     }
1916                     _ => "match arms have incompatible types",
1917                 }),
1918             IfExpression { .. } => Error0308("if and else have incompatible types"),
1919             IfExpressionWithNoElse => Error0317("if may be missing an else clause"),
1920             MainFunctionType => Error0580("main function has wrong type"),
1921             StartFunctionType => Error0308("start function has wrong type"),
1922             IntrinsicType => Error0308("intrinsic has wrong type"),
1923             MethodReceiver => Error0308("mismatched `self` parameter type"),
1924
1925             // In the case where we have no more specific thing to
1926             // say, also take a look at the error code, maybe we can
1927             // tailor to that.
1928             _ => match terr {
1929                 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
1930                     Error0644("closure/generator type that references itself")
1931                 }
1932                 TypeError::IntrinsicCast => {
1933                     Error0308("cannot coerce intrinsics to function pointers")
1934                 }
1935                 TypeError::ObjectUnsafeCoercion(did) => Error0038(did.clone()),
1936                 _ => Error0308("mismatched types"),
1937             },
1938         }
1939     }
1940
1941     fn as_requirement_str(&self) -> &'static str {
1942         use crate::traits::ObligationCauseCode::*;
1943         match self.code {
1944             CompareImplMethodObligation { .. } => "method type is compatible with trait",
1945             ExprAssignable => "expression is assignable",
1946             MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => match source {
1947                 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
1948                 _ => "match arms have compatible types",
1949             },
1950             IfExpression { .. } => "if and else have incompatible types",
1951             IfExpressionWithNoElse => "if missing an else returns ()",
1952             MainFunctionType => "`main` function has the correct type",
1953             StartFunctionType => "`start` function has the correct type",
1954             IntrinsicType => "intrinsic has the correct type",
1955             MethodReceiver => "method receiver has the correct type",
1956             _ => "types are compatible",
1957         }
1958     }
1959 }