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