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