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