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