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