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