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