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