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