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