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