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