]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs
Rename things to be a bit clearer
[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, 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, is_mut))` if `target_ty` is `&T` or `&mut T` and fails to impl `Send`
2348                 let non_send = match target_ty.kind() {
2349                     ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(&obligation) {
2350                         Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
2351                         _ => None,
2352                     },
2353                     _ => None,
2354                 };
2355
2356                 let (span_label, span_note) = match non_send {
2357                     // if `target_ty` is `&T` or `&mut T` and fails to impl `Send`,
2358                     // include suggestions to make `T: Sync` so that `&T: Send`,
2359                     // or to make `T: Send` so that `&mut T: Send`
2360                     Some((ref_ty, is_mut)) => {
2361                         let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
2362                         let ref_kind = if is_mut { "&mut" } else { "&" };
2363                         (
2364                             format!(
2365                                 "has type `{}` which {}, because `{}` is not `{}`",
2366                                 target_ty, trait_explanation, ref_ty, ref_ty_trait
2367                             ),
2368                             format!(
2369                                 "captured value {} because `{}` references cannot be sent unless their referent is `{}`",
2370                                 trait_explanation, ref_kind, ref_ty_trait
2371                             ),
2372                         )
2373                     }
2374                     None => (
2375                         format!("has type `{}` which {}", target_ty, trait_explanation),
2376                         format!("captured value {}", trait_explanation),
2377                     ),
2378                 };
2379
2380                 let mut span = MultiSpan::from_span(upvar_span);
2381                 span.push_span_label(upvar_span, span_label);
2382                 err.span_note(span, &span_note);
2383             }
2384         }
2385
2386         // Add a note for the item obligation that remains - normally a note pointing to the
2387         // bound that introduced the obligation (e.g. `T: Send`).
2388         debug!(?next_code);
2389         self.note_obligation_cause_code(
2390             err,
2391             obligation.predicate,
2392             obligation.param_env,
2393             next_code.unwrap(),
2394             &mut Vec::new(),
2395             &mut Default::default(),
2396         );
2397     }
2398
2399     fn note_obligation_cause_code<T>(
2400         &self,
2401         err: &mut Diagnostic,
2402         predicate: T,
2403         param_env: ty::ParamEnv<'tcx>,
2404         cause_code: &ObligationCauseCode<'tcx>,
2405         obligated_types: &mut Vec<Ty<'tcx>>,
2406         seen_requirements: &mut FxHashSet<DefId>,
2407     ) where
2408         T: ToPredicate<'tcx>,
2409     {
2410         let tcx = self.tcx;
2411         let predicate = predicate.to_predicate(tcx);
2412         match *cause_code {
2413             ObligationCauseCode::ExprAssignable
2414             | ObligationCauseCode::MatchExpressionArm { .. }
2415             | ObligationCauseCode::Pattern { .. }
2416             | ObligationCauseCode::IfExpression { .. }
2417             | ObligationCauseCode::IfExpressionWithNoElse
2418             | ObligationCauseCode::MainFunctionType
2419             | ObligationCauseCode::StartFunctionType
2420             | ObligationCauseCode::IntrinsicType
2421             | ObligationCauseCode::MethodReceiver
2422             | ObligationCauseCode::ReturnNoExpression
2423             | ObligationCauseCode::UnifyReceiver(..)
2424             | ObligationCauseCode::OpaqueType
2425             | ObligationCauseCode::MiscObligation
2426             | ObligationCauseCode::WellFormed(..)
2427             | ObligationCauseCode::MatchImpl(..)
2428             | ObligationCauseCode::ReturnType
2429             | ObligationCauseCode::ReturnValue(_)
2430             | ObligationCauseCode::BlockTailExpression(_)
2431             | ObligationCauseCode::AwaitableExpr(_)
2432             | ObligationCauseCode::ForLoopIterator
2433             | ObligationCauseCode::QuestionMark
2434             | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2435             | ObligationCauseCode::LetElse
2436             | ObligationCauseCode::BinOp { .. }
2437             | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2438             | ObligationCauseCode::RustCall => {}
2439             ObligationCauseCode::SliceOrArrayElem => {
2440                 err.note("slice and array elements must have `Sized` type");
2441             }
2442             ObligationCauseCode::TupleElem => {
2443                 err.note("only the last element of a tuple may have a dynamically sized type");
2444             }
2445             ObligationCauseCode::ProjectionWf(data) => {
2446                 err.note(&format!("required so that the projection `{data}` is well-formed"));
2447             }
2448             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2449                 err.note(&format!(
2450                     "required so that reference `{ref_ty}` does not outlive its referent"
2451                 ));
2452             }
2453             ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2454                 err.note(&format!(
2455                     "required so that the lifetime bound of `{}` for `{}` is satisfied",
2456                     region, object_ty,
2457                 ));
2458             }
2459             ObligationCauseCode::ItemObligation(_)
2460             | ObligationCauseCode::ExprItemObligation(..) => {
2461                 // We hold the `DefId` of the item introducing the obligation, but displaying it
2462                 // doesn't add user usable information. It always point at an associated item.
2463             }
2464             ObligationCauseCode::BindingObligation(item_def_id, span)
2465             | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2466                 let item_name = tcx.def_path_str(item_def_id);
2467                 let short_item_name = with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
2468                 let mut multispan = MultiSpan::from(span);
2469                 let sm = tcx.sess.source_map();
2470                 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2471                     let same_line =
2472                         match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2473                             (Ok(l), Ok(r)) => l.line == r.line,
2474                             _ => true,
2475                         };
2476                     if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
2477                         multispan.push_span_label(ident.span, "required by a bound in this");
2478                     }
2479                 }
2480                 let descr = format!("required by a bound in `{item_name}`");
2481                 if span.is_visible(sm) {
2482                     let msg = format!("required by this bound in `{short_item_name}`");
2483                     multispan.push_span_label(span, msg);
2484                     err.span_note(multispan, &descr);
2485                 } else {
2486                     err.span_note(tcx.def_span(item_def_id), &descr);
2487                 }
2488             }
2489             ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2490                 err.note(&format!(
2491                     "required for the cast from `{}` to the object type `{}`",
2492                     self.ty_to_string(concrete_ty),
2493                     self.ty_to_string(object_ty)
2494                 ));
2495             }
2496             ObligationCauseCode::Coercion { source: _, target } => {
2497                 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2498             }
2499             ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2500                 err.note(
2501                     "the `Copy` trait is required because this value will be copied for each element of the array",
2502                 );
2503
2504                 if is_const_fn {
2505                     err.help(
2506                         "consider creating a new `const` item and initializing it with the result \
2507                         of the function call to be used in the repeat position, like \
2508                         `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2509                     );
2510                 }
2511
2512                 if self.tcx.sess.is_nightly_build() && is_const_fn {
2513                     err.help(
2514                         "create an inline `const` block, see RFC #2920 \
2515                          <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2516                     );
2517                 }
2518             }
2519             ObligationCauseCode::VariableType(hir_id) => {
2520                 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2521                 match self.tcx.hir().find(parent_node) {
2522                     Some(Node::Local(hir::Local {
2523                         init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2524                         ..
2525                     })) => {
2526                         // When encountering an assignment of an unsized trait, like
2527                         // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2528                         // order to use have a slice instead.
2529                         err.span_suggestion_verbose(
2530                             span.shrink_to_lo(),
2531                             "consider borrowing here",
2532                             "&",
2533                             Applicability::MachineApplicable,
2534                         );
2535                         err.note("all local variables must have a statically known size");
2536                     }
2537                     Some(Node::Param(param)) => {
2538                         err.span_suggestion_verbose(
2539                             param.ty_span.shrink_to_lo(),
2540                             "function arguments must have a statically known size, borrowed types \
2541                             always have a known size",
2542                             "&",
2543                             Applicability::MachineApplicable,
2544                         );
2545                     }
2546                     _ => {
2547                         err.note("all local variables must have a statically known size");
2548                     }
2549                 }
2550                 if !self.tcx.features().unsized_locals {
2551                     err.help("unsized locals are gated as an unstable feature");
2552                 }
2553             }
2554             ObligationCauseCode::SizedArgumentType(sp) => {
2555                 if let Some(span) = sp {
2556                     if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder()
2557                         && let ty::Clause::Trait(trait_pred) = clause
2558                         && let ty::Dynamic(..) = trait_pred.self_ty().kind()
2559                     {
2560                         let span = if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2561                             && snippet.starts_with("dyn ")
2562                         {
2563                             let pos = snippet.len() - snippet[3..].trim_start().len();
2564                             span.with_hi(span.lo() + BytePos(pos as u32))
2565                         } else {
2566                             span.shrink_to_lo()
2567                         };
2568                         err.span_suggestion_verbose(
2569                             span,
2570                             "you can use `impl Trait` as the argument type",
2571                             "impl ".to_string(),
2572                             Applicability::MaybeIncorrect,
2573                         );
2574                     }
2575                     err.span_suggestion_verbose(
2576                         span.shrink_to_lo(),
2577                         "function arguments must have a statically known size, borrowed types \
2578                          always have a known size",
2579                         "&",
2580                         Applicability::MachineApplicable,
2581                     );
2582                 } else {
2583                     err.note("all function arguments must have a statically known size");
2584                 }
2585                 if tcx.sess.opts.unstable_features.is_nightly_build()
2586                     && !self.tcx.features().unsized_fn_params
2587                 {
2588                     err.help("unsized fn params are gated as an unstable feature");
2589                 }
2590             }
2591             ObligationCauseCode::SizedReturnType => {
2592                 err.note("the return type of a function must have a statically known size");
2593             }
2594             ObligationCauseCode::SizedYieldType => {
2595                 err.note("the yield type of a generator must have a statically known size");
2596             }
2597             ObligationCauseCode::SizedBoxType => {
2598                 err.note("the type of a box expression must have a statically known size");
2599             }
2600             ObligationCauseCode::AssignmentLhsSized => {
2601                 err.note("the left-hand-side of an assignment must have a statically known size");
2602             }
2603             ObligationCauseCode::TupleInitializerSized => {
2604                 err.note("tuples must have a statically known size to be initialized");
2605             }
2606             ObligationCauseCode::StructInitializerSized => {
2607                 err.note("structs must have a statically known size to be initialized");
2608             }
2609             ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2610                 match *item {
2611                     AdtKind::Struct => {
2612                         if last {
2613                             err.note(
2614                                 "the last field of a packed struct may only have a \
2615                                 dynamically sized type if it does not need drop to be run",
2616                             );
2617                         } else {
2618                             err.note(
2619                                 "only the last field of a struct may have a dynamically sized type",
2620                             );
2621                         }
2622                     }
2623                     AdtKind::Union => {
2624                         err.note("no field of a union may have a dynamically sized type");
2625                     }
2626                     AdtKind::Enum => {
2627                         err.note("no field of an enum variant may have a dynamically sized type");
2628                     }
2629                 }
2630                 err.help("change the field's type to have a statically known size");
2631                 err.span_suggestion(
2632                     span.shrink_to_lo(),
2633                     "borrowed types always have a statically known size",
2634                     "&",
2635                     Applicability::MachineApplicable,
2636                 );
2637                 err.multipart_suggestion(
2638                     "the `Box` type always has a statically known size and allocates its contents \
2639                      in the heap",
2640                     vec![
2641                         (span.shrink_to_lo(), "Box<".to_string()),
2642                         (span.shrink_to_hi(), ">".to_string()),
2643                     ],
2644                     Applicability::MachineApplicable,
2645                 );
2646             }
2647             ObligationCauseCode::ConstSized => {
2648                 err.note("constant expressions must have a statically known size");
2649             }
2650             ObligationCauseCode::InlineAsmSized => {
2651                 err.note("all inline asm arguments must have a statically known size");
2652             }
2653             ObligationCauseCode::ConstPatternStructural => {
2654                 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2655             }
2656             ObligationCauseCode::SharedStatic => {
2657                 err.note("shared static variables must have a type that implements `Sync`");
2658             }
2659             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2660                 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2661                 let ty = parent_trait_ref.skip_binder().self_ty();
2662                 if parent_trait_ref.references_error() {
2663                     // NOTE(eddyb) this was `.cancel()`, but `err`
2664                     // is borrowed, so we can't fully defuse it.
2665                     err.downgrade_to_delayed_bug();
2666                     return;
2667                 }
2668
2669                 // If the obligation for a tuple is set directly by a Generator or Closure,
2670                 // then the tuple must be the one containing capture types.
2671                 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2672                     false
2673                 } else {
2674                     if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2675                     {
2676                         let parent_trait_ref =
2677                             self.resolve_vars_if_possible(data.parent_trait_pred);
2678                         let nested_ty = parent_trait_ref.skip_binder().self_ty();
2679                         matches!(nested_ty.kind(), ty::Generator(..))
2680                             || matches!(nested_ty.kind(), ty::Closure(..))
2681                     } else {
2682                         false
2683                     }
2684                 };
2685
2686                 let identity_future = tcx.require_lang_item(LangItem::IdentityFuture, None);
2687
2688                 // Don't print the tuple of capture types
2689                 'print: {
2690                     if !is_upvar_tys_infer_tuple {
2691                         let msg = format!("required because it appears within the type `{}`", ty);
2692                         match ty.kind() {
2693                             ty::Adt(def, _) => match self.tcx.opt_item_ident(def.did()) {
2694                                 Some(ident) => err.span_note(ident.span, &msg),
2695                                 None => err.note(&msg),
2696                             },
2697                             ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
2698                                 // Avoid printing the future from `core::future::identity_future`, it's not helpful
2699                                 if tcx.parent(*def_id) == identity_future {
2700                                     break 'print;
2701                                 }
2702
2703                                 // If the previous type is `identity_future`, this is the future generated by the body of an async function.
2704                                 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
2705                                 let is_future = tcx.ty_is_opaque_future(ty);
2706                                 debug!(
2707                                     ?obligated_types,
2708                                     ?is_future,
2709                                     "note_obligation_cause_code: check for async fn"
2710                                 );
2711                                 if is_future
2712                                     && obligated_types.last().map_or(false, |ty| match ty.kind() {
2713                                         ty::Generator(last_def_id, ..) => {
2714                                             tcx.generator_is_async(*last_def_id)
2715                                         }
2716                                         _ => false,
2717                                     })
2718                                 {
2719                                     break 'print;
2720                                 }
2721                                 err.span_note(self.tcx.def_span(def_id), &msg)
2722                             }
2723                             ty::GeneratorWitness(bound_tys) => {
2724                                 use std::fmt::Write;
2725
2726                                 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
2727                                 // Maybe we should just remove this note altogether?
2728                                 // FIXME: only print types which don't meet the trait requirement
2729                                 let mut msg =
2730                                     "required because it captures the following types: ".to_owned();
2731                                 for ty in bound_tys.skip_binder() {
2732                                     write!(msg, "`{}`, ", ty).unwrap();
2733                                 }
2734                                 err.note(msg.trim_end_matches(", "))
2735                             }
2736                             ty::Generator(def_id, _, _) => {
2737                                 let sp = self.tcx.def_span(def_id);
2738
2739                                 // Special-case this to say "async block" instead of `[static generator]`.
2740                                 let kind = tcx.generator_kind(def_id).unwrap().descr();
2741                                 err.span_note(
2742                                     sp,
2743                                     &format!("required because it's used within this {}", kind),
2744                                 )
2745                             }
2746                             ty::Closure(def_id, _) => err.span_note(
2747                                 self.tcx.def_span(def_id),
2748                                 "required because it's used within this closure",
2749                             ),
2750                             _ => err.note(&msg),
2751                         };
2752                     }
2753                 }
2754
2755                 obligated_types.push(ty);
2756
2757                 let parent_predicate = parent_trait_ref;
2758                 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2759                     // #74711: avoid a stack overflow
2760                     ensure_sufficient_stack(|| {
2761                         self.note_obligation_cause_code(
2762                             err,
2763                             parent_predicate,
2764                             param_env,
2765                             &data.parent_code,
2766                             obligated_types,
2767                             seen_requirements,
2768                         )
2769                     });
2770                 } else {
2771                     ensure_sufficient_stack(|| {
2772                         self.note_obligation_cause_code(
2773                             err,
2774                             parent_predicate,
2775                             param_env,
2776                             cause_code.peel_derives(),
2777                             obligated_types,
2778                             seen_requirements,
2779                         )
2780                     });
2781                 }
2782             }
2783             ObligationCauseCode::ImplDerivedObligation(ref data) => {
2784                 let mut parent_trait_pred =
2785                     self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2786                 parent_trait_pred.remap_constness_diag(param_env);
2787                 let parent_def_id = parent_trait_pred.def_id();
2788                 let (self_ty, file) =
2789                     self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2790                 let msg = format!(
2791                     "required for `{self_ty}` to implement `{}`",
2792                     parent_trait_pred.print_modifiers_and_trait_path()
2793                 );
2794                 let mut is_auto_trait = false;
2795                 match self.tcx.hir().get_if_local(data.impl_def_id) {
2796                     Some(Node::Item(hir::Item {
2797                         kind: hir::ItemKind::Trait(is_auto, ..),
2798                         ident,
2799                         ..
2800                     })) => {
2801                         // FIXME: we should do something else so that it works even on crate foreign
2802                         // auto traits.
2803                         is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2804                         err.span_note(ident.span, &msg)
2805                     }
2806                     Some(Node::Item(hir::Item {
2807                         kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2808                         ..
2809                     })) => {
2810                         let mut spans = Vec::with_capacity(2);
2811                         if let Some(trait_ref) = of_trait {
2812                             spans.push(trait_ref.path.span);
2813                         }
2814                         spans.push(self_ty.span);
2815                         err.span_note(spans, &msg)
2816                     }
2817                     _ => err.note(&msg),
2818                 };
2819
2820                 if let Some(file) = file {
2821                     err.note(&format!(
2822                         "the full type name has been written to '{}'",
2823                         file.display(),
2824                     ));
2825                 }
2826                 let mut parent_predicate = parent_trait_pred;
2827                 let mut data = &data.derived;
2828                 let mut count = 0;
2829                 seen_requirements.insert(parent_def_id);
2830                 if is_auto_trait {
2831                     // We don't want to point at the ADT saying "required because it appears within
2832                     // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2833                     while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2834                         &*data.parent_code
2835                     {
2836                         let child_trait_ref =
2837                             self.resolve_vars_if_possible(derived.parent_trait_pred);
2838                         let child_def_id = child_trait_ref.def_id();
2839                         if seen_requirements.insert(child_def_id) {
2840                             break;
2841                         }
2842                         data = derived;
2843                         parent_predicate = child_trait_ref.to_predicate(tcx);
2844                         parent_trait_pred = child_trait_ref;
2845                     }
2846                 }
2847                 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2848                     // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2849                     let child_trait_pred =
2850                         self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2851                     let child_def_id = child_trait_pred.def_id();
2852                     if seen_requirements.insert(child_def_id) {
2853                         break;
2854                     }
2855                     count += 1;
2856                     data = &child.derived;
2857                     parent_predicate = child_trait_pred.to_predicate(tcx);
2858                     parent_trait_pred = child_trait_pred;
2859                 }
2860                 if count > 0 {
2861                     err.note(&format!(
2862                         "{} redundant requirement{} hidden",
2863                         count,
2864                         pluralize!(count)
2865                     ));
2866                     let (self_ty, file) =
2867                         self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2868                     err.note(&format!(
2869                         "required for `{self_ty}` to implement `{}`",
2870                         parent_trait_pred.print_modifiers_and_trait_path()
2871                     ));
2872                     if let Some(file) = file {
2873                         err.note(&format!(
2874                             "the full type name has been written to '{}'",
2875                             file.display(),
2876                         ));
2877                     }
2878                 }
2879                 // #74711: avoid a stack overflow
2880                 ensure_sufficient_stack(|| {
2881                     self.note_obligation_cause_code(
2882                         err,
2883                         parent_predicate,
2884                         param_env,
2885                         &data.parent_code,
2886                         obligated_types,
2887                         seen_requirements,
2888                     )
2889                 });
2890             }
2891             ObligationCauseCode::DerivedObligation(ref data) => {
2892                 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2893                 let parent_predicate = parent_trait_ref;
2894                 // #74711: avoid a stack overflow
2895                 ensure_sufficient_stack(|| {
2896                     self.note_obligation_cause_code(
2897                         err,
2898                         parent_predicate,
2899                         param_env,
2900                         &data.parent_code,
2901                         obligated_types,
2902                         seen_requirements,
2903                     )
2904                 });
2905             }
2906             ObligationCauseCode::FunctionArgumentObligation {
2907                 arg_hir_id,
2908                 call_hir_id,
2909                 ref parent_code,
2910                 ..
2911             } => {
2912                 self.function_argument_obligation(
2913                     arg_hir_id,
2914                     err,
2915                     parent_code,
2916                     param_env,
2917                     predicate,
2918                     call_hir_id,
2919                 );
2920                 ensure_sufficient_stack(|| {
2921                     self.note_obligation_cause_code(
2922                         err,
2923                         predicate,
2924                         param_env,
2925                         &parent_code,
2926                         obligated_types,
2927                         seen_requirements,
2928                     )
2929                 });
2930             }
2931             ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
2932                 let item_name = self.tcx.item_name(trait_item_def_id);
2933                 let msg = format!(
2934                     "the requirement `{predicate}` appears on the `impl`'s {kind} \
2935                      `{item_name}` but not on the corresponding trait's {kind}",
2936                 );
2937                 let sp = self
2938                     .tcx
2939                     .opt_item_ident(trait_item_def_id)
2940                     .map(|i| i.span)
2941                     .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2942                 let mut assoc_span: MultiSpan = sp.into();
2943                 assoc_span.push_span_label(
2944                     sp,
2945                     format!("this trait's {kind} doesn't have the requirement `{predicate}`"),
2946                 );
2947                 if let Some(ident) = self
2948                     .tcx
2949                     .opt_associated_item(trait_item_def_id)
2950                     .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
2951                 {
2952                     assoc_span.push_span_label(ident.span, "in this trait");
2953                 }
2954                 err.span_note(assoc_span, &msg);
2955             }
2956             ObligationCauseCode::TrivialBound => {
2957                 err.help("see issue #48214");
2958                 if tcx.sess.opts.unstable_features.is_nightly_build() {
2959                     err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2960                 }
2961             }
2962             ObligationCauseCode::OpaqueReturnType(expr_info) => {
2963                 if let Some((expr_ty, expr_span)) = expr_info {
2964                     let expr_ty = with_forced_trimmed_paths!(self.ty_to_string(expr_ty));
2965                     err.span_label(
2966                         expr_span,
2967                         format!("return type was inferred to be `{expr_ty}` here"),
2968                     );
2969                 }
2970             }
2971         }
2972     }
2973
2974     #[instrument(
2975         level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
2976     )]
2977     fn suggest_await_before_try(
2978         &self,
2979         err: &mut Diagnostic,
2980         obligation: &PredicateObligation<'tcx>,
2981         trait_pred: ty::PolyTraitPredicate<'tcx>,
2982         span: Span,
2983     ) {
2984         let body_hir_id = obligation.cause.body_id;
2985         let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2986
2987         if let Some(body_id) =
2988             self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id))
2989         {
2990             let body = self.tcx.hir().body(body_id);
2991             if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2992                 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2993
2994                 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
2995                 let impls_future = self.type_implements_trait(
2996                     future_trait,
2997                     [self.tcx.erase_late_bound_regions(self_ty)],
2998                     obligation.param_env,
2999                 );
3000                 if !impls_future.must_apply_modulo_regions() {
3001                     return;
3002                 }
3003
3004                 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
3005                 // `<T as Future>::Output`
3006                 let projection_ty = trait_pred.map_bound(|trait_pred| {
3007                     self.tcx.mk_projection(
3008                         item_def_id,
3009                         // Future::Output has no substs
3010                         [trait_pred.self_ty()],
3011                     )
3012                 });
3013                 let InferOk { value: projection_ty, .. } =
3014                     self.at(&obligation.cause, obligation.param_env).normalize(projection_ty);
3015
3016                 debug!(
3017                     normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
3018                 );
3019                 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
3020                     obligation.param_env,
3021                     trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
3022                 );
3023                 debug!(try_trait_obligation = ?try_obligation);
3024                 if self.predicate_may_hold(&try_obligation)
3025                     && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
3026                     && snippet.ends_with('?')
3027                 {
3028                     err.span_suggestion_verbose(
3029                         span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
3030                         "consider `await`ing on the `Future`",
3031                         ".await",
3032                         Applicability::MaybeIncorrect,
3033                     );
3034                 }
3035             }
3036         }
3037     }
3038
3039     fn suggest_floating_point_literal(
3040         &self,
3041         obligation: &PredicateObligation<'tcx>,
3042         err: &mut Diagnostic,
3043         trait_ref: &ty::PolyTraitRef<'tcx>,
3044     ) {
3045         let rhs_span = match obligation.cause.code() {
3046             ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
3047             _ => return,
3048         };
3049         if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind()
3050             && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind()
3051         {
3052             err.span_suggestion_verbose(
3053                 rhs_span.shrink_to_hi(),
3054                 "consider using a floating-point literal by writing it with `.0`",
3055                 ".0",
3056                 Applicability::MaybeIncorrect,
3057             );
3058         }
3059     }
3060
3061     fn suggest_derive(
3062         &self,
3063         obligation: &PredicateObligation<'tcx>,
3064         err: &mut Diagnostic,
3065         trait_pred: ty::PolyTraitPredicate<'tcx>,
3066     ) {
3067         let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3068             return;
3069         };
3070         let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
3071             ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
3072             _ => return,
3073         };
3074         let can_derive = {
3075             let is_derivable_trait = match diagnostic_name {
3076                 sym::Default => !adt.is_enum(),
3077                 sym::PartialEq | sym::PartialOrd => {
3078                     let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
3079                     trait_pred.skip_binder().self_ty() == rhs_ty
3080                 }
3081                 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3082                 _ => false,
3083             };
3084             is_derivable_trait &&
3085                 // Ensure all fields impl the trait.
3086                 adt.all_fields().all(|field| {
3087                     let field_ty = field.ty(self.tcx, substs);
3088                     let trait_substs = match diagnostic_name {
3089                         sym::PartialEq | sym::PartialOrd => {
3090                             Some(field_ty)
3091                         }
3092                         _ => None,
3093                     };
3094                     let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3095                         trait_ref: self.tcx.mk_trait_ref(
3096                             trait_pred.def_id(),
3097                             [field_ty].into_iter().chain(trait_substs),
3098                         ),
3099                         ..*tr
3100                     });
3101                     let field_obl = Obligation::new(
3102                         self.tcx,
3103                         obligation.cause.clone(),
3104                         obligation.param_env,
3105                         trait_pred,
3106                     );
3107                     self.predicate_must_hold_modulo_regions(&field_obl)
3108                 })
3109         };
3110         if can_derive {
3111             err.span_suggestion_verbose(
3112                 self.tcx.def_span(adt.did()).shrink_to_lo(),
3113                 &format!(
3114                     "consider annotating `{}` with `#[derive({})]`",
3115                     trait_pred.skip_binder().self_ty(),
3116                     diagnostic_name,
3117                 ),
3118                 format!("#[derive({})]\n", diagnostic_name),
3119                 Applicability::MaybeIncorrect,
3120             );
3121         }
3122     }
3123
3124     fn suggest_dereferencing_index(
3125         &self,
3126         obligation: &PredicateObligation<'tcx>,
3127         err: &mut Diagnostic,
3128         trait_pred: ty::PolyTraitPredicate<'tcx>,
3129     ) {
3130         if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
3131             && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3132             && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
3133             && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3134             && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3135         {
3136             err.span_suggestion_verbose(
3137                 obligation.cause.span.shrink_to_lo(),
3138             "dereference this index",
3139             '*',
3140                 Applicability::MachineApplicable,
3141             );
3142         }
3143     }
3144     fn function_argument_obligation(
3145         &self,
3146         arg_hir_id: HirId,
3147         err: &mut Diagnostic,
3148         parent_code: &ObligationCauseCode<'tcx>,
3149         param_env: ty::ParamEnv<'tcx>,
3150         failed_pred: ty::Predicate<'tcx>,
3151         call_hir_id: HirId,
3152     ) {
3153         let tcx = self.tcx;
3154         let hir = tcx.hir();
3155         if let Some(Node::Expr(expr)) = hir.find(arg_hir_id) {
3156             let parent_id = hir.get_parent_item(arg_hir_id);
3157             let typeck_results: &TypeckResults<'tcx> = match &self.typeck_results {
3158                 Some(t) if t.hir_owner == parent_id => t,
3159                 _ => self.tcx.typeck(parent_id.def_id),
3160             };
3161             if let hir::Expr { kind: hir::ExprKind::Block(..), .. } = expr {
3162                 let expr = expr.peel_blocks();
3163                 let ty = typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error());
3164                 let span = expr.span;
3165                 if Some(span) != err.span.primary_span() {
3166                     err.span_label(
3167                         span,
3168                         if ty.references_error() {
3169                             String::new()
3170                         } else {
3171                             let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3172                             format!("this tail expression is of type `{ty}`")
3173                         },
3174                     );
3175                 }
3176             }
3177
3178             // FIXME: visit the ty to see if there's any closure involved, and if there is,
3179             // check whether its evaluated return type is the same as the one corresponding
3180             // to an associated type (as seen from `trait_pred`) in the predicate. Like in
3181             // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
3182             let mut type_diffs = vec![];
3183
3184             if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = parent_code.deref()
3185                 && let Some(node_substs) = typeck_results.node_substs_opt(call_hir_id)
3186                 && let where_clauses = self.tcx.predicates_of(def_id).instantiate(self.tcx, node_substs)
3187                 && let Some(where_pred) = where_clauses.predicates.get(*idx)
3188             {
3189                 if let Some(where_pred) = where_pred.to_opt_poly_trait_pred()
3190                     && let Some(failed_pred) = failed_pred.to_opt_poly_trait_pred()
3191                 {
3192                     let mut c = CollectAllMismatches {
3193                         infcx: self.infcx,
3194                         param_env,
3195                         errors: vec![],
3196                     };
3197                     if let Ok(_) = c.relate(where_pred, failed_pred) {
3198                         type_diffs = c.errors;
3199                     }
3200                 } else if let Some(where_pred) = where_pred.to_opt_poly_projection_pred()
3201                     && let Some(failed_pred) = failed_pred.to_opt_poly_projection_pred()
3202                     && let Some(found) = failed_pred.skip_binder().term.ty()
3203                 {
3204                     type_diffs = vec![
3205                         Sorts(ty::error::ExpectedFound {
3206                             expected: self.tcx.mk_ty(ty::Alias(ty::Projection, where_pred.skip_binder().projection_ty)),
3207                             found,
3208                         }),
3209                     ];
3210                 }
3211             }
3212             if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3213                 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3214                 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3215                 && let parent_hir_id = self.tcx.hir().get_parent_node(binding.hir_id)
3216                 && let Some(hir::Node::Local(local)) = self.tcx.hir().find(parent_hir_id)
3217                 && let Some(binding_expr) = local.init
3218             {
3219                 // If the expression we're calling on is a binding, we want to point at the
3220                 // `let` when talking about the type. Otherwise we'll point at every part
3221                 // of the method chain with the type.
3222                 self.point_at_chain(binding_expr, typeck_results, type_diffs, param_env, err);
3223             } else {
3224                 self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
3225             }
3226         }
3227         let call_node = hir.find(call_hir_id);
3228         if let Some(Node::Expr(hir::Expr {
3229             kind: hir::ExprKind::MethodCall(path, rcvr, ..), ..
3230         })) = call_node
3231         {
3232             if Some(rcvr.span) == err.span.primary_span() {
3233                 err.replace_span_with(path.ident.span);
3234             }
3235         }
3236         if let Some(Node::Expr(hir::Expr {
3237             kind:
3238                 hir::ExprKind::Call(hir::Expr { span, .. }, _)
3239                 | hir::ExprKind::MethodCall(hir::PathSegment { ident: Ident { span, .. }, .. }, ..),
3240             ..
3241         })) = hir.find(call_hir_id)
3242         {
3243             if Some(*span) != err.span.primary_span() {
3244                 err.span_label(*span, "required by a bound introduced by this call");
3245             }
3246         }
3247     }
3248
3249     fn point_at_chain(
3250         &self,
3251         expr: &hir::Expr<'_>,
3252         typeck_results: &TypeckResults<'tcx>,
3253         type_diffs: Vec<TypeError<'tcx>>,
3254         param_env: ty::ParamEnv<'tcx>,
3255         err: &mut Diagnostic,
3256     ) {
3257         let mut primary_spans = vec![];
3258         let mut span_labels = vec![];
3259
3260         let tcx = self.tcx;
3261
3262         let mut print_root_expr = true;
3263         let mut assocs = vec![];
3264         let mut expr = expr;
3265         let mut prev_ty = self.resolve_vars_if_possible(
3266             typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3267         );
3268         while let hir::ExprKind::MethodCall(_path_segment, rcvr_expr, _args, span) = expr.kind {
3269             // Point at every method call in the chain with the resulting type.
3270             // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3271             //               ^^^^^^ ^^^^^^^^^^^
3272             expr = rcvr_expr;
3273             let assocs_in_this_method =
3274                 self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
3275             assocs.push(assocs_in_this_method);
3276             prev_ty = self.resolve_vars_if_possible(
3277                 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3278             );
3279
3280             if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3281                 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3282                 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3283                 && let parent_hir_id = self.tcx.hir().get_parent_node(binding.hir_id)
3284                 && let Some(parent) = self.tcx.hir().find(parent_hir_id)
3285             {
3286                 // We've reached the root of the method call chain...
3287                 if let hir::Node::Local(local) = parent
3288                     && let Some(binding_expr) = local.init
3289                 {
3290                     // ...and it is a binding. Get the binding creation and continue the chain.
3291                     expr = binding_expr;
3292                 }
3293                 if let hir::Node::Param(param) = parent {
3294                     // ...and it is a an fn argument.
3295                     let prev_ty = self.resolve_vars_if_possible(
3296                         typeck_results.node_type_opt(param.hir_id).unwrap_or(tcx.ty_error()),
3297                     );
3298                     let assocs_in_this_method = self.probe_assoc_types_at_expr(&type_diffs, param.ty_span, prev_ty, param.hir_id, param_env);
3299                     if assocs_in_this_method.iter().any(|a| a.is_some()) {
3300                         assocs.push(assocs_in_this_method);
3301                         print_root_expr = false;
3302                     }
3303                     break;
3304                 }
3305             }
3306         }
3307         // We want the type before deref coercions, otherwise we talk about `&[_]`
3308         // instead of `Vec<_>`.
3309         if let Some(ty) = typeck_results.expr_ty_opt(expr) && print_root_expr {
3310             let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3311             // Point at the root expression
3312             // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3313             // ^^^^^^^^^^^^^
3314             span_labels.push((expr.span, format!("this expression has type `{ty}`")));
3315         };
3316         // Only show this if it is not a "trivial" expression (not a method
3317         // chain) and there are associated types to talk about.
3318         let mut assocs = assocs.into_iter().peekable();
3319         while let Some(assocs_in_method) = assocs.next() {
3320             let Some(prev_assoc_in_method) = assocs.peek() else {
3321                 for entry in assocs_in_method {
3322                     let Some((span, (assoc, ty))) = entry else { continue; };
3323                     if primary_spans.is_empty() || type_diffs.iter().any(|diff| {
3324                         let Sorts(expected_found) = diff else { return false; };
3325                         self.can_eq(param_env, expected_found.found, ty).is_ok()
3326                     }) {
3327                         // FIXME: this doesn't quite work for `Iterator::collect`
3328                         // because we have `Vec<i32>` and `()`, but we'd want `i32`
3329                         // to point at the `.into_iter()` call, but as long as we
3330                         // still point at the other method calls that might have
3331                         // introduced the issue, this is fine for now.
3332                         primary_spans.push(span);
3333                     }
3334                     span_labels.push((
3335                         span,
3336                         with_forced_trimmed_paths!(format!(
3337                             "`{}` is `{ty}` here",
3338                             self.tcx.def_path_str(assoc),
3339                         )),
3340                     ));
3341                 }
3342                 break;
3343             };
3344             for (entry, prev_entry) in
3345                 assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
3346             {
3347                 match (entry, prev_entry) {
3348                     (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
3349                         let ty_str = with_forced_trimmed_paths!(self.ty_to_string(ty));
3350
3351                         let assoc = with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
3352                         if self.can_eq(param_env, ty, *prev_ty).is_err() {
3353                             if type_diffs.iter().any(|diff| {
3354                                 let Sorts(expected_found) = diff else { return false; };
3355                                 self.can_eq(param_env, expected_found.found, ty).is_ok()
3356                             }) {
3357                                 primary_spans.push(span);
3358                             }
3359                             span_labels
3360                                 .push((span, format!("`{assoc}` changed to `{ty_str}` here")));
3361                         } else {
3362                             span_labels.push((span, format!("`{assoc}` remains `{ty_str}` here")));
3363                         }
3364                     }
3365                     (Some((span, (assoc, ty))), None) => {
3366                         span_labels.push((
3367                             span,
3368                             with_forced_trimmed_paths!(format!(
3369                                 "`{}` is `{}` here",
3370                                 self.tcx.def_path_str(assoc),
3371                                 self.ty_to_string(ty),
3372                             )),
3373                         ));
3374                     }
3375                     (None, Some(_)) | (None, None) => {}
3376                 }
3377             }
3378         }
3379         if !primary_spans.is_empty() {
3380             let mut multi_span: MultiSpan = primary_spans.into();
3381             for (span, label) in span_labels {
3382                 multi_span.push_span_label(span, label);
3383             }
3384             err.span_note(
3385                 multi_span,
3386                 "the method call chain might not have had the expected associated types",
3387             );
3388         }
3389     }
3390
3391     fn probe_assoc_types_at_expr(
3392         &self,
3393         type_diffs: &[TypeError<'tcx>],
3394         span: Span,
3395         prev_ty: Ty<'tcx>,
3396         body_id: hir::HirId,
3397         param_env: ty::ParamEnv<'tcx>,
3398     ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
3399         let ocx = ObligationCtxt::new_in_snapshot(self.infcx);
3400         let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
3401         for diff in type_diffs {
3402             let Sorts(expected_found) = diff else { continue; };
3403             let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else { continue; };
3404
3405             let origin = TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span };
3406             let trait_def_id = proj.trait_def_id(self.tcx);
3407             // Make `Self` be equivalent to the type of the call chain
3408             // expression we're looking at now, so that we can tell what
3409             // for example `Iterator::Item` is at this point in the chain.
3410             let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
3411                 match param.kind {
3412                     ty::GenericParamDefKind::Type { .. } => {
3413                         if param.index == 0 {
3414                             return prev_ty.into();
3415                         }
3416                     }
3417                     ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Const { .. } => {}
3418                 }
3419                 self.var_for_def(span, param)
3420             });
3421             // This will hold the resolved type of the associated type, if the
3422             // current expression implements the trait that associated type is
3423             // in. For example, this would be what `Iterator::Item` is here.
3424             let ty_var = self.infcx.next_ty_var(origin);
3425             // This corresponds to `<ExprTy as Iterator>::Item = _`.
3426             let projection = ty::Binder::dummy(ty::PredicateKind::Clause(ty::Clause::Projection(
3427                 ty::ProjectionPredicate {
3428                     projection_ty: self.tcx.mk_alias_ty(proj.def_id, substs),
3429                     term: ty_var.into(),
3430                 },
3431             )));
3432             // Add `<ExprTy as Iterator>::Item = _` obligation.
3433             ocx.register_obligation(Obligation::misc(
3434                 self.tcx, span, body_id, param_env, projection,
3435             ));
3436             if ocx.select_where_possible().is_empty() {
3437                 // `ty_var` now holds the type that `Item` is for `ExprTy`.
3438                 let ty_var = self.resolve_vars_if_possible(ty_var);
3439                 assocs_in_this_method.push(Some((span, (proj.def_id, ty_var))));
3440             } else {
3441                 // `<ExprTy as Iterator>` didn't select, so likely we've
3442                 // reached the end of the iterator chain, like the originating
3443                 // `Vec<_>`.
3444                 // Keep the space consistent for later zipping.
3445                 assocs_in_this_method.push(None);
3446             }
3447         }
3448         assocs_in_this_method
3449     }
3450 }
3451
3452 /// Add a hint to add a missing borrow or remove an unnecessary one.
3453 fn hint_missing_borrow<'tcx>(
3454     span: Span,
3455     found: Ty<'tcx>,
3456     expected: Ty<'tcx>,
3457     found_node: Node<'_>,
3458     err: &mut Diagnostic,
3459 ) {
3460     let found_args = match found.kind() {
3461         ty::FnPtr(f) => f.inputs().skip_binder().iter(),
3462         kind => {
3463             span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
3464         }
3465     };
3466     let expected_args = match expected.kind() {
3467         ty::FnPtr(f) => f.inputs().skip_binder().iter(),
3468         kind => {
3469             span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
3470         }
3471     };
3472
3473     // This could be a variant constructor, for example.
3474     let Some(fn_decl) = found_node.fn_decl() else { return; };
3475
3476     let arg_spans = fn_decl.inputs.iter().map(|ty| ty.span);
3477
3478     fn get_deref_type_and_refs<'tcx>(mut ty: Ty<'tcx>) -> (Ty<'tcx>, usize) {
3479         let mut refs = 0;
3480
3481         while let ty::Ref(_, new_ty, _) = ty.kind() {
3482             ty = *new_ty;
3483             refs += 1;
3484         }
3485
3486         (ty, refs)
3487     }
3488
3489     let mut to_borrow = Vec::new();
3490     let mut remove_borrow = Vec::new();
3491
3492     for ((found_arg, expected_arg), arg_span) in found_args.zip(expected_args).zip(arg_spans) {
3493         let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
3494         let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
3495
3496         if found_ty == expected_ty {
3497             if found_refs < expected_refs {
3498                 to_borrow.push((arg_span, expected_arg.to_string()));
3499             } else if found_refs > expected_refs {
3500                 remove_borrow.push((arg_span, expected_arg.to_string()));
3501             }
3502         }
3503     }
3504
3505     if !to_borrow.is_empty() {
3506         err.multipart_suggestion(
3507             "consider borrowing the argument",
3508             to_borrow,
3509             Applicability::MaybeIncorrect,
3510         );
3511     }
3512
3513     if !remove_borrow.is_empty() {
3514         err.multipart_suggestion(
3515             "do not borrow the argument",
3516             remove_borrow,
3517             Applicability::MaybeIncorrect,
3518         );
3519     }
3520 }
3521
3522 /// Collect all the returned expressions within the input expression.
3523 /// Used to point at the return spans when we want to suggest some change to them.
3524 #[derive(Default)]
3525 pub struct ReturnsVisitor<'v> {
3526     pub returns: Vec<&'v hir::Expr<'v>>,
3527     in_block_tail: bool,
3528 }
3529
3530 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3531     fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3532         // Visit every expression to detect `return` paths, either through the function's tail
3533         // expression or `return` statements. We walk all nodes to find `return` statements, but
3534         // we only care about tail expressions when `in_block_tail` is `true`, which means that
3535         // they're in the return path of the function body.
3536         match ex.kind {
3537             hir::ExprKind::Ret(Some(ex)) => {
3538                 self.returns.push(ex);
3539             }
3540             hir::ExprKind::Block(block, _) if self.in_block_tail => {
3541                 self.in_block_tail = false;
3542                 for stmt in block.stmts {
3543                     hir::intravisit::walk_stmt(self, stmt);
3544                 }
3545                 self.in_block_tail = true;
3546                 if let Some(expr) = block.expr {
3547                     self.visit_expr(expr);
3548                 }
3549             }
3550             hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3551                 self.visit_expr(then);
3552                 if let Some(el) = else_opt {
3553                     self.visit_expr(el);
3554                 }
3555             }
3556             hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3557                 for arm in arms {
3558                     self.visit_expr(arm.body);
3559                 }
3560             }
3561             // We need to walk to find `return`s in the entire body.
3562             _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3563             _ => self.returns.push(ex),
3564         }
3565     }
3566
3567     fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3568         assert!(!self.in_block_tail);
3569         if body.generator_kind().is_none() {
3570             if let hir::ExprKind::Block(block, None) = body.value.kind {
3571                 if block.expr.is_some() {
3572                     self.in_block_tail = true;
3573                 }
3574             }
3575         }
3576         hir::intravisit::walk_body(self, body);
3577     }
3578 }
3579
3580 /// Collect all the awaited expressions within the input expression.
3581 #[derive(Default)]
3582 struct AwaitsVisitor {
3583     awaits: Vec<hir::HirId>,
3584 }
3585
3586 impl<'v> Visitor<'v> for AwaitsVisitor {
3587     fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3588         if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3589             self.awaits.push(id)
3590         }
3591         hir::intravisit::walk_expr(self, ex)
3592     }
3593 }
3594
3595 pub trait NextTypeParamName {
3596     fn next_type_param_name(&self, name: Option<&str>) -> String;
3597 }
3598
3599 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3600     fn next_type_param_name(&self, name: Option<&str>) -> String {
3601         // This is the list of possible parameter names that we might suggest.
3602         let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3603         let name = name.as_deref();
3604         let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3605         let used_names = self
3606             .iter()
3607             .filter_map(|p| match p.name {
3608                 hir::ParamName::Plain(ident) => Some(ident.name),
3609                 _ => None,
3610             })
3611             .collect::<Vec<_>>();
3612
3613         possible_names
3614             .iter()
3615             .find(|n| !used_names.contains(&Symbol::intern(n)))
3616             .unwrap_or(&"ParamName")
3617             .to_string()
3618     }
3619 }
3620
3621 fn suggest_trait_object_return_type_alternatives(
3622     err: &mut Diagnostic,
3623     ret_ty: Span,
3624     trait_obj: &str,
3625     is_object_safe: bool,
3626 ) {
3627     err.span_suggestion(
3628         ret_ty,
3629         &format!(
3630             "use `impl {}` as the return type if all return paths have the same type but you \
3631                 want to expose only the trait in the signature",
3632             trait_obj,
3633         ),
3634         format!("impl {}", trait_obj),
3635         Applicability::MaybeIncorrect,
3636     );
3637     if is_object_safe {
3638         err.multipart_suggestion(
3639             &format!(
3640                 "use a boxed trait object if all return paths implement trait `{}`",
3641                 trait_obj,
3642             ),
3643             vec![
3644                 (ret_ty.shrink_to_lo(), "Box<".to_string()),
3645                 (ret_ty.shrink_to_hi(), ">".to_string()),
3646             ],
3647             Applicability::MaybeIncorrect,
3648         );
3649     }
3650 }
3651
3652 /// Collect the spans that we see the generic param `param_did`
3653 struct ReplaceImplTraitVisitor<'a> {
3654     ty_spans: &'a mut Vec<Span>,
3655     param_did: DefId,
3656 }
3657
3658 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
3659     fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
3660         if let hir::TyKind::Path(hir::QPath::Resolved(
3661             None,
3662             hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
3663         )) = t.kind
3664         {
3665             if self.param_did == *segment_did {
3666                 // `fn foo(t: impl Trait)`
3667                 //            ^^^^^^^^^^ get this to suggest `T` instead
3668
3669                 // There might be more than one `impl Trait`.
3670                 self.ty_spans.push(t.span);
3671                 return;
3672             }
3673         }
3674
3675         hir::intravisit::walk_ty(self, t);
3676     }
3677 }
3678
3679 // Replace `param` with `replace_ty`
3680 struct ReplaceImplTraitFolder<'tcx> {
3681     tcx: TyCtxt<'tcx>,
3682     param: &'tcx ty::GenericParamDef,
3683     replace_ty: Ty<'tcx>,
3684 }
3685
3686 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
3687     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3688         if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
3689             if self.param.index == *index {
3690                 return self.replace_ty;
3691             }
3692         }
3693         t.super_fold_with(self)
3694     }
3695
3696     fn tcx(&self) -> TyCtxt<'tcx> {
3697         self.tcx
3698     }
3699 }