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