]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/error_reporting/mod.rs
Remove logging iterator
[rust.git] / compiler / rustc_infer / src / 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::infer;
53 use crate::traits::error_reporting::report_object_safety_error;
54 use crate::traits::{
55     IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
56     StatementAsExpression,
57 };
58
59 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
60 use rustc_errors::{pluralize, struct_span_err};
61 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString};
62 use rustc_hir as hir;
63 use rustc_hir::def_id::DefId;
64 use rustc_hir::lang_items::LangItem;
65 use rustc_hir::{Item, ItemKind, Node};
66 use rustc_middle::ty::error::TypeError;
67 use rustc_middle::ty::{
68     self,
69     subst::{Subst, SubstsRef},
70     Region, Ty, TyCtxt, TypeFoldable,
71 };
72 use rustc_span::{sym, BytePos, DesugaringKind, Pos, Span};
73 use rustc_target::spec::abi;
74 use std::ops::ControlFlow;
75 use std::{cmp, fmt};
76
77 mod note;
78
79 mod need_type_info;
80 pub use need_type_info::TypeAnnotationNeeded;
81
82 pub mod nice_region_error;
83
84 pub(super) fn note_and_explain_region(
85     tcx: TyCtxt<'tcx>,
86     err: &mut DiagnosticBuilder<'_>,
87     prefix: &str,
88     region: ty::Region<'tcx>,
89     suffix: &str,
90 ) {
91     let (description, span) = match *region {
92         ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
93             msg_span_from_free_region(tcx, region)
94         }
95
96         ty::ReEmpty(ty::UniverseIndex::ROOT) => ("the empty lifetime".to_owned(), None),
97
98         // uh oh, hope no user ever sees THIS
99         ty::ReEmpty(ui) => (format!("the empty lifetime in universe {:?}", ui), None),
100
101         ty::RePlaceholder(_) => return,
102
103         // FIXME(#13998) RePlaceholder should probably print like
104         // ReFree rather than dumping Debug output on the user.
105         //
106         // We shouldn't really be having unification failures with ReVar
107         // and ReLateBound though.
108         ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
109             (format!("lifetime {:?}", region), None)
110         }
111     };
112
113     emit_msg_span(err, prefix, description, span, suffix);
114 }
115
116 pub(super) fn note_and_explain_free_region(
117     tcx: TyCtxt<'tcx>,
118     err: &mut DiagnosticBuilder<'_>,
119     prefix: &str,
120     region: ty::Region<'tcx>,
121     suffix: &str,
122 ) {
123     let (description, span) = msg_span_from_free_region(tcx, region);
124
125     emit_msg_span(err, prefix, description, span, suffix);
126 }
127
128 fn msg_span_from_free_region(
129     tcx: TyCtxt<'tcx>,
130     region: ty::Region<'tcx>,
131 ) -> (String, Option<Span>) {
132     match *region {
133         ty::ReEarlyBound(_) | ty::ReFree(_) => {
134             msg_span_from_early_bound_and_free_regions(tcx, region)
135         }
136         ty::ReStatic => ("the static lifetime".to_owned(), None),
137         ty::ReEmpty(ty::UniverseIndex::ROOT) => ("an empty lifetime".to_owned(), None),
138         ty::ReEmpty(ui) => (format!("an empty lifetime in universe {:?}", ui), None),
139         _ => bug!("{:?}", region),
140     }
141 }
142
143 fn msg_span_from_early_bound_and_free_regions(
144     tcx: TyCtxt<'tcx>,
145     region: ty::Region<'tcx>,
146 ) -> (String, Option<Span>) {
147     let sm = tcx.sess.source_map();
148
149     let scope = region.free_region_binding_scope(tcx);
150     let node = tcx.hir().local_def_id_to_hir_id(scope.expect_local());
151     let tag = match tcx.hir().find(node) {
152         Some(Node::Block(_) | Node::Expr(_)) => "body",
153         Some(Node::Item(it)) => item_scope_tag(&it),
154         Some(Node::TraitItem(it)) => trait_item_scope_tag(&it),
155         Some(Node::ImplItem(it)) => impl_item_scope_tag(&it),
156         Some(Node::ForeignItem(it)) => foreign_item_scope_tag(&it),
157         _ => unreachable!(),
158     };
159     let (prefix, span) = match *region {
160         ty::ReEarlyBound(ref br) => {
161             let mut sp = sm.guess_head_span(tcx.hir().span(node));
162             if let Some(param) =
163                 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(br.name))
164             {
165                 sp = param.span;
166             }
167             (format!("the lifetime `{}` as defined on", br.name), sp)
168         }
169         ty::ReFree(ty::FreeRegion {
170             bound_region: ty::BoundRegionKind::BrNamed(_, name), ..
171         }) => {
172             let mut sp = sm.guess_head_span(tcx.hir().span(node));
173             if let Some(param) =
174                 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(name))
175             {
176                 sp = param.span;
177             }
178             (format!("the lifetime `{}` as defined on", name), sp)
179         }
180         ty::ReFree(ref fr) => match fr.bound_region {
181             ty::BrAnon(idx) => {
182                 (format!("the anonymous lifetime #{} defined on", idx + 1), tcx.hir().span(node))
183             }
184             _ => (
185                 format!("the lifetime `{}` as defined on", region),
186                 sm.guess_head_span(tcx.hir().span(node)),
187             ),
188         },
189         _ => bug!(),
190     };
191     let (msg, opt_span) = explain_span(tcx, tag, span);
192     (format!("{} {}", prefix, msg), opt_span)
193 }
194
195 fn emit_msg_span(
196     err: &mut DiagnosticBuilder<'_>,
197     prefix: &str,
198     description: String,
199     span: Option<Span>,
200     suffix: &str,
201 ) {
202     let message = format!("{}{}{}", prefix, description, suffix);
203
204     if let Some(span) = span {
205         err.span_note(span, &message);
206     } else {
207         err.note(&message);
208     }
209 }
210
211 fn item_scope_tag(item: &hir::Item<'_>) -> &'static str {
212     match item.kind {
213         hir::ItemKind::Impl { .. } => "impl",
214         hir::ItemKind::Struct(..) => "struct",
215         hir::ItemKind::Union(..) => "union",
216         hir::ItemKind::Enum(..) => "enum",
217         hir::ItemKind::Trait(..) => "trait",
218         hir::ItemKind::Fn(..) => "function body",
219         _ => "item",
220     }
221 }
222
223 fn trait_item_scope_tag(item: &hir::TraitItem<'_>) -> &'static str {
224     match item.kind {
225         hir::TraitItemKind::Fn(..) => "method body",
226         hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => "associated item",
227     }
228 }
229
230 fn impl_item_scope_tag(item: &hir::ImplItem<'_>) -> &'static str {
231     match item.kind {
232         hir::ImplItemKind::Fn(..) => "method body",
233         hir::ImplItemKind::Const(..) | hir::ImplItemKind::TyAlias(..) => "associated item",
234     }
235 }
236
237 fn foreign_item_scope_tag(item: &hir::ForeignItem<'_>) -> &'static str {
238     match item.kind {
239         hir::ForeignItemKind::Fn(..) => "method body",
240         hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => "associated item",
241     }
242 }
243
244 fn explain_span(tcx: TyCtxt<'tcx>, heading: &str, span: Span) -> (String, Option<Span>) {
245     let lo = tcx.sess.source_map().lookup_char_pos(span.lo());
246     (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1), Some(span))
247 }
248
249 pub fn unexpected_hidden_region_diagnostic(
250     tcx: TyCtxt<'tcx>,
251     span: Span,
252     hidden_ty: Ty<'tcx>,
253     hidden_region: ty::Region<'tcx>,
254 ) -> DiagnosticBuilder<'tcx> {
255     let mut err = struct_span_err!(
256         tcx.sess,
257         span,
258         E0700,
259         "hidden type for `impl Trait` captures lifetime that does not appear in bounds",
260     );
261
262     // Explain the region we are capturing.
263     match hidden_region {
264         ty::ReEmpty(ty::UniverseIndex::ROOT) => {
265             // All lifetimes shorter than the function body are `empty` in
266             // lexical region resolution. The default explanation of "an empty
267             // lifetime" isn't really accurate here.
268             let message = format!(
269                 "hidden type `{}` captures lifetime smaller than the function body",
270                 hidden_ty
271             );
272             err.span_note(span, &message);
273         }
274         ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic | ty::ReEmpty(_) => {
275             // Assuming regionck succeeded (*), we ought to always be
276             // capturing *some* region from the fn header, and hence it
277             // ought to be free. So under normal circumstances, we will go
278             // down this path which gives a decent human readable
279             // explanation.
280             //
281             // (*) if not, the `tainted_by_errors` field would be set to
282             // `Some(ErrorReported)` in any case, so we wouldn't be here at all.
283             note_and_explain_free_region(
284                 tcx,
285                 &mut err,
286                 &format!("hidden type `{}` captures ", hidden_ty),
287                 hidden_region,
288                 "",
289             );
290         }
291         _ => {
292             // Ugh. This is a painful case: the hidden region is not one
293             // that we can easily summarize or explain. This can happen
294             // in a case like
295             // `src/test/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
296             //
297             // ```
298             // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
299             //   if condition() { a } else { b }
300             // }
301             // ```
302             //
303             // Here the captured lifetime is the intersection of `'a` and
304             // `'b`, which we can't quite express.
305
306             // We can at least report a really cryptic error for now.
307             note_and_explain_region(
308                 tcx,
309                 &mut err,
310                 &format!("hidden type `{}` captures ", hidden_ty),
311                 hidden_region,
312                 "",
313             );
314         }
315     }
316
317     err
318 }
319
320 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
321     pub fn report_region_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>) {
322         debug!("report_region_errors(): {} errors to start", errors.len());
323
324         // try to pre-process the errors, which will group some of them
325         // together into a `ProcessedErrors` group:
326         let errors = self.process_errors(errors);
327
328         debug!("report_region_errors: {} errors after preprocessing", errors.len());
329
330         for error in errors {
331             debug!("report_region_errors: error = {:?}", error);
332
333             if !self.try_report_nice_region_error(&error) {
334                 match error.clone() {
335                     // These errors could indicate all manner of different
336                     // problems with many different solutions. Rather
337                     // than generate a "one size fits all" error, what we
338                     // attempt to do is go through a number of specific
339                     // scenarios and try to find the best way to present
340                     // the error. If all of these fails, we fall back to a rather
341                     // general bit of code that displays the error information
342                     RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
343                         if sub.is_placeholder() || sup.is_placeholder() {
344                             self.report_placeholder_failure(origin, sub, sup).emit();
345                         } else {
346                             self.report_concrete_failure(origin, sub, sup).emit();
347                         }
348                     }
349
350                     RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
351                         self.report_generic_bound_failure(
352                             origin.span(),
353                             Some(origin),
354                             param_ty,
355                             sub,
356                         );
357                     }
358
359                     RegionResolutionError::SubSupConflict(
360                         _,
361                         var_origin,
362                         sub_origin,
363                         sub_r,
364                         sup_origin,
365                         sup_r,
366                     ) => {
367                         if sub_r.is_placeholder() {
368                             self.report_placeholder_failure(sub_origin, sub_r, sup_r).emit();
369                         } else if sup_r.is_placeholder() {
370                             self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
371                         } else {
372                             self.report_sub_sup_conflict(
373                                 var_origin, sub_origin, sub_r, sup_origin, sup_r,
374                             );
375                         }
376                     }
377
378                     RegionResolutionError::UpperBoundUniverseConflict(
379                         _,
380                         _,
381                         var_universe,
382                         sup_origin,
383                         sup_r,
384                     ) => {
385                         assert!(sup_r.is_placeholder());
386
387                         // Make a dummy value for the "sub region" --
388                         // this is the initial value of the
389                         // placeholder. In practice, we expect more
390                         // tailored errors that don't really use this
391                         // value.
392                         let sub_r = self.tcx.mk_region(ty::ReEmpty(var_universe));
393
394                         self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
395                     }
396
397                     RegionResolutionError::MemberConstraintFailure {
398                         hidden_ty,
399                         member_region,
400                         span,
401                     } => {
402                         let hidden_ty = self.resolve_vars_if_possible(hidden_ty);
403                         unexpected_hidden_region_diagnostic(
404                             self.tcx,
405                             span,
406                             hidden_ty,
407                             member_region,
408                         )
409                         .emit();
410                     }
411                 }
412             }
413         }
414     }
415
416     // This method goes through all the errors and try to group certain types
417     // of error together, for the purpose of suggesting explicit lifetime
418     // parameters to the user. This is done so that we can have a more
419     // complete view of what lifetimes should be the same.
420     // If the return value is an empty vector, it means that processing
421     // failed (so the return value of this method should not be used).
422     //
423     // The method also attempts to weed out messages that seem like
424     // duplicates that will be unhelpful to the end-user. But
425     // obviously it never weeds out ALL errors.
426     fn process_errors(
427         &self,
428         errors: &[RegionResolutionError<'tcx>],
429     ) -> Vec<RegionResolutionError<'tcx>> {
430         debug!("process_errors()");
431
432         // We want to avoid reporting generic-bound failures if we can
433         // avoid it: these have a very high rate of being unhelpful in
434         // practice. This is because they are basically secondary
435         // checks that test the state of the region graph after the
436         // rest of inference is done, and the other kinds of errors
437         // indicate that the region constraint graph is internally
438         // inconsistent, so these test results are likely to be
439         // meaningless.
440         //
441         // Therefore, we filter them out of the list unless they are
442         // the only thing in the list.
443
444         let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
445             RegionResolutionError::GenericBoundFailure(..) => true,
446             RegionResolutionError::ConcreteFailure(..)
447             | RegionResolutionError::SubSupConflict(..)
448             | RegionResolutionError::UpperBoundUniverseConflict(..)
449             | RegionResolutionError::MemberConstraintFailure { .. } => false,
450         };
451
452         let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
453             errors.to_owned()
454         } else {
455             errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
456         };
457
458         // sort the errors by span, for better error message stability.
459         errors.sort_by_key(|u| match *u {
460             RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
461             RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
462             RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _) => rvo.span(),
463             RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(),
464             RegionResolutionError::MemberConstraintFailure { span, .. } => span,
465         });
466         errors
467     }
468
469     /// Adds a note if the types come from similarly named crates
470     fn check_and_note_conflicting_crates(
471         &self,
472         err: &mut DiagnosticBuilder<'_>,
473         terr: &TypeError<'tcx>,
474     ) {
475         use hir::def_id::CrateNum;
476         use rustc_hir::definitions::DisambiguatedDefPathData;
477         use ty::print::Printer;
478         use ty::subst::GenericArg;
479
480         struct AbsolutePathPrinter<'tcx> {
481             tcx: TyCtxt<'tcx>,
482         }
483
484         struct NonTrivialPath;
485
486         impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
487             type Error = NonTrivialPath;
488
489             type Path = Vec<String>;
490             type Region = !;
491             type Type = !;
492             type DynExistential = !;
493             type Const = !;
494
495             fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
496                 self.tcx
497             }
498
499             fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
500                 Err(NonTrivialPath)
501             }
502
503             fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
504                 Err(NonTrivialPath)
505             }
506
507             fn print_dyn_existential(
508                 self,
509                 _predicates: &'tcx ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>,
510             ) -> Result<Self::DynExistential, Self::Error> {
511                 Err(NonTrivialPath)
512             }
513
514             fn print_const(self, _ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
515                 Err(NonTrivialPath)
516             }
517
518             fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
519                 Ok(vec![self.tcx.original_crate_name(cnum).to_string()])
520             }
521             fn path_qualified(
522                 self,
523                 _self_ty: Ty<'tcx>,
524                 _trait_ref: Option<ty::TraitRef<'tcx>>,
525             ) -> Result<Self::Path, Self::Error> {
526                 Err(NonTrivialPath)
527             }
528
529             fn path_append_impl(
530                 self,
531                 _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
532                 _disambiguated_data: &DisambiguatedDefPathData,
533                 _self_ty: Ty<'tcx>,
534                 _trait_ref: Option<ty::TraitRef<'tcx>>,
535             ) -> Result<Self::Path, Self::Error> {
536                 Err(NonTrivialPath)
537             }
538             fn path_append(
539                 self,
540                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
541                 disambiguated_data: &DisambiguatedDefPathData,
542             ) -> Result<Self::Path, Self::Error> {
543                 let mut path = print_prefix(self)?;
544                 path.push(disambiguated_data.to_string());
545                 Ok(path)
546             }
547             fn path_generic_args(
548                 self,
549                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
550                 _args: &[GenericArg<'tcx>],
551             ) -> Result<Self::Path, Self::Error> {
552                 print_prefix(self)
553             }
554         }
555
556         let report_path_match = |err: &mut DiagnosticBuilder<'_>, did1: DefId, did2: DefId| {
557             // Only external crates, if either is from a local
558             // module we could have false positives
559             if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
560                 let abs_path =
561                     |def_id| AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]);
562
563                 // We compare strings because DefPath can be different
564                 // for imported and non-imported crates
565                 let same_path = || -> Result<_, NonTrivialPath> {
566                     Ok(self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2)
567                         || abs_path(did1)? == abs_path(did2)?)
568                 };
569                 if same_path().unwrap_or(false) {
570                     let crate_name = self.tcx.crate_name(did1.krate);
571                     err.note(&format!(
572                         "perhaps two different versions of crate `{}` are being used?",
573                         crate_name
574                     ));
575                 }
576             }
577         };
578         match *terr {
579             TypeError::Sorts(ref exp_found) => {
580                 // if they are both "path types", there's a chance of ambiguity
581                 // due to different versions of the same crate
582                 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
583                     (exp_found.expected.kind(), exp_found.found.kind())
584                 {
585                     report_path_match(err, exp_adt.did, found_adt.did);
586                 }
587             }
588             TypeError::Traits(ref exp_found) => {
589                 report_path_match(err, exp_found.expected, exp_found.found);
590             }
591             _ => (), // FIXME(#22750) handle traits and stuff
592         }
593     }
594
595     fn note_error_origin(
596         &self,
597         err: &mut DiagnosticBuilder<'tcx>,
598         cause: &ObligationCause<'tcx>,
599         exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
600     ) {
601         match cause.code {
602             ObligationCauseCode::Pattern { origin_expr: true, span: Some(span), root_ty } => {
603                 let ty = self.resolve_vars_if_possible(root_ty);
604                 if ty.is_suggestable() {
605                     // don't show type `_`
606                     err.span_label(span, format!("this expression has type `{}`", ty));
607                 }
608                 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found {
609                     if ty.is_box() && ty.boxed_ty() == found {
610                         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
611                             err.span_suggestion(
612                                 span,
613                                 "consider dereferencing the boxed value",
614                                 format!("*{}", snippet),
615                                 Applicability::MachineApplicable,
616                             );
617                         }
618                     }
619                 }
620             }
621             ObligationCauseCode::Pattern { origin_expr: false, span: Some(span), .. } => {
622                 err.span_label(span, "expected due to this");
623             }
624             ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
625                 semi_span,
626                 source,
627                 ref prior_arms,
628                 last_ty,
629                 scrut_hir_id,
630                 opt_suggest_box_span,
631                 arm_span,
632                 scrut_span,
633                 ..
634             }) => match source {
635                 hir::MatchSource::IfLetDesugar { .. } => {
636                     let msg = "`if let` arms have incompatible types";
637                     err.span_label(cause.span, msg);
638                     if let Some(ret_sp) = opt_suggest_box_span {
639                         self.suggest_boxing_for_return_impl_trait(
640                             err,
641                             ret_sp,
642                             prior_arms.iter().chain(std::iter::once(&arm_span)).map(|s| *s),
643                         );
644                     }
645                 }
646                 hir::MatchSource::TryDesugar => {
647                     if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
648                         let scrut_expr = self.tcx.hir().expect_expr(scrut_hir_id);
649                         let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
650                             let arg_expr = args.first().expect("try desugaring call w/out arg");
651                             self.in_progress_typeck_results.and_then(|typeck_results| {
652                                 typeck_results.borrow().expr_ty_opt(arg_expr)
653                             })
654                         } else {
655                             bug!("try desugaring w/out call expr as scrutinee");
656                         };
657
658                         match scrut_ty {
659                             Some(ty) if expected == ty => {
660                                 let source_map = self.tcx.sess.source_map();
661                                 err.span_suggestion(
662                                     source_map.end_point(cause.span),
663                                     "try removing this `?`",
664                                     "".to_string(),
665                                     Applicability::MachineApplicable,
666                                 );
667                             }
668                             _ => {}
669                         }
670                     }
671                 }
672                 _ => {
673                     // `last_ty` can be `!`, `expected` will have better info when present.
674                     let t = self.resolve_vars_if_possible(match exp_found {
675                         Some(ty::error::ExpectedFound { expected, .. }) => expected,
676                         _ => last_ty,
677                     });
678                     let source_map = self.tcx.sess.source_map();
679                     let mut any_multiline_arm = source_map.is_multiline(arm_span);
680                     if prior_arms.len() <= 4 {
681                         for sp in prior_arms {
682                             any_multiline_arm |= source_map.is_multiline(*sp);
683                             err.span_label(*sp, format!("this is found to be of type `{}`", t));
684                         }
685                     } else if let Some(sp) = prior_arms.last() {
686                         any_multiline_arm |= source_map.is_multiline(*sp);
687                         err.span_label(
688                             *sp,
689                             format!("this and all prior arms are found to be of type `{}`", t),
690                         );
691                     }
692                     let outer_error_span = if any_multiline_arm {
693                         // Cover just `match` and the scrutinee expression, not
694                         // the entire match body, to reduce diagram noise.
695                         cause.span.shrink_to_lo().to(scrut_span)
696                     } else {
697                         cause.span
698                     };
699                     let msg = "`match` arms have incompatible types";
700                     err.span_label(outer_error_span, msg);
701                     if let Some((sp, boxed)) = semi_span {
702                         if let (StatementAsExpression::NeedsBoxing, [.., prior_arm]) =
703                             (boxed, &prior_arms[..])
704                         {
705                             err.multipart_suggestion(
706                                 "consider removing this semicolon and boxing the expressions",
707                                 vec![
708                                     (prior_arm.shrink_to_lo(), "Box::new(".to_string()),
709                                     (prior_arm.shrink_to_hi(), ")".to_string()),
710                                     (arm_span.shrink_to_lo(), "Box::new(".to_string()),
711                                     (arm_span.shrink_to_hi(), ")".to_string()),
712                                     (sp, String::new()),
713                                 ],
714                                 Applicability::HasPlaceholders,
715                             );
716                         } else if matches!(boxed, StatementAsExpression::NeedsBoxing) {
717                             err.span_suggestion_short(
718                                 sp,
719                                 "consider removing this semicolon and boxing the expressions",
720                                 String::new(),
721                                 Applicability::MachineApplicable,
722                             );
723                         } else {
724                             err.span_suggestion_short(
725                                 sp,
726                                 "consider removing this semicolon",
727                                 String::new(),
728                                 Applicability::MachineApplicable,
729                             );
730                         }
731                     }
732                     if let Some(ret_sp) = opt_suggest_box_span {
733                         // Get return type span and point to it.
734                         self.suggest_boxing_for_return_impl_trait(
735                             err,
736                             ret_sp,
737                             prior_arms.iter().chain(std::iter::once(&arm_span)).map(|s| *s),
738                         );
739                     }
740                 }
741             },
742             ObligationCauseCode::IfExpression(box IfExpressionCause {
743                 then,
744                 else_sp,
745                 outer,
746                 semicolon,
747                 opt_suggest_box_span,
748             }) => {
749                 err.span_label(then, "expected because of this");
750                 if let Some(sp) = outer {
751                     err.span_label(sp, "`if` and `else` have incompatible types");
752                 }
753                 if let Some((sp, boxed)) = semicolon {
754                     if matches!(boxed, StatementAsExpression::NeedsBoxing) {
755                         err.multipart_suggestion(
756                             "consider removing this semicolon and boxing the expression",
757                             vec![
758                                 (then.shrink_to_lo(), "Box::new(".to_string()),
759                                 (then.shrink_to_hi(), ")".to_string()),
760                                 (else_sp.shrink_to_lo(), "Box::new(".to_string()),
761                                 (else_sp.shrink_to_hi(), ")".to_string()),
762                                 (sp, String::new()),
763                             ],
764                             Applicability::MachineApplicable,
765                         );
766                     } else {
767                         err.span_suggestion_short(
768                             sp,
769                             "consider removing this semicolon",
770                             String::new(),
771                             Applicability::MachineApplicable,
772                         );
773                     }
774                 }
775                 if let Some(ret_sp) = opt_suggest_box_span {
776                     self.suggest_boxing_for_return_impl_trait(
777                         err,
778                         ret_sp,
779                         vec![then, else_sp].into_iter(),
780                     );
781                 }
782             }
783             _ => (),
784         }
785     }
786
787     fn suggest_boxing_for_return_impl_trait(
788         &self,
789         err: &mut DiagnosticBuilder<'tcx>,
790         return_sp: Span,
791         arm_spans: impl Iterator<Item = Span>,
792     ) {
793         err.multipart_suggestion(
794             "you could change the return type to be a boxed trait object",
795             vec![
796                 (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
797                 (return_sp.shrink_to_hi(), ">".to_string()),
798             ],
799             Applicability::MaybeIncorrect,
800         );
801         let sugg = arm_spans
802             .flat_map(|sp| {
803                 vec![
804                     (sp.shrink_to_lo(), "Box::new(".to_string()),
805                     (sp.shrink_to_hi(), ")".to_string()),
806                 ]
807                 .into_iter()
808             })
809             .collect::<Vec<_>>();
810         err.multipart_suggestion(
811             "if you change the return type to expect trait objects, box the returned expressions",
812             sugg,
813             Applicability::MaybeIncorrect,
814         );
815     }
816
817     /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
818     /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
819     /// populate `other_value` with `other_ty`.
820     ///
821     /// ```text
822     /// Foo<Bar<Qux>>
823     /// ^^^^--------^ this is highlighted
824     /// |   |
825     /// |   this type argument is exactly the same as the other type, not highlighted
826     /// this is highlighted
827     /// Bar<Qux>
828     /// -------- this type is the same as a type argument in the other type, not highlighted
829     /// ```
830     fn highlight_outer(
831         &self,
832         value: &mut DiagnosticStyledString,
833         other_value: &mut DiagnosticStyledString,
834         name: String,
835         sub: ty::subst::SubstsRef<'tcx>,
836         pos: usize,
837         other_ty: Ty<'tcx>,
838     ) {
839         // `value` and `other_value` hold two incomplete type representation for display.
840         // `name` is the path of both types being compared. `sub`
841         value.push_highlighted(name);
842         let len = sub.len();
843         if len > 0 {
844             value.push_highlighted("<");
845         }
846
847         // Output the lifetimes for the first type
848         let lifetimes = sub
849             .regions()
850             .map(|lifetime| {
851                 let s = lifetime.to_string();
852                 if s.is_empty() { "'_".to_string() } else { s }
853             })
854             .collect::<Vec<_>>()
855             .join(", ");
856         if !lifetimes.is_empty() {
857             if sub.regions().count() < len {
858                 value.push_normal(lifetimes + ", ");
859             } else {
860                 value.push_normal(lifetimes);
861             }
862         }
863
864         // Highlight all the type arguments that aren't at `pos` and compare the type argument at
865         // `pos` and `other_ty`.
866         for (i, type_arg) in sub.types().enumerate() {
867             if i == pos {
868                 let values = self.cmp(type_arg, other_ty);
869                 value.0.extend((values.0).0);
870                 other_value.0.extend((values.1).0);
871             } else {
872                 value.push_highlighted(type_arg.to_string());
873             }
874
875             if len > 0 && i != len - 1 {
876                 value.push_normal(", ");
877             }
878         }
879         if len > 0 {
880             value.push_highlighted(">");
881         }
882     }
883
884     /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
885     /// as that is the difference to the other type.
886     ///
887     /// For the following code:
888     ///
889     /// ```no_run
890     /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
891     /// ```
892     ///
893     /// The type error output will behave in the following way:
894     ///
895     /// ```text
896     /// Foo<Bar<Qux>>
897     /// ^^^^--------^ this is highlighted
898     /// |   |
899     /// |   this type argument is exactly the same as the other type, not highlighted
900     /// this is highlighted
901     /// Bar<Qux>
902     /// -------- this type is the same as a type argument in the other type, not highlighted
903     /// ```
904     fn cmp_type_arg(
905         &self,
906         mut t1_out: &mut DiagnosticStyledString,
907         mut t2_out: &mut DiagnosticStyledString,
908         path: String,
909         sub: ty::subst::SubstsRef<'tcx>,
910         other_path: String,
911         other_ty: Ty<'tcx>,
912     ) -> Option<()> {
913         for (i, ta) in sub.types().enumerate() {
914             if ta == other_ty {
915                 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
916                 return Some(());
917             }
918             if let ty::Adt(def, _) = ta.kind() {
919                 let path_ = self.tcx.def_path_str(def.did);
920                 if path_ == other_path {
921                     self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
922                     return Some(());
923                 }
924             }
925         }
926         None
927     }
928
929     /// Adds a `,` to the type representation only if it is appropriate.
930     fn push_comma(
931         &self,
932         value: &mut DiagnosticStyledString,
933         other_value: &mut DiagnosticStyledString,
934         len: usize,
935         pos: usize,
936     ) {
937         if len > 0 && pos != len - 1 {
938             value.push_normal(", ");
939             other_value.push_normal(", ");
940         }
941     }
942
943     /// For generic types with parameters with defaults, remove the parameters corresponding to
944     /// the defaults. This repeats a lot of the logic found in `ty::print::pretty`.
945     fn strip_generic_default_params(
946         &self,
947         def_id: DefId,
948         substs: ty::subst::SubstsRef<'tcx>,
949     ) -> SubstsRef<'tcx> {
950         let generics = self.tcx.generics_of(def_id);
951         let mut num_supplied_defaults = 0;
952         let mut type_params = generics
953             .params
954             .iter()
955             .rev()
956             .filter_map(|param| match param.kind {
957                 ty::GenericParamDefKind::Lifetime => None,
958                 ty::GenericParamDefKind::Type { has_default, .. } => {
959                     Some((param.def_id, has_default))
960                 }
961                 ty::GenericParamDefKind::Const => None, // FIXME(const_generics_defaults)
962             })
963             .peekable();
964         let has_default = {
965             let has_default = type_params.peek().map(|(_, has_default)| has_default);
966             *has_default.unwrap_or(&false)
967         };
968         if has_default {
969             let types = substs.types().rev();
970             for ((def_id, has_default), actual) in type_params.zip(types) {
971                 if !has_default {
972                     break;
973                 }
974                 if self.tcx.type_of(def_id).subst(self.tcx, substs) != actual {
975                     break;
976                 }
977                 num_supplied_defaults += 1;
978             }
979         }
980         let len = generics.params.len();
981         let mut generics = generics.clone();
982         generics.params.truncate(len - num_supplied_defaults);
983         substs.truncate_to(self.tcx, &generics)
984     }
985
986     /// Given two `fn` signatures highlight only sub-parts that are different.
987     fn cmp_fn_sig(
988         &self,
989         sig1: &ty::PolyFnSig<'tcx>,
990         sig2: &ty::PolyFnSig<'tcx>,
991     ) -> (DiagnosticStyledString, DiagnosticStyledString) {
992         let get_lifetimes = |sig| {
993             use rustc_hir::def::Namespace;
994             let mut s = String::new();
995             let (_, (sig, reg)) = ty::print::FmtPrinter::new(self.tcx, &mut s, Namespace::TypeNS)
996                 .name_all_regions(sig)
997                 .unwrap();
998             let lts: Vec<String> = reg.into_iter().map(|(_, kind)| kind.to_string()).collect();
999             (if lts.is_empty() { String::new() } else { format!("for<{}> ", lts.join(", ")) }, sig)
1000         };
1001
1002         let (lt1, sig1) = get_lifetimes(sig1);
1003         let (lt2, sig2) = get_lifetimes(sig2);
1004
1005         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1006         let mut values = (
1007             DiagnosticStyledString::normal("".to_string()),
1008             DiagnosticStyledString::normal("".to_string()),
1009         );
1010
1011         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1012         // ^^^^^^
1013         values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1014         values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1015
1016         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1017         //        ^^^^^^^^^^
1018         if sig1.abi != abi::Abi::Rust {
1019             values.0.push(format!("extern {} ", sig1.abi), sig1.abi != sig2.abi);
1020         }
1021         if sig2.abi != abi::Abi::Rust {
1022             values.1.push(format!("extern {} ", sig2.abi), sig1.abi != sig2.abi);
1023         }
1024
1025         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1026         //                   ^^^^^^^^
1027         let lifetime_diff = lt1 != lt2;
1028         values.0.push(lt1, lifetime_diff);
1029         values.1.push(lt2, lifetime_diff);
1030
1031         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1032         //                           ^^^
1033         values.0.push_normal("fn(");
1034         values.1.push_normal("fn(");
1035
1036         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1037         //                              ^^^^^
1038         let len1 = sig1.inputs().len();
1039         let len2 = sig2.inputs().len();
1040         if len1 == len2 {
1041             for (i, (l, r)) in sig1.inputs().iter().zip(sig2.inputs().iter()).enumerate() {
1042                 let (x1, x2) = self.cmp(l, r);
1043                 (values.0).0.extend(x1.0);
1044                 (values.1).0.extend(x2.0);
1045                 self.push_comma(&mut values.0, &mut values.1, len1, i);
1046             }
1047         } else {
1048             for (i, l) in sig1.inputs().iter().enumerate() {
1049                 values.0.push_highlighted(l.to_string());
1050                 if i != len1 - 1 {
1051                     values.0.push_highlighted(", ");
1052                 }
1053             }
1054             for (i, r) in sig2.inputs().iter().enumerate() {
1055                 values.1.push_highlighted(r.to_string());
1056                 if i != len2 - 1 {
1057                     values.1.push_highlighted(", ");
1058                 }
1059             }
1060         }
1061
1062         if sig1.c_variadic {
1063             if len1 > 0 {
1064                 values.0.push_normal(", ");
1065             }
1066             values.0.push("...", !sig2.c_variadic);
1067         }
1068         if sig2.c_variadic {
1069             if len2 > 0 {
1070                 values.1.push_normal(", ");
1071             }
1072             values.1.push("...", !sig1.c_variadic);
1073         }
1074
1075         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1076         //                                   ^
1077         values.0.push_normal(")");
1078         values.1.push_normal(")");
1079
1080         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1081         //                                     ^^^^^^^^
1082         let output1 = sig1.output();
1083         let output2 = sig2.output();
1084         let (x1, x2) = self.cmp(output1, output2);
1085         if !output1.is_unit() {
1086             values.0.push_normal(" -> ");
1087             (values.0).0.extend(x1.0);
1088         }
1089         if !output2.is_unit() {
1090             values.1.push_normal(" -> ");
1091             (values.1).0.extend(x2.0);
1092         }
1093         values
1094     }
1095
1096     /// Compares two given types, eliding parts that are the same between them and highlighting
1097     /// relevant differences, and return two representation of those types for highlighted printing.
1098     fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
1099         debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind(), t2, t2.kind());
1100
1101         // helper functions
1102         fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1103             match (a.kind(), b.kind()) {
1104                 (a, b) if *a == *b => true,
1105                 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
1106                 | (
1107                     &ty::Infer(ty::InferTy::IntVar(_)),
1108                     &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)),
1109                 )
1110                 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
1111                 | (
1112                     &ty::Infer(ty::InferTy::FloatVar(_)),
1113                     &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
1114                 ) => true,
1115                 _ => false,
1116             }
1117         }
1118
1119         fn push_ty_ref<'tcx>(
1120             region: &ty::Region<'tcx>,
1121             ty: Ty<'tcx>,
1122             mutbl: hir::Mutability,
1123             s: &mut DiagnosticStyledString,
1124         ) {
1125             let mut r = region.to_string();
1126             if r == "'_" {
1127                 r.clear();
1128             } else {
1129                 r.push(' ');
1130             }
1131             s.push_highlighted(format!("&{}{}", r, mutbl.prefix_str()));
1132             s.push_normal(ty.to_string());
1133         }
1134
1135         // process starts here
1136         match (t1.kind(), t2.kind()) {
1137             (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1138                 let sub_no_defaults_1 = self.strip_generic_default_params(def1.did, sub1);
1139                 let sub_no_defaults_2 = self.strip_generic_default_params(def2.did, sub2);
1140                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1141                 let path1 = self.tcx.def_path_str(def1.did);
1142                 let path2 = self.tcx.def_path_str(def2.did);
1143                 if def1.did == def2.did {
1144                     // Easy case. Replace same types with `_` to shorten the output and highlight
1145                     // the differing ones.
1146                     //     let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1147                     //     Foo<Bar, _>
1148                     //     Foo<Quz, _>
1149                     //         ---  ^ type argument elided
1150                     //         |
1151                     //         highlighted in output
1152                     values.0.push_normal(path1);
1153                     values.1.push_normal(path2);
1154
1155                     // Avoid printing out default generic parameters that are common to both
1156                     // types.
1157                     let len1 = sub_no_defaults_1.len();
1158                     let len2 = sub_no_defaults_2.len();
1159                     let common_len = cmp::min(len1, len2);
1160                     let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
1161                     let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
1162                     let common_default_params = remainder1
1163                         .iter()
1164                         .rev()
1165                         .zip(remainder2.iter().rev())
1166                         .filter(|(a, b)| a == b)
1167                         .count();
1168                     let len = sub1.len() - common_default_params;
1169                     let consts_offset = len - sub1.consts().count();
1170
1171                     // Only draw `<...>` if there're lifetime/type arguments.
1172                     if len > 0 {
1173                         values.0.push_normal("<");
1174                         values.1.push_normal("<");
1175                     }
1176
1177                     fn lifetime_display(lifetime: Region<'_>) -> String {
1178                         let s = lifetime.to_string();
1179                         if s.is_empty() { "'_".to_string() } else { s }
1180                     }
1181                     // At one point we'd like to elide all lifetimes here, they are irrelevant for
1182                     // all diagnostics that use this output
1183                     //
1184                     //     Foo<'x, '_, Bar>
1185                     //     Foo<'y, '_, Qux>
1186                     //         ^^  ^^  --- type arguments are not elided
1187                     //         |   |
1188                     //         |   elided as they were the same
1189                     //         not elided, they were different, but irrelevant
1190                     let lifetimes = sub1.regions().zip(sub2.regions());
1191                     for (i, lifetimes) in lifetimes.enumerate() {
1192                         let l1 = lifetime_display(lifetimes.0);
1193                         let l2 = lifetime_display(lifetimes.1);
1194                         if lifetimes.0 == lifetimes.1 {
1195                             values.0.push_normal("'_");
1196                             values.1.push_normal("'_");
1197                         } else {
1198                             values.0.push_highlighted(l1);
1199                             values.1.push_highlighted(l2);
1200                         }
1201                         self.push_comma(&mut values.0, &mut values.1, len, i);
1202                     }
1203
1204                     // We're comparing two types with the same path, so we compare the type
1205                     // arguments for both. If they are the same, do not highlight and elide from the
1206                     // output.
1207                     //     Foo<_, Bar>
1208                     //     Foo<_, Qux>
1209                     //         ^ elided type as this type argument was the same in both sides
1210                     let type_arguments = sub1.types().zip(sub2.types());
1211                     let regions_len = sub1.regions().count();
1212                     let num_display_types = consts_offset - regions_len;
1213                     for (i, (ta1, ta2)) in type_arguments.take(num_display_types).enumerate() {
1214                         let i = i + regions_len;
1215                         if ta1 == ta2 {
1216                             values.0.push_normal("_");
1217                             values.1.push_normal("_");
1218                         } else {
1219                             let (x1, x2) = self.cmp(ta1, ta2);
1220                             (values.0).0.extend(x1.0);
1221                             (values.1).0.extend(x2.0);
1222                         }
1223                         self.push_comma(&mut values.0, &mut values.1, len, i);
1224                     }
1225
1226                     // Do the same for const arguments, if they are equal, do not highlight and
1227                     // elide them from the output.
1228                     let const_arguments = sub1.consts().zip(sub2.consts());
1229                     for (i, (ca1, ca2)) in const_arguments.enumerate() {
1230                         let i = i + consts_offset;
1231                         if ca1 == ca2 {
1232                             values.0.push_normal("_");
1233                             values.1.push_normal("_");
1234                         } else {
1235                             values.0.push_highlighted(ca1.to_string());
1236                             values.1.push_highlighted(ca2.to_string());
1237                         }
1238                         self.push_comma(&mut values.0, &mut values.1, len, i);
1239                     }
1240
1241                     // Close the type argument bracket.
1242                     // Only draw `<...>` if there're lifetime/type arguments.
1243                     if len > 0 {
1244                         values.0.push_normal(">");
1245                         values.1.push_normal(">");
1246                     }
1247                     values
1248                 } else {
1249                     // Check for case:
1250                     //     let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1251                     //     Foo<Bar<Qux>
1252                     //         ------- this type argument is exactly the same as the other type
1253                     //     Bar<Qux>
1254                     if self
1255                         .cmp_type_arg(
1256                             &mut values.0,
1257                             &mut values.1,
1258                             path1.clone(),
1259                             sub_no_defaults_1,
1260                             path2.clone(),
1261                             &t2,
1262                         )
1263                         .is_some()
1264                     {
1265                         return values;
1266                     }
1267                     // Check for case:
1268                     //     let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1269                     //     Bar<Qux>
1270                     //     Foo<Bar<Qux>>
1271                     //         ------- this type argument is exactly the same as the other type
1272                     if self
1273                         .cmp_type_arg(
1274                             &mut values.1,
1275                             &mut values.0,
1276                             path2,
1277                             sub_no_defaults_2,
1278                             path1,
1279                             &t1,
1280                         )
1281                         .is_some()
1282                     {
1283                         return values;
1284                     }
1285
1286                     // We can't find anything in common, highlight relevant part of type path.
1287                     //     let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1288                     //     foo::bar::Baz<Qux>
1289                     //     foo::bar::Bar<Zar>
1290                     //               -------- this part of the path is different
1291
1292                     let t1_str = t1.to_string();
1293                     let t2_str = t2.to_string();
1294                     let min_len = t1_str.len().min(t2_str.len());
1295
1296                     const SEPARATOR: &str = "::";
1297                     let separator_len = SEPARATOR.len();
1298                     let split_idx: usize = t1_str
1299                         .split(SEPARATOR)
1300                         .zip(t2_str.split(SEPARATOR))
1301                         .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1302                         .map(|(mod_str, _)| mod_str.len() + separator_len)
1303                         .sum();
1304
1305                     debug!(
1306                         "cmp: separator_len={}, split_idx={}, min_len={}",
1307                         separator_len, split_idx, min_len
1308                     );
1309
1310                     if split_idx >= min_len {
1311                         // paths are identical, highlight everything
1312                         (
1313                             DiagnosticStyledString::highlighted(t1_str),
1314                             DiagnosticStyledString::highlighted(t2_str),
1315                         )
1316                     } else {
1317                         let (common, uniq1) = t1_str.split_at(split_idx);
1318                         let (_, uniq2) = t2_str.split_at(split_idx);
1319                         debug!("cmp: common={}, uniq1={}, uniq2={}", common, uniq1, uniq2);
1320
1321                         values.0.push_normal(common);
1322                         values.0.push_highlighted(uniq1);
1323                         values.1.push_normal(common);
1324                         values.1.push_highlighted(uniq2);
1325
1326                         values
1327                     }
1328                 }
1329             }
1330
1331             // When finding T != &T, highlight only the borrow
1332             (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
1333                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1334                 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1335                 values.1.push_normal(t2.to_string());
1336                 values
1337             }
1338             (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
1339                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1340                 values.0.push_normal(t1.to_string());
1341                 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1342                 values
1343             }
1344
1345             // When encountering &T != &mut T, highlight only the borrow
1346             (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1347                 if equals(&ref_ty1, &ref_ty2) =>
1348             {
1349                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1350                 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1351                 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1352                 values
1353             }
1354
1355             // When encountering tuples of the same size, highlight only the differing types
1356             (&ty::Tuple(substs1), &ty::Tuple(substs2)) if substs1.len() == substs2.len() => {
1357                 let mut values =
1358                     (DiagnosticStyledString::normal("("), DiagnosticStyledString::normal("("));
1359                 let len = substs1.len();
1360                 for (i, (left, right)) in substs1.types().zip(substs2.types()).enumerate() {
1361                     let (x1, x2) = self.cmp(left, right);
1362                     (values.0).0.extend(x1.0);
1363                     (values.1).0.extend(x2.0);
1364                     self.push_comma(&mut values.0, &mut values.1, len, i);
1365                 }
1366                 if len == 1 {
1367                     // Keep the output for single element tuples as `(ty,)`.
1368                     values.0.push_normal(",");
1369                     values.1.push_normal(",");
1370                 }
1371                 values.0.push_normal(")");
1372                 values.1.push_normal(")");
1373                 values
1374             }
1375
1376             (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1377                 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1378                 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1379                 let mut values = self.cmp_fn_sig(&sig1, &sig2);
1380                 let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did1, substs1));
1381                 let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did2, substs2));
1382                 let same_path = path1 == path2;
1383                 values.0.push(path1, !same_path);
1384                 values.1.push(path2, !same_path);
1385                 values
1386             }
1387
1388             (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => {
1389                 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1390                 let mut values = self.cmp_fn_sig(&sig1, sig2);
1391                 values.0.push_highlighted(format!(
1392                     " {{{}}}",
1393                     self.tcx.def_path_str_with_substs(*did1, substs1)
1394                 ));
1395                 values
1396             }
1397
1398             (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => {
1399                 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1400                 let mut values = self.cmp_fn_sig(sig1, &sig2);
1401                 values.1.push_normal(format!(
1402                     " {{{}}}",
1403                     self.tcx.def_path_str_with_substs(*did2, substs2)
1404                 ));
1405                 values
1406             }
1407
1408             (ty::FnPtr(sig1), ty::FnPtr(sig2)) => self.cmp_fn_sig(sig1, sig2),
1409
1410             _ => {
1411                 if t1 == t2 {
1412                     // The two types are the same, elide and don't highlight.
1413                     (DiagnosticStyledString::normal("_"), DiagnosticStyledString::normal("_"))
1414                 } else {
1415                     // We couldn't find anything in common, highlight everything.
1416                     (
1417                         DiagnosticStyledString::highlighted(t1.to_string()),
1418                         DiagnosticStyledString::highlighted(t2.to_string()),
1419                     )
1420                 }
1421             }
1422         }
1423     }
1424
1425     pub fn note_type_err(
1426         &self,
1427         diag: &mut DiagnosticBuilder<'tcx>,
1428         cause: &ObligationCause<'tcx>,
1429         secondary_span: Option<(Span, String)>,
1430         mut values: Option<ValuePairs<'tcx>>,
1431         terr: &TypeError<'tcx>,
1432     ) {
1433         let span = cause.span(self.tcx);
1434         debug!("note_type_err cause={:?} values={:?}, terr={:?}", cause, values, terr);
1435
1436         // For some types of errors, expected-found does not make
1437         // sense, so just ignore the values we were given.
1438         if let TypeError::CyclicTy(_) = terr {
1439             values = None;
1440         }
1441         struct OpaqueTypesVisitor<'tcx> {
1442             types: FxHashMap<TyCategory, FxHashSet<Span>>,
1443             expected: FxHashMap<TyCategory, FxHashSet<Span>>,
1444             found: FxHashMap<TyCategory, FxHashSet<Span>>,
1445             ignore_span: Span,
1446             tcx: TyCtxt<'tcx>,
1447         }
1448
1449         impl<'tcx> OpaqueTypesVisitor<'tcx> {
1450             fn visit_expected_found(
1451                 tcx: TyCtxt<'tcx>,
1452                 expected: Ty<'tcx>,
1453                 found: Ty<'tcx>,
1454                 ignore_span: Span,
1455             ) -> Self {
1456                 let mut types_visitor = OpaqueTypesVisitor {
1457                     types: Default::default(),
1458                     expected: Default::default(),
1459                     found: Default::default(),
1460                     ignore_span,
1461                     tcx,
1462                 };
1463                 // The visitor puts all the relevant encountered types in `self.types`, but in
1464                 // here we want to visit two separate types with no relation to each other, so we
1465                 // move the results from `types` to `expected` or `found` as appropriate.
1466                 expected.visit_with(&mut types_visitor);
1467                 std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1468                 found.visit_with(&mut types_visitor);
1469                 std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1470                 types_visitor
1471             }
1472
1473             fn report(&self, err: &mut DiagnosticBuilder<'_>) {
1474                 self.add_labels_for_types(err, "expected", &self.expected);
1475                 self.add_labels_for_types(err, "found", &self.found);
1476             }
1477
1478             fn add_labels_for_types(
1479                 &self,
1480                 err: &mut DiagnosticBuilder<'_>,
1481                 target: &str,
1482                 types: &FxHashMap<TyCategory, FxHashSet<Span>>,
1483             ) {
1484                 for (key, values) in types.iter() {
1485                     let count = values.len();
1486                     let kind = key.descr();
1487                     for sp in values {
1488                         err.span_label(
1489                             *sp,
1490                             format!(
1491                                 "{}{}{} {}{}",
1492                                 if sp.is_desugaring(DesugaringKind::Async) {
1493                                     "the `Output` of this `async fn`'s "
1494                                 } else if count == 1 {
1495                                     "the "
1496                                 } else {
1497                                     ""
1498                                 },
1499                                 if count > 1 { "one of the " } else { "" },
1500                                 target,
1501                                 kind,
1502                                 pluralize!(count),
1503                             ),
1504                         );
1505                     }
1506                 }
1507             }
1508         }
1509
1510         impl<'tcx> ty::fold::TypeVisitor<'tcx> for OpaqueTypesVisitor<'tcx> {
1511             fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1512                 if let Some((kind, def_id)) = TyCategory::from_ty(t) {
1513                     let span = self.tcx.def_span(def_id);
1514                     // Avoid cluttering the output when the "found" and error span overlap:
1515                     //
1516                     // error[E0308]: mismatched types
1517                     //   --> $DIR/issue-20862.rs:2:5
1518                     //    |
1519                     // LL |     |y| x + y
1520                     //    |     ^^^^^^^^^
1521                     //    |     |
1522                     //    |     the found closure
1523                     //    |     expected `()`, found closure
1524                     //    |
1525                     //    = note: expected unit type `()`
1526                     //                 found closure `[closure@$DIR/issue-20862.rs:2:5: 2:14 x:_]`
1527                     if !self.ignore_span.overlaps(span) {
1528                         self.types.entry(kind).or_default().insert(span);
1529                     }
1530                 }
1531                 t.super_visit_with(self)
1532             }
1533         }
1534
1535         debug!("note_type_err(diag={:?})", diag);
1536         enum Mismatch<'a> {
1537             Variable(ty::error::ExpectedFound<Ty<'a>>),
1538             Fixed(&'static str),
1539         }
1540         let (expected_found, exp_found, is_simple_error) = match values {
1541             None => (None, Mismatch::Fixed("type"), false),
1542             Some(values) => {
1543                 let (is_simple_error, exp_found) = match values {
1544                     ValuePairs::Types(exp_found) => {
1545                         let is_simple_err =
1546                             exp_found.expected.is_simple_text() && exp_found.found.is_simple_text();
1547                         OpaqueTypesVisitor::visit_expected_found(
1548                             self.tcx,
1549                             exp_found.expected,
1550                             exp_found.found,
1551                             span,
1552                         )
1553                         .report(diag);
1554
1555                         (is_simple_err, Mismatch::Variable(exp_found))
1556                     }
1557                     ValuePairs::TraitRefs(_) => (false, Mismatch::Fixed("trait")),
1558                     _ => (false, Mismatch::Fixed("type")),
1559                 };
1560                 let vals = match self.values_str(values) {
1561                     Some((expected, found)) => Some((expected, found)),
1562                     None => {
1563                         // Derived error. Cancel the emitter.
1564                         diag.cancel();
1565                         return;
1566                     }
1567                 };
1568                 (vals, exp_found, is_simple_error)
1569             }
1570         };
1571
1572         // Ignore msg for object safe coercion
1573         // since E0038 message will be printed
1574         match terr {
1575             TypeError::ObjectUnsafeCoercion(_) => {}
1576             _ => {
1577                 diag.span_label(span, terr.to_string());
1578                 if let Some((sp, msg)) = secondary_span {
1579                     diag.span_label(sp, msg);
1580                 }
1581             }
1582         };
1583         if let Some((expected, found)) = expected_found {
1584             let expected_label = match exp_found {
1585                 Mismatch::Variable(ef) => ef.expected.prefix_string(),
1586                 Mismatch::Fixed(s) => s.into(),
1587             };
1588             let found_label = match exp_found {
1589                 Mismatch::Variable(ef) => ef.found.prefix_string(),
1590                 Mismatch::Fixed(s) => s.into(),
1591             };
1592             let exp_found = match exp_found {
1593                 Mismatch::Variable(exp_found) => Some(exp_found),
1594                 Mismatch::Fixed(_) => None,
1595             };
1596             match (&terr, expected == found) {
1597                 (TypeError::Sorts(values), extra) => {
1598                     let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
1599                         (true, ty::Opaque(def_id, _)) => format!(
1600                             " (opaque type at {})",
1601                             self.tcx
1602                                 .sess
1603                                 .source_map()
1604                                 .mk_substr_filename(self.tcx.def_span(*def_id)),
1605                         ),
1606                         (true, _) => format!(" ({})", ty.sort_string(self.tcx)),
1607                         (false, _) => "".to_string(),
1608                     };
1609                     if !(values.expected.is_simple_text() && values.found.is_simple_text())
1610                         || (exp_found.map_or(false, |ef| {
1611                             // This happens when the type error is a subset of the expectation,
1612                             // like when you have two references but one is `usize` and the other
1613                             // is `f32`. In those cases we still want to show the `note`. If the
1614                             // value from `ef` is `Infer(_)`, then we ignore it.
1615                             if !ef.expected.is_ty_infer() {
1616                                 ef.expected != values.expected
1617                             } else if !ef.found.is_ty_infer() {
1618                                 ef.found != values.found
1619                             } else {
1620                                 false
1621                             }
1622                         }))
1623                     {
1624                         diag.note_expected_found_extra(
1625                             &expected_label,
1626                             expected,
1627                             &found_label,
1628                             found,
1629                             &sort_string(values.expected),
1630                             &sort_string(values.found),
1631                         );
1632                     }
1633                 }
1634                 (TypeError::ObjectUnsafeCoercion(_), _) => {
1635                     diag.note_unsuccessful_coercion(found, expected);
1636                 }
1637                 (_, _) => {
1638                     debug!(
1639                         "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1640                         exp_found, expected, found
1641                     );
1642                     if !is_simple_error || terr.must_include_note() {
1643                         diag.note_expected_found(&expected_label, expected, &found_label, found);
1644                     }
1645                 }
1646             }
1647         }
1648         let exp_found = match exp_found {
1649             Mismatch::Variable(exp_found) => Some(exp_found),
1650             Mismatch::Fixed(_) => None,
1651         };
1652         let exp_found = match terr {
1653             // `terr` has more accurate type information than `exp_found` in match expressions.
1654             ty::error::TypeError::Sorts(terr)
1655                 if exp_found.map_or(false, |ef| terr.found == ef.found) =>
1656             {
1657                 Some(*terr)
1658             }
1659             _ => exp_found,
1660         };
1661         debug!("exp_found {:?} terr {:?}", exp_found, terr);
1662         if let Some(exp_found) = exp_found {
1663             self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1664             self.suggest_field_where_appropriate(cause, &exp_found, diag);
1665             self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
1666         }
1667
1668         // In some (most?) cases cause.body_id points to actual body, but in some cases
1669         // it's a actual definition. According to the comments (e.g. in
1670         // librustc_typeck/check/compare_method.rs:compare_predicate_entailment) the latter
1671         // is relied upon by some other code. This might (or might not) need cleanup.
1672         let body_owner_def_id =
1673             self.tcx.hir().opt_local_def_id(cause.body_id).unwrap_or_else(|| {
1674                 self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id })
1675             });
1676         self.check_and_note_conflicting_crates(diag, terr);
1677         self.tcx.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id.to_def_id());
1678
1679         if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values {
1680             if let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind() {
1681                 if let Some(def_id) = def_id.as_local() {
1682                     let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1683                     let span = self.tcx.hir().span(hir_id);
1684                     diag.span_note(span, "this closure does not fulfill the lifetime requirements");
1685                 }
1686             }
1687         }
1688
1689         // It reads better to have the error origin as the final
1690         // thing.
1691         self.note_error_origin(diag, cause, exp_found);
1692     }
1693
1694     pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1695         if let ty::Opaque(def_id, substs) = ty.kind() {
1696             let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
1697             // Future::Output
1698             let item_def_id = self
1699                 .tcx
1700                 .associated_items(future_trait)
1701                 .in_definition_order()
1702                 .next()
1703                 .unwrap()
1704                 .def_id;
1705
1706             let bounds = self.tcx.explicit_item_bounds(*def_id);
1707
1708             for (predicate, _) in bounds {
1709                 let predicate = predicate.subst(self.tcx, substs);
1710                 if let ty::PredicateKind::Projection(projection_predicate) =
1711                     predicate.kind().skip_binder()
1712                 {
1713                     if projection_predicate.projection_ty.item_def_id == item_def_id {
1714                         // We don't account for multiple `Future::Output = Ty` contraints.
1715                         return Some(projection_predicate.ty);
1716                     }
1717                 }
1718             }
1719         }
1720         None
1721     }
1722
1723     /// A possible error is to forget to add `.await` when using futures:
1724     ///
1725     /// ```
1726     /// async fn make_u32() -> u32 {
1727     ///     22
1728     /// }
1729     ///
1730     /// fn take_u32(x: u32) {}
1731     ///
1732     /// async fn foo() {
1733     ///     let x = make_u32();
1734     ///     take_u32(x);
1735     /// }
1736     /// ```
1737     ///
1738     /// This routine checks if the found type `T` implements `Future<Output=U>` where `U` is the
1739     /// expected type. If this is the case, and we are inside of an async body, it suggests adding
1740     /// `.await` to the tail of the expression.
1741     fn suggest_await_on_expect_found(
1742         &self,
1743         cause: &ObligationCause<'tcx>,
1744         exp_span: Span,
1745         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1746         diag: &mut DiagnosticBuilder<'tcx>,
1747     ) {
1748         debug!(
1749             "suggest_await_on_expect_found: exp_span={:?}, expected_ty={:?}, found_ty={:?}",
1750             exp_span, exp_found.expected, exp_found.found,
1751         );
1752
1753         if let ObligationCauseCode::CompareImplMethodObligation { .. } = &cause.code {
1754             return;
1755         }
1756
1757         match (
1758             self.get_impl_future_output_ty(exp_found.expected),
1759             self.get_impl_future_output_ty(exp_found.found),
1760         ) {
1761             (Some(exp), Some(found)) if ty::TyS::same_type(exp, found) => match &cause.code {
1762                 ObligationCauseCode::IfExpression(box IfExpressionCause { then, .. }) => {
1763                     diag.multipart_suggestion(
1764                         "consider `await`ing on both `Future`s",
1765                         vec![
1766                             (then.shrink_to_hi(), ".await".to_string()),
1767                             (exp_span.shrink_to_hi(), ".await".to_string()),
1768                         ],
1769                         Applicability::MaybeIncorrect,
1770                     );
1771                 }
1772                 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1773                     prior_arms,
1774                     ..
1775                 }) => {
1776                     if let [.., arm_span] = &prior_arms[..] {
1777                         diag.multipart_suggestion(
1778                             "consider `await`ing on both `Future`s",
1779                             vec![
1780                                 (arm_span.shrink_to_hi(), ".await".to_string()),
1781                                 (exp_span.shrink_to_hi(), ".await".to_string()),
1782                             ],
1783                             Applicability::MaybeIncorrect,
1784                         );
1785                     } else {
1786                         diag.help("consider `await`ing on both `Future`s");
1787                     }
1788                 }
1789                 _ => {
1790                     diag.help("consider `await`ing on both `Future`s");
1791                 }
1792             },
1793             (_, Some(ty)) if ty::TyS::same_type(exp_found.expected, ty) => {
1794                 let span = match cause.code {
1795                     // scrutinee's span
1796                     ObligationCauseCode::Pattern { span: Some(span), .. } => span,
1797                     _ => exp_span,
1798                 };
1799                 diag.span_suggestion_verbose(
1800                     span.shrink_to_hi(),
1801                     "consider `await`ing on the `Future`",
1802                     ".await".to_string(),
1803                     Applicability::MaybeIncorrect,
1804                 );
1805             }
1806             (Some(ty), _) if ty::TyS::same_type(ty, exp_found.found) => {
1807                 let span = match cause.code {
1808                     // scrutinee's span
1809                     ObligationCauseCode::Pattern { span: Some(span), .. } => span,
1810                     _ => exp_span,
1811                 };
1812                 diag.span_suggestion_verbose(
1813                     span.shrink_to_hi(),
1814                     "consider `await`ing on the `Future`",
1815                     ".await".to_string(),
1816                     Applicability::MaybeIncorrect,
1817                 );
1818             }
1819             _ => {}
1820         }
1821     }
1822
1823     fn suggest_field_where_appropriate(
1824         &self,
1825         cause: &ObligationCause<'tcx>,
1826         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1827         diag: &mut DiagnosticBuilder<'tcx>,
1828     ) {
1829         debug!("suggest_field_where_appropriate(cause={:?}, exp_found={:?})", cause, exp_found);
1830         if let ty::Adt(expected_def, expected_substs) = exp_found.expected.kind() {
1831             if expected_def.is_enum() {
1832                 return;
1833             }
1834
1835             if let Some((name, ty)) = expected_def
1836                 .non_enum_variant()
1837                 .fields
1838                 .iter()
1839                 .filter(|field| field.vis.is_accessible_from(field.did, self.tcx))
1840                 .map(|field| (field.ident.name, field.ty(self.tcx, expected_substs)))
1841                 .find(|(_, ty)| ty::TyS::same_type(ty, exp_found.found))
1842             {
1843                 if let ObligationCauseCode::Pattern { span: Some(span), .. } = cause.code {
1844                     if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1845                         diag.span_suggestion(
1846                             span,
1847                             &format!(
1848                                 "you might have meant to use field `{}` of type `{}`",
1849                                 name, ty
1850                             ),
1851                             format!("{}.{}", snippet, name),
1852                             Applicability::MaybeIncorrect,
1853                         );
1854                     }
1855                 }
1856             }
1857         }
1858     }
1859
1860     /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
1861     /// suggests it.
1862     fn suggest_as_ref_where_appropriate(
1863         &self,
1864         span: Span,
1865         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1866         diag: &mut DiagnosticBuilder<'tcx>,
1867     ) {
1868         if let (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) =
1869             (exp_found.expected.kind(), exp_found.found.kind())
1870         {
1871             if let ty::Adt(found_def, found_substs) = *found_ty.kind() {
1872                 let path_str = format!("{:?}", exp_def);
1873                 if exp_def == &found_def {
1874                     let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
1875                                        `.as_ref()`";
1876                     let result_msg = "you can convert from `&Result<T, E>` to \
1877                                           `Result<&T, &E>` using `.as_ref()`";
1878                     let have_as_ref = &[
1879                         ("std::option::Option", opt_msg),
1880                         ("core::option::Option", opt_msg),
1881                         ("std::result::Result", result_msg),
1882                         ("core::result::Result", result_msg),
1883                     ];
1884                     if let Some(msg) = have_as_ref
1885                         .iter()
1886                         .find_map(|(path, msg)| (&path_str == path).then_some(msg))
1887                     {
1888                         let mut show_suggestion = true;
1889                         for (exp_ty, found_ty) in exp_substs.types().zip(found_substs.types()) {
1890                             match *exp_ty.kind() {
1891                                 ty::Ref(_, exp_ty, _) => {
1892                                     match (exp_ty.kind(), found_ty.kind()) {
1893                                         (_, ty::Param(_))
1894                                         | (_, ty::Infer(_))
1895                                         | (ty::Param(_), _)
1896                                         | (ty::Infer(_), _) => {}
1897                                         _ if ty::TyS::same_type(exp_ty, found_ty) => {}
1898                                         _ => show_suggestion = false,
1899                                     };
1900                                 }
1901                                 ty::Param(_) | ty::Infer(_) => {}
1902                                 _ => show_suggestion = false,
1903                             }
1904                         }
1905                         if let (Ok(snippet), true) =
1906                             (self.tcx.sess.source_map().span_to_snippet(span), show_suggestion)
1907                         {
1908                             diag.span_suggestion(
1909                                 span,
1910                                 msg,
1911                                 format!("{}.as_ref()", snippet),
1912                                 Applicability::MachineApplicable,
1913                             );
1914                         }
1915                     }
1916                 }
1917             }
1918         }
1919     }
1920
1921     pub fn report_and_explain_type_error(
1922         &self,
1923         trace: TypeTrace<'tcx>,
1924         terr: &TypeError<'tcx>,
1925     ) -> DiagnosticBuilder<'tcx> {
1926         debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
1927
1928         let span = trace.cause.span(self.tcx);
1929         let failure_code = trace.cause.as_failure_code(terr);
1930         let mut diag = match failure_code {
1931             FailureCode::Error0038(did) => {
1932                 let violations = self.tcx.object_safety_violations(did);
1933                 report_object_safety_error(self.tcx, span, did, violations)
1934             }
1935             FailureCode::Error0317(failure_str) => {
1936                 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
1937             }
1938             FailureCode::Error0580(failure_str) => {
1939                 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
1940             }
1941             FailureCode::Error0308(failure_str) => {
1942                 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
1943             }
1944             FailureCode::Error0644(failure_str) => {
1945                 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
1946             }
1947         };
1948         self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
1949         diag
1950     }
1951
1952     fn values_str(
1953         &self,
1954         values: ValuePairs<'tcx>,
1955     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1956         match values {
1957             infer::Types(exp_found) => self.expected_found_str_ty(exp_found),
1958             infer::Regions(exp_found) => self.expected_found_str(exp_found),
1959             infer::Consts(exp_found) => self.expected_found_str(exp_found),
1960             infer::TraitRefs(exp_found) => {
1961                 let pretty_exp_found = ty::error::ExpectedFound {
1962                     expected: exp_found.expected.print_only_trait_path(),
1963                     found: exp_found.found.print_only_trait_path(),
1964                 };
1965                 self.expected_found_str(pretty_exp_found)
1966             }
1967             infer::PolyTraitRefs(exp_found) => {
1968                 let pretty_exp_found = ty::error::ExpectedFound {
1969                     expected: exp_found.expected.print_only_trait_path(),
1970                     found: exp_found.found.print_only_trait_path(),
1971                 };
1972                 self.expected_found_str(pretty_exp_found)
1973             }
1974         }
1975     }
1976
1977     fn expected_found_str_ty(
1978         &self,
1979         exp_found: ty::error::ExpectedFound<Ty<'tcx>>,
1980     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1981         let exp_found = self.resolve_vars_if_possible(exp_found);
1982         if exp_found.references_error() {
1983             return None;
1984         }
1985
1986         Some(self.cmp(exp_found.expected, exp_found.found))
1987     }
1988
1989     /// Returns a string of the form "expected `{}`, found `{}`".
1990     fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
1991         &self,
1992         exp_found: ty::error::ExpectedFound<T>,
1993     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1994         let exp_found = self.resolve_vars_if_possible(exp_found);
1995         if exp_found.references_error() {
1996             return None;
1997         }
1998
1999         Some((
2000             DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2001             DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2002         ))
2003     }
2004
2005     pub fn report_generic_bound_failure(
2006         &self,
2007         span: Span,
2008         origin: Option<SubregionOrigin<'tcx>>,
2009         bound_kind: GenericKind<'tcx>,
2010         sub: Region<'tcx>,
2011     ) {
2012         self.construct_generic_bound_failure(span, origin, bound_kind, sub).emit();
2013     }
2014
2015     pub fn construct_generic_bound_failure(
2016         &self,
2017         span: Span,
2018         origin: Option<SubregionOrigin<'tcx>>,
2019         bound_kind: GenericKind<'tcx>,
2020         sub: Region<'tcx>,
2021     ) -> DiagnosticBuilder<'a> {
2022         let hir = &self.tcx.hir();
2023         // Attempt to obtain the span of the parameter so we can
2024         // suggest adding an explicit lifetime bound to it.
2025         let generics = self
2026             .in_progress_typeck_results
2027             .map(|typeck_results| typeck_results.borrow().hir_owner)
2028             .map(|owner| {
2029                 let hir_id = hir.local_def_id_to_hir_id(owner);
2030                 let parent_id = hir.get_parent_item(hir_id);
2031                 (
2032                     // Parent item could be a `mod`, so we check the HIR before calling:
2033                     if let Some(Node::Item(Item {
2034                         kind: ItemKind::Trait(..) | ItemKind::Impl { .. },
2035                         ..
2036                     })) = hir.find(parent_id)
2037                     {
2038                         Some(self.tcx.generics_of(hir.local_def_id(parent_id).to_def_id()))
2039                     } else {
2040                         None
2041                     },
2042                     self.tcx.generics_of(owner.to_def_id()),
2043                 )
2044             });
2045         let type_param_span = match (generics, bound_kind) {
2046             (Some((_, ref generics)), GenericKind::Param(ref param)) => {
2047                 // Account for the case where `param` corresponds to `Self`,
2048                 // which doesn't have the expected type argument.
2049                 if !(generics.has_self && param.index == 0) {
2050                     let type_param = generics.type_param(param, self.tcx);
2051                     type_param.def_id.as_local().map(|def_id| {
2052                         // Get the `hir::Param` to verify whether it already has any bounds.
2053                         // We do this to avoid suggesting code that ends up as `T: 'a'b`,
2054                         // instead we suggest `T: 'a + 'b` in that case.
2055                         let id = hir.local_def_id_to_hir_id(def_id);
2056                         let mut has_bounds = false;
2057                         if let Node::GenericParam(param) = hir.get(id) {
2058                             has_bounds = !param.bounds.is_empty();
2059                         }
2060                         let sp = hir.span(id);
2061                         // `sp` only covers `T`, change it so that it covers
2062                         // `T:` when appropriate
2063                         let is_impl_trait = bound_kind.to_string().starts_with("impl ");
2064                         let sp = if has_bounds && !is_impl_trait {
2065                             sp.to(self
2066                                 .tcx
2067                                 .sess
2068                                 .source_map()
2069                                 .next_point(self.tcx.sess.source_map().next_point(sp)))
2070                         } else {
2071                             sp
2072                         };
2073                         (sp, has_bounds, is_impl_trait)
2074                     })
2075                 } else {
2076                     None
2077                 }
2078             }
2079             _ => None,
2080         };
2081         let new_lt = generics
2082             .as_ref()
2083             .and_then(|(parent_g, g)| {
2084                 let possible: Vec<_> = (b'a'..=b'z').map(|c| format!("'{}", c as char)).collect();
2085                 let mut lts_names = g
2086                     .params
2087                     .iter()
2088                     .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2089                     .map(|p| p.name.as_str())
2090                     .collect::<Vec<_>>();
2091                 if let Some(g) = parent_g {
2092                     lts_names.extend(
2093                         g.params
2094                             .iter()
2095                             .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2096                             .map(|p| p.name.as_str()),
2097                     );
2098                 }
2099                 let lts = lts_names.iter().map(|s| -> &str { &*s }).collect::<Vec<_>>();
2100                 possible.into_iter().find(|candidate| !lts.contains(&candidate.as_str()))
2101             })
2102             .unwrap_or("'lt".to_string());
2103         let add_lt_sugg = generics
2104             .as_ref()
2105             .and_then(|(_, g)| g.params.first())
2106             .and_then(|param| param.def_id.as_local())
2107             .map(|def_id| {
2108                 (
2109                     hir.span(hir.local_def_id_to_hir_id(def_id)).shrink_to_lo(),
2110                     format!("{}, ", new_lt),
2111                 )
2112             });
2113
2114         let labeled_user_string = match bound_kind {
2115             GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
2116             GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
2117         };
2118
2119         if let Some(SubregionOrigin::CompareImplMethodObligation {
2120             span,
2121             item_name,
2122             impl_item_def_id,
2123             trait_item_def_id,
2124         }) = origin
2125         {
2126             return self.report_extra_impl_obligation(
2127                 span,
2128                 item_name,
2129                 impl_item_def_id,
2130                 trait_item_def_id,
2131                 &format!("`{}: {}`", bound_kind, sub),
2132             );
2133         }
2134
2135         fn binding_suggestion<'tcx, S: fmt::Display>(
2136             err: &mut DiagnosticBuilder<'tcx>,
2137             type_param_span: Option<(Span, bool, bool)>,
2138             bound_kind: GenericKind<'tcx>,
2139             sub: S,
2140         ) {
2141             let msg = "consider adding an explicit lifetime bound";
2142             if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
2143                 let suggestion = if is_impl_trait {
2144                     format!("{} + {}", bound_kind, sub)
2145                 } else {
2146                     let tail = if has_lifetimes { " + " } else { "" };
2147                     format!("{}: {}{}", bound_kind, sub, tail)
2148                 };
2149                 err.span_suggestion(
2150                     sp,
2151                     &format!("{}...", msg),
2152                     suggestion,
2153                     Applicability::MaybeIncorrect, // Issue #41966
2154                 );
2155             } else {
2156                 let consider = format!(
2157                     "{} {}...",
2158                     msg,
2159                     if type_param_span.map_or(false, |(_, _, is_impl_trait)| is_impl_trait) {
2160                         format!(" `{}` to `{}`", sub, bound_kind)
2161                     } else {
2162                         format!("`{}: {}`", bound_kind, sub)
2163                     },
2164                 );
2165                 err.help(&consider);
2166             }
2167         }
2168
2169         let new_binding_suggestion =
2170             |err: &mut DiagnosticBuilder<'tcx>,
2171              type_param_span: Option<(Span, bool, bool)>,
2172              bound_kind: GenericKind<'tcx>| {
2173                 let msg = "consider introducing an explicit lifetime bound";
2174                 if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
2175                     let suggestion = if is_impl_trait {
2176                         (sp.shrink_to_hi(), format!(" + {}", new_lt))
2177                     } else {
2178                         let tail = if has_lifetimes { " +" } else { "" };
2179                         (sp, format!("{}: {}{}", bound_kind, new_lt, tail))
2180                     };
2181                     let mut sugg =
2182                         vec![suggestion, (span.shrink_to_hi(), format!(" + {}", new_lt))];
2183                     if let Some(lt) = add_lt_sugg {
2184                         sugg.push(lt);
2185                         sugg.rotate_right(1);
2186                     }
2187                     // `MaybeIncorrect` due to issue #41966.
2188                     err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2189                 }
2190             };
2191
2192         let mut err = match *sub {
2193             ty::ReEarlyBound(ty::EarlyBoundRegion { name, .. })
2194             | ty::ReFree(ty::FreeRegion { bound_region: ty::BrNamed(_, name), .. }) => {
2195                 // Does the required lifetime have a nice name we can print?
2196                 let mut err = struct_span_err!(
2197                     self.tcx.sess,
2198                     span,
2199                     E0309,
2200                     "{} may not live long enough",
2201                     labeled_user_string
2202                 );
2203                 // Explicitly use the name instead of `sub`'s `Display` impl. The `Display` impl
2204                 // for the bound is not suitable for suggestions when `-Zverbose` is set because it
2205                 // uses `Debug` output, so we handle it specially here so that suggestions are
2206                 // always correct.
2207                 binding_suggestion(&mut err, type_param_span, bound_kind, name);
2208                 err
2209             }
2210
2211             ty::ReStatic => {
2212                 // Does the required lifetime have a nice name we can print?
2213                 let mut err = struct_span_err!(
2214                     self.tcx.sess,
2215                     span,
2216                     E0310,
2217                     "{} may not live long enough",
2218                     labeled_user_string
2219                 );
2220                 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
2221                 err
2222             }
2223
2224             _ => {
2225                 // If not, be less specific.
2226                 let mut err = struct_span_err!(
2227                     self.tcx.sess,
2228                     span,
2229                     E0311,
2230                     "{} may not live long enough",
2231                     labeled_user_string
2232                 );
2233                 note_and_explain_region(
2234                     self.tcx,
2235                     &mut err,
2236                     &format!("{} must be valid for ", labeled_user_string),
2237                     sub,
2238                     "...",
2239                 );
2240                 if let Some(infer::RelateParamBound(_, t)) = origin {
2241                     let t = self.resolve_vars_if_possible(t);
2242                     match t.kind() {
2243                         // We've got:
2244                         // fn get_later<G, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
2245                         // suggest:
2246                         // fn get_later<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ + 'a
2247                         ty::Closure(_, _substs) | ty::Opaque(_, _substs) => {
2248                             new_binding_suggestion(&mut err, type_param_span, bound_kind);
2249                         }
2250                         _ => {
2251                             binding_suggestion(&mut err, type_param_span, bound_kind, new_lt);
2252                         }
2253                     }
2254                 }
2255                 err
2256             }
2257         };
2258
2259         if let Some(origin) = origin {
2260             self.note_region_origin(&mut err, &origin);
2261         }
2262         err
2263     }
2264
2265     fn report_sub_sup_conflict(
2266         &self,
2267         var_origin: RegionVariableOrigin,
2268         sub_origin: SubregionOrigin<'tcx>,
2269         sub_region: Region<'tcx>,
2270         sup_origin: SubregionOrigin<'tcx>,
2271         sup_region: Region<'tcx>,
2272     ) {
2273         let mut err = self.report_inference_failure(var_origin);
2274
2275         note_and_explain_region(
2276             self.tcx,
2277             &mut err,
2278             "first, the lifetime cannot outlive ",
2279             sup_region,
2280             "...",
2281         );
2282
2283         debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
2284         debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
2285         debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
2286         debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
2287         debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
2288
2289         if let (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) =
2290             (&sup_origin, &sub_origin)
2291         {
2292             debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
2293             debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
2294             debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
2295             debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
2296
2297             if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) =
2298                 (self.values_str(sup_trace.values), self.values_str(sub_trace.values))
2299             {
2300                 if sub_expected == sup_expected && sub_found == sup_found {
2301                     note_and_explain_region(
2302                         self.tcx,
2303                         &mut err,
2304                         "...but the lifetime must also be valid for ",
2305                         sub_region,
2306                         "...",
2307                     );
2308                     err.span_note(
2309                         sup_trace.cause.span,
2310                         &format!("...so that the {}", sup_trace.cause.as_requirement_str()),
2311                     );
2312
2313                     err.note_expected_found(&"", sup_expected, &"", sup_found);
2314                     err.emit();
2315                     return;
2316                 }
2317             }
2318         }
2319
2320         self.note_region_origin(&mut err, &sup_origin);
2321
2322         note_and_explain_region(
2323             self.tcx,
2324             &mut err,
2325             "but, the lifetime must be valid for ",
2326             sub_region,
2327             "...",
2328         );
2329
2330         self.note_region_origin(&mut err, &sub_origin);
2331         err.emit();
2332     }
2333
2334     /// Determine whether an error associated with the given span and definition
2335     /// should be treated as being caused by the implicit `From` conversion
2336     /// within `?` desugaring.
2337     pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool {
2338         span.is_desugaring(DesugaringKind::QuestionMark)
2339             && self.tcx.is_diagnostic_item(sym::from_trait, trait_def_id)
2340     }
2341 }
2342
2343 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
2344     fn report_inference_failure(
2345         &self,
2346         var_origin: RegionVariableOrigin,
2347     ) -> DiagnosticBuilder<'tcx> {
2348         let br_string = |br: ty::BoundRegionKind| {
2349             let mut s = match br {
2350                 ty::BrNamed(_, name) => name.to_string(),
2351                 _ => String::new(),
2352             };
2353             if !s.is_empty() {
2354                 s.push(' ');
2355             }
2356             s
2357         };
2358         let var_description = match var_origin {
2359             infer::MiscVariable(_) => String::new(),
2360             infer::PatternRegion(_) => " for pattern".to_string(),
2361             infer::AddrOfRegion(_) => " for borrow expression".to_string(),
2362             infer::Autoref(_, _) => " for autoref".to_string(),
2363             infer::Coercion(_) => " for automatic coercion".to_string(),
2364             infer::LateBoundRegion(_, br, infer::FnCall) => {
2365                 format!(" for lifetime parameter {}in function call", br_string(br))
2366             }
2367             infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
2368                 format!(" for lifetime parameter {}in generic type", br_string(br))
2369             }
2370             infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
2371                 " for lifetime parameter {}in trait containing associated type `{}`",
2372                 br_string(br),
2373                 self.tcx.associated_item(def_id).ident
2374             ),
2375             infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
2376             infer::BoundRegionInCoherence(name) => {
2377                 format!(" for lifetime parameter `{}` in coherence check", name)
2378             }
2379             infer::UpvarRegion(ref upvar_id, _) => {
2380                 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
2381                 format!(" for capture of `{}` by closure", var_name)
2382             }
2383             infer::NLL(..) => bug!("NLL variable found in lexical phase"),
2384         };
2385
2386         struct_span_err!(
2387             self.tcx.sess,
2388             var_origin.span(),
2389             E0495,
2390             "cannot infer an appropriate lifetime{} due to conflicting requirements",
2391             var_description
2392         )
2393     }
2394 }
2395
2396 enum FailureCode {
2397     Error0038(DefId),
2398     Error0317(&'static str),
2399     Error0580(&'static str),
2400     Error0308(&'static str),
2401     Error0644(&'static str),
2402 }
2403
2404 trait ObligationCauseExt<'tcx> {
2405     fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode;
2406     fn as_requirement_str(&self) -> &'static str;
2407 }
2408
2409 impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
2410     fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
2411         use self::FailureCode::*;
2412         use crate::traits::ObligationCauseCode::*;
2413         match self.code {
2414             CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
2415             CompareImplTypeObligation { .. } => Error0308("type not compatible with trait"),
2416             MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => {
2417                 Error0308(match source {
2418                     hir::MatchSource::IfLetDesugar { .. } => {
2419                         "`if let` arms have incompatible types"
2420                     }
2421                     hir::MatchSource::TryDesugar => {
2422                         "try expression alternatives have incompatible types"
2423                     }
2424                     _ => "`match` arms have incompatible types",
2425                 })
2426             }
2427             IfExpression { .. } => Error0308("`if` and `else` have incompatible types"),
2428             IfExpressionWithNoElse => Error0317("`if` may be missing an `else` clause"),
2429             MainFunctionType => Error0580("`main` function has wrong type"),
2430             StartFunctionType => Error0308("`#[start]` function has wrong type"),
2431             IntrinsicType => Error0308("intrinsic has wrong type"),
2432             MethodReceiver => Error0308("mismatched `self` parameter type"),
2433
2434             // In the case where we have no more specific thing to
2435             // say, also take a look at the error code, maybe we can
2436             // tailor to that.
2437             _ => match terr {
2438                 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
2439                     Error0644("closure/generator type that references itself")
2440                 }
2441                 TypeError::IntrinsicCast => {
2442                     Error0308("cannot coerce intrinsics to function pointers")
2443                 }
2444                 TypeError::ObjectUnsafeCoercion(did) => Error0038(*did),
2445                 _ => Error0308("mismatched types"),
2446             },
2447         }
2448     }
2449
2450     fn as_requirement_str(&self) -> &'static str {
2451         use crate::traits::ObligationCauseCode::*;
2452         match self.code {
2453             CompareImplMethodObligation { .. } => "method type is compatible with trait",
2454             CompareImplTypeObligation { .. } => "associated type is compatible with trait",
2455             ExprAssignable => "expression is assignable",
2456             MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => match source {
2457                 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
2458                 _ => "`match` arms have compatible types",
2459             },
2460             IfExpression { .. } => "`if` and `else` have incompatible types",
2461             IfExpressionWithNoElse => "`if` missing an `else` returns `()`",
2462             MainFunctionType => "`main` function has the correct type",
2463             StartFunctionType => "`#[start]` function has the correct type",
2464             IntrinsicType => "intrinsic has the correct type",
2465             MethodReceiver => "method receiver has the correct type",
2466             _ => "types are compatible",
2467         }
2468     }
2469 }
2470
2471 /// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
2472 /// extra information about each type, but we only care about the category.
2473 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2474 pub enum TyCategory {
2475     Closure,
2476     Opaque,
2477     Generator,
2478     Foreign,
2479 }
2480
2481 impl TyCategory {
2482     fn descr(&self) -> &'static str {
2483         match self {
2484             Self::Closure => "closure",
2485             Self::Opaque => "opaque type",
2486             Self::Generator => "generator",
2487             Self::Foreign => "foreign type",
2488         }
2489     }
2490
2491     pub fn from_ty(ty: Ty<'_>) -> Option<(Self, DefId)> {
2492         match *ty.kind() {
2493             ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
2494             ty::Opaque(def_id, _) => Some((Self::Opaque, def_id)),
2495             ty::Generator(def_id, ..) => Some((Self::Generator, def_id)),
2496             ty::Foreign(def_id) => Some((Self::Foreign, def_id)),
2497             _ => None,
2498         }
2499     }
2500 }