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