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