]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs
Provide associated type information in method chains
[rust.git] / compiler / rustc_trait_selection / src / traits / error_reporting / suggestions.rs
1 // ignore-tidy-filelength
2 use super::{DefIdOrName, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation};
3
4 use crate::autoderef::Autoderef;
5 use crate::infer::InferCtxt;
6 use crate::traits::{NormalizeExt, ObligationCtxt};
7
8 use hir::def::CtorOf;
9 use hir::HirId;
10 use rustc_data_structures::fx::FxHashSet;
11 use rustc_data_structures::stack::ensure_sufficient_stack;
12 use rustc_errors::{
13     error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
14     ErrorGuaranteed, MultiSpan, Style,
15 };
16 use rustc_hir as hir;
17 use rustc_hir::def::DefKind;
18 use rustc_hir::def_id::DefId;
19 use rustc_hir::intravisit::Visitor;
20 use rustc_hir::lang_items::LangItem;
21 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
22 use rustc_infer::infer::error_reporting::TypeErrCtxt;
23 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
24 use rustc_infer::infer::{InferOk, LateBoundRegionConversionTime};
25 use rustc_middle::hir::map;
26 use rustc_middle::ty::error::TypeError::{self, Sorts};
27 use rustc_middle::ty::relate::{self, Relate, RelateResult, TypeRelation};
28 use rustc_middle::ty::{
29     self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
30     GeneratorDiagnosticData, GeneratorInteriorTypeCause, Infer, InferTy, InternalSubsts,
31     IsSuggestable, ToPredicate, Ty, TyCtxt, TypeAndMut, TypeFoldable, TypeFolder,
32     TypeSuperFoldable, TypeVisitable, TypeckResults,
33 };
34 use rustc_span::symbol::{sym, Ident, Symbol};
35 use rustc_span::{BytePos, DesugaringKind, ExpnKind, Span, DUMMY_SP};
36 use rustc_target::spec::abi;
37 use std::ops::Deref;
38
39 use super::InferCtxtPrivExt;
40 use crate::infer::InferCtxtExt as _;
41 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
42 use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};
43
44 #[derive(Debug)]
45 pub enum GeneratorInteriorOrUpvar {
46     // span of interior type
47     Interior(Span, Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>),
48     // span of upvar
49     Upvar(Span),
50 }
51
52 // This type provides a uniform interface to retrieve data on generators, whether it originated from
53 // the local crate being compiled or from a foreign crate.
54 #[derive(Debug)]
55 pub enum GeneratorData<'tcx, 'a> {
56     Local(&'a TypeckResults<'tcx>),
57     Foreign(&'tcx GeneratorDiagnosticData<'tcx>),
58 }
59
60 impl<'tcx, 'a> GeneratorData<'tcx, 'a> {
61     // Try to get information about variables captured by the generator that matches a type we are
62     // looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
63     // meet an obligation
64     fn try_get_upvar_span<F>(
65         &self,
66         infer_context: &InferCtxt<'tcx>,
67         generator_did: DefId,
68         ty_matches: F,
69     ) -> Option<GeneratorInteriorOrUpvar>
70     where
71         F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
72     {
73         match self {
74             GeneratorData::Local(typeck_results) => {
75                 infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| {
76                     upvars.iter().find_map(|(upvar_id, upvar)| {
77                         let upvar_ty = typeck_results.node_type(*upvar_id);
78                         let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
79                         if ty_matches(ty::Binder::dummy(upvar_ty)) {
80                             Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
81                         } else {
82                             None
83                         }
84                     })
85                 })
86             }
87             GeneratorData::Foreign(_) => None,
88         }
89     }
90
91     // Try to get the span of a type being awaited on that matches the type we are looking with the
92     // `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
93     // obligation
94     fn get_from_await_ty<F>(
95         &self,
96         visitor: AwaitsVisitor,
97         hir: map::Map<'tcx>,
98         ty_matches: F,
99     ) -> Option<Span>
100     where
101         F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
102     {
103         match self {
104             GeneratorData::Local(typeck_results) => visitor
105                 .awaits
106                 .into_iter()
107                 .map(|id| hir.expect_expr(id))
108                 .find(|await_expr| {
109                     ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
110                 })
111                 .map(|expr| expr.span),
112             GeneratorData::Foreign(generator_diagnostic_data) => visitor
113                 .awaits
114                 .into_iter()
115                 .map(|id| hir.expect_expr(id))
116                 .find(|await_expr| {
117                     ty_matches(ty::Binder::dummy(
118                         generator_diagnostic_data
119                             .adjustments
120                             .get(&await_expr.hir_id.local_id)
121                             .map_or::<&[ty::adjustment::Adjustment<'tcx>], _>(&[], |a| &a[..])
122                             .last()
123                             .map_or_else::<Ty<'tcx>, _, _>(
124                                 || {
125                                     generator_diagnostic_data
126                                         .nodes_types
127                                         .get(&await_expr.hir_id.local_id)
128                                         .cloned()
129                                         .unwrap_or_else(|| {
130                                             bug!(
131                                                 "node_type: no type for node `{}`",
132                                                 ty::tls::with(|tcx| tcx
133                                                     .hir()
134                                                     .node_to_string(await_expr.hir_id))
135                                             )
136                                         })
137                                 },
138                                 |adj| adj.target,
139                             ),
140                     ))
141                 })
142                 .map(|expr| expr.span),
143         }
144     }
145
146     /// Get the type, expression, span and optional scope span of all types
147     /// that are live across the yield of this generator
148     fn get_generator_interior_types(
149         &self,
150     ) -> ty::Binder<'tcx, &[GeneratorInteriorTypeCause<'tcx>]> {
151         match self {
152             GeneratorData::Local(typeck_result) => {
153                 typeck_result.generator_interior_types.as_deref()
154             }
155             GeneratorData::Foreign(generator_diagnostic_data) => {
156                 generator_diagnostic_data.generator_interior_types.as_deref()
157             }
158         }
159     }
160
161     // Used to get the source of the data, note we don't have as much information for generators
162     // originated from foreign crates
163     fn is_foreign(&self) -> bool {
164         match self {
165             GeneratorData::Local(_) => false,
166             GeneratorData::Foreign(_) => true,
167         }
168     }
169 }
170
171 // This trait is public to expose the diagnostics methods to clippy.
172 pub trait TypeErrCtxtExt<'tcx> {
173     fn suggest_restricting_param_bound(
174         &self,
175         err: &mut Diagnostic,
176         trait_pred: ty::PolyTraitPredicate<'tcx>,
177         associated_item: Option<(&'static str, Ty<'tcx>)>,
178         body_id: hir::HirId,
179     );
180
181     fn suggest_dereferences(
182         &self,
183         obligation: &PredicateObligation<'tcx>,
184         err: &mut Diagnostic,
185         trait_pred: ty::PolyTraitPredicate<'tcx>,
186     ) -> bool;
187
188     fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol>;
189
190     fn suggest_fn_call(
191         &self,
192         obligation: &PredicateObligation<'tcx>,
193         err: &mut Diagnostic,
194         trait_pred: ty::PolyTraitPredicate<'tcx>,
195     ) -> bool;
196
197     fn suggest_add_reference_to_arg(
198         &self,
199         obligation: &PredicateObligation<'tcx>,
200         err: &mut Diagnostic,
201         trait_pred: ty::PolyTraitPredicate<'tcx>,
202         has_custom_message: bool,
203     ) -> bool;
204
205     fn suggest_borrowing_for_object_cast(
206         &self,
207         err: &mut Diagnostic,
208         obligation: &PredicateObligation<'tcx>,
209         self_ty: Ty<'tcx>,
210         object_ty: Ty<'tcx>,
211     );
212
213     fn suggest_remove_reference(
214         &self,
215         obligation: &PredicateObligation<'tcx>,
216         err: &mut Diagnostic,
217         trait_pred: ty::PolyTraitPredicate<'tcx>,
218     ) -> bool;
219
220     fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
221
222     fn suggest_change_mut(
223         &self,
224         obligation: &PredicateObligation<'tcx>,
225         err: &mut Diagnostic,
226         trait_pred: ty::PolyTraitPredicate<'tcx>,
227     );
228
229     fn suggest_semicolon_removal(
230         &self,
231         obligation: &PredicateObligation<'tcx>,
232         err: &mut Diagnostic,
233         span: Span,
234         trait_pred: ty::PolyTraitPredicate<'tcx>,
235     ) -> bool;
236
237     fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
238
239     fn suggest_impl_trait(
240         &self,
241         err: &mut Diagnostic,
242         span: Span,
243         obligation: &PredicateObligation<'tcx>,
244         trait_pred: ty::PolyTraitPredicate<'tcx>,
245     ) -> bool;
246
247     fn point_at_returns_when_relevant(
248         &self,
249         err: &mut Diagnostic,
250         obligation: &PredicateObligation<'tcx>,
251     );
252
253     fn report_closure_arg_mismatch(
254         &self,
255         span: Span,
256         found_span: Option<Span>,
257         found: ty::PolyTraitRef<'tcx>,
258         expected: ty::PolyTraitRef<'tcx>,
259         cause: &ObligationCauseCode<'tcx>,
260     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
261
262     fn note_conflicting_closure_bounds(
263         &self,
264         cause: &ObligationCauseCode<'tcx>,
265         err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
266     );
267
268     fn suggest_fully_qualified_path(
269         &self,
270         err: &mut Diagnostic,
271         item_def_id: DefId,
272         span: Span,
273         trait_ref: DefId,
274     );
275
276     fn maybe_note_obligation_cause_for_async_await(
277         &self,
278         err: &mut Diagnostic,
279         obligation: &PredicateObligation<'tcx>,
280     ) -> bool;
281
282     fn note_obligation_cause_for_async_await(
283         &self,
284         err: &mut Diagnostic,
285         interior_or_upvar_span: GeneratorInteriorOrUpvar,
286         is_async: bool,
287         outer_generator: Option<DefId>,
288         trait_pred: ty::TraitPredicate<'tcx>,
289         target_ty: Ty<'tcx>,
290         typeck_results: Option<&ty::TypeckResults<'tcx>>,
291         obligation: &PredicateObligation<'tcx>,
292         next_code: Option<&ObligationCauseCode<'tcx>>,
293     );
294
295     fn note_obligation_cause_code<T>(
296         &self,
297         err: &mut Diagnostic,
298         predicate: T,
299         param_env: ty::ParamEnv<'tcx>,
300         cause_code: &ObligationCauseCode<'tcx>,
301         obligated_types: &mut Vec<Ty<'tcx>>,
302         seen_requirements: &mut FxHashSet<DefId>,
303     ) where
304         T: ToPredicate<'tcx>;
305
306     /// Suggest to await before try: future? => future.await?
307     fn suggest_await_before_try(
308         &self,
309         err: &mut Diagnostic,
310         obligation: &PredicateObligation<'tcx>,
311         trait_pred: ty::PolyTraitPredicate<'tcx>,
312         span: Span,
313     );
314
315     fn suggest_floating_point_literal(
316         &self,
317         obligation: &PredicateObligation<'tcx>,
318         err: &mut Diagnostic,
319         trait_ref: &ty::PolyTraitRef<'tcx>,
320     );
321
322     fn suggest_derive(
323         &self,
324         obligation: &PredicateObligation<'tcx>,
325         err: &mut Diagnostic,
326         trait_pred: ty::PolyTraitPredicate<'tcx>,
327     );
328
329     fn suggest_dereferencing_index(
330         &self,
331         obligation: &PredicateObligation<'tcx>,
332         err: &mut Diagnostic,
333         trait_pred: ty::PolyTraitPredicate<'tcx>,
334     );
335 }
336
337 fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
338     (
339         generics.tail_span_for_predicate_suggestion(),
340         format!("{} {}", generics.add_where_or_trailing_comma(), pred),
341     )
342 }
343
344 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
345 /// it can also be an `impl Trait` param that needs to be decomposed to a type
346 /// param for cleaner code.
347 fn suggest_restriction<'tcx>(
348     tcx: TyCtxt<'tcx>,
349     hir_id: HirId,
350     hir_generics: &hir::Generics<'tcx>,
351     msg: &str,
352     err: &mut Diagnostic,
353     fn_sig: Option<&hir::FnSig<'_>>,
354     projection: Option<&ty::ProjectionTy<'_>>,
355     trait_pred: ty::PolyTraitPredicate<'tcx>,
356     // When we are dealing with a trait, `super_traits` will be `Some`:
357     // Given `trait T: A + B + C {}`
358     //              -  ^^^^^^^^^ GenericBounds
359     //              |
360     //              &Ident
361     super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
362 ) {
363     if hir_generics.where_clause_span.from_expansion()
364         || hir_generics.where_clause_span.desugaring_kind().is_some()
365     {
366         return;
367     }
368     let Some(item_id) = hir_id.as_owner() else { return; };
369     let generics = tcx.generics_of(item_id);
370     // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
371     if let Some((param, bound_str, fn_sig)) =
372         fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
373             // Shenanigans to get the `Trait` from the `impl Trait`.
374             ty::Param(param) => {
375                 let param_def = generics.type_param(param, tcx);
376                 if param_def.kind.is_synthetic() {
377                     let bound_str =
378                         param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
379                     return Some((param_def, bound_str, sig));
380                 }
381                 None
382             }
383             _ => None,
384         })
385     {
386         let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
387         let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
388             tcx,
389             param,
390             replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
391                 .to_ty(tcx),
392         });
393         if !trait_pred.is_suggestable(tcx, false) {
394             return;
395         }
396         // We know we have an `impl Trait` that doesn't satisfy a required projection.
397
398         // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
399         // types. There should be at least one, but there might be *more* than one. In that
400         // case we could just ignore it and try to identify which one needs the restriction,
401         // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
402         // where `T: Trait`.
403         let mut ty_spans = vec![];
404         for input in fn_sig.decl.inputs {
405             ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
406                 .visit_ty(input);
407         }
408         // The type param `T: Trait` we will suggest to introduce.
409         let type_param = format!("{}: {}", type_param_name, bound_str);
410
411         let mut sugg = vec![
412             if let Some(span) = hir_generics.span_for_param_suggestion() {
413                 (span, format!(", {}", type_param))
414             } else {
415                 (hir_generics.span, format!("<{}>", type_param))
416             },
417             // `fn foo(t: impl Trait)`
418             //                       ^ suggest `where <T as Trait>::A: Bound`
419             predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
420         ];
421         sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
422
423         // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
424         // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
425         // `fn foo(t: impl Trait<A: Bound>)` instead.
426         err.multipart_suggestion(
427             "introduce a type parameter with a trait bound instead of using `impl Trait`",
428             sugg,
429             Applicability::MaybeIncorrect,
430         );
431     } else {
432         if !trait_pred.is_suggestable(tcx, false) {
433             return;
434         }
435         // Trivial case: `T` needs an extra bound: `T: Bound`.
436         let (sp, suggestion) = match (
437             hir_generics
438                 .params
439                 .iter()
440                 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
441             super_traits,
442         ) {
443             (_, None) => predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
444             (None, Some((ident, []))) => (
445                 ident.span.shrink_to_hi(),
446                 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
447             ),
448             (_, Some((_, [.., bounds]))) => (
449                 bounds.span().shrink_to_hi(),
450                 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
451             ),
452             (Some(_), Some((_, []))) => (
453                 hir_generics.span.shrink_to_hi(),
454                 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
455             ),
456         };
457
458         err.span_suggestion_verbose(
459             sp,
460             &format!("consider further restricting {}", msg),
461             suggestion,
462             Applicability::MachineApplicable,
463         );
464     }
465 }
466
467 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
468     fn suggest_restricting_param_bound(
469         &self,
470         mut err: &mut Diagnostic,
471         trait_pred: ty::PolyTraitPredicate<'tcx>,
472         associated_ty: Option<(&'static str, Ty<'tcx>)>,
473         body_id: hir::HirId,
474     ) {
475         let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
476
477         let self_ty = trait_pred.skip_binder().self_ty();
478         let (param_ty, projection) = match self_ty.kind() {
479             ty::Param(_) => (true, None),
480             ty::Projection(projection) => (false, Some(projection)),
481             _ => (false, None),
482         };
483
484         // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
485         //        don't suggest `T: Sized + ?Sized`.
486         let mut hir_id = body_id;
487         while let Some(node) = self.tcx.hir().find(hir_id) {
488             match node {
489                 hir::Node::Item(hir::Item {
490                     ident,
491                     kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
492                     ..
493                 }) if self_ty == self.tcx.types.self_param => {
494                     assert!(param_ty);
495                     // Restricting `Self` for a single method.
496                     suggest_restriction(
497                         self.tcx,
498                         hir_id,
499                         &generics,
500                         "`Self`",
501                         err,
502                         None,
503                         projection,
504                         trait_pred,
505                         Some((ident, bounds)),
506                     );
507                     return;
508                 }
509
510                 hir::Node::TraitItem(hir::TraitItem {
511                     generics,
512                     kind: hir::TraitItemKind::Fn(..),
513                     ..
514                 }) if self_ty == self.tcx.types.self_param => {
515                     assert!(param_ty);
516                     // Restricting `Self` for a single method.
517                     suggest_restriction(
518                         self.tcx, hir_id, &generics, "`Self`", err, None, projection, trait_pred,
519                         None,
520                     );
521                     return;
522                 }
523
524                 hir::Node::TraitItem(hir::TraitItem {
525                     generics,
526                     kind: hir::TraitItemKind::Fn(fn_sig, ..),
527                     ..
528                 })
529                 | hir::Node::ImplItem(hir::ImplItem {
530                     generics,
531                     kind: hir::ImplItemKind::Fn(fn_sig, ..),
532                     ..
533                 })
534                 | hir::Node::Item(hir::Item {
535                     kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
536                 }) if projection.is_some() => {
537                     // Missing restriction on associated type of type parameter (unmet projection).
538                     suggest_restriction(
539                         self.tcx,
540                         hir_id,
541                         &generics,
542                         "the associated type",
543                         err,
544                         Some(fn_sig),
545                         projection,
546                         trait_pred,
547                         None,
548                     );
549                     return;
550                 }
551                 hir::Node::Item(hir::Item {
552                     kind:
553                         hir::ItemKind::Trait(_, _, generics, ..)
554                         | hir::ItemKind::Impl(hir::Impl { generics, .. }),
555                     ..
556                 }) if projection.is_some() => {
557                     // Missing restriction on associated type of type parameter (unmet projection).
558                     suggest_restriction(
559                         self.tcx,
560                         hir_id,
561                         &generics,
562                         "the associated type",
563                         err,
564                         None,
565                         projection,
566                         trait_pred,
567                         None,
568                     );
569                     return;
570                 }
571
572                 hir::Node::Item(hir::Item {
573                     kind:
574                         hir::ItemKind::Struct(_, generics)
575                         | hir::ItemKind::Enum(_, generics)
576                         | hir::ItemKind::Union(_, generics)
577                         | hir::ItemKind::Trait(_, _, generics, ..)
578                         | hir::ItemKind::Impl(hir::Impl { generics, .. })
579                         | hir::ItemKind::Fn(_, generics, _)
580                         | hir::ItemKind::TyAlias(_, generics)
581                         | hir::ItemKind::TraitAlias(generics, _)
582                         | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
583                     ..
584                 })
585                 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
586                 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
587                     if param_ty =>
588                 {
589                     // We skip the 0'th subst (self) because we do not want
590                     // to consider the predicate as not suggestible if the
591                     // self type is an arg position `impl Trait` -- instead,
592                     // we handle that by adding ` + Bound` below.
593                     // FIXME(compiler-errors): It would be nice to do the same
594                     // this that we do in `suggest_restriction` and pull the
595                     // `impl Trait` into a new generic if it shows up somewhere
596                     // else in the predicate.
597                     if !trait_pred.skip_binder().trait_ref.substs[1..]
598                         .iter()
599                         .all(|g| g.is_suggestable(self.tcx, false))
600                     {
601                         return;
602                     }
603                     // Missing generic type parameter bound.
604                     let param_name = self_ty.to_string();
605                     let mut constraint = with_no_trimmed_paths!(
606                         trait_pred.print_modifiers_and_trait_path().to_string()
607                     );
608
609                     if let Some((name, term)) = associated_ty {
610                         // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
611                         // That should be extracted into a helper function.
612                         if constraint.ends_with('>') {
613                             constraint = format!(
614                                 "{}, {} = {}>",
615                                 &constraint[..constraint.len() - 1],
616                                 name,
617                                 term
618                             );
619                         } else {
620                             constraint.push_str(&format!("<{} = {}>", name, term));
621                         }
622                     }
623
624                     if suggest_constraining_type_param(
625                         self.tcx,
626                         generics,
627                         &mut err,
628                         &param_name,
629                         &constraint,
630                         Some(trait_pred.def_id()),
631                     ) {
632                         return;
633                     }
634                 }
635
636                 hir::Node::Item(hir::Item {
637                     kind:
638                         hir::ItemKind::Struct(_, generics)
639                         | hir::ItemKind::Enum(_, generics)
640                         | hir::ItemKind::Union(_, generics)
641                         | hir::ItemKind::Trait(_, _, generics, ..)
642                         | hir::ItemKind::Impl(hir::Impl { generics, .. })
643                         | hir::ItemKind::Fn(_, generics, _)
644                         | hir::ItemKind::TyAlias(_, generics)
645                         | hir::ItemKind::TraitAlias(generics, _)
646                         | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
647                     ..
648                 }) if !param_ty => {
649                     // Missing generic type parameter bound.
650                     if suggest_arbitrary_trait_bound(
651                         self.tcx,
652                         generics,
653                         &mut err,
654                         trait_pred,
655                         associated_ty,
656                     ) {
657                         return;
658                     }
659                 }
660                 hir::Node::Crate(..) => return,
661
662                 _ => {}
663             }
664
665             hir_id = self.tcx.hir().get_parent_item(hir_id).into();
666         }
667     }
668
669     /// When after several dereferencing, the reference satisfies the trait
670     /// binding. This function provides dereference suggestion for this
671     /// specific situation.
672     fn suggest_dereferences(
673         &self,
674         obligation: &PredicateObligation<'tcx>,
675         err: &mut Diagnostic,
676         trait_pred: ty::PolyTraitPredicate<'tcx>,
677     ) -> bool {
678         // It only make sense when suggesting dereferences for arguments
679         let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code()
680             else { return false; };
681         let Some(typeck_results) = &self.typeck_results
682             else { return false; };
683         let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
684             else { return false; };
685         let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
686             else { return false; };
687
688         let span = obligation.cause.span;
689         let mut real_trait_pred = trait_pred;
690         let mut code = obligation.cause.code();
691         while let Some((parent_code, parent_trait_pred)) = code.parent() {
692             code = parent_code;
693             if let Some(parent_trait_pred) = parent_trait_pred {
694                 real_trait_pred = parent_trait_pred;
695             }
696
697             let real_ty = real_trait_pred.self_ty();
698             // We `erase_late_bound_regions` here because `make_subregion` does not handle
699             // `ReLateBound`, and we don't particularly care about the regions.
700             if self
701                 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
702                 .is_err()
703             {
704                 continue;
705             }
706
707             if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
708                 let mut autoderef = Autoderef::new(
709                     self,
710                     obligation.param_env,
711                     obligation.cause.body_id,
712                     span,
713                     base_ty,
714                 );
715                 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
716                     // Re-add the `&`
717                     let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
718
719                     // Remapping bound vars here
720                     let real_trait_pred_and_ty =
721                         real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
722                     let obligation = self.mk_trait_obligation_with_new_self_ty(
723                         obligation.param_env,
724                         real_trait_pred_and_ty,
725                     );
726                     Some(steps).filter(|_| self.predicate_may_hold(&obligation))
727                 }) {
728                     if steps > 0 {
729                         // Don't care about `&mut` because `DerefMut` is used less
730                         // often and user will not expect autoderef happens.
731                         if let Some(hir::Node::Expr(hir::Expr {
732                             kind:
733                                 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
734                             ..
735                         })) = self.tcx.hir().find(*arg_hir_id)
736                         {
737                             let derefs = "*".repeat(steps);
738                             err.span_suggestion_verbose(
739                                 expr.span.shrink_to_lo(),
740                                 "consider dereferencing here",
741                                 derefs,
742                                 Applicability::MachineApplicable,
743                             );
744                             return true;
745                         }
746                     }
747                 } else if real_trait_pred != trait_pred {
748                     // This branch addresses #87437.
749
750                     // Remapping bound vars here
751                     let real_trait_pred_and_base_ty =
752                         real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
753                     let obligation = self.mk_trait_obligation_with_new_self_ty(
754                         obligation.param_env,
755                         real_trait_pred_and_base_ty,
756                     );
757                     if self.predicate_may_hold(&obligation) {
758                         err.span_suggestion_verbose(
759                             span.shrink_to_lo(),
760                             "consider dereferencing here",
761                             "*",
762                             Applicability::MachineApplicable,
763                         );
764                         return true;
765                     }
766                 }
767             }
768         }
769         false
770     }
771
772     /// Given a closure's `DefId`, return the given name of the closure.
773     ///
774     /// This doesn't account for reassignments, but it's only used for suggestions.
775     fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
776         let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
777             // Get the local name of this closure. This can be inaccurate because
778             // of the possibility of reassignment, but this should be good enough.
779             match &kind {
780                 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
781                     Some(ident.name)
782                 }
783                 _ => {
784                     err.note(msg);
785                     None
786                 }
787             }
788         };
789
790         let hir = self.tcx.hir();
791         let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
792         let parent_node = hir.get_parent_node(hir_id);
793         match hir.find(parent_node) {
794             Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
795                 get_name(err, &local.pat.kind)
796             }
797             // Different to previous arm because one is `&hir::Local` and the other
798             // is `P<hir::Local>`.
799             Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
800             _ => None,
801         }
802     }
803
804     /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
805     /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
806     /// it: `bar(foo)` â†’ `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
807     fn suggest_fn_call(
808         &self,
809         obligation: &PredicateObligation<'tcx>,
810         err: &mut Diagnostic,
811         trait_pred: ty::PolyTraitPredicate<'tcx>,
812     ) -> bool {
813         if let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = obligation.predicate.kind().skip_binder()
814             && Some(trait_pred.def_id()) == self.tcx.lang_items().sized_trait()
815         {
816             // Don't suggest calling to turn an unsized type into a sized type
817             return false;
818         }
819
820         // This is duplicated from `extract_callable_info` in typeck, which
821         // relies on autoderef, so we can't use it here.
822         let found = trait_pred.self_ty().skip_binder().peel_refs();
823         let Some((def_id_or_name, output, inputs)) = (match *found.kind()
824         {
825             ty::FnPtr(fn_sig) => {
826                 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs()))
827             }
828             ty::FnDef(def_id, _) => {
829                 let fn_sig = found.fn_sig(self.tcx);
830                 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
831             }
832             ty::Closure(def_id, substs) => {
833                 let fn_sig = substs.as_closure().sig();
834                 Some((
835                     DefIdOrName::DefId(def_id),
836                     fn_sig.output(),
837                     fn_sig.inputs().map_bound(|inputs| &inputs[1..]),
838                 ))
839             }
840             ty::Opaque(def_id, substs) => {
841                 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
842                     if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
843                     && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
844                     // args tuple will always be substs[1]
845                     && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
846                     {
847                         Some((
848                             DefIdOrName::DefId(def_id),
849                             pred.kind().rebind(proj.term.ty().unwrap()),
850                             pred.kind().rebind(args.as_slice()),
851                         ))
852                     } else {
853                         None
854                     }
855                 })
856             }
857             ty::Dynamic(data, _, ty::Dyn) => {
858                 data.iter().find_map(|pred| {
859                     if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
860                     && Some(proj.item_def_id) == self.tcx.lang_items().fn_once_output()
861                     // for existential projection, substs are shifted over by 1
862                     && let ty::Tuple(args) = proj.substs.type_at(0).kind()
863                     {
864                         Some((
865                             DefIdOrName::Name("trait object"),
866                             pred.rebind(proj.term.ty().unwrap()),
867                             pred.rebind(args.as_slice()),
868                         ))
869                     } else {
870                         None
871                     }
872                 })
873             }
874             ty::Param(_) => {
875                 obligation.param_env.caller_bounds().iter().find_map(|pred| {
876                     if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
877                     && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
878                     && proj.projection_ty.self_ty() == found
879                     // args tuple will always be substs[1]
880                     && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
881                     {
882                         Some((
883                             DefIdOrName::Name("type parameter"),
884                             pred.kind().rebind(proj.term.ty().unwrap()),
885                             pred.kind().rebind(args.as_slice()),
886                         ))
887                     } else {
888                         None
889                     }
890                 })
891             }
892             _ => None,
893         }) else { return false; };
894         let output = self.replace_bound_vars_with_fresh_vars(
895             obligation.cause.span,
896             LateBoundRegionConversionTime::FnCall,
897             output,
898         );
899         let inputs = inputs.skip_binder().iter().map(|ty| {
900             self.replace_bound_vars_with_fresh_vars(
901                 obligation.cause.span,
902                 LateBoundRegionConversionTime::FnCall,
903                 inputs.rebind(*ty),
904             )
905         });
906
907         // Remapping bound vars here
908         let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
909
910         let new_obligation =
911             self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
912         if !self.predicate_must_hold_modulo_regions(&new_obligation) {
913             return false;
914         }
915
916         // Get the name of the callable and the arguments to be used in the suggestion.
917         let hir = self.tcx.hir();
918
919         let msg = match def_id_or_name {
920             DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
921                 DefKind::Ctor(CtorOf::Struct, _) => {
922                     "use parentheses to construct this tuple struct".to_string()
923                 }
924                 DefKind::Ctor(CtorOf::Variant, _) => {
925                     "use parentheses to construct this tuple variant".to_string()
926                 }
927                 kind => format!("use parentheses to call this {}", kind.descr(def_id)),
928             },
929             DefIdOrName::Name(name) => format!("use parentheses to call this {name}"),
930         };
931
932         let args = inputs
933             .map(|ty| {
934                 if ty.is_suggestable(self.tcx, false) {
935                     format!("/* {ty} */")
936                 } else {
937                     "/* value */".to_string()
938                 }
939             })
940             .collect::<Vec<_>>()
941             .join(", ");
942
943         if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
944             && obligation.cause.span.can_be_used_for_suggestions()
945         {
946             // When the obligation error has been ensured to have been caused by
947             // an argument, the `obligation.cause.span` points at the expression
948             // of the argument, so we can provide a suggestion. Otherwise, we give
949             // a more general note.
950             err.span_suggestion_verbose(
951                 obligation.cause.span.shrink_to_hi(),
952                 &msg,
953                 format!("({args})"),
954                 Applicability::HasPlaceholders,
955             );
956         } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
957             let name = match hir.get_if_local(def_id) {
958                 Some(hir::Node::Expr(hir::Expr {
959                     kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
960                     ..
961                 })) => {
962                     err.span_label(*fn_decl_span, "consider calling this closure");
963                     let Some(name) = self.get_closure_name(def_id, err, &msg) else {
964                         return false;
965                     };
966                     name.to_string()
967                 }
968                 Some(hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(..), .. })) => {
969                     err.span_label(ident.span, "consider calling this function");
970                     ident.to_string()
971                 }
972                 Some(hir::Node::Ctor(..)) => {
973                     let name = self.tcx.def_path_str(def_id);
974                     err.span_label(
975                         self.tcx.def_span(def_id),
976                         format!("consider calling the constructor for `{}`", name),
977                     );
978                     name
979                 }
980                 _ => return false,
981             };
982             err.help(&format!("{msg}: `{name}({args})`"));
983         }
984         true
985     }
986
987     fn suggest_add_reference_to_arg(
988         &self,
989         obligation: &PredicateObligation<'tcx>,
990         err: &mut Diagnostic,
991         poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
992         has_custom_message: bool,
993     ) -> bool {
994         let span = obligation.cause.span;
995
996         let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
997             obligation.cause.code()
998         {
999             &parent_code
1000         } else if let ObligationCauseCode::ItemObligation(_)
1001         | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1002         {
1003             obligation.cause.code()
1004         } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
1005             span.ctxt().outer_expn_data().kind
1006         {
1007             obligation.cause.code()
1008         } else {
1009             return false;
1010         };
1011
1012         // List of traits for which it would be nonsensical to suggest borrowing.
1013         // For instance, immutable references are always Copy, so suggesting to
1014         // borrow would always succeed, but it's probably not what the user wanted.
1015         let mut never_suggest_borrow: Vec<_> =
1016             [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1017                 .iter()
1018                 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1019                 .collect();
1020
1021         if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1022             never_suggest_borrow.push(def_id);
1023         }
1024
1025         let param_env = obligation.param_env;
1026
1027         // Try to apply the original trait binding obligation by borrowing.
1028         let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1029                                  blacklist: &[DefId]|
1030          -> bool {
1031             if blacklist.contains(&old_pred.def_id()) {
1032                 return false;
1033             }
1034             // We map bounds to `&T` and `&mut T`
1035             let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1036                 (
1037                     trait_pred,
1038                     self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1039                 )
1040             });
1041             let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1042                 (
1043                     trait_pred,
1044                     self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1045                 )
1046             });
1047
1048             let mk_result = |trait_pred_and_new_ty| {
1049                 let obligation =
1050                     self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1051                 self.predicate_must_hold_modulo_regions(&obligation)
1052             };
1053             let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1054             let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1055
1056             let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1057                 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1058                     && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1059                 {
1060                     (
1061                         mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1062                         mutability.is_mut(),
1063                     )
1064                 } else {
1065                     (false, false)
1066                 };
1067
1068             if imm_ref_self_ty_satisfies_pred
1069                 || mut_ref_self_ty_satisfies_pred
1070                 || ref_inner_ty_satisfies_pred
1071             {
1072                 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1073                     // We don't want a borrowing suggestion on the fields in structs,
1074                     // ```
1075                     // struct Foo {
1076                     //  the_foos: Vec<Foo>
1077                     // }
1078                     // ```
1079                     if !matches!(
1080                         span.ctxt().outer_expn_data().kind,
1081                         ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1082                     ) {
1083                         return false;
1084                     }
1085                     if snippet.starts_with('&') {
1086                         // This is already a literal borrow and the obligation is failing
1087                         // somewhere else in the obligation chain. Do not suggest non-sense.
1088                         return false;
1089                     }
1090                     // We have a very specific type of error, where just borrowing this argument
1091                     // might solve the problem. In cases like this, the important part is the
1092                     // original type obligation, not the last one that failed, which is arbitrary.
1093                     // Because of this, we modify the error to refer to the original obligation and
1094                     // return early in the caller.
1095
1096                     let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1097                     if has_custom_message {
1098                         err.note(&msg);
1099                     } else {
1100                         err.message =
1101                             vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1102                     }
1103                     err.span_label(
1104                         span,
1105                         format!(
1106                             "the trait `{}` is not implemented for `{}`",
1107                             old_pred.print_modifiers_and_trait_path(),
1108                             old_pred.self_ty().skip_binder(),
1109                         ),
1110                     );
1111
1112                     if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1113                         err.span_suggestions(
1114                             span.shrink_to_lo(),
1115                             "consider borrowing here",
1116                             ["&".to_string(), "&mut ".to_string()],
1117                             Applicability::MaybeIncorrect,
1118                         );
1119                     } else {
1120                         let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1121                         err.span_suggestion_verbose(
1122                             span.shrink_to_lo(),
1123                             &format!(
1124                                 "consider{} borrowing here",
1125                                 if is_mut { " mutably" } else { "" }
1126                             ),
1127                             format!("&{}", if is_mut { "mut " } else { "" }),
1128                             Applicability::MaybeIncorrect,
1129                         );
1130                     }
1131                     return true;
1132                 }
1133             }
1134             return false;
1135         };
1136
1137         if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1138             try_borrowing(cause.derived.parent_trait_pred, &[])
1139         } else if let ObligationCauseCode::BindingObligation(_, _)
1140         | ObligationCauseCode::ItemObligation(_)
1141         | ObligationCauseCode::ExprItemObligation(..)
1142         | ObligationCauseCode::ExprBindingObligation(..) = code
1143         {
1144             try_borrowing(poly_trait_pred, &never_suggest_borrow)
1145         } else {
1146             false
1147         }
1148     }
1149
1150     // Suggest borrowing the type
1151     fn suggest_borrowing_for_object_cast(
1152         &self,
1153         err: &mut Diagnostic,
1154         obligation: &PredicateObligation<'tcx>,
1155         self_ty: Ty<'tcx>,
1156         object_ty: Ty<'tcx>,
1157     ) {
1158         let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; };
1159         let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1160
1161         for predicate in predicates.iter() {
1162             if !self.predicate_must_hold_modulo_regions(
1163                 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1164             ) {
1165                 return;
1166             }
1167         }
1168
1169         err.span_suggestion(
1170             obligation.cause.span.shrink_to_lo(),
1171             &format!(
1172                 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1173             ),
1174             "&",
1175             Applicability::MaybeIncorrect,
1176         );
1177     }
1178
1179     /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1180     /// suggest removing these references until we reach a type that implements the trait.
1181     fn suggest_remove_reference(
1182         &self,
1183         obligation: &PredicateObligation<'tcx>,
1184         err: &mut Diagnostic,
1185         trait_pred: ty::PolyTraitPredicate<'tcx>,
1186     ) -> bool {
1187         let span = obligation.cause.span;
1188
1189         let mut suggested = false;
1190         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1191             let refs_number =
1192                 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1193             if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1194                 // Do not suggest removal of borrow from type arguments.
1195                 return false;
1196             }
1197
1198             // Skipping binder here, remapping below
1199             let mut suggested_ty = trait_pred.self_ty().skip_binder();
1200
1201             for refs_remaining in 0..refs_number {
1202                 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1203                     break;
1204                 };
1205                 suggested_ty = *inner_ty;
1206
1207                 // Remapping bound vars here
1208                 let trait_pred_and_suggested_ty =
1209                     trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1210
1211                 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1212                     obligation.param_env,
1213                     trait_pred_and_suggested_ty,
1214                 );
1215
1216                 if self.predicate_may_hold(&new_obligation) {
1217                     let sp = self
1218                         .tcx
1219                         .sess
1220                         .source_map()
1221                         .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1222
1223                     let remove_refs = refs_remaining + 1;
1224
1225                     let msg = if remove_refs == 1 {
1226                         "consider removing the leading `&`-reference".to_string()
1227                     } else {
1228                         format!("consider removing {} leading `&`-references", remove_refs)
1229                     };
1230
1231                     err.span_suggestion_short(sp, &msg, "", Applicability::MachineApplicable);
1232                     suggested = true;
1233                     break;
1234                 }
1235             }
1236         }
1237         suggested
1238     }
1239
1240     fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1241         let span = obligation.cause.span;
1242
1243         if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1244             let hir = self.tcx.hir();
1245             if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1246                 if let hir::Node::Expr(expr) = node {
1247                     // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1248                     // and if not maybe suggest doing something else? If we kept the expression around we
1249                     // could also check if it is an fn call (very likely) and suggest changing *that*, if
1250                     // it is from the local crate.
1251                     err.span_suggestion(
1252                         span,
1253                         "remove the `.await`",
1254                         "",
1255                         Applicability::MachineApplicable,
1256                     );
1257                     // FIXME: account for associated `async fn`s.
1258                     if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1259                         if let ty::PredicateKind::Clause(ty::Clause::Trait(pred)) =
1260                             obligation.predicate.kind().skip_binder()
1261                         {
1262                             err.span_label(
1263                                 *span,
1264                                 &format!("this call returns `{}`", pred.self_ty()),
1265                             );
1266                         }
1267                         if let Some(typeck_results) = &self.typeck_results
1268                             && let ty = typeck_results.expr_ty_adjusted(base)
1269                             && let ty::FnDef(def_id, _substs) = ty.kind()
1270                             && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1271                                 hir.get_if_local(*def_id)
1272                         {
1273                             let msg = format!(
1274                                 "alternatively, consider making `fn {}` asynchronous",
1275                                 ident
1276                             );
1277                             if vis_span.is_empty() {
1278                                 err.span_suggestion_verbose(
1279                                     span.shrink_to_lo(),
1280                                     &msg,
1281                                     "async ",
1282                                     Applicability::MaybeIncorrect,
1283                                 );
1284                             } else {
1285                                 err.span_suggestion_verbose(
1286                                     vis_span.shrink_to_hi(),
1287                                     &msg,
1288                                     " async",
1289                                     Applicability::MaybeIncorrect,
1290                                 );
1291                             }
1292                         }
1293                     }
1294                 }
1295             }
1296         }
1297     }
1298
1299     /// Check if the trait bound is implemented for a different mutability and note it in the
1300     /// final error.
1301     fn suggest_change_mut(
1302         &self,
1303         obligation: &PredicateObligation<'tcx>,
1304         err: &mut Diagnostic,
1305         trait_pred: ty::PolyTraitPredicate<'tcx>,
1306     ) {
1307         let points_at_arg = matches!(
1308             obligation.cause.code(),
1309             ObligationCauseCode::FunctionArgumentObligation { .. },
1310         );
1311
1312         let span = obligation.cause.span;
1313         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1314             let refs_number =
1315                 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1316             if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1317                 // Do not suggest removal of borrow from type arguments.
1318                 return;
1319             }
1320             let trait_pred = self.resolve_vars_if_possible(trait_pred);
1321             if trait_pred.has_non_region_infer() {
1322                 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1323                 // unresolved bindings.
1324                 return;
1325             }
1326
1327             // Skipping binder here, remapping below
1328             if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1329             {
1330                 let suggested_ty = match mutability {
1331                     hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1332                     hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1333                 };
1334
1335                 // Remapping bound vars here
1336                 let trait_pred_and_suggested_ty =
1337                     trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1338
1339                 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1340                     obligation.param_env,
1341                     trait_pred_and_suggested_ty,
1342                 );
1343                 let suggested_ty_would_satisfy_obligation = self
1344                     .evaluate_obligation_no_overflow(&new_obligation)
1345                     .must_apply_modulo_regions();
1346                 if suggested_ty_would_satisfy_obligation {
1347                     let sp = self
1348                         .tcx
1349                         .sess
1350                         .source_map()
1351                         .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1352                     if points_at_arg && mutability.is_not() && refs_number > 0 {
1353                         err.span_suggestion_verbose(
1354                             sp,
1355                             "consider changing this borrow's mutability",
1356                             "&mut ",
1357                             Applicability::MachineApplicable,
1358                         );
1359                     } else {
1360                         err.note(&format!(
1361                             "`{}` is implemented for `{:?}`, but not for `{:?}`",
1362                             trait_pred.print_modifiers_and_trait_path(),
1363                             suggested_ty,
1364                             trait_pred.skip_binder().self_ty(),
1365                         ));
1366                     }
1367                 }
1368             }
1369         }
1370     }
1371
1372     fn suggest_semicolon_removal(
1373         &self,
1374         obligation: &PredicateObligation<'tcx>,
1375         err: &mut Diagnostic,
1376         span: Span,
1377         trait_pred: ty::PolyTraitPredicate<'tcx>,
1378     ) -> bool {
1379         let hir = self.tcx.hir();
1380         let parent_node = hir.get_parent_node(obligation.cause.body_id);
1381         let node = hir.find(parent_node);
1382         if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1383             && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1384             && sig.decl.output.span().overlaps(span)
1385             && blk.expr.is_none()
1386             && trait_pred.self_ty().skip_binder().is_unit()
1387             && let Some(stmt) = blk.stmts.last()
1388             && let hir::StmtKind::Semi(expr) = stmt.kind
1389             // Only suggest this if the expression behind the semicolon implements the predicate
1390             && let Some(typeck_results) = &self.typeck_results
1391             && let Some(ty) = typeck_results.expr_ty_opt(expr)
1392             && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1393                 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1394             ))
1395         {
1396             err.span_label(
1397                 expr.span,
1398                 &format!(
1399                     "this expression has type `{}`, which implements `{}`",
1400                     ty,
1401                     trait_pred.print_modifiers_and_trait_path()
1402                 )
1403             );
1404             err.span_suggestion(
1405                 self.tcx.sess.source_map().end_point(stmt.span),
1406                 "remove this semicolon",
1407                 "",
1408                 Applicability::MachineApplicable
1409             );
1410             return true;
1411         }
1412         false
1413     }
1414
1415     fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1416         let hir = self.tcx.hir();
1417         let parent_node = hir.get_parent_node(obligation.cause.body_id);
1418         let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1419             return None;
1420         };
1421
1422         if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1423     }
1424
1425     /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1426     /// applicable and signal that the error has been expanded appropriately and needs to be
1427     /// emitted.
1428     fn suggest_impl_trait(
1429         &self,
1430         err: &mut Diagnostic,
1431         span: Span,
1432         obligation: &PredicateObligation<'tcx>,
1433         trait_pred: ty::PolyTraitPredicate<'tcx>,
1434     ) -> bool {
1435         match obligation.cause.code().peel_derives() {
1436             // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1437             ObligationCauseCode::SizedReturnType => {}
1438             _ => return false,
1439         }
1440
1441         let hir = self.tcx.hir();
1442         let fn_hir_id = hir.get_parent_node(obligation.cause.body_id);
1443         let node = hir.find(fn_hir_id);
1444         let Some(hir::Node::Item(hir::Item {
1445             kind: hir::ItemKind::Fn(sig, _, body_id),
1446             ..
1447         })) = node
1448         else {
1449             return false;
1450         };
1451         let body = hir.body(*body_id);
1452         let trait_pred = self.resolve_vars_if_possible(trait_pred);
1453         let ty = trait_pred.skip_binder().self_ty();
1454         let is_object_safe = match ty.kind() {
1455             ty::Dynamic(predicates, _, ty::Dyn) => {
1456                 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1457                 predicates
1458                     .principal_def_id()
1459                     .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1460             }
1461             // We only want to suggest `impl Trait` to `dyn Trait`s.
1462             // For example, `fn foo() -> str` needs to be filtered out.
1463             _ => return false,
1464         };
1465
1466         let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1467             return false;
1468         };
1469
1470         // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1471         // cases like `fn foo() -> (dyn Trait, i32) {}`.
1472         // Recursively look for `TraitObject` types and if there's only one, use that span to
1473         // suggest `impl Trait`.
1474
1475         // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1476         // otherwise suggest using `Box<dyn Trait>` or an enum.
1477         let mut visitor = ReturnsVisitor::default();
1478         visitor.visit_body(&body);
1479
1480         let typeck_results = self.typeck_results.as_ref().unwrap();
1481         let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1482
1483         let ret_types = visitor
1484             .returns
1485             .iter()
1486             .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1487             .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1488         let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1489             (None, true, true),
1490             |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1491              (_, ty)| {
1492                 let ty = self.resolve_vars_if_possible(ty);
1493                 same &=
1494                     !matches!(ty.kind(), ty::Error(_))
1495                         && last_ty.map_or(true, |last_ty| {
1496                             // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1497                             // *after* in the dependency graph.
1498                             match (ty.kind(), last_ty.kind()) {
1499                                 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1500                                 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1501                                 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1502                                 | (
1503                                     Infer(InferTy::FreshFloatTy(_)),
1504                                     Infer(InferTy::FreshFloatTy(_)),
1505                                 ) => true,
1506                                 _ => ty == last_ty,
1507                             }
1508                         });
1509                 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1510             },
1511         );
1512         let mut spans_and_needs_box = vec![];
1513
1514         match liberated_sig.output().kind() {
1515             ty::Dynamic(predicates, _, ty::Dyn) => {
1516                 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1517                 let param_env = ty::ParamEnv::empty();
1518
1519                 if !only_never_return {
1520                     for (expr_span, return_ty) in ret_types {
1521                         let self_ty_satisfies_dyn_predicates = |self_ty| {
1522                             predicates.iter().all(|predicate| {
1523                                 let pred = predicate.with_self_ty(self.tcx, self_ty);
1524                                 let obl = Obligation::new(self.tcx, cause.clone(), param_env, pred);
1525                                 self.predicate_may_hold(&obl)
1526                             })
1527                         };
1528
1529                         if let ty::Adt(def, substs) = return_ty.kind()
1530                             && def.is_box()
1531                             && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1532                         {
1533                             spans_and_needs_box.push((expr_span, false));
1534                         } else if self_ty_satisfies_dyn_predicates(return_ty) {
1535                             spans_and_needs_box.push((expr_span, true));
1536                         } else {
1537                             return false;
1538                         }
1539                     }
1540                 }
1541             }
1542             _ => return false,
1543         };
1544
1545         let sm = self.tcx.sess.source_map();
1546         if !ret_ty.span.overlaps(span) {
1547             return false;
1548         }
1549         let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1550             if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1551                 snippet
1552             } else {
1553                 return false;
1554             }
1555         } else {
1556             // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1557             let name = liberated_sig.output().to_string();
1558             let name =
1559                 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1560             if !name.starts_with("dyn ") {
1561                 return false;
1562             }
1563             name.to_owned()
1564         };
1565
1566         err.code(error_code!(E0746));
1567         err.set_primary_message("return type cannot have an unboxed trait object");
1568         err.children.clear();
1569         let impl_trait_msg = "for information on `impl Trait`, see \
1570             <https://doc.rust-lang.org/book/ch10-02-traits.html\
1571             #returning-types-that-implement-traits>";
1572         let trait_obj_msg = "for information on trait objects, see \
1573             <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1574             #using-trait-objects-that-allow-for-values-of-different-types>";
1575
1576         let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1577         let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1578         if only_never_return {
1579             // No return paths, probably using `panic!()` or similar.
1580             // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1581             suggest_trait_object_return_type_alternatives(
1582                 err,
1583                 ret_ty.span,
1584                 trait_obj,
1585                 is_object_safe,
1586             );
1587         } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1588             // Suggest `-> impl Trait`.
1589             err.span_suggestion(
1590                 ret_ty.span,
1591                 &format!(
1592                     "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1593                      which implements `{1}`",
1594                     last_ty, trait_obj,
1595                 ),
1596                 format!("impl {}", trait_obj),
1597                 Applicability::MachineApplicable,
1598             );
1599             err.note(impl_trait_msg);
1600         } else {
1601             if is_object_safe {
1602                 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1603                 err.multipart_suggestion(
1604                     "return a boxed trait object instead",
1605                     vec![
1606                         (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1607                         (span.shrink_to_hi(), ">".to_string()),
1608                     ],
1609                     Applicability::MaybeIncorrect,
1610                 );
1611                 for (span, needs_box) in spans_and_needs_box {
1612                     if needs_box {
1613                         err.multipart_suggestion(
1614                             "... and box this value",
1615                             vec![
1616                                 (span.shrink_to_lo(), "Box::new(".to_string()),
1617                                 (span.shrink_to_hi(), ")".to_string()),
1618                             ],
1619                             Applicability::MaybeIncorrect,
1620                         );
1621                     }
1622                 }
1623             } else {
1624                 // This is currently not possible to trigger because E0038 takes precedence, but
1625                 // leave it in for completeness in case anything changes in an earlier stage.
1626                 err.note(&format!(
1627                     "if trait `{}` were object-safe, you could return a trait object",
1628                     trait_obj,
1629                 ));
1630             }
1631             err.note(trait_obj_msg);
1632             err.note(&format!(
1633                 "if all the returned values were of the same type you could use `impl {}` as the \
1634                  return type",
1635                 trait_obj,
1636             ));
1637             err.note(impl_trait_msg);
1638             err.note("you can create a new `enum` with a variant for each returned type");
1639         }
1640         true
1641     }
1642
1643     fn point_at_returns_when_relevant(
1644         &self,
1645         err: &mut Diagnostic,
1646         obligation: &PredicateObligation<'tcx>,
1647     ) {
1648         match obligation.cause.code().peel_derives() {
1649             ObligationCauseCode::SizedReturnType => {}
1650             _ => return,
1651         }
1652
1653         let hir = self.tcx.hir();
1654         let parent_node = hir.get_parent_node(obligation.cause.body_id);
1655         let node = hir.find(parent_node);
1656         if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1657             node
1658         {
1659             let body = hir.body(*body_id);
1660             // Point at all the `return`s in the function as they have failed trait bounds.
1661             let mut visitor = ReturnsVisitor::default();
1662             visitor.visit_body(&body);
1663             let typeck_results = self.typeck_results.as_ref().unwrap();
1664             for expr in &visitor.returns {
1665                 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1666                     let ty = self.resolve_vars_if_possible(returned_ty);
1667                     err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1668                 }
1669             }
1670         }
1671     }
1672
1673     fn report_closure_arg_mismatch(
1674         &self,
1675         span: Span,
1676         found_span: Option<Span>,
1677         found: ty::PolyTraitRef<'tcx>,
1678         expected: ty::PolyTraitRef<'tcx>,
1679         cause: &ObligationCauseCode<'tcx>,
1680     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1681         pub(crate) fn build_fn_sig_ty<'tcx>(
1682             infcx: &InferCtxt<'tcx>,
1683             trait_ref: ty::PolyTraitRef<'tcx>,
1684         ) -> Ty<'tcx> {
1685             let inputs = trait_ref.skip_binder().substs.type_at(1);
1686             let sig = match inputs.kind() {
1687                 ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id()) => {
1688                     infcx.tcx.mk_fn_sig(
1689                         inputs.iter(),
1690                         infcx.next_ty_var(TypeVariableOrigin {
1691                             span: DUMMY_SP,
1692                             kind: TypeVariableOriginKind::MiscVariable,
1693                         }),
1694                         false,
1695                         hir::Unsafety::Normal,
1696                         abi::Abi::Rust,
1697                     )
1698                 }
1699                 _ => infcx.tcx.mk_fn_sig(
1700                     std::iter::once(inputs),
1701                     infcx.next_ty_var(TypeVariableOrigin {
1702                         span: DUMMY_SP,
1703                         kind: TypeVariableOriginKind::MiscVariable,
1704                     }),
1705                     false,
1706                     hir::Unsafety::Normal,
1707                     abi::Abi::Rust,
1708                 ),
1709             };
1710
1711             infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
1712         }
1713
1714         let argument_kind = match expected.skip_binder().self_ty().kind() {
1715             ty::Closure(..) => "closure",
1716             ty::Generator(..) => "generator",
1717             _ => "function",
1718         };
1719         let mut err = struct_span_err!(
1720             self.tcx.sess,
1721             span,
1722             E0631,
1723             "type mismatch in {argument_kind} arguments",
1724         );
1725
1726         err.span_label(span, "expected due to this");
1727
1728         let found_span = found_span.unwrap_or(span);
1729         err.span_label(found_span, "found signature defined here");
1730
1731         let expected = build_fn_sig_ty(self, expected);
1732         let found = build_fn_sig_ty(self, found);
1733
1734         let (expected_str, found_str) = self.cmp(expected, found);
1735
1736         let signature_kind = format!("{argument_kind} signature");
1737         err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
1738
1739         self.note_conflicting_closure_bounds(cause, &mut err);
1740
1741         err
1742     }
1743
1744     // Add a note if there are two `Fn`-family bounds that have conflicting argument
1745     // requirements, which will always cause a closure to have a type error.
1746     fn note_conflicting_closure_bounds(
1747         &self,
1748         cause: &ObligationCauseCode<'tcx>,
1749         err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1750     ) {
1751         // First, look for an `ExprBindingObligation`, which means we can get
1752         // the unsubstituted predicate list of the called function. And check
1753         // that the predicate that we failed to satisfy is a `Fn`-like trait.
1754         if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = cause
1755             && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
1756             && let Some(pred) = predicates.predicates.get(*idx)
1757             && let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = pred.kind().skip_binder()
1758             && self.tcx.is_fn_trait(trait_pred.def_id())
1759         {
1760             let expected_self =
1761                 self.tcx.anonymize_late_bound_regions(pred.kind().rebind(trait_pred.self_ty()));
1762             let expected_substs = self
1763                 .tcx
1764                 .anonymize_late_bound_regions(pred.kind().rebind(trait_pred.trait_ref.substs));
1765
1766             // Find another predicate whose self-type is equal to the expected self type,
1767             // but whose substs don't match.
1768             let other_pred = std::iter::zip(&predicates.predicates, &predicates.spans)
1769                 .enumerate()
1770                 .find(|(other_idx, (pred, _))| match pred.kind().skip_binder() {
1771                     ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred))
1772                         if self.tcx.is_fn_trait(trait_pred.def_id())
1773                             && other_idx != idx
1774                             // Make sure that the self type matches
1775                             // (i.e. constraining this closure)
1776                             && expected_self
1777                                 == self.tcx.anonymize_late_bound_regions(
1778                                     pred.kind().rebind(trait_pred.self_ty()),
1779                                 )
1780                             // But the substs don't match (i.e. incompatible args)
1781                             && expected_substs
1782                                 != self.tcx.anonymize_late_bound_regions(
1783                                     pred.kind().rebind(trait_pred.trait_ref.substs),
1784                                 ) =>
1785                     {
1786                         true
1787                     }
1788                     _ => false,
1789                 });
1790             // If we found one, then it's very likely the cause of the error.
1791             if let Some((_, (_, other_pred_span))) = other_pred {
1792                 err.span_note(
1793                     *other_pred_span,
1794                     "closure inferred to have a different signature due to this bound",
1795                 );
1796             }
1797         }
1798     }
1799
1800     fn suggest_fully_qualified_path(
1801         &self,
1802         err: &mut Diagnostic,
1803         item_def_id: DefId,
1804         span: Span,
1805         trait_ref: DefId,
1806     ) {
1807         if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1808             if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1809                 err.note(&format!(
1810                     "{}s cannot be accessed directly on a `trait`, they can only be \
1811                         accessed through a specific `impl`",
1812                     assoc_item.kind.as_def_kind().descr(item_def_id)
1813                 ));
1814                 err.span_suggestion(
1815                     span,
1816                     "use the fully qualified path to an implementation",
1817                     format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1818                     Applicability::HasPlaceholders,
1819                 );
1820             }
1821         }
1822     }
1823
1824     /// Adds an async-await specific note to the diagnostic when the future does not implement
1825     /// an auto trait because of a captured type.
1826     ///
1827     /// ```text
1828     /// note: future does not implement `Qux` as this value is used across an await
1829     ///   --> $DIR/issue-64130-3-other.rs:17:5
1830     ///    |
1831     /// LL |     let x = Foo;
1832     ///    |         - has type `Foo`
1833     /// LL |     baz().await;
1834     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1835     /// LL | }
1836     ///    | - `x` is later dropped here
1837     /// ```
1838     ///
1839     /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1840     /// is "replaced" with a different message and a more specific error.
1841     ///
1842     /// ```text
1843     /// error: future cannot be sent between threads safely
1844     ///   --> $DIR/issue-64130-2-send.rs:21:5
1845     ///    |
1846     /// LL | fn is_send<T: Send>(t: T) { }
1847     ///    |               ---- required by this bound in `is_send`
1848     /// ...
1849     /// LL |     is_send(bar());
1850     ///    |     ^^^^^^^ future returned by `bar` is not send
1851     ///    |
1852     ///    = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1853     ///            implemented for `Foo`
1854     /// note: future is not send as this value is used across an await
1855     ///   --> $DIR/issue-64130-2-send.rs:15:5
1856     ///    |
1857     /// LL |     let x = Foo;
1858     ///    |         - has type `Foo`
1859     /// LL |     baz().await;
1860     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1861     /// LL | }
1862     ///    | - `x` is later dropped here
1863     /// ```
1864     ///
1865     /// Returns `true` if an async-await specific note was added to the diagnostic.
1866     #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
1867     fn maybe_note_obligation_cause_for_async_await(
1868         &self,
1869         err: &mut Diagnostic,
1870         obligation: &PredicateObligation<'tcx>,
1871     ) -> bool {
1872         let hir = self.tcx.hir();
1873
1874         // Attempt to detect an async-await error by looking at the obligation causes, looking
1875         // for a generator to be present.
1876         //
1877         // When a future does not implement a trait because of a captured type in one of the
1878         // generators somewhere in the call stack, then the result is a chain of obligations.
1879         //
1880         // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1881         // future is passed as an argument to a function C which requires a `Send` type, then the
1882         // chain looks something like this:
1883         //
1884         // - `BuiltinDerivedObligation` with a generator witness (B)
1885         // - `BuiltinDerivedObligation` with a generator (B)
1886         // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1887         // - `BuiltinDerivedObligation` with a generator witness (A)
1888         // - `BuiltinDerivedObligation` with a generator (A)
1889         // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1890         // - `BindingObligation` with `impl_send (Send requirement)
1891         //
1892         // The first obligation in the chain is the most useful and has the generator that captured
1893         // the type. The last generator (`outer_generator` below) has information about where the
1894         // bound was introduced. At least one generator should be present for this diagnostic to be
1895         // modified.
1896         let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1897             ty::PredicateKind::Clause(ty::Clause::Trait(p)) => (Some(p), Some(p.self_ty())),
1898             _ => (None, None),
1899         };
1900         let mut generator = None;
1901         let mut outer_generator = None;
1902         let mut next_code = Some(obligation.cause.code());
1903
1904         let mut seen_upvar_tys_infer_tuple = false;
1905
1906         while let Some(code) = next_code {
1907             debug!(?code);
1908             match code {
1909                 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1910                     next_code = Some(parent_code);
1911                 }
1912                 ObligationCauseCode::ImplDerivedObligation(cause) => {
1913                     let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
1914                     debug!(
1915                         parent_trait_ref = ?cause.derived.parent_trait_pred,
1916                         self_ty.kind = ?ty.kind(),
1917                         "ImplDerived",
1918                     );
1919
1920                     match *ty.kind() {
1921                         ty::Generator(did, ..) => {
1922                             generator = generator.or(Some(did));
1923                             outer_generator = Some(did);
1924                         }
1925                         ty::GeneratorWitness(..) => {}
1926                         ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1927                             // By introducing a tuple of upvar types into the chain of obligations
1928                             // of a generator, the first non-generator item is now the tuple itself,
1929                             // we shall ignore this.
1930
1931                             seen_upvar_tys_infer_tuple = true;
1932                         }
1933                         _ if generator.is_none() => {
1934                             trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
1935                             target_ty = Some(ty);
1936                         }
1937                         _ => {}
1938                     }
1939
1940                     next_code = Some(&cause.derived.parent_code);
1941                 }
1942                 ObligationCauseCode::DerivedObligation(derived_obligation)
1943                 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
1944                     let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1945                     debug!(
1946                         parent_trait_ref = ?derived_obligation.parent_trait_pred,
1947                         self_ty.kind = ?ty.kind(),
1948                     );
1949
1950                     match *ty.kind() {
1951                         ty::Generator(did, ..) => {
1952                             generator = generator.or(Some(did));
1953                             outer_generator = Some(did);
1954                         }
1955                         ty::GeneratorWitness(..) => {}
1956                         ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1957                             // By introducing a tuple of upvar types into the chain of obligations
1958                             // of a generator, the first non-generator item is now the tuple itself,
1959                             // we shall ignore this.
1960
1961                             seen_upvar_tys_infer_tuple = true;
1962                         }
1963                         _ if generator.is_none() => {
1964                             trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
1965                             target_ty = Some(ty);
1966                         }
1967                         _ => {}
1968                     }
1969
1970                     next_code = Some(&derived_obligation.parent_code);
1971                 }
1972                 _ => break,
1973             }
1974         }
1975
1976         // Only continue if a generator was found.
1977         debug!(?generator, ?trait_ref, ?target_ty);
1978         let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
1979             return false;
1980         };
1981
1982         let span = self.tcx.def_span(generator_did);
1983
1984         let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
1985         debug!(
1986             ?generator_did,
1987             ?generator_did_root,
1988             typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
1989             ?span,
1990         );
1991
1992         let generator_body = generator_did
1993             .as_local()
1994             .and_then(|def_id| hir.maybe_body_owned_by(def_id))
1995             .map(|body_id| hir.body(body_id));
1996         let mut visitor = AwaitsVisitor::default();
1997         if let Some(body) = generator_body {
1998             visitor.visit_body(body);
1999         }
2000         debug!(awaits = ?visitor.awaits);
2001
2002         // Look for a type inside the generator interior that matches the target type to get
2003         // a span.
2004         let target_ty_erased = self.tcx.erase_regions(target_ty);
2005         let ty_matches = |ty| -> bool {
2006             // Careful: the regions for types that appear in the
2007             // generator interior are not generally known, so we
2008             // want to erase them when comparing (and anyway,
2009             // `Send` and other bounds are generally unaffected by
2010             // the choice of region).  When erasing regions, we
2011             // also have to erase late-bound regions. This is
2012             // because the types that appear in the generator
2013             // interior generally contain "bound regions" to
2014             // represent regions that are part of the suspended
2015             // generator frame. Bound regions are preserved by
2016             // `erase_regions` and so we must also call
2017             // `erase_late_bound_regions`.
2018             let ty_erased = self.tcx.erase_late_bound_regions(ty);
2019             let ty_erased = self.tcx.erase_regions(ty_erased);
2020             let eq = ty_erased == target_ty_erased;
2021             debug!(?ty_erased, ?target_ty_erased, ?eq);
2022             eq
2023         };
2024
2025         // Get the typeck results from the infcx if the generator is the function we are currently
2026         // type-checking; otherwise, get them by performing a query.  This is needed to avoid
2027         // cycles. If we can't use resolved types because the generator comes from another crate,
2028         // we still provide a targeted error but without all the relevant spans.
2029         let generator_data = match &self.typeck_results {
2030             Some(t) if t.hir_owner.to_def_id() == generator_did_root => GeneratorData::Local(&t),
2031             _ if generator_did.is_local() => {
2032                 GeneratorData::Local(self.tcx.typeck(generator_did.expect_local()))
2033             }
2034             _ if let Some(generator_diag_data) = self.tcx.generator_diagnostic_data(generator_did) => {
2035                 GeneratorData::Foreign(generator_diag_data)
2036             }
2037             _ => return false,
2038         };
2039
2040         let mut interior_or_upvar_span = None;
2041
2042         let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
2043         debug!(?from_awaited_ty);
2044
2045         // The generator interior types share the same binders
2046         if let Some(cause) =
2047             generator_data.get_generator_interior_types().skip_binder().iter().find(
2048                 |ty::GeneratorInteriorTypeCause { ty, .. }| {
2049                     ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
2050                 },
2051             )
2052         {
2053             let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;
2054
2055             interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(
2056                 *span,
2057                 Some((*scope_span, *yield_span, *expr, from_awaited_ty)),
2058             ));
2059         }
2060
2061         if interior_or_upvar_span.is_none() {
2062             interior_or_upvar_span =
2063                 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
2064         }
2065
2066         if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2067             interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span, None));
2068         }
2069
2070         debug!(?interior_or_upvar_span);
2071         if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2072             let is_async = self.tcx.generator_is_async(generator_did);
2073             let typeck_results = match generator_data {
2074                 GeneratorData::Local(typeck_results) => Some(typeck_results),
2075                 GeneratorData::Foreign(_) => None,
2076             };
2077             self.note_obligation_cause_for_async_await(
2078                 err,
2079                 interior_or_upvar_span,
2080                 is_async,
2081                 outer_generator,
2082                 trait_ref,
2083                 target_ty,
2084                 typeck_results,
2085                 obligation,
2086                 next_code,
2087             );
2088             true
2089         } else {
2090             false
2091         }
2092     }
2093
2094     /// Unconditionally adds the diagnostic note described in
2095     /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2096     #[instrument(level = "debug", skip_all)]
2097     fn note_obligation_cause_for_async_await(
2098         &self,
2099         err: &mut Diagnostic,
2100         interior_or_upvar_span: GeneratorInteriorOrUpvar,
2101         is_async: bool,
2102         outer_generator: Option<DefId>,
2103         trait_pred: ty::TraitPredicate<'tcx>,
2104         target_ty: Ty<'tcx>,
2105         typeck_results: Option<&ty::TypeckResults<'tcx>>,
2106         obligation: &PredicateObligation<'tcx>,
2107         next_code: Option<&ObligationCauseCode<'tcx>>,
2108     ) {
2109         let source_map = self.tcx.sess.source_map();
2110
2111         let (await_or_yield, an_await_or_yield) =
2112             if is_async { ("await", "an await") } else { ("yield", "a yield") };
2113         let future_or_generator = if is_async { "future" } else { "generator" };
2114
2115         // Special case the primary error message when send or sync is the trait that was
2116         // not implemented.
2117         let hir = self.tcx.hir();
2118         let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2119             self.tcx.get_diagnostic_name(trait_pred.def_id())
2120         {
2121             let (trait_name, trait_verb) =
2122                 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2123
2124             err.clear_code();
2125             err.set_primary_message(format!(
2126                 "{} cannot be {} between threads safely",
2127                 future_or_generator, trait_verb
2128             ));
2129
2130             let original_span = err.span.primary_span().unwrap();
2131             let mut span = MultiSpan::from_span(original_span);
2132
2133             let message = outer_generator
2134                 .and_then(|generator_did| {
2135                     Some(match self.tcx.generator_kind(generator_did).unwrap() {
2136                         GeneratorKind::Gen => format!("generator is not {}", trait_name),
2137                         GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2138                             .tcx
2139                             .parent(generator_did)
2140                             .as_local()
2141                             .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2142                             .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2143                             .map(|name| {
2144                                 format!("future returned by `{}` is not {}", name, trait_name)
2145                             })?,
2146                         GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2147                             format!("future created by async block is not {}", trait_name)
2148                         }
2149                         GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2150                             format!("future created by async closure is not {}", trait_name)
2151                         }
2152                     })
2153                 })
2154                 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2155
2156             span.push_span_label(original_span, message);
2157             err.set_span(span);
2158
2159             format!("is not {}", trait_name)
2160         } else {
2161             format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2162         };
2163
2164         let mut explain_yield = |interior_span: Span,
2165                                  yield_span: Span,
2166                                  scope_span: Option<Span>| {
2167             let mut span = MultiSpan::from_span(yield_span);
2168             if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
2169                 // #70935: If snippet contains newlines, display "the value" instead
2170                 // so that we do not emit complex diagnostics.
2171                 let snippet = &format!("`{}`", snippet);
2172                 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
2173                 // note: future is not `Send` as this value is used across an await
2174                 //   --> $DIR/issue-70935-complex-spans.rs:13:9
2175                 //    |
2176                 // LL |            baz(|| async {
2177                 //    |  ______________-
2178                 //    | |
2179                 //    | |
2180                 // LL | |              foo(tx.clone());
2181                 // LL | |          }).await;
2182                 //    | |          - ^^^^^^ await occurs here, with value maybe used later
2183                 //    | |__________|
2184                 //    |            has type `closure` which is not `Send`
2185                 // note: value is later dropped here
2186                 // LL | |          }).await;
2187                 //    | |                  ^
2188                 //
2189                 span.push_span_label(
2190                     yield_span,
2191                     format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2192                 );
2193                 span.push_span_label(
2194                     interior_span,
2195                     format!("has type `{}` which {}", target_ty, trait_explanation),
2196                 );
2197                 // If available, use the scope span to annotate the drop location.
2198                 let mut scope_note = None;
2199                 if let Some(scope_span) = scope_span {
2200                     let scope_span = source_map.end_point(scope_span);
2201
2202                     let msg = format!("{} is later dropped here", snippet);
2203                     if source_map.is_multiline(yield_span.between(scope_span)) {
2204                         span.push_span_label(scope_span, msg);
2205                     } else {
2206                         scope_note = Some((scope_span, msg));
2207                     }
2208                 }
2209                 err.span_note(
2210                     span,
2211                     &format!(
2212                         "{} {} as this value is used across {}",
2213                         future_or_generator, trait_explanation, an_await_or_yield
2214                     ),
2215                 );
2216                 if let Some((span, msg)) = scope_note {
2217                     err.span_note(span, &msg);
2218                 }
2219             }
2220         };
2221         match interior_or_upvar_span {
2222             GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2223                 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2224                     if let Some(await_span) = from_awaited_ty {
2225                         // The type causing this obligation is one being awaited at await_span.
2226                         let mut span = MultiSpan::from_span(await_span);
2227                         span.push_span_label(
2228                             await_span,
2229                             format!(
2230                                 "await occurs here on type `{}`, which {}",
2231                                 target_ty, trait_explanation
2232                             ),
2233                         );
2234                         err.span_note(
2235                             span,
2236                             &format!(
2237                                 "future {not_trait} as it awaits another future which {not_trait}",
2238                                 not_trait = trait_explanation
2239                             ),
2240                         );
2241                     } else {
2242                         // Look at the last interior type to get a span for the `.await`.
2243                         debug!(
2244                             generator_interior_types = ?format_args!(
2245                                 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2246                             ),
2247                         );
2248                         explain_yield(interior_span, yield_span, scope_span);
2249                     }
2250
2251                     if let Some(expr_id) = expr {
2252                         let expr = hir.expect_expr(expr_id);
2253                         debug!("target_ty evaluated from {:?}", expr);
2254
2255                         let parent = hir.get_parent_node(expr_id);
2256                         if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2257                             let parent_span = hir.span(parent);
2258                             let parent_did = parent.owner.to_def_id();
2259                             // ```rust
2260                             // impl T {
2261                             //     fn foo(&self) -> i32 {}
2262                             // }
2263                             // T.foo();
2264                             // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2265                             // ```
2266                             //
2267                             let is_region_borrow = if let Some(typeck_results) = typeck_results {
2268                                 typeck_results
2269                                     .expr_adjustments(expr)
2270                                     .iter()
2271                                     .any(|adj| adj.is_region_borrow())
2272                             } else {
2273                                 false
2274                             };
2275
2276                             // ```rust
2277                             // struct Foo(*const u8);
2278                             // bar(Foo(std::ptr::null())).await;
2279                             //     ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2280                             // ```
2281                             debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2282                             let is_raw_borrow_inside_fn_like_call =
2283                                 match self.tcx.def_kind(parent_did) {
2284                                     DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2285                                     _ => false,
2286                                 };
2287                             if let Some(typeck_results) = typeck_results {
2288                                 if (typeck_results.is_method_call(e) && is_region_borrow)
2289                                     || is_raw_borrow_inside_fn_like_call
2290                                 {
2291                                     err.span_help(
2292                                         parent_span,
2293                                         "consider moving this into a `let` \
2294                         binding to create a shorter lived borrow",
2295                                     );
2296                                 }
2297                             }
2298                         }
2299                     }
2300                 }
2301             }
2302             GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2303                 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
2304                 let refers_to_non_sync = match target_ty.kind() {
2305                     ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
2306                         Ok(eval) if !eval.may_apply() => Some(ref_ty),
2307                         _ => None,
2308                     },
2309                     _ => None,
2310                 };
2311
2312                 let (span_label, span_note) = match refers_to_non_sync {
2313                     // if `target_ty` is `&T` and `T` fails to impl `Sync`,
2314                     // include suggestions to make `T: Sync` so that `&T: Send`
2315                     Some(ref_ty) => (
2316                         format!(
2317                             "has type `{}` which {}, because `{}` is not `Sync`",
2318                             target_ty, trait_explanation, ref_ty
2319                         ),
2320                         format!(
2321                             "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
2322                             trait_explanation
2323                         ),
2324                     ),
2325                     None => (
2326                         format!("has type `{}` which {}", target_ty, trait_explanation),
2327                         format!("captured value {}", trait_explanation),
2328                     ),
2329                 };
2330
2331                 let mut span = MultiSpan::from_span(upvar_span);
2332                 span.push_span_label(upvar_span, span_label);
2333                 err.span_note(span, &span_note);
2334             }
2335         }
2336
2337         // Add a note for the item obligation that remains - normally a note pointing to the
2338         // bound that introduced the obligation (e.g. `T: Send`).
2339         debug!(?next_code);
2340         self.note_obligation_cause_code(
2341             err,
2342             obligation.predicate,
2343             obligation.param_env,
2344             next_code.unwrap(),
2345             &mut Vec::new(),
2346             &mut Default::default(),
2347         );
2348     }
2349
2350     fn note_obligation_cause_code<T>(
2351         &self,
2352         err: &mut Diagnostic,
2353         predicate: T,
2354         param_env: ty::ParamEnv<'tcx>,
2355         cause_code: &ObligationCauseCode<'tcx>,
2356         obligated_types: &mut Vec<Ty<'tcx>>,
2357         seen_requirements: &mut FxHashSet<DefId>,
2358     ) where
2359         T: ToPredicate<'tcx>,
2360     {
2361         let tcx = self.tcx;
2362         let predicate = predicate.to_predicate(tcx);
2363         match *cause_code {
2364             ObligationCauseCode::ExprAssignable
2365             | ObligationCauseCode::MatchExpressionArm { .. }
2366             | ObligationCauseCode::Pattern { .. }
2367             | ObligationCauseCode::IfExpression { .. }
2368             | ObligationCauseCode::IfExpressionWithNoElse
2369             | ObligationCauseCode::MainFunctionType
2370             | ObligationCauseCode::StartFunctionType
2371             | ObligationCauseCode::IntrinsicType
2372             | ObligationCauseCode::MethodReceiver
2373             | ObligationCauseCode::ReturnNoExpression
2374             | ObligationCauseCode::UnifyReceiver(..)
2375             | ObligationCauseCode::OpaqueType
2376             | ObligationCauseCode::MiscObligation
2377             | ObligationCauseCode::WellFormed(..)
2378             | ObligationCauseCode::MatchImpl(..)
2379             | ObligationCauseCode::ReturnType
2380             | ObligationCauseCode::ReturnValue(_)
2381             | ObligationCauseCode::BlockTailExpression(_)
2382             | ObligationCauseCode::AwaitableExpr(_)
2383             | ObligationCauseCode::ForLoopIterator
2384             | ObligationCauseCode::QuestionMark
2385             | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2386             | ObligationCauseCode::LetElse
2387             | ObligationCauseCode::BinOp { .. }
2388             | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2389             | ObligationCauseCode::RustCall => {}
2390             ObligationCauseCode::SliceOrArrayElem => {
2391                 err.note("slice and array elements must have `Sized` type");
2392             }
2393             ObligationCauseCode::TupleElem => {
2394                 err.note("only the last element of a tuple may have a dynamically sized type");
2395             }
2396             ObligationCauseCode::ProjectionWf(data) => {
2397                 err.note(&format!("required so that the projection `{}` is well-formed", data,));
2398             }
2399             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2400                 err.note(&format!(
2401                     "required so that reference `{}` does not outlive its referent",
2402                     ref_ty,
2403                 ));
2404             }
2405             ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2406                 err.note(&format!(
2407                     "required so that the lifetime bound of `{}` for `{}` is satisfied",
2408                     region, object_ty,
2409                 ));
2410             }
2411             ObligationCauseCode::ItemObligation(_)
2412             | ObligationCauseCode::ExprItemObligation(..) => {
2413                 // We hold the `DefId` of the item introducing the obligation, but displaying it
2414                 // doesn't add user usable information. It always point at an associated item.
2415             }
2416             ObligationCauseCode::BindingObligation(item_def_id, span)
2417             | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2418                 let item_name = tcx.def_path_str(item_def_id);
2419                 let short_item_name = with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
2420                 let mut multispan = MultiSpan::from(span);
2421                 let sm = tcx.sess.source_map();
2422                 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2423                     let same_line =
2424                         match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2425                             (Ok(l), Ok(r)) => l.line == r.line,
2426                             _ => true,
2427                         };
2428                     if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
2429                         multispan.push_span_label(ident.span, "required by a bound in this");
2430                     }
2431                 }
2432                 let descr = format!("required by a bound in `{item_name}`");
2433                 if span.is_visible(sm) {
2434                     let msg = format!("required by this bound in `{short_item_name}`");
2435                     multispan.push_span_label(span, msg);
2436                     err.span_note(multispan, &descr);
2437                 } else {
2438                     err.span_note(tcx.def_span(item_def_id), &descr);
2439                 }
2440             }
2441             ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2442                 err.note(&format!(
2443                     "required for the cast from `{}` to the object type `{}`",
2444                     self.ty_to_string(concrete_ty),
2445                     self.ty_to_string(object_ty)
2446                 ));
2447             }
2448             ObligationCauseCode::Coercion { source: _, target } => {
2449                 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2450             }
2451             ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2452                 err.note(
2453                     "the `Copy` trait is required because this value will be copied for each element of the array",
2454                 );
2455
2456                 if is_const_fn {
2457                     err.help(
2458                         "consider creating a new `const` item and initializing it with the result \
2459                         of the function call to be used in the repeat position, like \
2460                         `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2461                     );
2462                 }
2463
2464                 if self.tcx.sess.is_nightly_build() && is_const_fn {
2465                     err.help(
2466                         "create an inline `const` block, see RFC #2920 \
2467                          <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2468                     );
2469                 }
2470             }
2471             ObligationCauseCode::VariableType(hir_id) => {
2472                 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2473                 match self.tcx.hir().find(parent_node) {
2474                     Some(Node::Local(hir::Local {
2475                         init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2476                         ..
2477                     })) => {
2478                         // When encountering an assignment of an unsized trait, like
2479                         // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2480                         // order to use have a slice instead.
2481                         err.span_suggestion_verbose(
2482                             span.shrink_to_lo(),
2483                             "consider borrowing here",
2484                             "&",
2485                             Applicability::MachineApplicable,
2486                         );
2487                         err.note("all local variables must have a statically known size");
2488                     }
2489                     Some(Node::Param(param)) => {
2490                         err.span_suggestion_verbose(
2491                             param.ty_span.shrink_to_lo(),
2492                             "function arguments must have a statically known size, borrowed types \
2493                             always have a known size",
2494                             "&",
2495                             Applicability::MachineApplicable,
2496                         );
2497                     }
2498                     _ => {
2499                         err.note("all local variables must have a statically known size");
2500                     }
2501                 }
2502                 if !self.tcx.features().unsized_locals {
2503                     err.help("unsized locals are gated as an unstable feature");
2504                 }
2505             }
2506             ObligationCauseCode::SizedArgumentType(sp) => {
2507                 if let Some(span) = sp {
2508                     err.span_suggestion_verbose(
2509                         span.shrink_to_lo(),
2510                         "function arguments must have a statically known size, borrowed types \
2511                          always have a known size",
2512                         "&",
2513                         Applicability::MachineApplicable,
2514                     );
2515                 } else {
2516                     err.note("all function arguments must have a statically known size");
2517                 }
2518                 if tcx.sess.opts.unstable_features.is_nightly_build()
2519                     && !self.tcx.features().unsized_fn_params
2520                 {
2521                     err.help("unsized fn params are gated as an unstable feature");
2522                 }
2523             }
2524             ObligationCauseCode::SizedReturnType => {
2525                 err.note("the return type of a function must have a statically known size");
2526             }
2527             ObligationCauseCode::SizedYieldType => {
2528                 err.note("the yield type of a generator must have a statically known size");
2529             }
2530             ObligationCauseCode::SizedBoxType => {
2531                 err.note("the type of a box expression must have a statically known size");
2532             }
2533             ObligationCauseCode::AssignmentLhsSized => {
2534                 err.note("the left-hand-side of an assignment must have a statically known size");
2535             }
2536             ObligationCauseCode::TupleInitializerSized => {
2537                 err.note("tuples must have a statically known size to be initialized");
2538             }
2539             ObligationCauseCode::StructInitializerSized => {
2540                 err.note("structs must have a statically known size to be initialized");
2541             }
2542             ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2543                 match *item {
2544                     AdtKind::Struct => {
2545                         if last {
2546                             err.note(
2547                                 "the last field of a packed struct may only have a \
2548                                 dynamically sized type if it does not need drop to be run",
2549                             );
2550                         } else {
2551                             err.note(
2552                                 "only the last field of a struct may have a dynamically sized type",
2553                             );
2554                         }
2555                     }
2556                     AdtKind::Union => {
2557                         err.note("no field of a union may have a dynamically sized type");
2558                     }
2559                     AdtKind::Enum => {
2560                         err.note("no field of an enum variant may have a dynamically sized type");
2561                     }
2562                 }
2563                 err.help("change the field's type to have a statically known size");
2564                 err.span_suggestion(
2565                     span.shrink_to_lo(),
2566                     "borrowed types always have a statically known size",
2567                     "&",
2568                     Applicability::MachineApplicable,
2569                 );
2570                 err.multipart_suggestion(
2571                     "the `Box` type always has a statically known size and allocates its contents \
2572                      in the heap",
2573                     vec![
2574                         (span.shrink_to_lo(), "Box<".to_string()),
2575                         (span.shrink_to_hi(), ">".to_string()),
2576                     ],
2577                     Applicability::MachineApplicable,
2578                 );
2579             }
2580             ObligationCauseCode::ConstSized => {
2581                 err.note("constant expressions must have a statically known size");
2582             }
2583             ObligationCauseCode::InlineAsmSized => {
2584                 err.note("all inline asm arguments must have a statically known size");
2585             }
2586             ObligationCauseCode::ConstPatternStructural => {
2587                 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2588             }
2589             ObligationCauseCode::SharedStatic => {
2590                 err.note("shared static variables must have a type that implements `Sync`");
2591             }
2592             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2593                 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2594                 let ty = parent_trait_ref.skip_binder().self_ty();
2595                 if parent_trait_ref.references_error() {
2596                     // NOTE(eddyb) this was `.cancel()`, but `err`
2597                     // is borrowed, so we can't fully defuse it.
2598                     err.downgrade_to_delayed_bug();
2599                     return;
2600                 }
2601
2602                 // If the obligation for a tuple is set directly by a Generator or Closure,
2603                 // then the tuple must be the one containing capture types.
2604                 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2605                     false
2606                 } else {
2607                     if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2608                     {
2609                         let parent_trait_ref =
2610                             self.resolve_vars_if_possible(data.parent_trait_pred);
2611                         let nested_ty = parent_trait_ref.skip_binder().self_ty();
2612                         matches!(nested_ty.kind(), ty::Generator(..))
2613                             || matches!(nested_ty.kind(), ty::Closure(..))
2614                     } else {
2615                         false
2616                     }
2617                 };
2618
2619                 let identity_future = tcx.require_lang_item(LangItem::IdentityFuture, None);
2620
2621                 // Don't print the tuple of capture types
2622                 'print: {
2623                     if !is_upvar_tys_infer_tuple {
2624                         let msg = format!("required because it appears within the type `{}`", ty);
2625                         match ty.kind() {
2626                             ty::Adt(def, _) => match self.tcx.opt_item_ident(def.did()) {
2627                                 Some(ident) => err.span_note(ident.span, &msg),
2628                                 None => err.note(&msg),
2629                             },
2630                             ty::Opaque(def_id, _) => {
2631                                 // Avoid printing the future from `core::future::identity_future`, it's not helpful
2632                                 if tcx.parent(*def_id) == identity_future {
2633                                     break 'print;
2634                                 }
2635
2636                                 // If the previous type is `identity_future`, this is the future generated by the body of an async function.
2637                                 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
2638                                 let is_future = tcx.ty_is_opaque_future(ty);
2639                                 debug!(
2640                                     ?obligated_types,
2641                                     ?is_future,
2642                                     "note_obligation_cause_code: check for async fn"
2643                                 );
2644                                 if is_future
2645                                     && obligated_types.last().map_or(false, |ty| match ty.kind() {
2646                                         ty::Generator(last_def_id, ..) => {
2647                                             tcx.generator_is_async(*last_def_id)
2648                                         }
2649                                         _ => false,
2650                                     })
2651                                 {
2652                                     break 'print;
2653                                 }
2654                                 err.span_note(self.tcx.def_span(def_id), &msg)
2655                             }
2656                             ty::GeneratorWitness(bound_tys) => {
2657                                 use std::fmt::Write;
2658
2659                                 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
2660                                 // Maybe we should just remove this note altogether?
2661                                 // FIXME: only print types which don't meet the trait requirement
2662                                 let mut msg =
2663                                     "required because it captures the following types: ".to_owned();
2664                                 for ty in bound_tys.skip_binder() {
2665                                     write!(msg, "`{}`, ", ty).unwrap();
2666                                 }
2667                                 err.note(msg.trim_end_matches(", "))
2668                             }
2669                             ty::Generator(def_id, _, _) => {
2670                                 let sp = self.tcx.def_span(def_id);
2671
2672                                 // Special-case this to say "async block" instead of `[static generator]`.
2673                                 let kind = tcx.generator_kind(def_id).unwrap().descr();
2674                                 err.span_note(
2675                                     sp,
2676                                     &format!("required because it's used within this {}", kind),
2677                                 )
2678                             }
2679                             ty::Closure(def_id, _) => err.span_note(
2680                                 self.tcx.def_span(def_id),
2681                                 &format!("required because it's used within this closure"),
2682                             ),
2683                             _ => err.note(&msg),
2684                         };
2685                     }
2686                 }
2687
2688                 obligated_types.push(ty);
2689
2690                 let parent_predicate = parent_trait_ref;
2691                 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2692                     // #74711: avoid a stack overflow
2693                     ensure_sufficient_stack(|| {
2694                         self.note_obligation_cause_code(
2695                             err,
2696                             parent_predicate,
2697                             param_env,
2698                             &data.parent_code,
2699                             obligated_types,
2700                             seen_requirements,
2701                         )
2702                     });
2703                 } else {
2704                     ensure_sufficient_stack(|| {
2705                         self.note_obligation_cause_code(
2706                             err,
2707                             parent_predicate,
2708                             param_env,
2709                             cause_code.peel_derives(),
2710                             obligated_types,
2711                             seen_requirements,
2712                         )
2713                     });
2714                 }
2715             }
2716             ObligationCauseCode::ImplDerivedObligation(ref data) => {
2717                 let mut parent_trait_pred =
2718                     self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2719                 parent_trait_pred.remap_constness_diag(param_env);
2720                 let parent_def_id = parent_trait_pred.def_id();
2721                 let (self_ty, file) =
2722                     self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2723                 let msg = format!(
2724                     "required for `{self_ty}` to implement `{}`",
2725                     parent_trait_pred.print_modifiers_and_trait_path()
2726                 );
2727                 let mut is_auto_trait = false;
2728                 match self.tcx.hir().get_if_local(data.impl_def_id) {
2729                     Some(Node::Item(hir::Item {
2730                         kind: hir::ItemKind::Trait(is_auto, ..),
2731                         ident,
2732                         ..
2733                     })) => {
2734                         // FIXME: we should do something else so that it works even on crate foreign
2735                         // auto traits.
2736                         is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2737                         err.span_note(ident.span, &msg)
2738                     }
2739                     Some(Node::Item(hir::Item {
2740                         kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2741                         ..
2742                     })) => {
2743                         let mut spans = Vec::with_capacity(2);
2744                         if let Some(trait_ref) = of_trait {
2745                             spans.push(trait_ref.path.span);
2746                         }
2747                         spans.push(self_ty.span);
2748                         err.span_note(spans, &msg)
2749                     }
2750                     _ => err.note(&msg),
2751                 };
2752
2753                 if let Some(file) = file {
2754                     err.note(&format!(
2755                         "the full type name has been written to '{}'",
2756                         file.display(),
2757                     ));
2758                 }
2759                 let mut parent_predicate = parent_trait_pred;
2760                 let mut data = &data.derived;
2761                 let mut count = 0;
2762                 seen_requirements.insert(parent_def_id);
2763                 if is_auto_trait {
2764                     // We don't want to point at the ADT saying "required because it appears within
2765                     // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2766                     while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2767                         &*data.parent_code
2768                     {
2769                         let child_trait_ref =
2770                             self.resolve_vars_if_possible(derived.parent_trait_pred);
2771                         let child_def_id = child_trait_ref.def_id();
2772                         if seen_requirements.insert(child_def_id) {
2773                             break;
2774                         }
2775                         data = derived;
2776                         parent_predicate = child_trait_ref.to_predicate(tcx);
2777                         parent_trait_pred = child_trait_ref;
2778                     }
2779                 }
2780                 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2781                     // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2782                     let child_trait_pred =
2783                         self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2784                     let child_def_id = child_trait_pred.def_id();
2785                     if seen_requirements.insert(child_def_id) {
2786                         break;
2787                     }
2788                     count += 1;
2789                     data = &child.derived;
2790                     parent_predicate = child_trait_pred.to_predicate(tcx);
2791                     parent_trait_pred = child_trait_pred;
2792                 }
2793                 if count > 0 {
2794                     err.note(&format!(
2795                         "{} redundant requirement{} hidden",
2796                         count,
2797                         pluralize!(count)
2798                     ));
2799                     let (self_ty, file) =
2800                         self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2801                     err.note(&format!(
2802                         "required for `{self_ty}` to implement `{}`",
2803                         parent_trait_pred.print_modifiers_and_trait_path()
2804                     ));
2805                     if let Some(file) = file {
2806                         err.note(&format!(
2807                             "the full type name has been written to '{}'",
2808                             file.display(),
2809                         ));
2810                     }
2811                 }
2812                 // #74711: avoid a stack overflow
2813                 ensure_sufficient_stack(|| {
2814                     self.note_obligation_cause_code(
2815                         err,
2816                         parent_predicate,
2817                         param_env,
2818                         &data.parent_code,
2819                         obligated_types,
2820                         seen_requirements,
2821                     )
2822                 });
2823             }
2824             ObligationCauseCode::DerivedObligation(ref data) => {
2825                 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2826                 let parent_predicate = parent_trait_ref;
2827                 // #74711: avoid a stack overflow
2828                 ensure_sufficient_stack(|| {
2829                     self.note_obligation_cause_code(
2830                         err,
2831                         parent_predicate,
2832                         param_env,
2833                         &data.parent_code,
2834                         obligated_types,
2835                         seen_requirements,
2836                     )
2837                 });
2838             }
2839             ObligationCauseCode::FunctionArgumentObligation {
2840                 arg_hir_id,
2841                 call_hir_id,
2842                 ref parent_code,
2843             } => {
2844                 let hir = self.tcx.hir();
2845                 if let Some(Node::Expr(expr)) = hir.find(arg_hir_id) {
2846                     let parent_id = hir.get_parent_item(arg_hir_id);
2847                     let typeck_results: &TypeckResults<'tcx> = match &self.typeck_results {
2848                         Some(t) if t.hir_owner == parent_id => t,
2849                         _ => self.tcx.typeck(parent_id.def_id),
2850                     };
2851                     if let hir::Expr { kind: hir::ExprKind::Block(..), .. } = expr {
2852                         let expr = expr.peel_blocks();
2853                         let ty =
2854                             typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error());
2855                         let span = expr.span;
2856                         if Some(span) != err.span.primary_span() {
2857                             err.span_label(
2858                                 span,
2859                                 if ty.references_error() {
2860                                     String::new()
2861                                 } else {
2862                                     format!("this tail expression is of type `{:?}`", ty)
2863                                 },
2864                             );
2865                         }
2866                     }
2867
2868                     let span = expr.span;
2869                     let mut multi_span: MultiSpan = match expr.kind {
2870                         hir::ExprKind::MethodCall(_, _, _, span) => span.into(),
2871                         _ => span.into(),
2872                     };
2873
2874                     // FIXME: visit the ty to see if there's any closure involved, and if there is,
2875                     // check whether its evaluated return type is the same as the one corresponding
2876                     // to an associated type (as seen from `trait_pred`) in the predicate. Like in
2877                     // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
2878                     let mut type_diffs = vec![];
2879
2880                     if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = parent_code.deref()
2881                         && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
2882                         && let Some(pred) = predicates.predicates.get(*idx)
2883                         && let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = pred.kind().skip_binder()
2884                     {
2885                         let mut c = CollectAllMismatches {
2886                             infcx: self.infcx,
2887                             param_env: param_env,
2888                             errors: vec![],
2889                         };
2890                         if let ty::PredicateKind::Clause(ty::Clause::Trait(
2891                                 predicate
2892                             )) = predicate.kind().skip_binder()
2893                         {
2894                             if let Ok(_) = c.relate(trait_pred, predicate) {
2895                                 type_diffs = c.errors;
2896                             }
2897                         }
2898                     }
2899                     let point_at_chain = |expr: &hir::Expr<'_>| {
2900                         let mut expr = expr;
2901                         let mut prev_ty = self.resolve_vars_if_possible(
2902                             typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
2903                         );
2904                         let outer_ty = prev_ty;
2905                         let mut assoc_seen = 0;
2906                         while let hir::ExprKind::MethodCall(_path_segment, rcvr_expr, _args, span) =
2907                             expr.kind
2908                         {
2909                             // Point at every method call in the chain with the resulting type.
2910                             // vec![1, 2, 3].iter().map(mapper).sum<i32>()
2911                             //               ^^^^^^ ^^^^^^^^^^^
2912                             expr = rcvr_expr;
2913
2914                             let ocx = ObligationCtxt::new_in_snapshot(self.infcx);
2915                             for diff in &type_diffs {
2916                                 let Sorts(expected_found) = diff else { continue; };
2917                                 let ty::Projection(proj) = expected_found.expected.kind() else { continue; };
2918                                 assoc_seen += 1;
2919
2920                                 let origin = TypeVariableOrigin {
2921                                     kind: TypeVariableOriginKind::TypeInference,
2922                                     span,
2923                                 };
2924                                 let trait_def_id = proj.trait_def_id(self.tcx);
2925                                 // Make `Self` be equivalent to the type of the call chain
2926                                 // expression we're looking at now, so that we can tell what
2927                                 // for example `Iterator::Item` is at this point in the chain.
2928                                 let substs =
2929                                     InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
2930                                         match param.kind {
2931                                             ty::GenericParamDefKind::Type { .. } => {
2932                                                 if param.index == 0 {
2933                                                     return prev_ty.into();
2934                                                 }
2935                                             }
2936                                             ty::GenericParamDefKind::Lifetime
2937                                             | ty::GenericParamDefKind::Const { .. } => {}
2938                                         }
2939                                         self.var_for_def(span, param)
2940                                     });
2941                                 // This will hold the resolved type of the associated type, if the
2942                                 // current expression implements the trait that associated type is
2943                                 // in. For example, this would be what `Iterator::Item` is here.
2944                                 let ty_var = self.infcx.next_ty_var(origin);
2945                                 // This corresponds to `<ExprTy as Iterator>::Item = _`.
2946                                 let trait_ref = ty::Binder::dummy(ty::PredicateKind::Clause(
2947                                     ty::Clause::Projection(ty::ProjectionPredicate {
2948                                         projection_ty: ty::ProjectionTy {
2949                                             substs,
2950                                             item_def_id: proj.item_def_id,
2951                                         },
2952                                         term: ty_var.into(),
2953                                     }),
2954                                 ));
2955                                 // Add `<ExprTy as Iterator>::Item = _` obligation.
2956                                 ocx.register_obligation(Obligation::misc(
2957                                     self.tcx,
2958                                     span,
2959                                     expr.hir_id,
2960                                     param_env,
2961                                     trait_ref,
2962                                 ));
2963                                 if ocx.select_where_possible().is_empty() {
2964                                     // `ty_var` now holds the type that `Item` is for `ExprTy`.
2965                                     let assoc = self.tcx.def_path_str(proj.item_def_id);
2966                                     multi_span.push_span_label(
2967                                         span,
2968                                         &format!(
2969                                             "associated type `{assoc}` is `{}` here",
2970                                             self.resolve_vars_if_possible(ty_var),
2971                                         ),
2972                                     );
2973                                 } else {
2974                                     // `<ExprTy as Iterator>` didn't select, so likely we've
2975                                     // reached the end of the iterator chain, like the originating
2976                                     // `Vec<_>`.
2977                                     multi_span.push_span_label(
2978                                         span,
2979                                         format!("this call has type `{prev_ty}`"),
2980                                     );
2981                                 }
2982                             }
2983                             prev_ty = self.resolve_vars_if_possible(
2984                                 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
2985                             );
2986                         }
2987
2988                         // We want the type before deref coercions, otherwise we talk about `&[_]`
2989                         // instead of `Vec<_>`.
2990                         if let Some(ty) = typeck_results.expr_ty_opt(expr) {
2991                             let ty = self.resolve_vars_if_possible(ty);
2992                             // Point at the root expression
2993                             // vec![1, 2, 3].iter().map(mapper).sum<i32>()
2994                             // ^^^^^^^^^^^^^
2995                             multi_span.push_span_label(
2996                                 expr.span,
2997                                 format!("this expression has type `{ty}`"),
2998                             );
2999                         };
3000                         if assoc_seen > 0 {
3001                             // Only show this if it is not a "trivial" expression (not a method
3002                             // chain) and there are associated types to talk about.
3003                             err.span_note(
3004                                 multi_span,
3005                                 format!("the expression is of type `{outer_ty}`"),
3006                             );
3007                         }
3008                     };
3009                     if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3010                         && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3011                         && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3012                         && let parent_hir_id = self.tcx.hir().get_parent_node(binding.hir_id)
3013                         && let Some(hir::Node::Local(local)) = self.tcx.hir().find(parent_hir_id)
3014                         && let Some(binding_expr) = local.init
3015                     {
3016                         // If the expression we're calling on is a binding, we want to point at the
3017                         // `let` when talking about the type. Otherwise we'll point at every part
3018                         // of the method chain with the type.
3019                         point_at_chain(binding_expr);
3020                     } else {
3021                         point_at_chain(expr);
3022                     }
3023                 }
3024                 if let Some(Node::Expr(hir::Expr {
3025                     kind:
3026                         hir::ExprKind::Call(hir::Expr { span, .. }, _)
3027                         | hir::ExprKind::MethodCall(
3028                             hir::PathSegment { ident: Ident { span, .. }, .. },
3029                             ..,
3030                         ),
3031                     ..
3032                 })) = hir.find(call_hir_id)
3033                 {
3034                     if Some(*span) != err.span.primary_span() {
3035                         err.span_label(*span, "required by a bound introduced by this call");
3036                     }
3037                 }
3038                 ensure_sufficient_stack(|| {
3039                     self.note_obligation_cause_code(
3040                         err,
3041                         predicate,
3042                         param_env,
3043                         &parent_code,
3044                         obligated_types,
3045                         seen_requirements,
3046                     )
3047                 });
3048             }
3049             ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
3050                 let item_name = self.tcx.item_name(trait_item_def_id);
3051                 let msg = format!(
3052                     "the requirement `{predicate}` appears on the `impl`'s {kind} \
3053                      `{item_name}` but not on the corresponding trait's {kind}",
3054                 );
3055                 let sp = self
3056                     .tcx
3057                     .opt_item_ident(trait_item_def_id)
3058                     .map(|i| i.span)
3059                     .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
3060                 let mut assoc_span: MultiSpan = sp.into();
3061                 assoc_span.push_span_label(
3062                     sp,
3063                     format!("this trait's {kind} doesn't have the requirement `{predicate}`"),
3064                 );
3065                 if let Some(ident) = self
3066                     .tcx
3067                     .opt_associated_item(trait_item_def_id)
3068                     .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
3069                 {
3070                     assoc_span.push_span_label(ident.span, "in this trait");
3071                 }
3072                 err.span_note(assoc_span, &msg);
3073             }
3074             ObligationCauseCode::TrivialBound => {
3075                 err.help("see issue #48214");
3076                 if tcx.sess.opts.unstable_features.is_nightly_build() {
3077                     err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
3078                 }
3079             }
3080             ObligationCauseCode::OpaqueReturnType(expr_info) => {
3081                 if let Some((expr_ty, expr_span)) = expr_info {
3082                     let expr_ty = self.resolve_vars_if_possible(expr_ty);
3083                     err.span_label(
3084                         expr_span,
3085                         format!("return type was inferred to be `{expr_ty}` here"),
3086                     );
3087                 }
3088             }
3089         }
3090     }
3091
3092     #[instrument(
3093         level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
3094     )]
3095     fn suggest_await_before_try(
3096         &self,
3097         err: &mut Diagnostic,
3098         obligation: &PredicateObligation<'tcx>,
3099         trait_pred: ty::PolyTraitPredicate<'tcx>,
3100         span: Span,
3101     ) {
3102         let body_hir_id = obligation.cause.body_id;
3103         let item_id = self.tcx.hir().get_parent_node(body_hir_id);
3104
3105         if let Some(body_id) =
3106             self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id))
3107         {
3108             let body = self.tcx.hir().body(body_id);
3109             if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
3110                 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
3111
3112                 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
3113                 let impls_future = self.type_implements_trait(
3114                     future_trait,
3115                     [self.tcx.erase_late_bound_regions(self_ty)],
3116                     obligation.param_env,
3117                 );
3118                 if !impls_future.must_apply_modulo_regions() {
3119                     return;
3120                 }
3121
3122                 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
3123                 // `<T as Future>::Output`
3124                 let projection_ty = trait_pred.map_bound(|trait_pred| {
3125                     self.tcx.mk_projection(
3126                         item_def_id,
3127                         // Future::Output has no substs
3128                         self.tcx.mk_substs_trait(trait_pred.self_ty(), []),
3129                     )
3130                 });
3131                 let InferOk { value: projection_ty, .. } =
3132                     self.at(&obligation.cause, obligation.param_env).normalize(projection_ty);
3133
3134                 debug!(
3135                     normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
3136                 );
3137                 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
3138                     obligation.param_env,
3139                     trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
3140                 );
3141                 debug!(try_trait_obligation = ?try_obligation);
3142                 if self.predicate_may_hold(&try_obligation)
3143                     && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
3144                     && snippet.ends_with('?')
3145                 {
3146                     err.span_suggestion_verbose(
3147                         span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
3148                         "consider `await`ing on the `Future`",
3149                         ".await",
3150                         Applicability::MaybeIncorrect,
3151                     );
3152                 }
3153             }
3154         }
3155     }
3156
3157     fn suggest_floating_point_literal(
3158         &self,
3159         obligation: &PredicateObligation<'tcx>,
3160         err: &mut Diagnostic,
3161         trait_ref: &ty::PolyTraitRef<'tcx>,
3162     ) {
3163         let rhs_span = match obligation.cause.code() {
3164             ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
3165             _ => return,
3166         };
3167         if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind()
3168             && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind()
3169         {
3170             err.span_suggestion_verbose(
3171                 rhs_span.shrink_to_hi(),
3172                 "consider using a floating-point literal by writing it with `.0`",
3173                 ".0",
3174                 Applicability::MaybeIncorrect,
3175             );
3176         }
3177     }
3178
3179     fn suggest_derive(
3180         &self,
3181         obligation: &PredicateObligation<'tcx>,
3182         err: &mut Diagnostic,
3183         trait_pred: ty::PolyTraitPredicate<'tcx>,
3184     ) {
3185         let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3186             return;
3187         };
3188         let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
3189             ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
3190             _ => return,
3191         };
3192         let can_derive = {
3193             let is_derivable_trait = match diagnostic_name {
3194                 sym::Default => !adt.is_enum(),
3195                 sym::PartialEq | sym::PartialOrd => {
3196                     let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
3197                     trait_pred.skip_binder().self_ty() == rhs_ty
3198                 }
3199                 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3200                 _ => false,
3201             };
3202             is_derivable_trait &&
3203                 // Ensure all fields impl the trait.
3204                 adt.all_fields().all(|field| {
3205                     let field_ty = field.ty(self.tcx, substs);
3206                     let trait_substs = match diagnostic_name {
3207                         sym::PartialEq | sym::PartialOrd => {
3208                             Some(field_ty)
3209                         }
3210                         _ => None,
3211                     };
3212                     let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3213                         trait_ref: self.tcx.mk_trait_ref(
3214                             trait_pred.def_id(),
3215                             [field_ty].into_iter().chain(trait_substs),
3216                         ),
3217                         ..*tr
3218                     });
3219                     let field_obl = Obligation::new(
3220                         self.tcx,
3221                         obligation.cause.clone(),
3222                         obligation.param_env,
3223                         trait_pred,
3224                     );
3225                     self.predicate_must_hold_modulo_regions(&field_obl)
3226                 })
3227         };
3228         if can_derive {
3229             err.span_suggestion_verbose(
3230                 self.tcx.def_span(adt.did()).shrink_to_lo(),
3231                 &format!(
3232                     "consider annotating `{}` with `#[derive({})]`",
3233                     trait_pred.skip_binder().self_ty(),
3234                     diagnostic_name,
3235                 ),
3236                 format!("#[derive({})]\n", diagnostic_name),
3237                 Applicability::MaybeIncorrect,
3238             );
3239         }
3240     }
3241
3242     fn suggest_dereferencing_index(
3243         &self,
3244         obligation: &PredicateObligation<'tcx>,
3245         err: &mut Diagnostic,
3246         trait_pred: ty::PolyTraitPredicate<'tcx>,
3247     ) {
3248         if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
3249             && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3250             && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
3251             && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3252             && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3253         {
3254             err.span_suggestion_verbose(
3255                 obligation.cause.span.shrink_to_lo(),
3256             "dereference this index",
3257             '*',
3258                 Applicability::MachineApplicable,
3259             );
3260         }
3261     }
3262 }
3263
3264 /// Collect all the returned expressions within the input expression.
3265 /// Used to point at the return spans when we want to suggest some change to them.
3266 #[derive(Default)]
3267 pub struct ReturnsVisitor<'v> {
3268     pub returns: Vec<&'v hir::Expr<'v>>,
3269     in_block_tail: bool,
3270 }
3271
3272 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3273     fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3274         // Visit every expression to detect `return` paths, either through the function's tail
3275         // expression or `return` statements. We walk all nodes to find `return` statements, but
3276         // we only care about tail expressions when `in_block_tail` is `true`, which means that
3277         // they're in the return path of the function body.
3278         match ex.kind {
3279             hir::ExprKind::Ret(Some(ex)) => {
3280                 self.returns.push(ex);
3281             }
3282             hir::ExprKind::Block(block, _) if self.in_block_tail => {
3283                 self.in_block_tail = false;
3284                 for stmt in block.stmts {
3285                     hir::intravisit::walk_stmt(self, stmt);
3286                 }
3287                 self.in_block_tail = true;
3288                 if let Some(expr) = block.expr {
3289                     self.visit_expr(expr);
3290                 }
3291             }
3292             hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3293                 self.visit_expr(then);
3294                 if let Some(el) = else_opt {
3295                     self.visit_expr(el);
3296                 }
3297             }
3298             hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3299                 for arm in arms {
3300                     self.visit_expr(arm.body);
3301                 }
3302             }
3303             // We need to walk to find `return`s in the entire body.
3304             _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3305             _ => self.returns.push(ex),
3306         }
3307     }
3308
3309     fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3310         assert!(!self.in_block_tail);
3311         if body.generator_kind().is_none() {
3312             if let hir::ExprKind::Block(block, None) = body.value.kind {
3313                 if block.expr.is_some() {
3314                     self.in_block_tail = true;
3315                 }
3316             }
3317         }
3318         hir::intravisit::walk_body(self, body);
3319     }
3320 }
3321
3322 /// Collect all the awaited expressions within the input expression.
3323 #[derive(Default)]
3324 struct AwaitsVisitor {
3325     awaits: Vec<hir::HirId>,
3326 }
3327
3328 impl<'v> Visitor<'v> for AwaitsVisitor {
3329     fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3330         if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3331             self.awaits.push(id)
3332         }
3333         hir::intravisit::walk_expr(self, ex)
3334     }
3335 }
3336
3337 pub trait NextTypeParamName {
3338     fn next_type_param_name(&self, name: Option<&str>) -> String;
3339 }
3340
3341 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3342     fn next_type_param_name(&self, name: Option<&str>) -> String {
3343         // This is the list of possible parameter names that we might suggest.
3344         let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3345         let name = name.as_deref();
3346         let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3347         let used_names = self
3348             .iter()
3349             .filter_map(|p| match p.name {
3350                 hir::ParamName::Plain(ident) => Some(ident.name),
3351                 _ => None,
3352             })
3353             .collect::<Vec<_>>();
3354
3355         possible_names
3356             .iter()
3357             .find(|n| !used_names.contains(&Symbol::intern(n)))
3358             .unwrap_or(&"ParamName")
3359             .to_string()
3360     }
3361 }
3362
3363 fn suggest_trait_object_return_type_alternatives(
3364     err: &mut Diagnostic,
3365     ret_ty: Span,
3366     trait_obj: &str,
3367     is_object_safe: bool,
3368 ) {
3369     err.span_suggestion(
3370         ret_ty,
3371         "use some type `T` that is `T: Sized` as the return type if all return paths have the \
3372             same type",
3373         "T",
3374         Applicability::MaybeIncorrect,
3375     );
3376     err.span_suggestion(
3377         ret_ty,
3378         &format!(
3379             "use `impl {}` as the return type if all return paths have the same type but you \
3380                 want to expose only the trait in the signature",
3381             trait_obj,
3382         ),
3383         format!("impl {}", trait_obj),
3384         Applicability::MaybeIncorrect,
3385     );
3386     if is_object_safe {
3387         err.multipart_suggestion(
3388             &format!(
3389                 "use a boxed trait object if all return paths implement trait `{}`",
3390                 trait_obj,
3391             ),
3392             vec![
3393                 (ret_ty.shrink_to_lo(), "Box<".to_string()),
3394                 (ret_ty.shrink_to_hi(), ">".to_string()),
3395             ],
3396             Applicability::MaybeIncorrect,
3397         );
3398     }
3399 }
3400
3401 /// Collect the spans that we see the generic param `param_did`
3402 struct ReplaceImplTraitVisitor<'a> {
3403     ty_spans: &'a mut Vec<Span>,
3404     param_did: DefId,
3405 }
3406
3407 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
3408     fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
3409         if let hir::TyKind::Path(hir::QPath::Resolved(
3410             None,
3411             hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
3412         )) = t.kind
3413         {
3414             if self.param_did == *segment_did {
3415                 // `fn foo(t: impl Trait)`
3416                 //            ^^^^^^^^^^ get this to suggest `T` instead
3417
3418                 // There might be more than one `impl Trait`.
3419                 self.ty_spans.push(t.span);
3420                 return;
3421             }
3422         }
3423
3424         hir::intravisit::walk_ty(self, t);
3425     }
3426 }
3427
3428 // Replace `param` with `replace_ty`
3429 struct ReplaceImplTraitFolder<'tcx> {
3430     tcx: TyCtxt<'tcx>,
3431     param: &'tcx ty::GenericParamDef,
3432     replace_ty: Ty<'tcx>,
3433 }
3434
3435 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
3436     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3437         if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
3438             if self.param.index == *index {
3439                 return self.replace_ty;
3440             }
3441         }
3442         t.super_fold_with(self)
3443     }
3444
3445     fn tcx(&self) -> TyCtxt<'tcx> {
3446         self.tcx
3447     }
3448 }
3449
3450 pub struct CollectAllMismatches<'a, 'tcx> {
3451     pub infcx: &'a InferCtxt<'tcx>,
3452     pub param_env: ty::ParamEnv<'tcx>,
3453     pub errors: Vec<TypeError<'tcx>>,
3454 }
3455
3456 impl<'a, 'tcx> TypeRelation<'tcx> for CollectAllMismatches<'a, 'tcx> {
3457     fn tag(&self) -> &'static str {
3458         "CollectAllMismatches"
3459     }
3460     fn tcx(&self) -> TyCtxt<'tcx> {
3461         self.infcx.tcx
3462     }
3463     fn intercrate(&self) -> bool {
3464         false
3465     }
3466     fn param_env(&self) -> ty::ParamEnv<'tcx> {
3467         self.param_env
3468     }
3469     fn a_is_expected(&self) -> bool {
3470         true
3471     } // irrelevant
3472     fn mark_ambiguous(&mut self) {
3473         bug!()
3474     }
3475     fn relate_with_variance<T: Relate<'tcx>>(
3476         &mut self,
3477         _: ty::Variance,
3478         _: ty::VarianceDiagInfo<'tcx>,
3479         a: T,
3480         b: T,
3481     ) -> RelateResult<'tcx, T> {
3482         self.relate(a, b)
3483     }
3484     fn regions(
3485         &mut self,
3486         a: ty::Region<'tcx>,
3487         _b: ty::Region<'tcx>,
3488     ) -> RelateResult<'tcx, ty::Region<'tcx>> {
3489         Ok(a)
3490     }
3491     fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
3492         if a == b || matches!(a.kind(), ty::Infer(_)) || matches!(b.kind(), ty::Infer(_)) {
3493             return Ok(a);
3494         }
3495         relate::super_relate_tys(self, a, b).or_else(|e| {
3496             self.errors.push(e);
3497             Ok(a)
3498         })
3499     }
3500     fn consts(
3501         &mut self,
3502         a: ty::Const<'tcx>,
3503         b: ty::Const<'tcx>,
3504     ) -> RelateResult<'tcx, ty::Const<'tcx>> {
3505         if a == b {
3506             return Ok(a);
3507         }
3508         relate::super_relate_consts(self, a, b) // could do something similar here for constants!
3509     }
3510     fn binders<T: Relate<'tcx>>(
3511         &mut self,
3512         a: ty::Binder<'tcx, T>,
3513         b: ty::Binder<'tcx, T>,
3514     ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> {
3515         Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
3516     }
3517 }