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