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