]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/error_reporting/mod.rs
Properly escape quotes when suggesting switching between char/string literals
[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 system is based around a set of "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::infer::ExpectedFound;
55 use crate::traits::error_reporting::report_object_safety_error;
56 use crate::traits::{
57     IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
58     StatementAsExpression,
59 };
60
61 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
62 use rustc_errors::{pluralize, struct_span_err, Diagnostic, ErrorGuaranteed, IntoDiagnosticArg};
63 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString, MultiSpan};
64 use rustc_hir as hir;
65 use rustc_hir::def::DefKind;
66 use rustc_hir::def_id::{DefId, LocalDefId};
67 use rustc_hir::lang_items::LangItem;
68 use rustc_hir::Node;
69 use rustc_middle::dep_graph::DepContext;
70 use rustc_middle::ty::print::with_no_trimmed_paths;
71 use rustc_middle::ty::relate::{self, RelateResult, TypeRelation};
72 use rustc_middle::ty::{
73     self, error::TypeError, Binder, List, Region, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable,
74     TypeVisitable,
75 };
76 use rustc_span::{sym, symbol::kw, BytePos, DesugaringKind, Pos, Span};
77 use rustc_target::spec::abi;
78 use std::ops::{ControlFlow, Deref};
79 use std::{cmp, fmt, iter};
80
81 mod note;
82
83 pub(crate) mod need_type_info;
84 pub use need_type_info::TypeAnnotationNeeded;
85
86 pub mod nice_region_error;
87
88 /// A helper for building type related errors. The `typeck_results`
89 /// field is only populated during an in-progress typeck.
90 /// Get an instance by calling `InferCtxt::err` or `FnCtxt::infer_err`.
91 pub struct TypeErrCtxt<'a, 'tcx> {
92     pub infcx: &'a InferCtxt<'tcx>,
93     pub typeck_results: Option<std::cell::Ref<'a, ty::TypeckResults<'tcx>>>,
94 }
95
96 impl TypeErrCtxt<'_, '_> {
97     /// This is just to avoid a potential footgun of accidentally
98     /// dropping `typeck_results` by calling `InferCtxt::err_ctxt`
99     #[deprecated(note = "you already have a `TypeErrCtxt`")]
100     #[allow(unused)]
101     pub fn err_ctxt(&self) -> ! {
102         bug!("called `err_ctxt` on `TypeErrCtxt`. Try removing the call");
103     }
104 }
105
106 impl<'tcx> Deref for TypeErrCtxt<'_, 'tcx> {
107     type Target = InferCtxt<'tcx>;
108     fn deref(&self) -> &InferCtxt<'tcx> {
109         &self.infcx
110     }
111 }
112
113 pub(super) fn note_and_explain_region<'tcx>(
114     tcx: TyCtxt<'tcx>,
115     err: &mut Diagnostic,
116     prefix: &str,
117     region: ty::Region<'tcx>,
118     suffix: &str,
119     alt_span: Option<Span>,
120 ) {
121     let (description, span) = match *region {
122         ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
123             msg_span_from_free_region(tcx, region, alt_span)
124         }
125
126         ty::RePlaceholder(_) => return,
127
128         // FIXME(#13998) RePlaceholder should probably print like
129         // ReFree rather than dumping Debug output on the user.
130         //
131         // We shouldn't really be having unification failures with ReVar
132         // and ReLateBound though.
133         ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
134             (format!("lifetime {:?}", region), alt_span)
135         }
136     };
137
138     emit_msg_span(err, prefix, description, span, suffix);
139 }
140
141 fn explain_free_region<'tcx>(
142     tcx: TyCtxt<'tcx>,
143     err: &mut Diagnostic,
144     prefix: &str,
145     region: ty::Region<'tcx>,
146     suffix: &str,
147 ) {
148     let (description, span) = msg_span_from_free_region(tcx, region, None);
149
150     label_msg_span(err, prefix, description, span, suffix);
151 }
152
153 fn msg_span_from_free_region<'tcx>(
154     tcx: TyCtxt<'tcx>,
155     region: ty::Region<'tcx>,
156     alt_span: Option<Span>,
157 ) -> (String, Option<Span>) {
158     match *region {
159         ty::ReEarlyBound(_) | ty::ReFree(_) => {
160             let (msg, span) = msg_span_from_early_bound_and_free_regions(tcx, region);
161             (msg, Some(span))
162         }
163         ty::ReStatic => ("the static lifetime".to_owned(), alt_span),
164         _ => bug!("{:?}", region),
165     }
166 }
167
168 fn msg_span_from_early_bound_and_free_regions<'tcx>(
169     tcx: TyCtxt<'tcx>,
170     region: ty::Region<'tcx>,
171 ) -> (String, Span) {
172     let scope = region.free_region_binding_scope(tcx).expect_local();
173     match *region {
174         ty::ReEarlyBound(ref br) => {
175             let mut sp = tcx.def_span(scope);
176             if let Some(param) =
177                 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(br.name))
178             {
179                 sp = param.span;
180             }
181             let text = if br.has_name() {
182                 format!("the lifetime `{}` as defined here", br.name)
183             } else {
184                 format!("the anonymous lifetime as defined here")
185             };
186             (text, sp)
187         }
188         ty::ReFree(ref fr) => {
189             if !fr.bound_region.is_named()
190                 && let Some((ty, _)) = find_anon_type(tcx, region, &fr.bound_region)
191             {
192                 ("the anonymous lifetime defined here".to_string(), ty.span)
193             } else {
194                 match fr.bound_region {
195                     ty::BoundRegionKind::BrNamed(_, name) => {
196                         let mut sp = tcx.def_span(scope);
197                         if let Some(param) =
198                             tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(name))
199                         {
200                             sp = param.span;
201                         }
202                         let text = if name == kw::UnderscoreLifetime {
203                             format!("the anonymous lifetime as defined here")
204                         } else {
205                             format!("the lifetime `{}` as defined here", name)
206                         };
207                         (text, sp)
208                     }
209                     ty::BrAnon(idx) => (
210                         format!("the anonymous lifetime #{} defined here", idx + 1),
211                         tcx.def_span(scope)
212                     ),
213                     _ => (
214                         format!("the lifetime `{}` as defined here", region),
215                         tcx.def_span(scope),
216                     ),
217                 }
218             }
219         }
220         _ => bug!(),
221     }
222 }
223
224 fn emit_msg_span(
225     err: &mut Diagnostic,
226     prefix: &str,
227     description: String,
228     span: Option<Span>,
229     suffix: &str,
230 ) {
231     let message = format!("{}{}{}", prefix, description, suffix);
232
233     if let Some(span) = span {
234         err.span_note(span, &message);
235     } else {
236         err.note(&message);
237     }
238 }
239
240 fn label_msg_span(
241     err: &mut Diagnostic,
242     prefix: &str,
243     description: String,
244     span: Option<Span>,
245     suffix: &str,
246 ) {
247     let message = format!("{}{}{}", prefix, description, suffix);
248
249     if let Some(span) = span {
250         err.span_label(span, &message);
251     } else {
252         err.note(&message);
253     }
254 }
255
256 pub fn unexpected_hidden_region_diagnostic<'tcx>(
257     tcx: TyCtxt<'tcx>,
258     span: Span,
259     hidden_ty: Ty<'tcx>,
260     hidden_region: ty::Region<'tcx>,
261     opaque_ty: ty::OpaqueTypeKey<'tcx>,
262 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
263     let opaque_ty = tcx.mk_opaque(opaque_ty.def_id.to_def_id(), opaque_ty.substs);
264     let mut err = struct_span_err!(
265         tcx.sess,
266         span,
267         E0700,
268         "hidden type for `{opaque_ty}` captures lifetime that does not appear in bounds",
269     );
270
271     // Explain the region we are capturing.
272     match *hidden_region {
273         ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
274             // Assuming regionck succeeded (*), we ought to always be
275             // capturing *some* region from the fn header, and hence it
276             // ought to be free. So under normal circumstances, we will go
277             // down this path which gives a decent human readable
278             // explanation.
279             //
280             // (*) if not, the `tainted_by_errors` field would be set to
281             // `Some(ErrorGuaranteed)` in any case, so we wouldn't be here at all.
282             explain_free_region(
283                 tcx,
284                 &mut err,
285                 &format!("hidden type `{}` captures ", hidden_ty),
286                 hidden_region,
287                 "",
288             );
289             if let Some(reg_info) = tcx.is_suitable_region(hidden_region) {
290                 let fn_returns = tcx.return_type_impl_or_dyn_traits(reg_info.def_id);
291                 nice_region_error::suggest_new_region_bound(
292                     tcx,
293                     &mut err,
294                     fn_returns,
295                     hidden_region.to_string(),
296                     None,
297                     format!("captures `{}`", hidden_region),
298                     None,
299                 )
300             }
301         }
302         _ => {
303             // Ugh. This is a painful case: the hidden region is not one
304             // that we can easily summarize or explain. This can happen
305             // in a case like
306             // `src/test/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
307             //
308             // ```
309             // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
310             //   if condition() { a } else { b }
311             // }
312             // ```
313             //
314             // Here the captured lifetime is the intersection of `'a` and
315             // `'b`, which we can't quite express.
316
317             // We can at least report a really cryptic error for now.
318             note_and_explain_region(
319                 tcx,
320                 &mut err,
321                 &format!("hidden type `{}` captures ", hidden_ty),
322                 hidden_region,
323                 "",
324                 None,
325             );
326         }
327     }
328
329     err
330 }
331
332 impl<'tcx> InferCtxt<'tcx> {
333     pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Binder<'tcx, Ty<'tcx>>> {
334         if let ty::Opaque(def_id, substs) = ty.kind() {
335             let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
336             // Future::Output
337             let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
338
339             let bounds = self.tcx.bound_explicit_item_bounds(*def_id);
340
341             for predicate in bounds.transpose_iter().map(|e| e.map_bound(|(p, _)| *p)) {
342                 let predicate = predicate.subst(self.tcx, substs);
343                 let output = predicate
344                     .kind()
345                     .map_bound(|kind| match kind {
346                         ty::PredicateKind::Projection(projection_predicate)
347                             if projection_predicate.projection_ty.item_def_id == item_def_id =>
348                         {
349                             projection_predicate.term.ty()
350                         }
351                         _ => None,
352                     })
353                     .transpose();
354                 if output.is_some() {
355                     // We don't account for multiple `Future::Output = Ty` constraints.
356                     return output;
357                 }
358             }
359         }
360         None
361     }
362 }
363
364 impl<'tcx> TypeErrCtxt<'_, 'tcx> {
365     pub fn report_region_errors(
366         &self,
367         generic_param_scope: LocalDefId,
368         errors: &[RegionResolutionError<'tcx>],
369     ) {
370         debug!("report_region_errors(): {} errors to start", errors.len());
371
372         // try to pre-process the errors, which will group some of them
373         // together into a `ProcessedErrors` group:
374         let errors = self.process_errors(errors);
375
376         debug!("report_region_errors: {} errors after preprocessing", errors.len());
377
378         for error in errors {
379             debug!("report_region_errors: error = {:?}", error);
380
381             if !self.try_report_nice_region_error(&error) {
382                 match error.clone() {
383                     // These errors could indicate all manner of different
384                     // problems with many different solutions. Rather
385                     // than generate a "one size fits all" error, what we
386                     // attempt to do is go through a number of specific
387                     // scenarios and try to find the best way to present
388                     // the error. If all of these fails, we fall back to a rather
389                     // general bit of code that displays the error information
390                     RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
391                         if sub.is_placeholder() || sup.is_placeholder() {
392                             self.report_placeholder_failure(origin, sub, sup).emit();
393                         } else {
394                             self.report_concrete_failure(origin, sub, sup).emit();
395                         }
396                     }
397
398                     RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
399                         self.report_generic_bound_failure(
400                             generic_param_scope,
401                             origin.span(),
402                             Some(origin),
403                             param_ty,
404                             sub,
405                         );
406                     }
407
408                     RegionResolutionError::SubSupConflict(
409                         _,
410                         var_origin,
411                         sub_origin,
412                         sub_r,
413                         sup_origin,
414                         sup_r,
415                         _,
416                     ) => {
417                         if sub_r.is_placeholder() {
418                             self.report_placeholder_failure(sub_origin, sub_r, sup_r).emit();
419                         } else if sup_r.is_placeholder() {
420                             self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
421                         } else {
422                             self.report_sub_sup_conflict(
423                                 var_origin, sub_origin, sub_r, sup_origin, sup_r,
424                             );
425                         }
426                     }
427
428                     RegionResolutionError::UpperBoundUniverseConflict(
429                         _,
430                         _,
431                         _,
432                         sup_origin,
433                         sup_r,
434                     ) => {
435                         assert!(sup_r.is_placeholder());
436
437                         // Make a dummy value for the "sub region" --
438                         // this is the initial value of the
439                         // placeholder. In practice, we expect more
440                         // tailored errors that don't really use this
441                         // value.
442                         let sub_r = self.tcx.lifetimes.re_erased;
443
444                         self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
445                     }
446                 }
447             }
448         }
449     }
450
451     // This method goes through all the errors and try to group certain types
452     // of error together, for the purpose of suggesting explicit lifetime
453     // parameters to the user. This is done so that we can have a more
454     // complete view of what lifetimes should be the same.
455     // If the return value is an empty vector, it means that processing
456     // failed (so the return value of this method should not be used).
457     //
458     // The method also attempts to weed out messages that seem like
459     // duplicates that will be unhelpful to the end-user. But
460     // obviously it never weeds out ALL errors.
461     fn process_errors(
462         &self,
463         errors: &[RegionResolutionError<'tcx>],
464     ) -> Vec<RegionResolutionError<'tcx>> {
465         debug!("process_errors()");
466
467         // We want to avoid reporting generic-bound failures if we can
468         // avoid it: these have a very high rate of being unhelpful in
469         // practice. This is because they are basically secondary
470         // checks that test the state of the region graph after the
471         // rest of inference is done, and the other kinds of errors
472         // indicate that the region constraint graph is internally
473         // inconsistent, so these test results are likely to be
474         // meaningless.
475         //
476         // Therefore, we filter them out of the list unless they are
477         // the only thing in the list.
478
479         let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
480             RegionResolutionError::GenericBoundFailure(..) => true,
481             RegionResolutionError::ConcreteFailure(..)
482             | RegionResolutionError::SubSupConflict(..)
483             | RegionResolutionError::UpperBoundUniverseConflict(..) => false,
484         };
485
486         let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
487             errors.to_owned()
488         } else {
489             errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
490         };
491
492         // sort the errors by span, for better error message stability.
493         errors.sort_by_key(|u| match *u {
494             RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
495             RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
496             RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _, _) => rvo.span(),
497             RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(),
498         });
499         errors
500     }
501
502     /// Adds a note if the types come from similarly named crates
503     fn check_and_note_conflicting_crates(&self, err: &mut Diagnostic, terr: TypeError<'tcx>) {
504         use hir::def_id::CrateNum;
505         use rustc_hir::definitions::DisambiguatedDefPathData;
506         use ty::print::Printer;
507         use ty::subst::GenericArg;
508
509         struct AbsolutePathPrinter<'tcx> {
510             tcx: TyCtxt<'tcx>,
511         }
512
513         struct NonTrivialPath;
514
515         impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
516             type Error = NonTrivialPath;
517
518             type Path = Vec<String>;
519             type Region = !;
520             type Type = !;
521             type DynExistential = !;
522             type Const = !;
523
524             fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
525                 self.tcx
526             }
527
528             fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
529                 Err(NonTrivialPath)
530             }
531
532             fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
533                 Err(NonTrivialPath)
534             }
535
536             fn print_dyn_existential(
537                 self,
538                 _predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
539             ) -> Result<Self::DynExistential, Self::Error> {
540                 Err(NonTrivialPath)
541             }
542
543             fn print_const(self, _ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
544                 Err(NonTrivialPath)
545             }
546
547             fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
548                 Ok(vec![self.tcx.crate_name(cnum).to_string()])
549             }
550             fn path_qualified(
551                 self,
552                 _self_ty: Ty<'tcx>,
553                 _trait_ref: Option<ty::TraitRef<'tcx>>,
554             ) -> Result<Self::Path, Self::Error> {
555                 Err(NonTrivialPath)
556             }
557
558             fn path_append_impl(
559                 self,
560                 _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
561                 _disambiguated_data: &DisambiguatedDefPathData,
562                 _self_ty: Ty<'tcx>,
563                 _trait_ref: Option<ty::TraitRef<'tcx>>,
564             ) -> Result<Self::Path, Self::Error> {
565                 Err(NonTrivialPath)
566             }
567             fn path_append(
568                 self,
569                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
570                 disambiguated_data: &DisambiguatedDefPathData,
571             ) -> Result<Self::Path, Self::Error> {
572                 let mut path = print_prefix(self)?;
573                 path.push(disambiguated_data.to_string());
574                 Ok(path)
575             }
576             fn path_generic_args(
577                 self,
578                 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
579                 _args: &[GenericArg<'tcx>],
580             ) -> Result<Self::Path, Self::Error> {
581                 print_prefix(self)
582             }
583         }
584
585         let report_path_match = |err: &mut Diagnostic, did1: DefId, did2: DefId| {
586             // Only external crates, if either is from a local
587             // module we could have false positives
588             if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
589                 let abs_path =
590                     |def_id| AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]);
591
592                 // We compare strings because DefPath can be different
593                 // for imported and non-imported crates
594                 let same_path = || -> Result<_, NonTrivialPath> {
595                     Ok(self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2)
596                         || abs_path(did1)? == abs_path(did2)?)
597                 };
598                 if same_path().unwrap_or(false) {
599                     let crate_name = self.tcx.crate_name(did1.krate);
600                     err.note(&format!(
601                         "perhaps two different versions of crate `{}` are being used?",
602                         crate_name
603                     ));
604                 }
605             }
606         };
607         match terr {
608             TypeError::Sorts(ref exp_found) => {
609                 // if they are both "path types", there's a chance of ambiguity
610                 // due to different versions of the same crate
611                 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
612                     (exp_found.expected.kind(), exp_found.found.kind())
613                 {
614                     report_path_match(err, exp_adt.did(), found_adt.did());
615                 }
616             }
617             TypeError::Traits(ref exp_found) => {
618                 report_path_match(err, exp_found.expected, exp_found.found);
619             }
620             _ => (), // FIXME(#22750) handle traits and stuff
621         }
622     }
623
624     fn note_error_origin(
625         &self,
626         err: &mut Diagnostic,
627         cause: &ObligationCause<'tcx>,
628         exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
629         terr: TypeError<'tcx>,
630     ) {
631         match *cause.code() {
632             ObligationCauseCode::Pattern { origin_expr: true, span: Some(span), root_ty } => {
633                 let ty = self.resolve_vars_if_possible(root_ty);
634                 if !matches!(ty.kind(), ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_)))
635                 {
636                     // don't show type `_`
637                     if span.desugaring_kind() == Some(DesugaringKind::ForLoop)
638                         && let ty::Adt(def, substs) = ty.kind()
639                         && Some(def.did()) == self.tcx.get_diagnostic_item(sym::Option)
640                     {
641                         err.span_label(span, format!("this is an iterator with items of type `{}`", substs.type_at(0)));
642                     } else {
643                     err.span_label(span, format!("this expression has type `{}`", ty));
644                 }
645                 }
646                 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found
647                     && ty.is_box() && ty.boxed_ty() == found
648                     && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
649                 {
650                     err.span_suggestion(
651                         span,
652                         "consider dereferencing the boxed value",
653                         format!("*{}", snippet),
654                         Applicability::MachineApplicable,
655                     );
656                 }
657             }
658             ObligationCauseCode::Pattern { origin_expr: false, span: Some(span), .. } => {
659                 err.span_label(span, "expected due to this");
660             }
661             ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
662                 arm_block_id,
663                 arm_span,
664                 arm_ty,
665                 prior_arm_block_id,
666                 prior_arm_span,
667                 prior_arm_ty,
668                 source,
669                 ref prior_arms,
670                 scrut_hir_id,
671                 opt_suggest_box_span,
672                 scrut_span,
673                 ..
674             }) => match source {
675                 hir::MatchSource::TryDesugar => {
676                     if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
677                         let scrut_expr = self.tcx.hir().expect_expr(scrut_hir_id);
678                         let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
679                             let arg_expr = args.first().expect("try desugaring call w/out arg");
680                             self.typeck_results.as_ref().and_then(|typeck_results| {
681                                 typeck_results.expr_ty_opt(arg_expr)
682                             })
683                         } else {
684                             bug!("try desugaring w/out call expr as scrutinee");
685                         };
686
687                         match scrut_ty {
688                             Some(ty) if expected == ty => {
689                                 let source_map = self.tcx.sess.source_map();
690                                 err.span_suggestion(
691                                     source_map.end_point(cause.span),
692                                     "try removing this `?`",
693                                     "",
694                                     Applicability::MachineApplicable,
695                                 );
696                             }
697                             _ => {}
698                         }
699                     }
700                 }
701                 _ => {
702                     // `prior_arm_ty` can be `!`, `expected` will have better info when present.
703                     let t = self.resolve_vars_if_possible(match exp_found {
704                         Some(ty::error::ExpectedFound { expected, .. }) => expected,
705                         _ => prior_arm_ty,
706                     });
707                     let source_map = self.tcx.sess.source_map();
708                     let mut any_multiline_arm = source_map.is_multiline(arm_span);
709                     if prior_arms.len() <= 4 {
710                         for sp in prior_arms {
711                             any_multiline_arm |= source_map.is_multiline(*sp);
712                             err.span_label(*sp, format!("this is found to be of type `{}`", t));
713                         }
714                     } else if let Some(sp) = prior_arms.last() {
715                         any_multiline_arm |= source_map.is_multiline(*sp);
716                         err.span_label(
717                             *sp,
718                             format!("this and all prior arms are found to be of type `{}`", t),
719                         );
720                     }
721                     let outer_error_span = if any_multiline_arm {
722                         // Cover just `match` and the scrutinee expression, not
723                         // the entire match body, to reduce diagram noise.
724                         cause.span.shrink_to_lo().to(scrut_span)
725                     } else {
726                         cause.span
727                     };
728                     let msg = "`match` arms have incompatible types";
729                     err.span_label(outer_error_span, msg);
730                     self.suggest_remove_semi_or_return_binding(
731                         err,
732                         prior_arm_block_id,
733                         prior_arm_ty,
734                         prior_arm_span,
735                         arm_block_id,
736                         arm_ty,
737                         arm_span,
738                     );
739                     if let Some(ret_sp) = opt_suggest_box_span {
740                         // Get return type span and point to it.
741                         self.suggest_boxing_for_return_impl_trait(
742                             err,
743                             ret_sp,
744                             prior_arms.iter().chain(std::iter::once(&arm_span)).map(|s| *s),
745                         );
746                     }
747                 }
748             },
749             ObligationCauseCode::IfExpression(box IfExpressionCause {
750                 then_id,
751                 else_id,
752                 then_ty,
753                 else_ty,
754                 outer_span,
755                 opt_suggest_box_span,
756             }) => {
757                 let then_span = self.find_block_span_from_hir_id(then_id);
758                 let else_span = self.find_block_span_from_hir_id(else_id);
759                 err.span_label(then_span, "expected because of this");
760                 if let Some(sp) = outer_span {
761                     err.span_label(sp, "`if` and `else` have incompatible types");
762                 }
763                 self.suggest_remove_semi_or_return_binding(
764                     err,
765                     Some(then_id),
766                     then_ty,
767                     then_span,
768                     Some(else_id),
769                     else_ty,
770                     else_span,
771                 );
772                 if let Some(ret_sp) = opt_suggest_box_span {
773                     self.suggest_boxing_for_return_impl_trait(
774                         err,
775                         ret_sp,
776                         [then_span, else_span].into_iter(),
777                     );
778                 }
779             }
780             ObligationCauseCode::LetElse => {
781                 err.help("try adding a diverging expression, such as `return` or `panic!(..)`");
782                 err.help("...or use `match` instead of `let...else`");
783             }
784             _ => {
785                 if let ObligationCauseCode::BindingObligation(_, span)
786                 | ObligationCauseCode::ExprBindingObligation(_, span, ..)
787                 = cause.code().peel_derives()
788                     && let TypeError::RegionsPlaceholderMismatch = terr
789                 {
790                     err.span_note( * span,
791                     "the lifetime requirement is introduced here");
792                 }
793             }
794         }
795     }
796
797     fn suggest_remove_semi_or_return_binding(
798         &self,
799         err: &mut Diagnostic,
800         first_id: Option<hir::HirId>,
801         first_ty: Ty<'tcx>,
802         first_span: Span,
803         second_id: Option<hir::HirId>,
804         second_ty: Ty<'tcx>,
805         second_span: Span,
806     ) {
807         let remove_semicolon = [
808             (first_id, self.resolve_vars_if_possible(second_ty)),
809             (second_id, self.resolve_vars_if_possible(first_ty)),
810         ]
811         .into_iter()
812         .find_map(|(id, ty)| {
813             let hir::Node::Block(blk) = self.tcx.hir().get(id?) else { return None };
814             self.could_remove_semicolon(blk, ty)
815         });
816         match remove_semicolon {
817             Some((sp, StatementAsExpression::NeedsBoxing)) => {
818                 err.multipart_suggestion(
819                     "consider removing this semicolon and boxing the expressions",
820                     vec![
821                         (first_span.shrink_to_lo(), "Box::new(".to_string()),
822                         (first_span.shrink_to_hi(), ")".to_string()),
823                         (second_span.shrink_to_lo(), "Box::new(".to_string()),
824                         (second_span.shrink_to_hi(), ")".to_string()),
825                         (sp, String::new()),
826                     ],
827                     Applicability::MachineApplicable,
828                 );
829             }
830             Some((sp, StatementAsExpression::CorrectType)) => {
831                 err.span_suggestion_short(
832                     sp,
833                     "consider removing this semicolon",
834                     "",
835                     Applicability::MachineApplicable,
836                 );
837             }
838             None => {
839                 for (id, ty) in [(first_id, second_ty), (second_id, first_ty)] {
840                     if let Some(id) = id
841                         && let hir::Node::Block(blk) = self.tcx.hir().get(id)
842                         && self.consider_returning_binding(blk, ty, err)
843                     {
844                         break;
845                     }
846                 }
847             }
848         }
849     }
850
851     fn suggest_boxing_for_return_impl_trait(
852         &self,
853         err: &mut Diagnostic,
854         return_sp: Span,
855         arm_spans: impl Iterator<Item = Span>,
856     ) {
857         err.multipart_suggestion(
858             "you could change the return type to be a boxed trait object",
859             vec![
860                 (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
861                 (return_sp.shrink_to_hi(), ">".to_string()),
862             ],
863             Applicability::MaybeIncorrect,
864         );
865         let sugg = arm_spans
866             .flat_map(|sp| {
867                 [(sp.shrink_to_lo(), "Box::new(".to_string()), (sp.shrink_to_hi(), ")".to_string())]
868                     .into_iter()
869             })
870             .collect::<Vec<_>>();
871         err.multipart_suggestion(
872             "if you change the return type to expect trait objects, box the returned expressions",
873             sugg,
874             Applicability::MaybeIncorrect,
875         );
876     }
877
878     /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
879     /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
880     /// populate `other_value` with `other_ty`.
881     ///
882     /// ```text
883     /// Foo<Bar<Qux>>
884     /// ^^^^--------^ this is highlighted
885     /// |   |
886     /// |   this type argument is exactly the same as the other type, not highlighted
887     /// this is highlighted
888     /// Bar<Qux>
889     /// -------- this type is the same as a type argument in the other type, not highlighted
890     /// ```
891     fn highlight_outer(
892         &self,
893         value: &mut DiagnosticStyledString,
894         other_value: &mut DiagnosticStyledString,
895         name: String,
896         sub: ty::subst::SubstsRef<'tcx>,
897         pos: usize,
898         other_ty: Ty<'tcx>,
899     ) {
900         // `value` and `other_value` hold two incomplete type representation for display.
901         // `name` is the path of both types being compared. `sub`
902         value.push_highlighted(name);
903         let len = sub.len();
904         if len > 0 {
905             value.push_highlighted("<");
906         }
907
908         // Output the lifetimes for the first type
909         let lifetimes = sub
910             .regions()
911             .map(|lifetime| {
912                 let s = lifetime.to_string();
913                 if s.is_empty() { "'_".to_string() } else { s }
914             })
915             .collect::<Vec<_>>()
916             .join(", ");
917         if !lifetimes.is_empty() {
918             if sub.regions().count() < len {
919                 value.push_normal(lifetimes + ", ");
920             } else {
921                 value.push_normal(lifetimes);
922             }
923         }
924
925         // Highlight all the type arguments that aren't at `pos` and compare the type argument at
926         // `pos` and `other_ty`.
927         for (i, type_arg) in sub.types().enumerate() {
928             if i == pos {
929                 let values = self.cmp(type_arg, other_ty);
930                 value.0.extend((values.0).0);
931                 other_value.0.extend((values.1).0);
932             } else {
933                 value.push_highlighted(type_arg.to_string());
934             }
935
936             if len > 0 && i != len - 1 {
937                 value.push_normal(", ");
938             }
939         }
940         if len > 0 {
941             value.push_highlighted(">");
942         }
943     }
944
945     /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
946     /// as that is the difference to the other type.
947     ///
948     /// For the following code:
949     ///
950     /// ```ignore (illustrative)
951     /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
952     /// ```
953     ///
954     /// The type error output will behave in the following way:
955     ///
956     /// ```text
957     /// Foo<Bar<Qux>>
958     /// ^^^^--------^ this is highlighted
959     /// |   |
960     /// |   this type argument is exactly the same as the other type, not highlighted
961     /// this is highlighted
962     /// Bar<Qux>
963     /// -------- this type is the same as a type argument in the other type, not highlighted
964     /// ```
965     fn cmp_type_arg(
966         &self,
967         mut t1_out: &mut DiagnosticStyledString,
968         mut t2_out: &mut DiagnosticStyledString,
969         path: String,
970         sub: &'tcx [ty::GenericArg<'tcx>],
971         other_path: String,
972         other_ty: Ty<'tcx>,
973     ) -> Option<()> {
974         // FIXME/HACK: Go back to `SubstsRef` to use its inherent methods,
975         // ideally that shouldn't be necessary.
976         let sub = self.tcx.intern_substs(sub);
977         for (i, ta) in sub.types().enumerate() {
978             if ta == other_ty {
979                 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
980                 return Some(());
981             }
982             if let ty::Adt(def, _) = ta.kind() {
983                 let path_ = self.tcx.def_path_str(def.did());
984                 if path_ == other_path {
985                     self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
986                     return Some(());
987                 }
988             }
989         }
990         None
991     }
992
993     /// Adds a `,` to the type representation only if it is appropriate.
994     fn push_comma(
995         &self,
996         value: &mut DiagnosticStyledString,
997         other_value: &mut DiagnosticStyledString,
998         len: usize,
999         pos: usize,
1000     ) {
1001         if len > 0 && pos != len - 1 {
1002             value.push_normal(", ");
1003             other_value.push_normal(", ");
1004         }
1005     }
1006
1007     fn normalize_fn_sig_for_diagnostic(&self, sig: ty::PolyFnSig<'tcx>) -> ty::PolyFnSig<'tcx> {
1008         if let Some(normalize) = &self.normalize_fn_sig_for_diagnostic {
1009             normalize(self, sig)
1010         } else {
1011             sig
1012         }
1013     }
1014
1015     /// Given two `fn` signatures highlight only sub-parts that are different.
1016     fn cmp_fn_sig(
1017         &self,
1018         sig1: &ty::PolyFnSig<'tcx>,
1019         sig2: &ty::PolyFnSig<'tcx>,
1020     ) -> (DiagnosticStyledString, DiagnosticStyledString) {
1021         let sig1 = &self.normalize_fn_sig_for_diagnostic(*sig1);
1022         let sig2 = &self.normalize_fn_sig_for_diagnostic(*sig2);
1023
1024         let get_lifetimes = |sig| {
1025             use rustc_hir::def::Namespace;
1026             let (_, sig, reg) = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS)
1027                 .name_all_regions(sig)
1028                 .unwrap();
1029             let lts: Vec<String> = reg.into_iter().map(|(_, kind)| kind.to_string()).collect();
1030             (if lts.is_empty() { String::new() } else { format!("for<{}> ", lts.join(", ")) }, sig)
1031         };
1032
1033         let (lt1, sig1) = get_lifetimes(sig1);
1034         let (lt2, sig2) = get_lifetimes(sig2);
1035
1036         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1037         let mut values = (
1038             DiagnosticStyledString::normal("".to_string()),
1039             DiagnosticStyledString::normal("".to_string()),
1040         );
1041
1042         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1043         // ^^^^^^
1044         values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1045         values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1046
1047         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1048         //        ^^^^^^^^^^
1049         if sig1.abi != abi::Abi::Rust {
1050             values.0.push(format!("extern {} ", sig1.abi), sig1.abi != sig2.abi);
1051         }
1052         if sig2.abi != abi::Abi::Rust {
1053             values.1.push(format!("extern {} ", sig2.abi), sig1.abi != sig2.abi);
1054         }
1055
1056         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1057         //                   ^^^^^^^^
1058         let lifetime_diff = lt1 != lt2;
1059         values.0.push(lt1, lifetime_diff);
1060         values.1.push(lt2, lifetime_diff);
1061
1062         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1063         //                           ^^^
1064         values.0.push_normal("fn(");
1065         values.1.push_normal("fn(");
1066
1067         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1068         //                              ^^^^^
1069         let len1 = sig1.inputs().len();
1070         let len2 = sig2.inputs().len();
1071         if len1 == len2 {
1072             for (i, (l, r)) in iter::zip(sig1.inputs(), sig2.inputs()).enumerate() {
1073                 let (x1, x2) = self.cmp(*l, *r);
1074                 (values.0).0.extend(x1.0);
1075                 (values.1).0.extend(x2.0);
1076                 self.push_comma(&mut values.0, &mut values.1, len1, i);
1077             }
1078         } else {
1079             for (i, l) in sig1.inputs().iter().enumerate() {
1080                 values.0.push_highlighted(l.to_string());
1081                 if i != len1 - 1 {
1082                     values.0.push_highlighted(", ");
1083                 }
1084             }
1085             for (i, r) in sig2.inputs().iter().enumerate() {
1086                 values.1.push_highlighted(r.to_string());
1087                 if i != len2 - 1 {
1088                     values.1.push_highlighted(", ");
1089                 }
1090             }
1091         }
1092
1093         if sig1.c_variadic {
1094             if len1 > 0 {
1095                 values.0.push_normal(", ");
1096             }
1097             values.0.push("...", !sig2.c_variadic);
1098         }
1099         if sig2.c_variadic {
1100             if len2 > 0 {
1101                 values.1.push_normal(", ");
1102             }
1103             values.1.push("...", !sig1.c_variadic);
1104         }
1105
1106         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1107         //                                   ^
1108         values.0.push_normal(")");
1109         values.1.push_normal(")");
1110
1111         // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1112         //                                     ^^^^^^^^
1113         let output1 = sig1.output();
1114         let output2 = sig2.output();
1115         let (x1, x2) = self.cmp(output1, output2);
1116         if !output1.is_unit() {
1117             values.0.push_normal(" -> ");
1118             (values.0).0.extend(x1.0);
1119         }
1120         if !output2.is_unit() {
1121             values.1.push_normal(" -> ");
1122             (values.1).0.extend(x2.0);
1123         }
1124         values
1125     }
1126
1127     /// Compares two given types, eliding parts that are the same between them and highlighting
1128     /// relevant differences, and return two representation of those types for highlighted printing.
1129     pub fn cmp(
1130         &self,
1131         t1: Ty<'tcx>,
1132         t2: Ty<'tcx>,
1133     ) -> (DiagnosticStyledString, DiagnosticStyledString) {
1134         debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind(), t2, t2.kind());
1135
1136         // helper functions
1137         fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1138             match (a.kind(), b.kind()) {
1139                 (a, b) if *a == *b => true,
1140                 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
1141                 | (
1142                     &ty::Infer(ty::InferTy::IntVar(_)),
1143                     &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)),
1144                 )
1145                 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
1146                 | (
1147                     &ty::Infer(ty::InferTy::FloatVar(_)),
1148                     &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
1149                 ) => true,
1150                 _ => false,
1151             }
1152         }
1153
1154         fn push_ty_ref<'tcx>(
1155             region: ty::Region<'tcx>,
1156             ty: Ty<'tcx>,
1157             mutbl: hir::Mutability,
1158             s: &mut DiagnosticStyledString,
1159         ) {
1160             let mut r = region.to_string();
1161             if r == "'_" {
1162                 r.clear();
1163             } else {
1164                 r.push(' ');
1165             }
1166             s.push_highlighted(format!("&{}{}", r, mutbl.prefix_str()));
1167             s.push_normal(ty.to_string());
1168         }
1169
1170         // process starts here
1171         match (t1.kind(), t2.kind()) {
1172             (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1173                 let did1 = def1.did();
1174                 let did2 = def2.did();
1175                 let sub_no_defaults_1 =
1176                     self.tcx.generics_of(did1).own_substs_no_defaults(self.tcx, sub1);
1177                 let sub_no_defaults_2 =
1178                     self.tcx.generics_of(did2).own_substs_no_defaults(self.tcx, sub2);
1179                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1180                 let path1 = self.tcx.def_path_str(did1);
1181                 let path2 = self.tcx.def_path_str(did2);
1182                 if did1 == did2 {
1183                     // Easy case. Replace same types with `_` to shorten the output and highlight
1184                     // the differing ones.
1185                     //     let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1186                     //     Foo<Bar, _>
1187                     //     Foo<Quz, _>
1188                     //         ---  ^ type argument elided
1189                     //         |
1190                     //         highlighted in output
1191                     values.0.push_normal(path1);
1192                     values.1.push_normal(path2);
1193
1194                     // Avoid printing out default generic parameters that are common to both
1195                     // types.
1196                     let len1 = sub_no_defaults_1.len();
1197                     let len2 = sub_no_defaults_2.len();
1198                     let common_len = cmp::min(len1, len2);
1199                     let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
1200                     let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
1201                     let common_default_params =
1202                         iter::zip(remainder1.iter().rev(), remainder2.iter().rev())
1203                             .filter(|(a, b)| a == b)
1204                             .count();
1205                     let len = sub1.len() - common_default_params;
1206                     let consts_offset = len - sub1.consts().count();
1207
1208                     // Only draw `<...>` if there are lifetime/type arguments.
1209                     if len > 0 {
1210                         values.0.push_normal("<");
1211                         values.1.push_normal("<");
1212                     }
1213
1214                     fn lifetime_display(lifetime: Region<'_>) -> String {
1215                         let s = lifetime.to_string();
1216                         if s.is_empty() { "'_".to_string() } else { s }
1217                     }
1218                     // At one point we'd like to elide all lifetimes here, they are irrelevant for
1219                     // all diagnostics that use this output
1220                     //
1221                     //     Foo<'x, '_, Bar>
1222                     //     Foo<'y, '_, Qux>
1223                     //         ^^  ^^  --- type arguments are not elided
1224                     //         |   |
1225                     //         |   elided as they were the same
1226                     //         not elided, they were different, but irrelevant
1227                     //
1228                     // For bound lifetimes, keep the names of the lifetimes,
1229                     // even if they are the same so that it's clear what's happening
1230                     // if we have something like
1231                     //
1232                     // for<'r, 's> fn(Inv<'r>, Inv<'s>)
1233                     // for<'r> fn(Inv<'r>, Inv<'r>)
1234                     let lifetimes = sub1.regions().zip(sub2.regions());
1235                     for (i, lifetimes) in lifetimes.enumerate() {
1236                         let l1 = lifetime_display(lifetimes.0);
1237                         let l2 = lifetime_display(lifetimes.1);
1238                         if lifetimes.0 != lifetimes.1 {
1239                             values.0.push_highlighted(l1);
1240                             values.1.push_highlighted(l2);
1241                         } else if lifetimes.0.is_late_bound() {
1242                             values.0.push_normal(l1);
1243                             values.1.push_normal(l2);
1244                         } else {
1245                             values.0.push_normal("'_");
1246                             values.1.push_normal("'_");
1247                         }
1248                         self.push_comma(&mut values.0, &mut values.1, len, i);
1249                     }
1250
1251                     // We're comparing two types with the same path, so we compare the type
1252                     // arguments for both. If they are the same, do not highlight and elide from the
1253                     // output.
1254                     //     Foo<_, Bar>
1255                     //     Foo<_, Qux>
1256                     //         ^ elided type as this type argument was the same in both sides
1257                     let type_arguments = sub1.types().zip(sub2.types());
1258                     let regions_len = sub1.regions().count();
1259                     let num_display_types = consts_offset - regions_len;
1260                     for (i, (ta1, ta2)) in type_arguments.take(num_display_types).enumerate() {
1261                         let i = i + regions_len;
1262                         if ta1 == ta2 {
1263                             values.0.push_normal("_");
1264                             values.1.push_normal("_");
1265                         } else {
1266                             let (x1, x2) = self.cmp(ta1, ta2);
1267                             (values.0).0.extend(x1.0);
1268                             (values.1).0.extend(x2.0);
1269                         }
1270                         self.push_comma(&mut values.0, &mut values.1, len, i);
1271                     }
1272
1273                     // Do the same for const arguments, if they are equal, do not highlight and
1274                     // elide them from the output.
1275                     let const_arguments = sub1.consts().zip(sub2.consts());
1276                     for (i, (ca1, ca2)) in const_arguments.enumerate() {
1277                         let i = i + consts_offset;
1278                         if ca1 == ca2 {
1279                             values.0.push_normal("_");
1280                             values.1.push_normal("_");
1281                         } else {
1282                             values.0.push_highlighted(ca1.to_string());
1283                             values.1.push_highlighted(ca2.to_string());
1284                         }
1285                         self.push_comma(&mut values.0, &mut values.1, len, i);
1286                     }
1287
1288                     // Close the type argument bracket.
1289                     // Only draw `<...>` if there are lifetime/type arguments.
1290                     if len > 0 {
1291                         values.0.push_normal(">");
1292                         values.1.push_normal(">");
1293                     }
1294                     values
1295                 } else {
1296                     // Check for case:
1297                     //     let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1298                     //     Foo<Bar<Qux>
1299                     //         ------- this type argument is exactly the same as the other type
1300                     //     Bar<Qux>
1301                     if self
1302                         .cmp_type_arg(
1303                             &mut values.0,
1304                             &mut values.1,
1305                             path1.clone(),
1306                             sub_no_defaults_1,
1307                             path2.clone(),
1308                             t2,
1309                         )
1310                         .is_some()
1311                     {
1312                         return values;
1313                     }
1314                     // Check for case:
1315                     //     let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1316                     //     Bar<Qux>
1317                     //     Foo<Bar<Qux>>
1318                     //         ------- this type argument is exactly the same as the other type
1319                     if self
1320                         .cmp_type_arg(
1321                             &mut values.1,
1322                             &mut values.0,
1323                             path2,
1324                             sub_no_defaults_2,
1325                             path1,
1326                             t1,
1327                         )
1328                         .is_some()
1329                     {
1330                         return values;
1331                     }
1332
1333                     // We can't find anything in common, highlight relevant part of type path.
1334                     //     let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1335                     //     foo::bar::Baz<Qux>
1336                     //     foo::bar::Bar<Zar>
1337                     //               -------- this part of the path is different
1338
1339                     let t1_str = t1.to_string();
1340                     let t2_str = t2.to_string();
1341                     let min_len = t1_str.len().min(t2_str.len());
1342
1343                     const SEPARATOR: &str = "::";
1344                     let separator_len = SEPARATOR.len();
1345                     let split_idx: usize =
1346                         iter::zip(t1_str.split(SEPARATOR), t2_str.split(SEPARATOR))
1347                             .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1348                             .map(|(mod_str, _)| mod_str.len() + separator_len)
1349                             .sum();
1350
1351                     debug!(
1352                         "cmp: separator_len={}, split_idx={}, min_len={}",
1353                         separator_len, split_idx, min_len
1354                     );
1355
1356                     if split_idx >= min_len {
1357                         // paths are identical, highlight everything
1358                         (
1359                             DiagnosticStyledString::highlighted(t1_str),
1360                             DiagnosticStyledString::highlighted(t2_str),
1361                         )
1362                     } else {
1363                         let (common, uniq1) = t1_str.split_at(split_idx);
1364                         let (_, uniq2) = t2_str.split_at(split_idx);
1365                         debug!("cmp: common={}, uniq1={}, uniq2={}", common, uniq1, uniq2);
1366
1367                         values.0.push_normal(common);
1368                         values.0.push_highlighted(uniq1);
1369                         values.1.push_normal(common);
1370                         values.1.push_highlighted(uniq2);
1371
1372                         values
1373                     }
1374                 }
1375             }
1376
1377             // When finding T != &T, highlight only the borrow
1378             (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(ref_ty1, t2) => {
1379                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1380                 push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
1381                 values.1.push_normal(t2.to_string());
1382                 values
1383             }
1384             (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(t1, ref_ty2) => {
1385                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1386                 values.0.push_normal(t1.to_string());
1387                 push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
1388                 values
1389             }
1390
1391             // When encountering &T != &mut T, highlight only the borrow
1392             (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1393                 if equals(ref_ty1, ref_ty2) =>
1394             {
1395                 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1396                 push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
1397                 push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
1398                 values
1399             }
1400
1401             // When encountering tuples of the same size, highlight only the differing types
1402             (&ty::Tuple(substs1), &ty::Tuple(substs2)) if substs1.len() == substs2.len() => {
1403                 let mut values =
1404                     (DiagnosticStyledString::normal("("), DiagnosticStyledString::normal("("));
1405                 let len = substs1.len();
1406                 for (i, (left, right)) in substs1.iter().zip(substs2).enumerate() {
1407                     let (x1, x2) = self.cmp(left, right);
1408                     (values.0).0.extend(x1.0);
1409                     (values.1).0.extend(x2.0);
1410                     self.push_comma(&mut values.0, &mut values.1, len, i);
1411                 }
1412                 if len == 1 {
1413                     // Keep the output for single element tuples as `(ty,)`.
1414                     values.0.push_normal(",");
1415                     values.1.push_normal(",");
1416                 }
1417                 values.0.push_normal(")");
1418                 values.1.push_normal(")");
1419                 values
1420             }
1421
1422             (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1423                 let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1);
1424                 let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2);
1425                 let mut values = self.cmp_fn_sig(&sig1, &sig2);
1426                 let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did1, substs1));
1427                 let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did2, substs2));
1428                 let same_path = path1 == path2;
1429                 values.0.push(path1, !same_path);
1430                 values.1.push(path2, !same_path);
1431                 values
1432             }
1433
1434             (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => {
1435                 let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1);
1436                 let mut values = self.cmp_fn_sig(&sig1, sig2);
1437                 values.0.push_highlighted(format!(
1438                     " {{{}}}",
1439                     self.tcx.def_path_str_with_substs(*did1, substs1)
1440                 ));
1441                 values
1442             }
1443
1444             (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => {
1445                 let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2);
1446                 let mut values = self.cmp_fn_sig(sig1, &sig2);
1447                 values.1.push_normal(format!(
1448                     " {{{}}}",
1449                     self.tcx.def_path_str_with_substs(*did2, substs2)
1450                 ));
1451                 values
1452             }
1453
1454             (ty::FnPtr(sig1), ty::FnPtr(sig2)) => self.cmp_fn_sig(sig1, sig2),
1455
1456             _ => {
1457                 if t1 == t2 {
1458                     // The two types are the same, elide and don't highlight.
1459                     (DiagnosticStyledString::normal("_"), DiagnosticStyledString::normal("_"))
1460                 } else {
1461                     // We couldn't find anything in common, highlight everything.
1462                     (
1463                         DiagnosticStyledString::highlighted(t1.to_string()),
1464                         DiagnosticStyledString::highlighted(t2.to_string()),
1465                     )
1466                 }
1467             }
1468         }
1469     }
1470
1471     /// Extend a type error with extra labels pointing at "non-trivial" types, like closures and
1472     /// the return type of `async fn`s.
1473     ///
1474     /// `secondary_span` gives the caller the opportunity to expand `diag` with a `span_label`.
1475     ///
1476     /// `swap_secondary_and_primary` is used to make projection errors in particular nicer by using
1477     /// the message in `secondary_span` as the primary label, and apply the message that would
1478     /// otherwise be used for the primary label on the `secondary_span` `Span`. This applies on
1479     /// E0271, like `src/test/ui/issues/issue-39970.stderr`.
1480     #[instrument(
1481         level = "debug",
1482         skip(self, diag, secondary_span, swap_secondary_and_primary, prefer_label)
1483     )]
1484     pub fn note_type_err(
1485         &self,
1486         diag: &mut Diagnostic,
1487         cause: &ObligationCause<'tcx>,
1488         secondary_span: Option<(Span, String)>,
1489         mut values: Option<ValuePairs<'tcx>>,
1490         terr: TypeError<'tcx>,
1491         swap_secondary_and_primary: bool,
1492         prefer_label: bool,
1493     ) {
1494         let span = cause.span();
1495
1496         // For some types of errors, expected-found does not make
1497         // sense, so just ignore the values we were given.
1498         if let TypeError::CyclicTy(_) = terr {
1499             values = None;
1500         }
1501         struct OpaqueTypesVisitor<'tcx> {
1502             types: FxHashMap<TyCategory, FxHashSet<Span>>,
1503             expected: FxHashMap<TyCategory, FxHashSet<Span>>,
1504             found: FxHashMap<TyCategory, FxHashSet<Span>>,
1505             ignore_span: Span,
1506             tcx: TyCtxt<'tcx>,
1507         }
1508
1509         impl<'tcx> OpaqueTypesVisitor<'tcx> {
1510             fn visit_expected_found(
1511                 tcx: TyCtxt<'tcx>,
1512                 expected: Ty<'tcx>,
1513                 found: Ty<'tcx>,
1514                 ignore_span: Span,
1515             ) -> Self {
1516                 let mut types_visitor = OpaqueTypesVisitor {
1517                     types: Default::default(),
1518                     expected: Default::default(),
1519                     found: Default::default(),
1520                     ignore_span,
1521                     tcx,
1522                 };
1523                 // The visitor puts all the relevant encountered types in `self.types`, but in
1524                 // here we want to visit two separate types with no relation to each other, so we
1525                 // move the results from `types` to `expected` or `found` as appropriate.
1526                 expected.visit_with(&mut types_visitor);
1527                 std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1528                 found.visit_with(&mut types_visitor);
1529                 std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1530                 types_visitor
1531             }
1532
1533             fn report(&self, err: &mut Diagnostic) {
1534                 self.add_labels_for_types(err, "expected", &self.expected);
1535                 self.add_labels_for_types(err, "found", &self.found);
1536             }
1537
1538             fn add_labels_for_types(
1539                 &self,
1540                 err: &mut Diagnostic,
1541                 target: &str,
1542                 types: &FxHashMap<TyCategory, FxHashSet<Span>>,
1543             ) {
1544                 for (key, values) in types.iter() {
1545                     let count = values.len();
1546                     let kind = key.descr();
1547                     let mut returned_async_output_error = false;
1548                     for &sp in values {
1549                         if sp.is_desugaring(DesugaringKind::Async) && !returned_async_output_error {
1550                             if [sp] != err.span.primary_spans() {
1551                                 let mut span: MultiSpan = sp.into();
1552                                 span.push_span_label(
1553                                     sp,
1554                                     format!(
1555                                         "checked the `Output` of this `async fn`, {}{} {}{}",
1556                                         if count > 1 { "one of the " } else { "" },
1557                                         target,
1558                                         kind,
1559                                         pluralize!(count),
1560                                     ),
1561                                 );
1562                                 err.span_note(
1563                                     span,
1564                                     "while checking the return type of the `async fn`",
1565                                 );
1566                             } else {
1567                                 err.span_label(
1568                                     sp,
1569                                     format!(
1570                                         "checked the `Output` of this `async fn`, {}{} {}{}",
1571                                         if count > 1 { "one of the " } else { "" },
1572                                         target,
1573                                         kind,
1574                                         pluralize!(count),
1575                                     ),
1576                                 );
1577                                 err.note("while checking the return type of the `async fn`");
1578                             }
1579                             returned_async_output_error = true;
1580                         } else {
1581                             err.span_label(
1582                                 sp,
1583                                 format!(
1584                                     "{}{} {}{}",
1585                                     if count == 1 { "the " } else { "one of the " },
1586                                     target,
1587                                     kind,
1588                                     pluralize!(count),
1589                                 ),
1590                             );
1591                         }
1592                     }
1593                 }
1594             }
1595         }
1596
1597         impl<'tcx> ty::visit::TypeVisitor<'tcx> for OpaqueTypesVisitor<'tcx> {
1598             fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1599                 if let Some((kind, def_id)) = TyCategory::from_ty(self.tcx, t) {
1600                     let span = self.tcx.def_span(def_id);
1601                     // Avoid cluttering the output when the "found" and error span overlap:
1602                     //
1603                     // error[E0308]: mismatched types
1604                     //   --> $DIR/issue-20862.rs:2:5
1605                     //    |
1606                     // LL |     |y| x + y
1607                     //    |     ^^^^^^^^^
1608                     //    |     |
1609                     //    |     the found closure
1610                     //    |     expected `()`, found closure
1611                     //    |
1612                     //    = note: expected unit type `()`
1613                     //                 found closure `[closure@$DIR/issue-20862.rs:2:5: 2:14 x:_]`
1614                     if !self.ignore_span.overlaps(span) {
1615                         self.types.entry(kind).or_default().insert(span);
1616                     }
1617                 }
1618                 t.super_visit_with(self)
1619             }
1620         }
1621
1622         debug!("note_type_err(diag={:?})", diag);
1623         enum Mismatch<'a> {
1624             Variable(ty::error::ExpectedFound<Ty<'a>>),
1625             Fixed(&'static str),
1626         }
1627         let (expected_found, exp_found, is_simple_error, values) = match values {
1628             None => (None, Mismatch::Fixed("type"), false, None),
1629             Some(values) => {
1630                 let values = self.resolve_vars_if_possible(values);
1631                 let (is_simple_error, exp_found) = match values {
1632                     ValuePairs::Terms(infer::ExpectedFound { expected, found }) => {
1633                         match (expected.unpack(), found.unpack()) {
1634                             (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
1635                                 let is_simple_err =
1636                                     expected.is_simple_text() && found.is_simple_text();
1637                                 OpaqueTypesVisitor::visit_expected_found(
1638                                     self.tcx, expected, found, span,
1639                                 )
1640                                 .report(diag);
1641
1642                                 (
1643                                     is_simple_err,
1644                                     Mismatch::Variable(infer::ExpectedFound { expected, found }),
1645                                 )
1646                             }
1647                             (ty::TermKind::Const(_), ty::TermKind::Const(_)) => {
1648                                 (false, Mismatch::Fixed("constant"))
1649                             }
1650                             _ => (false, Mismatch::Fixed("type")),
1651                         }
1652                     }
1653                     ValuePairs::TraitRefs(_) | ValuePairs::PolyTraitRefs(_) => {
1654                         (false, Mismatch::Fixed("trait"))
1655                     }
1656                     ValuePairs::Regions(_) => (false, Mismatch::Fixed("lifetime")),
1657                 };
1658                 let vals = match self.values_str(values) {
1659                     Some((expected, found)) => Some((expected, found)),
1660                     None => {
1661                         // Derived error. Cancel the emitter.
1662                         // NOTE(eddyb) this was `.cancel()`, but `diag`
1663                         // is borrowed, so we can't fully defuse it.
1664                         diag.downgrade_to_delayed_bug();
1665                         return;
1666                     }
1667                 };
1668                 (vals, exp_found, is_simple_error, Some(values))
1669             }
1670         };
1671
1672         match terr {
1673             // Ignore msg for object safe coercion
1674             // since E0038 message will be printed
1675             TypeError::ObjectUnsafeCoercion(_) => {}
1676             _ => {
1677                 let mut label_or_note = |span: Span, msg: &str| {
1678                     if (prefer_label && is_simple_error) || &[span] == diag.span.primary_spans() {
1679                         diag.span_label(span, msg);
1680                     } else {
1681                         diag.span_note(span, msg);
1682                     }
1683                 };
1684                 if let Some((sp, msg)) = secondary_span {
1685                     if swap_secondary_and_primary {
1686                         let terr = if let Some(infer::ValuePairs::Terms(infer::ExpectedFound {
1687                             expected,
1688                             ..
1689                         })) = values
1690                         {
1691                             format!("expected this to be `{}`", expected)
1692                         } else {
1693                             terr.to_string()
1694                         };
1695                         label_or_note(sp, &terr);
1696                         label_or_note(span, &msg);
1697                     } else {
1698                         label_or_note(span, &terr.to_string());
1699                         label_or_note(sp, &msg);
1700                     }
1701                 } else {
1702                     label_or_note(span, &terr.to_string());
1703                 }
1704             }
1705         };
1706         if let Some((expected, found)) = expected_found {
1707             let (expected_label, found_label, exp_found) = match exp_found {
1708                 Mismatch::Variable(ef) => (
1709                     ef.expected.prefix_string(self.tcx),
1710                     ef.found.prefix_string(self.tcx),
1711                     Some(ef),
1712                 ),
1713                 Mismatch::Fixed(s) => (s.into(), s.into(), None),
1714             };
1715
1716             enum Similar<'tcx> {
1717                 Adts { expected: ty::AdtDef<'tcx>, found: ty::AdtDef<'tcx> },
1718                 PrimitiveFound { expected: ty::AdtDef<'tcx>, found: Ty<'tcx> },
1719                 PrimitiveExpected { expected: Ty<'tcx>, found: ty::AdtDef<'tcx> },
1720             }
1721
1722             let similarity = |ExpectedFound { expected, found }: ExpectedFound<Ty<'tcx>>| {
1723                 if let ty::Adt(expected, _) = expected.kind() && let Some(primitive) = found.primitive_symbol() {
1724                     let path = self.tcx.def_path(expected.did()).data;
1725                     let name = path.last().unwrap().data.get_opt_name();
1726                     if name == Some(primitive) {
1727                         return Some(Similar::PrimitiveFound { expected: *expected, found });
1728                     }
1729                 } else if let Some(primitive) = expected.primitive_symbol() && let ty::Adt(found, _) = found.kind() {
1730                     let path = self.tcx.def_path(found.did()).data;
1731                     let name = path.last().unwrap().data.get_opt_name();
1732                     if name == Some(primitive) {
1733                         return Some(Similar::PrimitiveExpected { expected, found: *found });
1734                     }
1735                 } else if let ty::Adt(expected, _) = expected.kind() && let ty::Adt(found, _) = found.kind() {
1736                     if !expected.did().is_local() && expected.did().krate == found.did().krate {
1737                         // Most likely types from different versions of the same crate
1738                         // are in play, in which case this message isn't so helpful.
1739                         // A "perhaps two different versions..." error is already emitted for that.
1740                         return None;
1741                     }
1742                     let f_path = self.tcx.def_path(found.did()).data;
1743                     let e_path = self.tcx.def_path(expected.did()).data;
1744
1745                     if let (Some(e_last), Some(f_last)) = (e_path.last(), f_path.last()) && e_last ==  f_last {
1746                         return Some(Similar::Adts{expected: *expected, found: *found});
1747                     }
1748                 }
1749                 None
1750             };
1751
1752             match terr {
1753                 // If two types mismatch but have similar names, mention that specifically.
1754                 TypeError::Sorts(values) if let Some(s) = similarity(values) => {
1755                     let diagnose_primitive =
1756                         |prim: Ty<'tcx>,
1757                          shadow: Ty<'tcx>,
1758                          defid: DefId,
1759                          diagnostic: &mut Diagnostic| {
1760                             let name = shadow.sort_string(self.tcx);
1761                             diagnostic.note(format!(
1762                             "{prim} and {name} have similar names, but are actually distinct types"
1763                         ));
1764                             diagnostic
1765                                 .note(format!("{prim} is a primitive defined by the language"));
1766                             let def_span = self.tcx.def_span(defid);
1767                             let msg = if defid.is_local() {
1768                                 format!("{name} is defined in the current crate")
1769                             } else {
1770                                 let crate_name = self.tcx.crate_name(defid.krate);
1771                                 format!("{name} is defined in crate `{crate_name}")
1772                             };
1773                             diagnostic.span_note(def_span, msg);
1774                         };
1775
1776                     let diagnose_adts =
1777                         |expected_adt : ty::AdtDef<'tcx>,
1778                          found_adt: ty::AdtDef<'tcx>,
1779                          diagnostic: &mut Diagnostic| {
1780                             let found_name = values.found.sort_string(self.tcx);
1781                             let expected_name = values.expected.sort_string(self.tcx);
1782
1783                             let found_defid = found_adt.did();
1784                             let expected_defid = expected_adt.did();
1785
1786                             diagnostic.note(format!("{found_name} and {expected_name} have similar names, but are actually distinct types"));
1787                             for (defid, name) in
1788                                 [(found_defid, found_name), (expected_defid, expected_name)]
1789                             {
1790                                 let def_span = self.tcx.def_span(defid);
1791
1792                                 let msg = if found_defid.is_local() && expected_defid.is_local() {
1793                                     let module = self
1794                                         .tcx
1795                                         .parent_module_from_def_id(defid.expect_local())
1796                                         .to_def_id();
1797                                     let module_name = self.tcx.def_path(module).to_string_no_crate_verbose();
1798                                     format!("{name} is defined in module `crate{module_name}` of the current crate")
1799                                 } else if defid.is_local() {
1800                                     format!("{name} is defined in the current crate")
1801                                 } else {
1802                                     let crate_name = self.tcx.crate_name(defid.krate);
1803                                     format!("{name} is defined in crate `{crate_name}`")
1804                                 };
1805                                 diagnostic.span_note(def_span, msg);
1806                             }
1807                         };
1808
1809                     match s {
1810                         Similar::Adts{expected, found} => {
1811                             diagnose_adts(expected, found, diag)
1812                         }
1813                         Similar::PrimitiveFound{expected, found: prim} => {
1814                             diagnose_primitive(prim, values.expected, expected.did(), diag)
1815                         }
1816                         Similar::PrimitiveExpected{expected: prim, found} => {
1817                             diagnose_primitive(prim, values.found, found.did(), diag)
1818                         }
1819                     }
1820                 }
1821                 TypeError::Sorts(values) => {
1822                     let extra = expected == found;
1823                     let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
1824                         (true, ty::Opaque(def_id, _)) => {
1825                             let sm = self.tcx.sess.source_map();
1826                             let pos = sm.lookup_char_pos(self.tcx.def_span(*def_id).lo());
1827                             format!(
1828                                 " (opaque type at <{}:{}:{}>)",
1829                                 sm.filename_for_diagnostics(&pos.file.name),
1830                                 pos.line,
1831                                 pos.col.to_usize() + 1,
1832                             )
1833                         }
1834                         (true, ty::Projection(proj))
1835                             if self.tcx.def_kind(proj.item_def_id)
1836                                 == DefKind::ImplTraitPlaceholder =>
1837                         {
1838                             let sm = self.tcx.sess.source_map();
1839                             let pos = sm.lookup_char_pos(self.tcx.def_span(proj.item_def_id).lo());
1840                             format!(
1841                                 " (trait associated opaque type at <{}:{}:{}>)",
1842                                 sm.filename_for_diagnostics(&pos.file.name),
1843                                 pos.line,
1844                                 pos.col.to_usize() + 1,
1845                             )
1846                         }
1847                         (true, _) => format!(" ({})", ty.sort_string(self.tcx)),
1848                         (false, _) => "".to_string(),
1849                     };
1850                     if !(values.expected.is_simple_text() && values.found.is_simple_text())
1851                         || (exp_found.map_or(false, |ef| {
1852                             // This happens when the type error is a subset of the expectation,
1853                             // like when you have two references but one is `usize` and the other
1854                             // is `f32`. In those cases we still want to show the `note`. If the
1855                             // value from `ef` is `Infer(_)`, then we ignore it.
1856                             if !ef.expected.is_ty_infer() {
1857                                 ef.expected != values.expected
1858                             } else if !ef.found.is_ty_infer() {
1859                                 ef.found != values.found
1860                             } else {
1861                                 false
1862                             }
1863                         }))
1864                     {
1865                         diag.note_expected_found_extra(
1866                             &expected_label,
1867                             expected,
1868                             &found_label,
1869                             found,
1870                             &sort_string(values.expected),
1871                             &sort_string(values.found),
1872                         );
1873                     }
1874                 }
1875                 TypeError::ObjectUnsafeCoercion(_) => {
1876                     diag.note_unsuccessful_coercion(found, expected);
1877                 }
1878                 _ => {
1879                     debug!(
1880                         "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1881                         exp_found, expected, found
1882                     );
1883                     if !is_simple_error || terr.must_include_note() {
1884                         diag.note_expected_found(&expected_label, expected, &found_label, found);
1885                     }
1886                 }
1887             }
1888         }
1889         let exp_found = match exp_found {
1890             Mismatch::Variable(exp_found) => Some(exp_found),
1891             Mismatch::Fixed(_) => None,
1892         };
1893         let exp_found = match terr {
1894             // `terr` has more accurate type information than `exp_found` in match expressions.
1895             ty::error::TypeError::Sorts(terr)
1896                 if exp_found.map_or(false, |ef| terr.found == ef.found) =>
1897             {
1898                 Some(terr)
1899             }
1900             _ => exp_found,
1901         };
1902         debug!("exp_found {:?} terr {:?} cause.code {:?}", exp_found, terr, cause.code());
1903         if let Some(exp_found) = exp_found {
1904             let should_suggest_fixes =
1905                 if let ObligationCauseCode::Pattern { root_ty, .. } = cause.code() {
1906                     // Skip if the root_ty of the pattern is not the same as the expected_ty.
1907                     // If these types aren't equal then we've probably peeled off a layer of arrays.
1908                     self.same_type_modulo_infer(*root_ty, exp_found.expected)
1909                 } else {
1910                     true
1911                 };
1912
1913             if should_suggest_fixes {
1914                 self.suggest_tuple_pattern(cause, &exp_found, diag);
1915                 self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1916                 self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag);
1917                 self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
1918             }
1919         }
1920
1921         // In some (most?) cases cause.body_id points to actual body, but in some cases
1922         // it's an actual definition. According to the comments (e.g. in
1923         // rustc_hir_analysis/check/compare_method.rs:compare_predicate_entailment) the latter
1924         // is relied upon by some other code. This might (or might not) need cleanup.
1925         let body_owner_def_id =
1926             self.tcx.hir().opt_local_def_id(cause.body_id).unwrap_or_else(|| {
1927                 self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id })
1928             });
1929         self.check_and_note_conflicting_crates(diag, terr);
1930         self.tcx.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id.to_def_id());
1931
1932         if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values
1933             && let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind()
1934             && let Some(def_id) = def_id.as_local()
1935             && terr.involves_regions()
1936         {
1937             let span = self.tcx.def_span(def_id);
1938             diag.span_note(span, "this closure does not fulfill the lifetime requirements");
1939         }
1940
1941         // It reads better to have the error origin as the final
1942         // thing.
1943         self.note_error_origin(diag, cause, exp_found, terr);
1944
1945         debug!(?diag);
1946     }
1947
1948     fn suggest_tuple_pattern(
1949         &self,
1950         cause: &ObligationCause<'tcx>,
1951         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1952         diag: &mut Diagnostic,
1953     ) {
1954         // Heavily inspired by `FnCtxt::suggest_compatible_variants`, with
1955         // some modifications due to that being in typeck and this being in infer.
1956         if let ObligationCauseCode::Pattern { .. } = cause.code() {
1957             if let ty::Adt(expected_adt, substs) = exp_found.expected.kind() {
1958                 let compatible_variants: Vec<_> = expected_adt
1959                     .variants()
1960                     .iter()
1961                     .filter(|variant| {
1962                         variant.fields.len() == 1 && variant.ctor_kind == hir::def::CtorKind::Fn
1963                     })
1964                     .filter_map(|variant| {
1965                         let sole_field = &variant.fields[0];
1966                         let sole_field_ty = sole_field.ty(self.tcx, substs);
1967                         if self.same_type_modulo_infer(sole_field_ty, exp_found.found) {
1968                             let variant_path =
1969                                 with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
1970                             // FIXME #56861: DRYer prelude filtering
1971                             if let Some(path) = variant_path.strip_prefix("std::prelude::") {
1972                                 if let Some((_, path)) = path.split_once("::") {
1973                                     return Some(path.to_string());
1974                                 }
1975                             }
1976                             Some(variant_path)
1977                         } else {
1978                             None
1979                         }
1980                     })
1981                     .collect();
1982                 match &compatible_variants[..] {
1983                     [] => {}
1984                     [variant] => {
1985                         diag.multipart_suggestion_verbose(
1986                             &format!("try wrapping the pattern in `{}`", variant),
1987                             vec![
1988                                 (cause.span.shrink_to_lo(), format!("{}(", variant)),
1989                                 (cause.span.shrink_to_hi(), ")".to_string()),
1990                             ],
1991                             Applicability::MaybeIncorrect,
1992                         );
1993                     }
1994                     _ => {
1995                         // More than one matching variant.
1996                         diag.multipart_suggestions(
1997                             &format!(
1998                                 "try wrapping the pattern in a variant of `{}`",
1999                                 self.tcx.def_path_str(expected_adt.did())
2000                             ),
2001                             compatible_variants.into_iter().map(|variant| {
2002                                 vec![
2003                                     (cause.span.shrink_to_lo(), format!("{}(", variant)),
2004                                     (cause.span.shrink_to_hi(), ")".to_string()),
2005                                 ]
2006                             }),
2007                             Applicability::MaybeIncorrect,
2008                         );
2009                     }
2010                 }
2011             }
2012         }
2013     }
2014
2015     /// A possible error is to forget to add `.await` when using futures:
2016     ///
2017     /// ```compile_fail,E0308
2018     /// async fn make_u32() -> u32 {
2019     ///     22
2020     /// }
2021     ///
2022     /// fn take_u32(x: u32) {}
2023     ///
2024     /// async fn foo() {
2025     ///     let x = make_u32();
2026     ///     take_u32(x);
2027     /// }
2028     /// ```
2029     ///
2030     /// This routine checks if the found type `T` implements `Future<Output=U>` where `U` is the
2031     /// expected type. If this is the case, and we are inside of an async body, it suggests adding
2032     /// `.await` to the tail of the expression.
2033     fn suggest_await_on_expect_found(
2034         &self,
2035         cause: &ObligationCause<'tcx>,
2036         exp_span: Span,
2037         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
2038         diag: &mut Diagnostic,
2039     ) {
2040         debug!(
2041             "suggest_await_on_expect_found: exp_span={:?}, expected_ty={:?}, found_ty={:?}",
2042             exp_span, exp_found.expected, exp_found.found,
2043         );
2044
2045         if let ObligationCauseCode::CompareImplItemObligation { .. } = cause.code() {
2046             return;
2047         }
2048
2049         match (
2050             self.get_impl_future_output_ty(exp_found.expected).map(Binder::skip_binder),
2051             self.get_impl_future_output_ty(exp_found.found).map(Binder::skip_binder),
2052         ) {
2053             (Some(exp), Some(found)) if self.same_type_modulo_infer(exp, found) => match cause
2054                 .code()
2055             {
2056                 ObligationCauseCode::IfExpression(box IfExpressionCause { then_id, .. }) => {
2057                     let then_span = self.find_block_span_from_hir_id(*then_id);
2058                     diag.multipart_suggestion(
2059                         "consider `await`ing on both `Future`s",
2060                         vec![
2061                             (then_span.shrink_to_hi(), ".await".to_string()),
2062                             (exp_span.shrink_to_hi(), ".await".to_string()),
2063                         ],
2064                         Applicability::MaybeIncorrect,
2065                     );
2066                 }
2067                 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
2068                     prior_arms,
2069                     ..
2070                 }) => {
2071                     if let [.., arm_span] = &prior_arms[..] {
2072                         diag.multipart_suggestion(
2073                             "consider `await`ing on both `Future`s",
2074                             vec![
2075                                 (arm_span.shrink_to_hi(), ".await".to_string()),
2076                                 (exp_span.shrink_to_hi(), ".await".to_string()),
2077                             ],
2078                             Applicability::MaybeIncorrect,
2079                         );
2080                     } else {
2081                         diag.help("consider `await`ing on both `Future`s");
2082                     }
2083                 }
2084                 _ => {
2085                     diag.help("consider `await`ing on both `Future`s");
2086                 }
2087             },
2088             (_, Some(ty)) if self.same_type_modulo_infer(exp_found.expected, ty) => {
2089                 diag.span_suggestion_verbose(
2090                     exp_span.shrink_to_hi(),
2091                     "consider `await`ing on the `Future`",
2092                     ".await",
2093                     Applicability::MaybeIncorrect,
2094                 );
2095             }
2096             (Some(ty), _) if self.same_type_modulo_infer(ty, exp_found.found) => match cause.code()
2097             {
2098                 ObligationCauseCode::Pattern { span: Some(then_span), .. } => {
2099                     diag.span_suggestion_verbose(
2100                         then_span.shrink_to_hi(),
2101                         "consider `await`ing on the `Future`",
2102                         ".await",
2103                         Applicability::MaybeIncorrect,
2104                     );
2105                 }
2106                 ObligationCauseCode::IfExpression(box IfExpressionCause { then_id, .. }) => {
2107                     let then_span = self.find_block_span_from_hir_id(*then_id);
2108                     diag.span_suggestion_verbose(
2109                         then_span.shrink_to_hi(),
2110                         "consider `await`ing on the `Future`",
2111                         ".await",
2112                         Applicability::MaybeIncorrect,
2113                     );
2114                 }
2115                 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
2116                     ref prior_arms,
2117                     ..
2118                 }) => {
2119                     diag.multipart_suggestion_verbose(
2120                         "consider `await`ing on the `Future`",
2121                         prior_arms
2122                             .iter()
2123                             .map(|arm| (arm.shrink_to_hi(), ".await".to_string()))
2124                             .collect(),
2125                         Applicability::MaybeIncorrect,
2126                     );
2127                 }
2128                 _ => {}
2129             },
2130             _ => {}
2131         }
2132     }
2133
2134     fn suggest_accessing_field_where_appropriate(
2135         &self,
2136         cause: &ObligationCause<'tcx>,
2137         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
2138         diag: &mut Diagnostic,
2139     ) {
2140         debug!(
2141             "suggest_accessing_field_where_appropriate(cause={:?}, exp_found={:?})",
2142             cause, exp_found
2143         );
2144         if let ty::Adt(expected_def, expected_substs) = exp_found.expected.kind() {
2145             if expected_def.is_enum() {
2146                 return;
2147             }
2148
2149             if let Some((name, ty)) = expected_def
2150                 .non_enum_variant()
2151                 .fields
2152                 .iter()
2153                 .filter(|field| field.vis.is_accessible_from(field.did, self.tcx))
2154                 .map(|field| (field.name, field.ty(self.tcx, expected_substs)))
2155                 .find(|(_, ty)| self.same_type_modulo_infer(*ty, exp_found.found))
2156             {
2157                 if let ObligationCauseCode::Pattern { span: Some(span), .. } = *cause.code() {
2158                     if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2159                         let suggestion = if expected_def.is_struct() {
2160                             format!("{}.{}", snippet, name)
2161                         } else if expected_def.is_union() {
2162                             format!("unsafe {{ {}.{} }}", snippet, name)
2163                         } else {
2164                             return;
2165                         };
2166                         diag.span_suggestion(
2167                             span,
2168                             &format!(
2169                                 "you might have meant to use field `{}` whose type is `{}`",
2170                                 name, ty
2171                             ),
2172                             suggestion,
2173                             Applicability::MaybeIncorrect,
2174                         );
2175                     }
2176                 }
2177             }
2178         }
2179     }
2180
2181     /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
2182     /// suggests it.
2183     fn suggest_as_ref_where_appropriate(
2184         &self,
2185         span: Span,
2186         exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
2187         diag: &mut Diagnostic,
2188     ) {
2189         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2190             && let Some(msg) = self.should_suggest_as_ref(exp_found.expected, exp_found.found)
2191         {
2192             diag.span_suggestion(
2193                 span,
2194                 msg,
2195                 // HACK: fix issue# 100605, suggesting convert from &Option<T> to Option<&T>, remove the extra `&`
2196                 format!("{}.as_ref()", snippet.trim_start_matches('&')),
2197                 Applicability::MachineApplicable,
2198             );
2199         }
2200     }
2201
2202     pub fn should_suggest_as_ref(&self, expected: Ty<'tcx>, found: Ty<'tcx>) -> Option<&str> {
2203         if let (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) =
2204             (expected.kind(), found.kind())
2205         {
2206             if let ty::Adt(found_def, found_substs) = *found_ty.kind() {
2207                 if exp_def == &found_def {
2208                     let have_as_ref = &[
2209                         (
2210                             sym::Option,
2211                             "you can convert from `&Option<T>` to `Option<&T>` using \
2212                         `.as_ref()`",
2213                         ),
2214                         (
2215                             sym::Result,
2216                             "you can convert from `&Result<T, E>` to \
2217                         `Result<&T, &E>` using `.as_ref()`",
2218                         ),
2219                     ];
2220                     if let Some(msg) = have_as_ref.iter().find_map(|(name, msg)| {
2221                         self.tcx.is_diagnostic_item(*name, exp_def.did()).then_some(msg)
2222                     }) {
2223                         let mut show_suggestion = true;
2224                         for (exp_ty, found_ty) in
2225                             iter::zip(exp_substs.types(), found_substs.types())
2226                         {
2227                             match *exp_ty.kind() {
2228                                 ty::Ref(_, exp_ty, _) => {
2229                                     match (exp_ty.kind(), found_ty.kind()) {
2230                                         (_, ty::Param(_))
2231                                         | (_, ty::Infer(_))
2232                                         | (ty::Param(_), _)
2233                                         | (ty::Infer(_), _) => {}
2234                                         _ if self.same_type_modulo_infer(exp_ty, found_ty) => {}
2235                                         _ => show_suggestion = false,
2236                                     };
2237                                 }
2238                                 ty::Param(_) | ty::Infer(_) => {}
2239                                 _ => show_suggestion = false,
2240                             }
2241                         }
2242                         if show_suggestion {
2243                             return Some(*msg);
2244                         }
2245                     }
2246                 }
2247             }
2248         }
2249         None
2250     }
2251
2252     pub fn report_and_explain_type_error(
2253         &self,
2254         trace: TypeTrace<'tcx>,
2255         terr: TypeError<'tcx>,
2256     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2257         use crate::traits::ObligationCauseCode::MatchExpressionArm;
2258
2259         debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
2260
2261         let span = trace.cause.span();
2262         let failure_code = trace.cause.as_failure_code(terr);
2263         let mut diag = match failure_code {
2264             FailureCode::Error0038(did) => {
2265                 let violations = self.tcx.object_safety_violations(did);
2266                 report_object_safety_error(self.tcx, span, did, violations)
2267             }
2268             FailureCode::Error0317(failure_str) => {
2269                 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
2270             }
2271             FailureCode::Error0580(failure_str) => {
2272                 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
2273             }
2274             FailureCode::Error0308(failure_str) => {
2275                 fn escape_literal(s: &str) -> String {
2276                     let mut escaped = String::with_capacity(s.len());
2277                     let mut chrs = s.chars().peekable();
2278                     while let Some(first) = chrs.next() {
2279                         match (first, chrs.peek()) {
2280                             ('\\', Some(&delim @ '"') | Some(&delim @ '\'')) => {
2281                                 escaped.push('\\');
2282                                 escaped.push(delim);
2283                                 chrs.next();
2284                             }
2285                             ('"' | '\'', _) => {
2286                                 escaped.push('\\');
2287                                 escaped.push(first)
2288                             }
2289                             (c, _) => escaped.push(c),
2290                         };
2291                     }
2292                     escaped
2293                 }
2294                 let mut err = struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str);
2295                 if let Some((expected, found)) = trace.values.ty() {
2296                     match (expected.kind(), found.kind()) {
2297                         (ty::Tuple(_), ty::Tuple(_)) => {}
2298                         // If a tuple of length one was expected and the found expression has
2299                         // parentheses around it, perhaps the user meant to write `(expr,)` to
2300                         // build a tuple (issue #86100)
2301                         (ty::Tuple(fields), _) => {
2302                             self.emit_tuple_wrap_err(&mut err, span, found, fields)
2303                         }
2304                         // If a character was expected and the found expression is a string literal
2305                         // containing a single character, perhaps the user meant to write `'c'` to
2306                         // specify a character literal (issue #92479)
2307                         (ty::Char, ty::Ref(_, r, _)) if r.is_str() => {
2308                             if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
2309                                 && let Some(code) = code.strip_prefix('"').and_then(|s| s.strip_suffix('"'))
2310                                 && code.chars().count() == 1
2311                             {
2312                                 err.span_suggestion(
2313                                     span,
2314                                     "if you meant to write a `char` literal, use single quotes",
2315                                     format!("'{}'", escape_literal(code)),
2316                                     Applicability::MachineApplicable,
2317                                 );
2318                             }
2319                         }
2320                         // If a string was expected and the found expression is a character literal,
2321                         // perhaps the user meant to write `"s"` to specify a string literal.
2322                         (ty::Ref(_, r, _), ty::Char) if r.is_str() => {
2323                             if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) {
2324                                 if let Some(code) =
2325                                     code.strip_prefix('\'').and_then(|s| s.strip_suffix('\''))
2326                                 {
2327                                     err.span_suggestion(
2328                                         span,
2329                                         "if you meant to write a `str` literal, use double quotes",
2330                                         format!("\"{}\"", escape_literal(code)),
2331                                         Applicability::MachineApplicable,
2332                                     );
2333                                 }
2334                             }
2335                         }
2336                         _ => {}
2337                     }
2338                 }
2339                 let code = trace.cause.code();
2340                 if let &MatchExpressionArm(box MatchExpressionArmCause { source, .. }) = code
2341                     && let hir::MatchSource::TryDesugar = source
2342                     && let Some((expected_ty, found_ty)) = self.values_str(trace.values)
2343                 {
2344                     err.note(&format!(
2345                         "`?` operator cannot convert from `{}` to `{}`",
2346                         found_ty.content(),
2347                         expected_ty.content(),
2348                     ));
2349                 }
2350                 err
2351             }
2352             FailureCode::Error0644(failure_str) => {
2353                 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
2354             }
2355         };
2356         self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr, false, false);
2357         diag
2358     }
2359
2360     fn emit_tuple_wrap_err(
2361         &self,
2362         err: &mut Diagnostic,
2363         span: Span,
2364         found: Ty<'tcx>,
2365         expected_fields: &List<Ty<'tcx>>,
2366     ) {
2367         let [expected_tup_elem] = expected_fields[..] else { return };
2368
2369         if !self.same_type_modulo_infer(expected_tup_elem, found) {
2370             return;
2371         }
2372
2373         let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
2374             else { return };
2375
2376         let msg = "use a trailing comma to create a tuple with one element";
2377         if code.starts_with('(') && code.ends_with(')') {
2378             let before_close = span.hi() - BytePos::from_u32(1);
2379             err.span_suggestion(
2380                 span.with_hi(before_close).shrink_to_hi(),
2381                 msg,
2382                 ",",
2383                 Applicability::MachineApplicable,
2384             );
2385         } else {
2386             err.multipart_suggestion(
2387                 msg,
2388                 vec![(span.shrink_to_lo(), "(".into()), (span.shrink_to_hi(), ",)".into())],
2389                 Applicability::MachineApplicable,
2390             );
2391         }
2392     }
2393
2394     fn values_str(
2395         &self,
2396         values: ValuePairs<'tcx>,
2397     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2398         match values {
2399             infer::Regions(exp_found) => self.expected_found_str(exp_found),
2400             infer::Terms(exp_found) => self.expected_found_str_term(exp_found),
2401             infer::TraitRefs(exp_found) => {
2402                 let pretty_exp_found = ty::error::ExpectedFound {
2403                     expected: exp_found.expected.print_only_trait_path(),
2404                     found: exp_found.found.print_only_trait_path(),
2405                 };
2406                 match self.expected_found_str(pretty_exp_found) {
2407                     Some((expected, found)) if expected == found => {
2408                         self.expected_found_str(exp_found)
2409                     }
2410                     ret => ret,
2411                 }
2412             }
2413             infer::PolyTraitRefs(exp_found) => {
2414                 let pretty_exp_found = ty::error::ExpectedFound {
2415                     expected: exp_found.expected.print_only_trait_path(),
2416                     found: exp_found.found.print_only_trait_path(),
2417                 };
2418                 match self.expected_found_str(pretty_exp_found) {
2419                     Some((expected, found)) if expected == found => {
2420                         self.expected_found_str(exp_found)
2421                     }
2422                     ret => ret,
2423                 }
2424             }
2425         }
2426     }
2427
2428     fn expected_found_str_term(
2429         &self,
2430         exp_found: ty::error::ExpectedFound<ty::Term<'tcx>>,
2431     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2432         let exp_found = self.resolve_vars_if_possible(exp_found);
2433         if exp_found.references_error() {
2434             return None;
2435         }
2436
2437         Some(match (exp_found.expected.unpack(), exp_found.found.unpack()) {
2438             (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => self.cmp(expected, found),
2439             _ => (
2440                 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2441                 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2442             ),
2443         })
2444     }
2445
2446     /// Returns a string of the form "expected `{}`, found `{}`".
2447     fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
2448         &self,
2449         exp_found: ty::error::ExpectedFound<T>,
2450     ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2451         let exp_found = self.resolve_vars_if_possible(exp_found);
2452         if exp_found.references_error() {
2453             return None;
2454         }
2455
2456         Some((
2457             DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2458             DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2459         ))
2460     }
2461
2462     pub fn report_generic_bound_failure(
2463         &self,
2464         generic_param_scope: LocalDefId,
2465         span: Span,
2466         origin: Option<SubregionOrigin<'tcx>>,
2467         bound_kind: GenericKind<'tcx>,
2468         sub: Region<'tcx>,
2469     ) {
2470         self.construct_generic_bound_failure(generic_param_scope, span, origin, bound_kind, sub)
2471             .emit();
2472     }
2473
2474     pub fn construct_generic_bound_failure(
2475         &self,
2476         generic_param_scope: LocalDefId,
2477         span: Span,
2478         origin: Option<SubregionOrigin<'tcx>>,
2479         bound_kind: GenericKind<'tcx>,
2480         sub: Region<'tcx>,
2481     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2482         // Attempt to obtain the span of the parameter so we can
2483         // suggest adding an explicit lifetime bound to it.
2484         let generics = self.tcx.generics_of(generic_param_scope);
2485         // type_param_span is (span, has_bounds)
2486         let type_param_span = match bound_kind {
2487             GenericKind::Param(ref param) => {
2488                 // Account for the case where `param` corresponds to `Self`,
2489                 // which doesn't have the expected type argument.
2490                 if !(generics.has_self && param.index == 0) {
2491                     let type_param = generics.type_param(param, self.tcx);
2492                     type_param.def_id.as_local().map(|def_id| {
2493                         // Get the `hir::Param` to verify whether it already has any bounds.
2494                         // We do this to avoid suggesting code that ends up as `T: 'a'b`,
2495                         // instead we suggest `T: 'a + 'b` in that case.
2496                         let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
2497                         let ast_generics = self.tcx.hir().get_generics(hir_id.owner.def_id);
2498                         let bounds =
2499                             ast_generics.and_then(|g| g.bounds_span_for_suggestions(def_id));
2500                         // `sp` only covers `T`, change it so that it covers
2501                         // `T:` when appropriate
2502                         if let Some(span) = bounds {
2503                             (span, true)
2504                         } else {
2505                             let sp = self.tcx.def_span(def_id);
2506                             (sp.shrink_to_hi(), false)
2507                         }
2508                     })
2509                 } else {
2510                     None
2511                 }
2512             }
2513             _ => None,
2514         };
2515
2516         let new_lt = {
2517             let mut possible = (b'a'..=b'z').map(|c| format!("'{}", c as char));
2518             let lts_names =
2519                 iter::successors(Some(generics), |g| g.parent.map(|p| self.tcx.generics_of(p)))
2520                     .flat_map(|g| &g.params)
2521                     .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2522                     .map(|p| p.name.as_str())
2523                     .collect::<Vec<_>>();
2524             possible
2525                 .find(|candidate| !lts_names.contains(&&candidate[..]))
2526                 .unwrap_or("'lt".to_string())
2527         };
2528
2529         let add_lt_sugg = generics
2530             .params
2531             .first()
2532             .and_then(|param| param.def_id.as_local())
2533             .map(|def_id| (self.tcx.def_span(def_id).shrink_to_lo(), format!("{}, ", new_lt)));
2534
2535         let labeled_user_string = match bound_kind {
2536             GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
2537             GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
2538             GenericKind::Opaque(def_id, substs) => {
2539                 format!("the opaque type `{}`", self.tcx.def_path_str_with_substs(def_id, substs))
2540             }
2541         };
2542
2543         if let Some(SubregionOrigin::CompareImplItemObligation {
2544             span,
2545             impl_item_def_id,
2546             trait_item_def_id,
2547         }) = origin
2548         {
2549             return self.report_extra_impl_obligation(
2550                 span,
2551                 impl_item_def_id,
2552                 trait_item_def_id,
2553                 &format!("`{}: {}`", bound_kind, sub),
2554             );
2555         }
2556
2557         fn binding_suggestion<'tcx, S: fmt::Display>(
2558             err: &mut Diagnostic,
2559             type_param_span: Option<(Span, bool)>,
2560             bound_kind: GenericKind<'tcx>,
2561             sub: S,
2562             add_lt_sugg: Option<(Span, String)>,
2563         ) {
2564             let msg = "consider adding an explicit lifetime bound";
2565             if let Some((sp, has_lifetimes)) = type_param_span {
2566                 let suggestion =
2567                     if has_lifetimes { format!(" + {}", sub) } else { format!(": {}", sub) };
2568                 let mut suggestions = vec![(sp, suggestion)];
2569                 if let Some(add_lt_sugg) = add_lt_sugg {
2570                     suggestions.push(add_lt_sugg);
2571                 }
2572                 err.multipart_suggestion_verbose(
2573                     format!("{msg}..."),
2574                     suggestions,
2575                     Applicability::MaybeIncorrect, // Issue #41966
2576                 );
2577             } else {
2578                 let consider = format!("{} `{}: {}`...", msg, bound_kind, sub);
2579                 err.help(&consider);
2580             }
2581         }
2582
2583         let new_binding_suggestion =
2584             |err: &mut Diagnostic, type_param_span: Option<(Span, bool)>| {
2585                 let msg = "consider introducing an explicit lifetime bound";
2586                 if let Some((sp, has_lifetimes)) = type_param_span {
2587                     let suggestion = if has_lifetimes {
2588                         format!(" + {}", new_lt)
2589                     } else {
2590                         format!(": {}", new_lt)
2591                     };
2592                     let mut sugg =
2593                         vec![(sp, suggestion), (span.shrink_to_hi(), format!(" + {}", new_lt))];
2594                     if let Some(lt) = add_lt_sugg.clone() {
2595                         sugg.push(lt);
2596                         sugg.rotate_right(1);
2597                     }
2598                     // `MaybeIncorrect` due to issue #41966.
2599                     err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2600                 }
2601             };
2602
2603         #[derive(Debug)]
2604         enum SubOrigin<'hir> {
2605             GAT(&'hir hir::Generics<'hir>),
2606             Impl,
2607             Trait,
2608             Fn,
2609             Unknown,
2610         }
2611         let sub_origin = 'origin: {
2612             match *sub {
2613                 ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, .. }) => {
2614                     let node = self.tcx.hir().get_if_local(def_id).unwrap();
2615                     match node {
2616                         Node::GenericParam(param) => {
2617                             for h in self.tcx.hir().parent_iter(param.hir_id) {
2618                                 break 'origin match h.1 {
2619                                     Node::ImplItem(hir::ImplItem {
2620                                         kind: hir::ImplItemKind::Type(..),
2621                                         generics,
2622                                         ..
2623                                     })
2624                                     | Node::TraitItem(hir::TraitItem {
2625                                         kind: hir::TraitItemKind::Type(..),
2626                                         generics,
2627                                         ..
2628                                     }) => SubOrigin::GAT(generics),
2629                                     Node::ImplItem(hir::ImplItem {
2630                                         kind: hir::ImplItemKind::Fn(..),
2631                                         ..
2632                                     })
2633                                     | Node::TraitItem(hir::TraitItem {
2634                                         kind: hir::TraitItemKind::Fn(..),
2635                                         ..
2636                                     })
2637                                     | Node::Item(hir::Item {
2638                                         kind: hir::ItemKind::Fn(..), ..
2639                                     }) => SubOrigin::Fn,
2640                                     Node::Item(hir::Item {
2641                                         kind: hir::ItemKind::Trait(..),
2642                                         ..
2643                                     }) => SubOrigin::Trait,
2644                                     Node::Item(hir::Item {
2645                                         kind: hir::ItemKind::Impl(..), ..
2646                                     }) => SubOrigin::Impl,
2647                                     _ => continue,
2648                                 };
2649                             }
2650                         }
2651                         _ => {}
2652                     }
2653                 }
2654                 _ => {}
2655             }
2656             SubOrigin::Unknown
2657         };
2658         debug!(?sub_origin);
2659
2660         let mut err = match (*sub, sub_origin) {
2661             // In the case of GATs, we have to be careful. If we a type parameter `T` on an impl,
2662             // but a lifetime `'a` on an associated type, then we might need to suggest adding
2663             // `where T: 'a`. Importantly, this is on the GAT span, not on the `T` declaration.
2664             (ty::ReEarlyBound(ty::EarlyBoundRegion { name: _, .. }), SubOrigin::GAT(generics)) => {
2665                 // Does the required lifetime have a nice name we can print?
2666                 let mut err = struct_span_err!(
2667                     self.tcx.sess,
2668                     span,
2669                     E0309,
2670                     "{} may not live long enough",
2671                     labeled_user_string
2672                 );
2673                 let pred = format!("{}: {}", bound_kind, sub);
2674                 let suggestion = format!("{} {}", generics.add_where_or_trailing_comma(), pred,);
2675                 err.span_suggestion(
2676                     generics.tail_span_for_predicate_suggestion(),
2677                     "consider adding a where clause",
2678                     suggestion,
2679                     Applicability::MaybeIncorrect,
2680                 );
2681                 err
2682             }
2683             (
2684                 ty::ReEarlyBound(ty::EarlyBoundRegion { name, .. })
2685                 | ty::ReFree(ty::FreeRegion { bound_region: ty::BrNamed(_, name), .. }),
2686                 _,
2687             ) if name != kw::UnderscoreLifetime => {
2688                 // Does the required lifetime have a nice name we can print?
2689                 let mut err = struct_span_err!(
2690                     self.tcx.sess,
2691                     span,
2692                     E0309,
2693                     "{} may not live long enough",
2694                     labeled_user_string
2695                 );
2696                 // Explicitly use the name instead of `sub`'s `Display` impl. The `Display` impl
2697                 // for the bound is not suitable for suggestions when `-Zverbose` is set because it
2698                 // uses `Debug` output, so we handle it specially here so that suggestions are
2699                 // always correct.
2700                 binding_suggestion(&mut err, type_param_span, bound_kind, name, None);
2701                 err
2702             }
2703
2704             (ty::ReStatic, _) => {
2705                 // Does the required lifetime have a nice name we can print?
2706                 let mut err = struct_span_err!(
2707                     self.tcx.sess,
2708                     span,
2709                     E0310,
2710                     "{} may not live long enough",
2711                     labeled_user_string
2712                 );
2713                 binding_suggestion(&mut err, type_param_span, bound_kind, "'static", None);
2714                 err
2715             }
2716
2717             _ => {
2718                 // If not, be less specific.
2719                 let mut err = struct_span_err!(
2720                     self.tcx.sess,
2721                     span,
2722                     E0311,
2723                     "{} may not live long enough",
2724                     labeled_user_string
2725                 );
2726                 note_and_explain_region(
2727                     self.tcx,
2728                     &mut err,
2729                     &format!("{} must be valid for ", labeled_user_string),
2730                     sub,
2731                     "...",
2732                     None,
2733                 );
2734                 if let Some(infer::RelateParamBound(_, t, _)) = origin {
2735                     let return_impl_trait =
2736                         self.tcx.return_type_impl_trait(generic_param_scope).is_some();
2737                     let t = self.resolve_vars_if_possible(t);
2738                     match t.kind() {
2739                         // We've got:
2740                         // fn get_later<G, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
2741                         // suggest:
2742                         // fn get_later<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ + 'a
2743                         ty::Closure(_, _substs) | ty::Opaque(_, _substs) if return_impl_trait => {
2744                             new_binding_suggestion(&mut err, type_param_span);
2745                         }
2746                         _ => {
2747                             binding_suggestion(
2748                                 &mut err,
2749                                 type_param_span,
2750                                 bound_kind,
2751                                 new_lt,
2752                                 add_lt_sugg,
2753                             );
2754                         }
2755                     }
2756                 }
2757                 err
2758             }
2759         };
2760
2761         if let Some(origin) = origin {
2762             self.note_region_origin(&mut err, &origin);
2763         }
2764         err
2765     }
2766
2767     fn report_sub_sup_conflict(
2768         &self,
2769         var_origin: RegionVariableOrigin,
2770         sub_origin: SubregionOrigin<'tcx>,
2771         sub_region: Region<'tcx>,
2772         sup_origin: SubregionOrigin<'tcx>,
2773         sup_region: Region<'tcx>,
2774     ) {
2775         let mut err = self.report_inference_failure(var_origin);
2776
2777         note_and_explain_region(
2778             self.tcx,
2779             &mut err,
2780             "first, the lifetime cannot outlive ",
2781             sup_region,
2782             "...",
2783             None,
2784         );
2785
2786         debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
2787         debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
2788         debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
2789         debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
2790         debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
2791
2792         if let (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) =
2793             (&sup_origin, &sub_origin)
2794         {
2795             debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
2796             debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
2797             debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
2798             debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
2799
2800             if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) =
2801                 (self.values_str(sup_trace.values), self.values_str(sub_trace.values))
2802             {
2803                 if sub_expected == sup_expected && sub_found == sup_found {
2804                     note_and_explain_region(
2805                         self.tcx,
2806                         &mut err,
2807                         "...but the lifetime must also be valid for ",
2808                         sub_region,
2809                         "...",
2810                         None,
2811                     );
2812                     err.span_note(
2813                         sup_trace.cause.span,
2814                         &format!("...so that the {}", sup_trace.cause.as_requirement_str()),
2815                     );
2816
2817                     err.note_expected_found(&"", sup_expected, &"", sup_found);
2818                     err.emit();
2819                     return;
2820                 }
2821             }
2822         }
2823
2824         self.note_region_origin(&mut err, &sup_origin);
2825
2826         note_and_explain_region(
2827             self.tcx,
2828             &mut err,
2829             "but, the lifetime must be valid for ",
2830             sub_region,
2831             "...",
2832             None,
2833         );
2834
2835         self.note_region_origin(&mut err, &sub_origin);
2836         err.emit();
2837     }
2838
2839     /// Determine whether an error associated with the given span and definition
2840     /// should be treated as being caused by the implicit `From` conversion
2841     /// within `?` desugaring.
2842     pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool {
2843         span.is_desugaring(DesugaringKind::QuestionMark)
2844             && self.tcx.is_diagnostic_item(sym::From, trait_def_id)
2845     }
2846
2847     /// Structurally compares two types, modulo any inference variables.
2848     ///
2849     /// Returns `true` if two types are equal, or if one type is an inference variable compatible
2850     /// with the other type. A TyVar inference type is compatible with any type, and an IntVar or
2851     /// FloatVar inference type are compatible with themselves or their concrete types (Int and
2852     /// Float types, respectively). When comparing two ADTs, these rules apply recursively.
2853     pub fn same_type_modulo_infer(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
2854         let (a, b) = self.resolve_vars_if_possible((a, b));
2855         SameTypeModuloInfer(self).relate(a, b).is_ok()
2856     }
2857 }
2858
2859 struct SameTypeModuloInfer<'a, 'tcx>(&'a InferCtxt<'tcx>);
2860
2861 impl<'tcx> TypeRelation<'tcx> for SameTypeModuloInfer<'_, 'tcx> {
2862     fn tcx(&self) -> TyCtxt<'tcx> {
2863         self.0.tcx
2864     }
2865
2866     fn param_env(&self) -> ty::ParamEnv<'tcx> {
2867         // Unused, only for consts which we treat as always equal
2868         ty::ParamEnv::empty()
2869     }
2870
2871     fn tag(&self) -> &'static str {
2872         "SameTypeModuloInfer"
2873     }
2874
2875     fn a_is_expected(&self) -> bool {
2876         true
2877     }
2878
2879     fn relate_with_variance<T: relate::Relate<'tcx>>(
2880         &mut self,
2881         _variance: ty::Variance,
2882         _info: ty::VarianceDiagInfo<'tcx>,
2883         a: T,
2884         b: T,
2885     ) -> relate::RelateResult<'tcx, T> {
2886         self.relate(a, b)
2887     }
2888
2889     fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
2890         match (a.kind(), b.kind()) {
2891             (ty::Int(_) | ty::Uint(_), ty::Infer(ty::InferTy::IntVar(_)))
2892             | (
2893                 ty::Infer(ty::InferTy::IntVar(_)),
2894                 ty::Int(_) | ty::Uint(_) | ty::Infer(ty::InferTy::IntVar(_)),
2895             )
2896             | (ty::Float(_), ty::Infer(ty::InferTy::FloatVar(_)))
2897             | (
2898                 ty::Infer(ty::InferTy::FloatVar(_)),
2899                 ty::Float(_) | ty::Infer(ty::InferTy::FloatVar(_)),
2900             )
2901             | (ty::Infer(ty::InferTy::TyVar(_)), _)
2902             | (_, ty::Infer(ty::InferTy::TyVar(_))) => Ok(a),
2903             (ty::Infer(_), _) | (_, ty::Infer(_)) => Err(TypeError::Mismatch),
2904             _ => relate::super_relate_tys(self, a, b),
2905         }
2906     }
2907
2908     fn regions(
2909         &mut self,
2910         a: ty::Region<'tcx>,
2911         b: ty::Region<'tcx>,
2912     ) -> RelateResult<'tcx, ty::Region<'tcx>> {
2913         if (a.is_var() && b.is_free_or_static())
2914             || (b.is_var() && a.is_free_or_static())
2915             || (a.is_var() && b.is_var())
2916             || a == b
2917         {
2918             Ok(a)
2919         } else {
2920             Err(TypeError::Mismatch)
2921         }
2922     }
2923
2924     fn binders<T>(
2925         &mut self,
2926         a: ty::Binder<'tcx, T>,
2927         b: ty::Binder<'tcx, T>,
2928     ) -> relate::RelateResult<'tcx, ty::Binder<'tcx, T>>
2929     where
2930         T: relate::Relate<'tcx>,
2931     {
2932         Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
2933     }
2934
2935     fn consts(
2936         &mut self,
2937         a: ty::Const<'tcx>,
2938         _b: ty::Const<'tcx>,
2939     ) -> relate::RelateResult<'tcx, ty::Const<'tcx>> {
2940         // FIXME(compiler-errors): This could at least do some first-order
2941         // relation
2942         Ok(a)
2943     }
2944 }
2945
2946 impl<'tcx> InferCtxt<'tcx> {
2947     fn report_inference_failure(
2948         &self,
2949         var_origin: RegionVariableOrigin,
2950     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2951         let br_string = |br: ty::BoundRegionKind| {
2952             let mut s = match br {
2953                 ty::BrNamed(_, name) => name.to_string(),
2954                 _ => String::new(),
2955             };
2956             if !s.is_empty() {
2957                 s.push(' ');
2958             }
2959             s
2960         };
2961         let var_description = match var_origin {
2962             infer::MiscVariable(_) => String::new(),
2963             infer::PatternRegion(_) => " for pattern".to_string(),
2964             infer::AddrOfRegion(_) => " for borrow expression".to_string(),
2965             infer::Autoref(_) => " for autoref".to_string(),
2966             infer::Coercion(_) => " for automatic coercion".to_string(),
2967             infer::LateBoundRegion(_, br, infer::FnCall) => {
2968                 format!(" for lifetime parameter {}in function call", br_string(br))
2969             }
2970             infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
2971                 format!(" for lifetime parameter {}in generic type", br_string(br))
2972             }
2973             infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
2974                 " for lifetime parameter {}in trait containing associated type `{}`",
2975                 br_string(br),
2976                 self.tcx.associated_item(def_id).name
2977             ),
2978             infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
2979             infer::UpvarRegion(ref upvar_id, _) => {
2980                 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
2981                 format!(" for capture of `{}` by closure", var_name)
2982             }
2983             infer::Nll(..) => bug!("NLL variable found in lexical phase"),
2984         };
2985
2986         struct_span_err!(
2987             self.tcx.sess,
2988             var_origin.span(),
2989             E0495,
2990             "cannot infer an appropriate lifetime{} due to conflicting requirements",
2991             var_description
2992         )
2993     }
2994 }
2995
2996 pub enum FailureCode {
2997     Error0038(DefId),
2998     Error0317(&'static str),
2999     Error0580(&'static str),
3000     Error0308(&'static str),
3001     Error0644(&'static str),
3002 }
3003
3004 pub trait ObligationCauseExt<'tcx> {
3005     fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode;
3006     fn as_requirement_str(&self) -> &'static str;
3007 }
3008
3009 impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
3010     fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode {
3011         use self::FailureCode::*;
3012         use crate::traits::ObligationCauseCode::*;
3013         match self.code() {
3014             CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
3015                 Error0308("method not compatible with trait")
3016             }
3017             CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => {
3018                 Error0308("type not compatible with trait")
3019             }
3020             CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => {
3021                 Error0308("const not compatible with trait")
3022             }
3023             MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => {
3024                 Error0308(match source {
3025                     hir::MatchSource::TryDesugar => "`?` operator has incompatible types",
3026                     _ => "`match` arms have incompatible types",
3027                 })
3028             }
3029             IfExpression { .. } => Error0308("`if` and `else` have incompatible types"),
3030             IfExpressionWithNoElse => Error0317("`if` may be missing an `else` clause"),
3031             LetElse => Error0308("`else` clause of `let...else` does not diverge"),
3032             MainFunctionType => Error0580("`main` function has wrong type"),
3033             StartFunctionType => Error0308("`#[start]` function has wrong type"),
3034             IntrinsicType => Error0308("intrinsic has wrong type"),
3035             MethodReceiver => Error0308("mismatched `self` parameter type"),
3036
3037             // In the case where we have no more specific thing to
3038             // say, also take a look at the error code, maybe we can
3039             // tailor to that.
3040             _ => match terr {
3041                 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
3042                     Error0644("closure/generator type that references itself")
3043                 }
3044                 TypeError::IntrinsicCast => {
3045                     Error0308("cannot coerce intrinsics to function pointers")
3046                 }
3047                 TypeError::ObjectUnsafeCoercion(did) => Error0038(did),
3048                 _ => Error0308("mismatched types"),
3049             },
3050         }
3051     }
3052
3053     fn as_requirement_str(&self) -> &'static str {
3054         use crate::traits::ObligationCauseCode::*;
3055         match self.code() {
3056             CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
3057                 "method type is compatible with trait"
3058             }
3059             CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => {
3060                 "associated type is compatible with trait"
3061             }
3062             CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => {
3063                 "const is compatible with trait"
3064             }
3065             ExprAssignable => "expression is assignable",
3066             IfExpression { .. } => "`if` and `else` have incompatible types",
3067             IfExpressionWithNoElse => "`if` missing an `else` returns `()`",
3068             MainFunctionType => "`main` function has the correct type",
3069             StartFunctionType => "`#[start]` function has the correct type",
3070             IntrinsicType => "intrinsic has the correct type",
3071             MethodReceiver => "method receiver has the correct type",
3072             _ => "types are compatible",
3073         }
3074     }
3075 }
3076
3077 /// Newtype to allow implementing IntoDiagnosticArg
3078 pub struct ObligationCauseAsDiagArg<'tcx>(pub ObligationCause<'tcx>);
3079
3080 impl IntoDiagnosticArg for ObligationCauseAsDiagArg<'_> {
3081     fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
3082         use crate::traits::ObligationCauseCode::*;
3083         let kind = match self.0.code() {
3084             CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => "method_compat",
3085             CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => "type_compat",
3086             CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => "const_compat",
3087             ExprAssignable => "expr_assignable",
3088             IfExpression { .. } => "if_else_different",
3089             IfExpressionWithNoElse => "no_else",
3090             MainFunctionType => "fn_main_correct_type",
3091             StartFunctionType => "fn_start_correct_type",
3092             IntrinsicType => "intristic_correct_type",
3093             MethodReceiver => "method_correct_type",
3094             _ => "other",
3095         }
3096         .into();
3097         rustc_errors::DiagnosticArgValue::Str(kind)
3098     }
3099 }
3100
3101 /// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
3102 /// extra information about each type, but we only care about the category.
3103 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
3104 pub enum TyCategory {
3105     Closure,
3106     Opaque,
3107     Generator(hir::GeneratorKind),
3108     Foreign,
3109 }
3110
3111 impl TyCategory {
3112     fn descr(&self) -> &'static str {
3113         match self {
3114             Self::Closure => "closure",
3115             Self::Opaque => "opaque type",
3116             Self::Generator(gk) => gk.descr(),
3117             Self::Foreign => "foreign type",
3118         }
3119     }
3120
3121     pub fn from_ty(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Self, DefId)> {
3122         match *ty.kind() {
3123             ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
3124             ty::Opaque(def_id, _) => Some((Self::Opaque, def_id)),
3125             ty::Generator(def_id, ..) => {
3126                 Some((Self::Generator(tcx.generator_kind(def_id).unwrap()), def_id))
3127             }
3128             ty::Foreign(def_id) => Some((Self::Foreign, def_id)),
3129             _ => None,
3130         }
3131     }
3132 }
3133
3134 impl<'tcx> InferCtxt<'tcx> {
3135     /// Given a [`hir::Block`], get the span of its last expression or
3136     /// statement, peeling off any inner blocks.
3137     pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
3138         let block = block.innermost_block();
3139         if let Some(expr) = &block.expr {
3140             expr.span
3141         } else if let Some(stmt) = block.stmts.last() {
3142             // possibly incorrect trailing `;` in the else arm
3143             stmt.span
3144         } else {
3145             // empty block; point at its entirety
3146             block.span
3147         }
3148     }
3149
3150     /// Given a [`hir::HirId`] for a block, get the span of its last expression
3151     /// or statement, peeling off any inner blocks.
3152     pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
3153         match self.tcx.hir().get(hir_id) {
3154             hir::Node::Block(blk) => self.find_block_span(blk),
3155             // The parser was in a weird state if either of these happen, but
3156             // it's better not to panic.
3157             hir::Node::Expr(e) => e.span,
3158             _ => rustc_span::DUMMY_SP,
3159         }
3160     }
3161 }
3162
3163 impl<'tcx> TypeErrCtxt<'_, 'tcx> {
3164     /// Be helpful when the user wrote `{... expr; }` and taking the `;` off
3165     /// is enough to fix the error.
3166     pub fn could_remove_semicolon(
3167         &self,
3168         blk: &'tcx hir::Block<'tcx>,
3169         expected_ty: Ty<'tcx>,
3170     ) -> Option<(Span, StatementAsExpression)> {
3171         let blk = blk.innermost_block();
3172         // Do not suggest if we have a tail expr.
3173         if blk.expr.is_some() {
3174             return None;
3175         }
3176         let last_stmt = blk.stmts.last()?;
3177         let hir::StmtKind::Semi(ref last_expr) = last_stmt.kind else {
3178             return None;
3179         };
3180         let last_expr_ty = self.typeck_results.as_ref()?.expr_ty_opt(*last_expr)?;
3181         let needs_box = match (last_expr_ty.kind(), expected_ty.kind()) {
3182             _ if last_expr_ty.references_error() => return None,
3183             _ if self.same_type_modulo_infer(last_expr_ty, expected_ty) => {
3184                 StatementAsExpression::CorrectType
3185             }
3186             (ty::Opaque(last_def_id, _), ty::Opaque(exp_def_id, _))
3187                 if last_def_id == exp_def_id =>
3188             {
3189                 StatementAsExpression::CorrectType
3190             }
3191             (ty::Opaque(last_def_id, last_bounds), ty::Opaque(exp_def_id, exp_bounds)) => {
3192                 debug!(
3193                     "both opaque, likely future {:?} {:?} {:?} {:?}",
3194                     last_def_id, last_bounds, exp_def_id, exp_bounds
3195                 );
3196
3197                 let last_local_id = last_def_id.as_local()?;
3198                 let exp_local_id = exp_def_id.as_local()?;
3199
3200                 match (
3201                     &self.tcx.hir().expect_item(last_local_id).kind,
3202                     &self.tcx.hir().expect_item(exp_local_id).kind,
3203                 ) {
3204                     (
3205                         hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: last_bounds, .. }),
3206                         hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: exp_bounds, .. }),
3207                     ) if iter::zip(*last_bounds, *exp_bounds).all(|(left, right)| {
3208                         match (left, right) {
3209                             (
3210                                 hir::GenericBound::Trait(tl, ml),
3211                                 hir::GenericBound::Trait(tr, mr),
3212                             ) if tl.trait_ref.trait_def_id() == tr.trait_ref.trait_def_id()
3213                                 && ml == mr =>
3214                             {
3215                                 true
3216                             }
3217                             (
3218                                 hir::GenericBound::LangItemTrait(langl, _, _, argsl),
3219                                 hir::GenericBound::LangItemTrait(langr, _, _, argsr),
3220                             ) if langl == langr => {
3221                                 // FIXME: consider the bounds!
3222                                 debug!("{:?} {:?}", argsl, argsr);
3223                                 true
3224                             }
3225                             _ => false,
3226                         }
3227                     }) =>
3228                     {
3229                         StatementAsExpression::NeedsBoxing
3230                     }
3231                     _ => StatementAsExpression::CorrectType,
3232                 }
3233             }
3234             _ => return None,
3235         };
3236         let span = if last_stmt.span.from_expansion() {
3237             let mac_call = rustc_span::source_map::original_sp(last_stmt.span, blk.span);
3238             self.tcx.sess.source_map().mac_call_stmt_semi_span(mac_call)?
3239         } else {
3240             last_stmt.span.with_lo(last_stmt.span.hi() - BytePos(1))
3241         };
3242         Some((span, needs_box))
3243     }
3244
3245     /// Suggest returning a local binding with a compatible type if the block
3246     /// has no return expression.
3247     pub fn consider_returning_binding(
3248         &self,
3249         blk: &'tcx hir::Block<'tcx>,
3250         expected_ty: Ty<'tcx>,
3251         err: &mut Diagnostic,
3252     ) -> bool {
3253         let blk = blk.innermost_block();
3254         // Do not suggest if we have a tail expr.
3255         if blk.expr.is_some() {
3256             return false;
3257         }
3258         let mut shadowed = FxHashSet::default();
3259         let mut candidate_idents = vec![];
3260         let mut find_compatible_candidates = |pat: &hir::Pat<'_>| {
3261             if let hir::PatKind::Binding(_, hir_id, ident, _) = &pat.kind
3262                 && let Some(pat_ty) = self
3263                     .typeck_results
3264                     .as_ref()
3265                     .and_then(|typeck_results| typeck_results.node_type_opt(*hir_id))
3266             {
3267                 let pat_ty = self.resolve_vars_if_possible(pat_ty);
3268                 if self.same_type_modulo_infer(pat_ty, expected_ty)
3269                     && !(pat_ty, expected_ty).references_error()
3270                     && shadowed.insert(ident.name)
3271                 {
3272                     candidate_idents.push((*ident, pat_ty));
3273                 }
3274             }
3275             true
3276         };
3277
3278         let hir = self.tcx.hir();
3279         for stmt in blk.stmts.iter().rev() {
3280             let hir::StmtKind::Local(local) = &stmt.kind else { continue; };
3281             local.pat.walk(&mut find_compatible_candidates);
3282         }
3283         match hir.find(hir.get_parent_node(blk.hir_id)) {
3284             Some(hir::Node::Expr(hir::Expr { hir_id, .. })) => {
3285                 match hir.find(hir.get_parent_node(*hir_id)) {
3286                     Some(hir::Node::Arm(hir::Arm { pat, .. })) => {
3287                         pat.walk(&mut find_compatible_candidates);
3288                     }
3289                     Some(
3290                         hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body), .. })
3291                         | hir::Node::ImplItem(hir::ImplItem {
3292                             kind: hir::ImplItemKind::Fn(_, body),
3293                             ..
3294                         })
3295                         | hir::Node::TraitItem(hir::TraitItem {
3296                             kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body)),
3297                             ..
3298                         })
3299                         | hir::Node::Expr(hir::Expr {
3300                             kind: hir::ExprKind::Closure(hir::Closure { body, .. }),
3301                             ..
3302                         }),
3303                     ) => {
3304                         for param in hir.body(*body).params {
3305                             param.pat.walk(&mut find_compatible_candidates);
3306                         }
3307                     }
3308                     Some(hir::Node::Expr(hir::Expr {
3309                         kind:
3310                             hir::ExprKind::If(
3311                                 hir::Expr { kind: hir::ExprKind::Let(let_), .. },
3312                                 then_block,
3313                                 _,
3314                             ),
3315                         ..
3316                     })) if then_block.hir_id == *hir_id => {
3317                         let_.pat.walk(&mut find_compatible_candidates);
3318                     }
3319                     _ => {}
3320                 }
3321             }
3322             _ => {}
3323         }
3324
3325         match &candidate_idents[..] {
3326             [(ident, _ty)] => {
3327                 let sm = self.tcx.sess.source_map();
3328                 if let Some(stmt) = blk.stmts.last() {
3329                     let stmt_span = sm.stmt_span(stmt.span, blk.span);
3330                     let sugg = if sm.is_multiline(blk.span)
3331                         && let Some(spacing) = sm.indentation_before(stmt_span)
3332                     {
3333                         format!("\n{spacing}{ident}")
3334                     } else {
3335                         format!(" {ident}")
3336                     };
3337                     err.span_suggestion_verbose(
3338                         stmt_span.shrink_to_hi(),
3339                         format!("consider returning the local binding `{ident}`"),
3340                         sugg,
3341                         Applicability::MaybeIncorrect,
3342                     );
3343                 } else {
3344                     let sugg = if sm.is_multiline(blk.span)
3345                         && let Some(spacing) = sm.indentation_before(blk.span.shrink_to_lo())
3346                     {
3347                         format!("\n{spacing}    {ident}\n{spacing}")
3348                     } else {
3349                         format!(" {ident} ")
3350                     };
3351                     let left_span = sm.span_through_char(blk.span, '{').shrink_to_hi();
3352                     err.span_suggestion_verbose(
3353                         sm.span_extend_while(left_span, |c| c.is_whitespace()).unwrap_or(left_span),
3354                         format!("consider returning the local binding `{ident}`"),
3355                         sugg,
3356                         Applicability::MaybeIncorrect,
3357                     );
3358                 }
3359                 true
3360             }
3361             values if (1..3).contains(&values.len()) => {
3362                 let spans = values.iter().map(|(ident, _)| ident.span).collect::<Vec<_>>();
3363                 err.span_note(spans, "consider returning one of these bindings");
3364                 true
3365             }
3366             _ => false,
3367         }
3368     }
3369 }