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