]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs
b369c733871987970bed819e3416d524f5444187
[rust.git] / compiler / rustc_trait_selection / src / traits / error_reporting / suggestions.rs
1 use super::{
2     DerivedObligationCause, EvaluationResult, ImplDerivedObligationCause, Obligation,
3     ObligationCause, ObligationCauseCode, PredicateObligation, SelectionContext,
4 };
5
6 use crate::autoderef::Autoderef;
7 use crate::infer::InferCtxt;
8 use crate::traits::normalize_projection_type;
9
10 use rustc_data_structures::fx::FxHashSet;
11 use rustc_data_structures::stack::ensure_sufficient_stack;
12 use rustc_errors::{
13     error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
14     ErrorGuaranteed, Style,
15 };
16 use rustc_hir as hir;
17 use rustc_hir::def::DefKind;
18 use rustc_hir::def_id::DefId;
19 use rustc_hir::intravisit::Visitor;
20 use rustc_hir::lang_items::LangItem;
21 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
22 use rustc_middle::ty::{
23     self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
24     Infer, InferTy, ToPredicate, Ty, TyCtxt, TypeFoldable,
25 };
26 use rustc_middle::ty::{TypeAndMut, TypeckResults};
27 use rustc_session::Limit;
28 use rustc_span::def_id::LOCAL_CRATE;
29 use rustc_span::symbol::{kw, sym, Ident, Symbol};
30 use rustc_span::{BytePos, DesugaringKind, ExpnKind, MultiSpan, Span, DUMMY_SP};
31 use rustc_target::spec::abi;
32 use std::fmt;
33
34 use super::InferCtxtPrivExt;
35 use crate::infer::InferCtxtExt as _;
36 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
37 use rustc_middle::ty::print::with_no_trimmed_paths;
38
39 #[derive(Debug)]
40 pub enum GeneratorInteriorOrUpvar {
41     // span of interior type
42     Interior(Span),
43     // span of upvar
44     Upvar(Span),
45 }
46
47 // This trait is public to expose the diagnostics methods to clippy.
48 pub trait InferCtxtExt<'tcx> {
49     fn suggest_restricting_param_bound(
50         &self,
51         err: &mut Diagnostic,
52         trait_pred: ty::PolyTraitPredicate<'tcx>,
53         body_id: hir::HirId,
54     );
55
56     fn suggest_dereferences(
57         &self,
58         obligation: &PredicateObligation<'tcx>,
59         err: &mut Diagnostic,
60         trait_pred: ty::PolyTraitPredicate<'tcx>,
61     ) -> bool;
62
63     fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<String>;
64
65     fn suggest_fn_call(
66         &self,
67         obligation: &PredicateObligation<'tcx>,
68         err: &mut Diagnostic,
69         trait_pred: ty::PolyTraitPredicate<'tcx>,
70     ) -> bool;
71
72     fn suggest_add_reference_to_arg(
73         &self,
74         obligation: &PredicateObligation<'tcx>,
75         err: &mut Diagnostic,
76         trait_pred: ty::PolyTraitPredicate<'tcx>,
77         has_custom_message: bool,
78     ) -> bool;
79
80     fn suggest_remove_reference(
81         &self,
82         obligation: &PredicateObligation<'tcx>,
83         err: &mut Diagnostic,
84         trait_pred: ty::PolyTraitPredicate<'tcx>,
85     ) -> bool;
86
87     fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
88
89     fn suggest_change_mut(
90         &self,
91         obligation: &PredicateObligation<'tcx>,
92         err: &mut Diagnostic,
93         trait_pred: ty::PolyTraitPredicate<'tcx>,
94     );
95
96     fn suggest_semicolon_removal(
97         &self,
98         obligation: &PredicateObligation<'tcx>,
99         err: &mut Diagnostic,
100         span: Span,
101         trait_pred: ty::PolyTraitPredicate<'tcx>,
102     ) -> bool;
103
104     fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
105
106     fn suggest_impl_trait(
107         &self,
108         err: &mut Diagnostic,
109         span: Span,
110         obligation: &PredicateObligation<'tcx>,
111         trait_pred: ty::PolyTraitPredicate<'tcx>,
112     ) -> bool;
113
114     fn point_at_returns_when_relevant(
115         &self,
116         err: &mut Diagnostic,
117         obligation: &PredicateObligation<'tcx>,
118     );
119
120     fn report_closure_arg_mismatch(
121         &self,
122         span: Span,
123         found_span: Option<Span>,
124         expected_ref: ty::PolyTraitRef<'tcx>,
125         found: ty::PolyTraitRef<'tcx>,
126     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
127
128     fn suggest_fully_qualified_path(
129         &self,
130         err: &mut Diagnostic,
131         item_def_id: DefId,
132         span: Span,
133         trait_ref: DefId,
134     );
135
136     fn maybe_note_obligation_cause_for_async_await(
137         &self,
138         err: &mut Diagnostic,
139         obligation: &PredicateObligation<'tcx>,
140     ) -> bool;
141
142     fn note_obligation_cause_for_async_await(
143         &self,
144         err: &mut Diagnostic,
145         interior_or_upvar_span: GeneratorInteriorOrUpvar,
146         interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
147         inner_generator_body: Option<&hir::Body<'tcx>>,
148         outer_generator: Option<DefId>,
149         trait_pred: ty::TraitPredicate<'tcx>,
150         target_ty: Ty<'tcx>,
151         typeck_results: Option<&ty::TypeckResults<'tcx>>,
152         obligation: &PredicateObligation<'tcx>,
153         next_code: Option<&ObligationCauseCode<'tcx>>,
154     );
155
156     fn note_obligation_cause_code<T>(
157         &self,
158         err: &mut Diagnostic,
159         predicate: &T,
160         param_env: ty::ParamEnv<'tcx>,
161         cause_code: &ObligationCauseCode<'tcx>,
162         obligated_types: &mut Vec<Ty<'tcx>>,
163         seen_requirements: &mut FxHashSet<DefId>,
164     ) where
165         T: fmt::Display;
166
167     fn suggest_new_overflow_limit(&self, err: &mut Diagnostic);
168
169     /// Suggest to await before try: future? => future.await?
170     fn suggest_await_before_try(
171         &self,
172         err: &mut Diagnostic,
173         obligation: &PredicateObligation<'tcx>,
174         trait_pred: ty::PolyTraitPredicate<'tcx>,
175         span: Span,
176     );
177
178     fn suggest_floating_point_literal(
179         &self,
180         obligation: &PredicateObligation<'tcx>,
181         err: &mut Diagnostic,
182         trait_ref: &ty::PolyTraitRef<'tcx>,
183     );
184 }
185
186 fn predicate_constraint(generics: &hir::Generics<'_>, pred: String) -> (Span, String) {
187     (
188         generics.where_clause.tail_span_for_suggestion(),
189         format!(
190             "{} {}",
191             if !generics.where_clause.predicates.is_empty() { "," } else { " where" },
192             pred,
193         ),
194     )
195 }
196
197 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
198 /// it can also be an `impl Trait` param that needs to be decomposed to a type
199 /// param for cleaner code.
200 fn suggest_restriction<'tcx>(
201     tcx: TyCtxt<'tcx>,
202     generics: &hir::Generics<'tcx>,
203     msg: &str,
204     err: &mut Diagnostic,
205     fn_sig: Option<&hir::FnSig<'_>>,
206     projection: Option<&ty::ProjectionTy<'_>>,
207     trait_pred: ty::PolyTraitPredicate<'tcx>,
208     super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
209 ) {
210     // When we are dealing with a trait, `super_traits` will be `Some`:
211     // Given `trait T: A + B + C {}`
212     //              -  ^^^^^^^^^ GenericBounds
213     //              |
214     //              &Ident
215     let span = generics.where_clause.span_for_predicates_or_empty_place();
216     if span.from_expansion() || span.desugaring_kind().is_some() {
217         return;
218     }
219     // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
220     if let Some((bound_str, fn_sig)) =
221         fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
222             // Shenanigans to get the `Trait` from the `impl Trait`.
223             ty::Param(param) => {
224                 // `fn foo(t: impl Trait)`
225                 //                 ^^^^^ get this string
226                 param.name.as_str().strip_prefix("impl").map(|s| (s.trim_start().to_string(), sig))
227             }
228             _ => None,
229         })
230     {
231         // We know we have an `impl Trait` that doesn't satisfy a required projection.
232
233         // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
234         // types. There should be at least one, but there might be *more* than one. In that
235         // case we could just ignore it and try to identify which one needs the restriction,
236         // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
237         // where `T: Trait`.
238         let mut ty_spans = vec![];
239         let impl_trait_str = format!("impl {}", bound_str);
240         for input in fn_sig.decl.inputs {
241             if let hir::TyKind::Path(hir::QPath::Resolved(
242                 None,
243                 hir::Path { segments: [segment], .. },
244             )) = input.kind
245             {
246                 if segment.ident.as_str() == impl_trait_str.as_str() {
247                     // `fn foo(t: impl Trait)`
248                     //            ^^^^^^^^^^ get this to suggest `T` instead
249
250                     // There might be more than one `impl Trait`.
251                     ty_spans.push(input.span);
252                 }
253             }
254         }
255
256         let type_param_name = generics.params.next_type_param_name(Some(&bound_str));
257         // The type param `T: Trait` we will suggest to introduce.
258         let type_param = format!("{}: {}", type_param_name, bound_str);
259
260         // FIXME: modify the `trait_pred` instead of string shenanigans.
261         // Turn `<impl Trait as Foo>::Bar: Qux` into `<T as Foo>::Bar: Qux`.
262         let pred = trait_pred.to_predicate(tcx).to_string();
263         let pred = pred.replace(&impl_trait_str, &type_param_name);
264         let mut sugg = vec![
265             // Find the last of the generic parameters contained within the span of
266             // the generics
267             match generics
268                 .params
269                 .iter()
270                 .map(|p| p.bounds_span_for_suggestions().unwrap_or(p.span.shrink_to_hi()))
271                 .filter(|&span| generics.span.contains(span) && span.can_be_used_for_suggestions())
272                 .max_by_key(|span| span.hi())
273             {
274                 // `fn foo(t: impl Trait)`
275                 //        ^ suggest `<T: Trait>` here
276                 None => (generics.span, format!("<{}>", type_param)),
277                 // `fn foo<A>(t: impl Trait)`
278                 //        ^^^ suggest `<A, T: Trait>` here
279                 Some(span) => (span, format!(", {}", type_param)),
280             },
281             // `fn foo(t: impl Trait)`
282             //                       ^ suggest `where <T as Trait>::A: Bound`
283             predicate_constraint(generics, pred),
284         ];
285         sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
286
287         // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
288         // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
289         // `fn foo(t: impl Trait<A: Bound>)` instead.
290         err.multipart_suggestion(
291             "introduce a type parameter with a trait bound instead of using `impl Trait`",
292             sugg,
293             Applicability::MaybeIncorrect,
294         );
295     } else {
296         // Trivial case: `T` needs an extra bound: `T: Bound`.
297         let (sp, suggestion) = match (
298             generics
299                 .params
300                 .iter()
301                 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
302             super_traits,
303         ) {
304             (_, None) => predicate_constraint(generics, trait_pred.to_predicate(tcx).to_string()),
305             (None, Some((ident, []))) => (
306                 ident.span.shrink_to_hi(),
307                 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
308             ),
309             (_, Some((_, [.., bounds]))) => (
310                 bounds.span().shrink_to_hi(),
311                 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
312             ),
313             (Some(_), Some((_, []))) => (
314                 generics.span.shrink_to_hi(),
315                 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
316             ),
317         };
318
319         err.span_suggestion_verbose(
320             sp,
321             &format!("consider further restricting {}", msg),
322             suggestion,
323             Applicability::MachineApplicable,
324         );
325     }
326 }
327
328 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
329     fn suggest_restricting_param_bound(
330         &self,
331         mut err: &mut Diagnostic,
332         trait_pred: ty::PolyTraitPredicate<'tcx>,
333         body_id: hir::HirId,
334     ) {
335         let self_ty = trait_pred.skip_binder().self_ty();
336         let (param_ty, projection) = match self_ty.kind() {
337             ty::Param(_) => (true, None),
338             ty::Projection(projection) => (false, Some(projection)),
339             _ => (false, None),
340         };
341
342         // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
343         //        don't suggest `T: Sized + ?Sized`.
344         let mut hir_id = body_id;
345         while let Some(node) = self.tcx.hir().find(hir_id) {
346             match node {
347                 hir::Node::Item(hir::Item {
348                     ident,
349                     kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
350                     ..
351                 }) if self_ty == self.tcx.types.self_param => {
352                     assert!(param_ty);
353                     // Restricting `Self` for a single method.
354                     suggest_restriction(
355                         self.tcx,
356                         &generics,
357                         "`Self`",
358                         err,
359                         None,
360                         projection,
361                         trait_pred,
362                         Some((ident, bounds)),
363                     );
364                     return;
365                 }
366
367                 hir::Node::TraitItem(hir::TraitItem {
368                     generics,
369                     kind: hir::TraitItemKind::Fn(..),
370                     ..
371                 }) if self_ty == self.tcx.types.self_param => {
372                     assert!(param_ty);
373                     // Restricting `Self` for a single method.
374                     suggest_restriction(
375                         self.tcx, &generics, "`Self`", err, None, projection, trait_pred, None,
376                     );
377                     return;
378                 }
379
380                 hir::Node::TraitItem(hir::TraitItem {
381                     generics,
382                     kind: hir::TraitItemKind::Fn(fn_sig, ..),
383                     ..
384                 })
385                 | hir::Node::ImplItem(hir::ImplItem {
386                     generics,
387                     kind: hir::ImplItemKind::Fn(fn_sig, ..),
388                     ..
389                 })
390                 | hir::Node::Item(hir::Item {
391                     kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
392                 }) if projection.is_some() => {
393                     // Missing restriction on associated type of type parameter (unmet projection).
394                     suggest_restriction(
395                         self.tcx,
396                         &generics,
397                         "the associated type",
398                         err,
399                         Some(fn_sig),
400                         projection,
401                         trait_pred,
402                         None,
403                     );
404                     return;
405                 }
406                 hir::Node::Item(hir::Item {
407                     kind:
408                         hir::ItemKind::Trait(_, _, generics, ..)
409                         | hir::ItemKind::Impl(hir::Impl { generics, .. }),
410                     ..
411                 }) if projection.is_some() => {
412                     // Missing restriction on associated type of type parameter (unmet projection).
413                     suggest_restriction(
414                         self.tcx,
415                         &generics,
416                         "the associated type",
417                         err,
418                         None,
419                         projection,
420                         trait_pred,
421                         None,
422                     );
423                     return;
424                 }
425
426                 hir::Node::Item(hir::Item {
427                     kind:
428                         hir::ItemKind::Struct(_, generics)
429                         | hir::ItemKind::Enum(_, generics)
430                         | hir::ItemKind::Union(_, generics)
431                         | hir::ItemKind::Trait(_, _, generics, ..)
432                         | hir::ItemKind::Impl(hir::Impl { generics, .. })
433                         | hir::ItemKind::Fn(_, generics, _)
434                         | hir::ItemKind::TyAlias(_, generics)
435                         | hir::ItemKind::TraitAlias(generics, _)
436                         | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
437                     ..
438                 })
439                 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
440                 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
441                     if param_ty =>
442                 {
443                     // Missing generic type parameter bound.
444                     let param_name = self_ty.to_string();
445                     let constraint = with_no_trimmed_paths!(
446                         trait_pred.print_modifiers_and_trait_path().to_string()
447                     );
448                     if suggest_constraining_type_param(
449                         self.tcx,
450                         generics,
451                         &mut err,
452                         &param_name,
453                         &constraint,
454                         Some(trait_pred.def_id()),
455                     ) {
456                         return;
457                     }
458                 }
459
460                 hir::Node::Item(hir::Item {
461                     kind:
462                         hir::ItemKind::Struct(_, generics)
463                         | hir::ItemKind::Enum(_, generics)
464                         | hir::ItemKind::Union(_, generics)
465                         | hir::ItemKind::Trait(_, _, generics, ..)
466                         | hir::ItemKind::Impl(hir::Impl { generics, .. })
467                         | hir::ItemKind::Fn(_, generics, _)
468                         | hir::ItemKind::TyAlias(_, generics)
469                         | hir::ItemKind::TraitAlias(generics, _)
470                         | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
471                     ..
472                 }) if !param_ty => {
473                     // Missing generic type parameter bound.
474                     let param_name = self_ty.to_string();
475                     let constraint = trait_pred.print_modifiers_and_trait_path().to_string();
476                     if suggest_arbitrary_trait_bound(generics, &mut err, &param_name, &constraint) {
477                         return;
478                     }
479                 }
480                 hir::Node::Crate(..) => return,
481
482                 _ => {}
483             }
484
485             hir_id = self.tcx.hir().local_def_id_to_hir_id(self.tcx.hir().get_parent_item(hir_id));
486         }
487     }
488
489     /// When after several dereferencing, the reference satisfies the trait
490     /// binding. This function provides dereference suggestion for this
491     /// specific situation.
492     fn suggest_dereferences(
493         &self,
494         obligation: &PredicateObligation<'tcx>,
495         err: &mut Diagnostic,
496         trait_pred: ty::PolyTraitPredicate<'tcx>,
497     ) -> bool {
498         // It only make sense when suggesting dereferences for arguments
499         let ObligationCauseCode::FunctionArgumentObligation { .. } = obligation.cause.code() else {
500             return false;
501         };
502         let param_env = obligation.param_env;
503         let body_id = obligation.cause.body_id;
504         let span = obligation.cause.span;
505         let mut real_trait_pred = trait_pred;
506         let mut code = obligation.cause.code();
507         loop {
508             match &code {
509                 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
510                     code = &parent_code;
511                 }
512                 ObligationCauseCode::ImplDerivedObligation(box ImplDerivedObligationCause {
513                     derived: DerivedObligationCause { parent_code, parent_trait_pred },
514                     ..
515                 })
516                 | ObligationCauseCode::BuiltinDerivedObligation(DerivedObligationCause {
517                     parent_code,
518                     parent_trait_pred,
519                 })
520                 | ObligationCauseCode::DerivedObligation(DerivedObligationCause {
521                     parent_code,
522                     parent_trait_pred,
523                 }) => {
524                     code = &parent_code;
525                     real_trait_pred = *parent_trait_pred;
526                 }
527                 _ => break,
528             };
529             let Some(real_ty) = real_trait_pred.self_ty().no_bound_vars() else {
530                 continue;
531             };
532
533             if let ty::Ref(region, base_ty, mutbl) = *real_ty.kind() {
534                 let mut autoderef = Autoderef::new(self, param_env, body_id, span, base_ty, span);
535                 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
536                     // Re-add the `&`
537                     let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
538                     let obligation =
539                         self.mk_trait_obligation_with_new_self_ty(param_env, real_trait_pred, ty);
540                     Some(steps).filter(|_| self.predicate_may_hold(&obligation))
541                 }) {
542                     if steps > 0 {
543                         if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) {
544                             // Don't care about `&mut` because `DerefMut` is used less
545                             // often and user will not expect autoderef happens.
546                             if src.starts_with('&') && !src.starts_with("&mut ") {
547                                 let derefs = "*".repeat(steps);
548                                 err.span_suggestion(
549                                     span,
550                                     "consider dereferencing here",
551                                     format!("&{}{}", derefs, &src[1..]),
552                                     Applicability::MachineApplicable,
553                                 );
554                                 return true;
555                             }
556                         }
557                     }
558                 } else if real_trait_pred != trait_pred {
559                     // This branch addresses #87437.
560                     let obligation =
561                         self.mk_trait_obligation_with_new_self_ty(param_env, real_trait_pred, base_ty);
562                     if self.predicate_may_hold(&obligation) {
563                         err.span_suggestion_verbose(
564                             span.shrink_to_lo(),
565                             "consider dereferencing here",
566                             "*".to_string(),
567                             Applicability::MachineApplicable,
568                         );
569                         return true;
570                     }
571                 }
572             }
573         }
574         false
575     }
576
577     /// Given a closure's `DefId`, return the given name of the closure.
578     ///
579     /// This doesn't account for reassignments, but it's only used for suggestions.
580     fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<String> {
581         let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<String> {
582             // Get the local name of this closure. This can be inaccurate because
583             // of the possibility of reassignment, but this should be good enough.
584             match &kind {
585                 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
586                     Some(format!("{}", name))
587                 }
588                 _ => {
589                     err.note(&msg);
590                     None
591                 }
592             }
593         };
594
595         let hir = self.tcx.hir();
596         let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
597         let parent_node = hir.get_parent_node(hir_id);
598         match hir.find(parent_node) {
599             Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
600                 get_name(err, &local.pat.kind)
601             }
602             // Different to previous arm because one is `&hir::Local` and the other
603             // is `P<hir::Local>`.
604             Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
605             _ => None,
606         }
607     }
608
609     /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
610     /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
611     /// it: `bar(foo)` â†’ `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
612     fn suggest_fn_call(
613         &self,
614         obligation: &PredicateObligation<'tcx>,
615         err: &mut Diagnostic,
616         trait_pred: ty::PolyTraitPredicate<'tcx>,
617     ) -> bool {
618         let Some(self_ty) = trait_pred.self_ty().no_bound_vars() else {
619             return false;
620         };
621
622         let (def_id, output_ty, callable) = match *self_ty.kind() {
623             ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
624             ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
625             _ => return false,
626         };
627         let msg = format!("use parentheses to call the {}", callable);
628
629         // `mk_trait_obligation_with_new_self_ty` only works for types with no escaping bound
630         // variables, so bail out if we have any.
631         let Some(output_ty) = output_ty.no_bound_vars() else {
632             return false;
633         };
634
635         let new_obligation =
636             self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred, output_ty);
637
638         match self.evaluate_obligation(&new_obligation) {
639             Ok(
640                 EvaluationResult::EvaluatedToOk
641                 | EvaluationResult::EvaluatedToOkModuloRegions
642                 | EvaluationResult::EvaluatedToAmbig,
643             ) => {}
644             _ => return false,
645         }
646         let hir = self.tcx.hir();
647         // Get the name of the callable and the arguments to be used in the suggestion.
648         let (snippet, sugg) = match hir.get_if_local(def_id) {
649             Some(hir::Node::Expr(hir::Expr {
650                 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
651                 ..
652             })) => {
653                 err.span_label(*span, "consider calling this closure");
654                 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
655                     return false;
656                 };
657                 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
658                 let sugg = format!("({})", args);
659                 (format!("{}{}", name, sugg), sugg)
660             }
661             Some(hir::Node::Item(hir::Item {
662                 ident,
663                 kind: hir::ItemKind::Fn(.., body_id),
664                 ..
665             })) => {
666                 err.span_label(ident.span, "consider calling this function");
667                 let body = hir.body(*body_id);
668                 let args = body
669                     .params
670                     .iter()
671                     .map(|arg| match &arg.pat.kind {
672                         hir::PatKind::Binding(_, _, ident, None)
673                         // FIXME: provide a better suggestion when encountering `SelfLower`, it
674                         // should suggest a method call.
675                         if ident.name != kw::SelfLower => ident.to_string(),
676                         _ => "_".to_string(),
677                     })
678                     .collect::<Vec<_>>()
679                     .join(", ");
680                 let sugg = format!("({})", args);
681                 (format!("{}{}", ident, sugg), sugg)
682             }
683             _ => return false,
684         };
685         if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
686         {
687             // When the obligation error has been ensured to have been caused by
688             // an argument, the `obligation.cause.span` points at the expression
689             // of the argument, so we can provide a suggestion. Otherwise, we give
690             // a more general note.
691             err.span_suggestion_verbose(
692                 obligation.cause.span.shrink_to_hi(),
693                 &msg,
694                 sugg,
695                 Applicability::HasPlaceholders,
696             );
697         } else {
698             err.help(&format!("{}: `{}`", msg, snippet));
699         }
700         true
701     }
702
703     fn suggest_add_reference_to_arg(
704         &self,
705         obligation: &PredicateObligation<'tcx>,
706         err: &mut Diagnostic,
707         poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
708         has_custom_message: bool,
709     ) -> bool {
710         let span = obligation.cause.span;
711
712         let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
713             obligation.cause.code()
714         {
715             &parent_code
716         } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
717             span.ctxt().outer_expn_data().kind
718         {
719             obligation.cause.code()
720         } else {
721             return false;
722         };
723
724         // List of traits for which it would be nonsensical to suggest borrowing.
725         // For instance, immutable references are always Copy, so suggesting to
726         // borrow would always succeed, but it's probably not what the user wanted.
727         let mut never_suggest_borrow: Vec<_> =
728             [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
729                 .iter()
730                 .filter_map(|lang_item| self.tcx.lang_items().require(*lang_item).ok())
731                 .collect();
732
733         if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
734             never_suggest_borrow.push(def_id);
735         }
736
737         let param_env = obligation.param_env;
738
739         // Try to apply the original trait binding obligation by borrowing.
740         let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
741                                  blacklist: &[DefId]|
742          -> bool {
743             if blacklist.contains(&old_pred.def_id()) {
744                 return false;
745             }
746
747             let orig_ty = old_pred.self_ty().skip_binder();
748             let mk_result = |new_ty| {
749                 let obligation =
750                     self.mk_trait_obligation_with_new_self_ty(param_env, old_pred, new_ty);
751                 self.predicate_must_hold_modulo_regions(&obligation)
752             };
753             let imm_result = mk_result(self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, orig_ty));
754             let mut_result = mk_result(self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, orig_ty));
755
756             if imm_result || mut_result {
757                 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
758                     // We have a very specific type of error, where just borrowing this argument
759                     // might solve the problem. In cases like this, the important part is the
760                     // original type obligation, not the last one that failed, which is arbitrary.
761                     // Because of this, we modify the error to refer to the original obligation and
762                     // return early in the caller.
763
764                     let msg = format!(
765                         "the trait bound `{}: {}` is not satisfied",
766                         orig_ty,
767                         old_pred.print_modifiers_and_trait_path(),
768                     );
769                     if has_custom_message {
770                         err.note(&msg);
771                     } else {
772                         err.message = vec![(msg, Style::NoStyle)];
773                     }
774                     if snippet.starts_with('&') {
775                         // This is already a literal borrow and the obligation is failing
776                         // somewhere else in the obligation chain. Do not suggest non-sense.
777                         return false;
778                     }
779                     err.span_label(
780                         span,
781                         &format!(
782                             "expected an implementor of trait `{}`",
783                             old_pred.print_modifiers_and_trait_path(),
784                         ),
785                     );
786
787                     // This if is to prevent a special edge-case
788                     if matches!(
789                         span.ctxt().outer_expn_data().kind,
790                         ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
791                     ) {
792                         // We don't want a borrowing suggestion on the fields in structs,
793                         // ```
794                         // struct Foo {
795                         //  the_foos: Vec<Foo>
796                         // }
797                         // ```
798
799                         if imm_result && mut_result {
800                             err.span_suggestions(
801                                 span.shrink_to_lo(),
802                                 "consider borrowing here",
803                                 ["&".to_string(), "&mut ".to_string()].into_iter(),
804                                 Applicability::MaybeIncorrect,
805                             );
806                         } else {
807                             err.span_suggestion_verbose(
808                                 span.shrink_to_lo(),
809                                 &format!(
810                                     "consider{} borrowing here",
811                                     if mut_result { " mutably" } else { "" }
812                                 ),
813                                 format!("&{}", if mut_result { "mut " } else { "" }),
814                                 Applicability::MaybeIncorrect,
815                             );
816                         }
817                     }
818                     return true;
819                 }
820             }
821             return false;
822         };
823
824         if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
825             try_borrowing(cause.derived.parent_trait_pred, &[])
826         } else if let ObligationCauseCode::BindingObligation(_, _)
827         | ObligationCauseCode::ItemObligation(_) = code
828         {
829             try_borrowing(poly_trait_pred, &never_suggest_borrow)
830         } else {
831             false
832         }
833     }
834
835     /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
836     /// suggest removing these references until we reach a type that implements the trait.
837     fn suggest_remove_reference(
838         &self,
839         obligation: &PredicateObligation<'tcx>,
840         err: &mut Diagnostic,
841         trait_pred: ty::PolyTraitPredicate<'tcx>,
842     ) -> bool {
843         let span = obligation.cause.span;
844
845         let mut suggested = false;
846         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
847             let refs_number =
848                 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
849             if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
850                 // Do not suggest removal of borrow from type arguments.
851                 return false;
852             }
853
854             let Some(mut suggested_ty) = trait_pred.self_ty().no_bound_vars() else {
855                 return false;
856             };
857
858             for refs_remaining in 0..refs_number {
859                 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
860                     break;
861                 };
862                 suggested_ty = *inner_ty;
863
864                 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
865                     obligation.param_env,
866                     trait_pred,
867                     suggested_ty,
868                 );
869
870                 if self.predicate_may_hold(&new_obligation) {
871                     let sp = self
872                         .tcx
873                         .sess
874                         .source_map()
875                         .span_take_while(span, |c| c.is_whitespace() || *c == '&');
876
877                     let remove_refs = refs_remaining + 1;
878
879                     let msg = if remove_refs == 1 {
880                         "consider removing the leading `&`-reference".to_string()
881                     } else {
882                         format!("consider removing {} leading `&`-references", remove_refs)
883                     };
884
885                     err.span_suggestion_short(
886                         sp,
887                         &msg,
888                         String::new(),
889                         Applicability::MachineApplicable,
890                     );
891                     suggested = true;
892                     break;
893                 }
894             }
895         }
896         suggested
897     }
898
899     fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
900         let span = obligation.cause.span;
901
902         if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
903             let hir = self.tcx.hir();
904             if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
905                 if let hir::Node::Expr(expr) = node {
906                     // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
907                     // and if not maybe suggest doing something else? If we kept the expression around we
908                     // could also check if it is an fn call (very likely) and suggest changing *that*, if
909                     // it is from the local crate.
910                     err.span_suggestion_verbose(
911                         expr.span.shrink_to_hi().with_hi(span.hi()),
912                         "remove the `.await`",
913                         String::new(),
914                         Applicability::MachineApplicable,
915                     );
916                     // FIXME: account for associated `async fn`s.
917                     if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
918                         if let ty::PredicateKind::Trait(pred) =
919                             obligation.predicate.kind().skip_binder()
920                         {
921                             err.span_label(
922                                 *span,
923                                 &format!("this call returns `{}`", pred.self_ty()),
924                             );
925                         }
926                         if let Some(typeck_results) =
927                             self.in_progress_typeck_results.map(|t| t.borrow())
928                             && let ty = typeck_results.expr_ty_adjusted(base)
929                             && let ty::FnDef(def_id, _substs) = ty.kind()
930                             && let Some(hir::Node::Item(hir::Item { span, ident, .. })) =
931                                 hir.get_if_local(*def_id)
932                         {
933                             err.span_suggestion_verbose(
934                                 span.shrink_to_lo(),
935                                 &format!(
936                                     "alternatively, consider making `fn {}` asynchronous",
937                                     ident
938                                 ),
939                                 "async ".to_string(),
940                                 Applicability::MaybeIncorrect,
941                             );
942                         }
943                     }
944                 }
945             }
946         }
947     }
948
949     /// Check if the trait bound is implemented for a different mutability and note it in the
950     /// final error.
951     fn suggest_change_mut(
952         &self,
953         obligation: &PredicateObligation<'tcx>,
954         err: &mut Diagnostic,
955         trait_pred: ty::PolyTraitPredicate<'tcx>,
956     ) {
957         let points_at_arg = matches!(
958             obligation.cause.code(),
959             ObligationCauseCode::FunctionArgumentObligation { .. },
960         );
961
962         let span = obligation.cause.span;
963         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
964             let refs_number =
965                 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
966             if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
967                 // Do not suggest removal of borrow from type arguments.
968                 return;
969             }
970             let trait_pred = self.resolve_vars_if_possible(trait_pred);
971             if trait_pred.has_infer_types_or_consts() {
972                 // Do not ICE while trying to find if a reborrow would succeed on a trait with
973                 // unresolved bindings.
974                 return;
975             }
976
977             if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
978             {
979                 if region.is_late_bound() || t_type.has_escaping_bound_vars() {
980                     // Avoid debug assertion in `mk_obligation_for_def_id`.
981                     //
982                     // If the self type has escaping bound vars then it's not
983                     // going to be the type of an expression, so the suggestion
984                     // probably won't apply anyway.
985                     return;
986                 }
987
988                 let suggested_ty = match mutability {
989                     hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
990                     hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
991                 };
992
993                 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
994                     obligation.param_env,
995                     trait_pred,
996                     suggested_ty,
997                 );
998                 let suggested_ty_would_satisfy_obligation = self
999                     .evaluate_obligation_no_overflow(&new_obligation)
1000                     .must_apply_modulo_regions();
1001                 if suggested_ty_would_satisfy_obligation {
1002                     let sp = self
1003                         .tcx
1004                         .sess
1005                         .source_map()
1006                         .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1007                     if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
1008                         err.span_suggestion_verbose(
1009                             sp,
1010                             "consider changing this borrow's mutability",
1011                             "&mut ".to_string(),
1012                             Applicability::MachineApplicable,
1013                         );
1014                     } else {
1015                         err.note(&format!(
1016                             "`{}` is implemented for `{:?}`, but not for `{:?}`",
1017                             trait_pred.print_modifiers_and_trait_path(),
1018                             suggested_ty,
1019                             trait_pred.skip_binder().self_ty(),
1020                         ));
1021                     }
1022                 }
1023             }
1024         }
1025     }
1026
1027     fn suggest_semicolon_removal(
1028         &self,
1029         obligation: &PredicateObligation<'tcx>,
1030         err: &mut Diagnostic,
1031         span: Span,
1032         trait_pred: ty::PolyTraitPredicate<'tcx>,
1033     ) -> bool {
1034         let hir = self.tcx.hir();
1035         let parent_node = hir.get_parent_node(obligation.cause.body_id);
1036         let node = hir.find(parent_node);
1037         if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1038             && let body = hir.body(*body_id)
1039             && let hir::ExprKind::Block(blk, _) = &body.value.kind
1040             && sig.decl.output.span().overlaps(span)
1041             && blk.expr.is_none()
1042             && *trait_pred.self_ty().skip_binder().kind() == ty::Tuple(ty::List::empty())
1043             // FIXME(estebank): When encountering a method with a trait
1044             // bound not satisfied in the return type with a body that has
1045             // no return, suggest removal of semicolon on last statement.
1046             // Once that is added, close #54771.
1047             && let Some(stmt) = blk.stmts.last()
1048             && let hir::StmtKind::Semi(_) = stmt.kind
1049         {
1050             let sp = self.tcx.sess.source_map().end_point(stmt.span);
1051             err.span_label(sp, "consider removing this semicolon");
1052             return true;
1053         }
1054         false
1055     }
1056
1057     fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1058         let hir = self.tcx.hir();
1059         let parent_node = hir.get_parent_node(obligation.cause.body_id);
1060         let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1061             return None;
1062         };
1063
1064         if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1065     }
1066
1067     /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1068     /// applicable and signal that the error has been expanded appropriately and needs to be
1069     /// emitted.
1070     fn suggest_impl_trait(
1071         &self,
1072         err: &mut Diagnostic,
1073         span: Span,
1074         obligation: &PredicateObligation<'tcx>,
1075         trait_pred: ty::PolyTraitPredicate<'tcx>,
1076     ) -> bool {
1077         match obligation.cause.code().peel_derives() {
1078             // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1079             ObligationCauseCode::SizedReturnType => {}
1080             _ => return false,
1081         }
1082
1083         let hir = self.tcx.hir();
1084         let parent_node = hir.get_parent_node(obligation.cause.body_id);
1085         let node = hir.find(parent_node);
1086         let Some(hir::Node::Item(hir::Item {
1087             kind: hir::ItemKind::Fn(sig, _, body_id),
1088             ..
1089         })) = node
1090         else {
1091             return false;
1092         };
1093         let body = hir.body(*body_id);
1094         let trait_pred = self.resolve_vars_if_possible(trait_pred);
1095         let ty = trait_pred.skip_binder().self_ty();
1096         let is_object_safe = match ty.kind() {
1097             ty::Dynamic(predicates, _) => {
1098                 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1099                 predicates
1100                     .principal_def_id()
1101                     .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1102             }
1103             // We only want to suggest `impl Trait` to `dyn Trait`s.
1104             // For example, `fn foo() -> str` needs to be filtered out.
1105             _ => return false,
1106         };
1107
1108         let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1109             return false;
1110         };
1111
1112         // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1113         // cases like `fn foo() -> (dyn Trait, i32) {}`.
1114         // Recursively look for `TraitObject` types and if there's only one, use that span to
1115         // suggest `impl Trait`.
1116
1117         // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1118         // otherwise suggest using `Box<dyn Trait>` or an enum.
1119         let mut visitor = ReturnsVisitor::default();
1120         visitor.visit_body(&body);
1121
1122         let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1123
1124         let mut ret_types = visitor
1125             .returns
1126             .iter()
1127             .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1128             .map(|ty| self.resolve_vars_if_possible(ty));
1129         let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1130             (None, true, true),
1131             |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1132              ty| {
1133                 let ty = self.resolve_vars_if_possible(ty);
1134                 same &=
1135                     !matches!(ty.kind(), ty::Error(_))
1136                         && last_ty.map_or(true, |last_ty| {
1137                             // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1138                             // *after* in the dependency graph.
1139                             match (ty.kind(), last_ty.kind()) {
1140                                 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1141                                 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1142                                 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1143                                 | (
1144                                     Infer(InferTy::FreshFloatTy(_)),
1145                                     Infer(InferTy::FreshFloatTy(_)),
1146                                 ) => true,
1147                                 _ => ty == last_ty,
1148                             }
1149                         });
1150                 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1151             },
1152         );
1153         let all_returns_conform_to_trait =
1154             if let Some(ty_ret_ty) = typeck_results.node_type_opt(ret_ty.hir_id) {
1155                 match ty_ret_ty.kind() {
1156                     ty::Dynamic(predicates, _) => {
1157                         let cause = ObligationCause::misc(ret_ty.span, ret_ty.hir_id);
1158                         let param_env = ty::ParamEnv::empty();
1159                         only_never_return
1160                             || ret_types.all(|returned_ty| {
1161                                 predicates.iter().all(|predicate| {
1162                                     let pred = predicate.with_self_ty(self.tcx, returned_ty);
1163                                     let obl = Obligation::new(cause.clone(), param_env, pred);
1164                                     self.predicate_may_hold(&obl)
1165                                 })
1166                             })
1167                     }
1168                     _ => false,
1169                 }
1170             } else {
1171                 true
1172             };
1173
1174         let sm = self.tcx.sess.source_map();
1175         let (true, hir::TyKind::TraitObject(..), Ok(snippet), true) = (
1176             // Verify that we're dealing with a return `dyn Trait`
1177             ret_ty.span.overlaps(span),
1178             &ret_ty.kind,
1179             sm.span_to_snippet(ret_ty.span),
1180             // If any of the return types does not conform to the trait, then we can't
1181             // suggest `impl Trait` nor trait objects: it is a type mismatch error.
1182             all_returns_conform_to_trait,
1183         ) else {
1184             return false;
1185         };
1186         err.code(error_code!(E0746));
1187         err.set_primary_message("return type cannot have an unboxed trait object");
1188         err.children.clear();
1189         let impl_trait_msg = "for information on `impl Trait`, see \
1190             <https://doc.rust-lang.org/book/ch10-02-traits.html\
1191             #returning-types-that-implement-traits>";
1192         let trait_obj_msg = "for information on trait objects, see \
1193             <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1194             #using-trait-objects-that-allow-for-values-of-different-types>";
1195         let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1196         let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1197         if only_never_return {
1198             // No return paths, probably using `panic!()` or similar.
1199             // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1200             suggest_trait_object_return_type_alternatives(
1201                 err,
1202                 ret_ty.span,
1203                 trait_obj,
1204                 is_object_safe,
1205             );
1206         } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1207             // Suggest `-> impl Trait`.
1208             err.span_suggestion(
1209                 ret_ty.span,
1210                 &format!(
1211                     "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1212                      which implements `{1}`",
1213                     last_ty, trait_obj,
1214                 ),
1215                 format!("impl {}", trait_obj),
1216                 Applicability::MachineApplicable,
1217             );
1218             err.note(impl_trait_msg);
1219         } else {
1220             if is_object_safe {
1221                 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1222                 // Get all the return values and collect their span and suggestion.
1223                 let mut suggestions: Vec<_> = visitor
1224                     .returns
1225                     .iter()
1226                     .flat_map(|expr| {
1227                         [
1228                             (expr.span.shrink_to_lo(), "Box::new(".to_string()),
1229                             (expr.span.shrink_to_hi(), ")".to_string()),
1230                         ]
1231                         .into_iter()
1232                     })
1233                     .collect();
1234                 if !suggestions.is_empty() {
1235                     // Add the suggestion for the return type.
1236                     suggestions.push((ret_ty.span, format!("Box<dyn {}>", trait_obj)));
1237                     err.multipart_suggestion(
1238                         "return a boxed trait object instead",
1239                         suggestions,
1240                         Applicability::MaybeIncorrect,
1241                     );
1242                 }
1243             } else {
1244                 // This is currently not possible to trigger because E0038 takes precedence, but
1245                 // leave it in for completeness in case anything changes in an earlier stage.
1246                 err.note(&format!(
1247                     "if trait `{}` were object-safe, you could return a trait object",
1248                     trait_obj,
1249                 ));
1250             }
1251             err.note(trait_obj_msg);
1252             err.note(&format!(
1253                 "if all the returned values were of the same type you could use `impl {}` as the \
1254                  return type",
1255                 trait_obj,
1256             ));
1257             err.note(impl_trait_msg);
1258             err.note("you can create a new `enum` with a variant for each returned type");
1259         }
1260         true
1261     }
1262
1263     fn point_at_returns_when_relevant(
1264         &self,
1265         err: &mut Diagnostic,
1266         obligation: &PredicateObligation<'tcx>,
1267     ) {
1268         match obligation.cause.code().peel_derives() {
1269             ObligationCauseCode::SizedReturnType => {}
1270             _ => return,
1271         }
1272
1273         let hir = self.tcx.hir();
1274         let parent_node = hir.get_parent_node(obligation.cause.body_id);
1275         let node = hir.find(parent_node);
1276         if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1277             node
1278         {
1279             let body = hir.body(*body_id);
1280             // Point at all the `return`s in the function as they have failed trait bounds.
1281             let mut visitor = ReturnsVisitor::default();
1282             visitor.visit_body(&body);
1283             let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1284             for expr in &visitor.returns {
1285                 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1286                     let ty = self.resolve_vars_if_possible(returned_ty);
1287                     err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1288                 }
1289             }
1290         }
1291     }
1292
1293     fn report_closure_arg_mismatch(
1294         &self,
1295         span: Span,
1296         found_span: Option<Span>,
1297         expected_ref: ty::PolyTraitRef<'tcx>,
1298         found: ty::PolyTraitRef<'tcx>,
1299     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1300         crate fn build_fn_sig_string<'tcx>(
1301             tcx: TyCtxt<'tcx>,
1302             trait_ref: ty::PolyTraitRef<'tcx>,
1303         ) -> String {
1304             let inputs = trait_ref.skip_binder().substs.type_at(1);
1305             let sig = match inputs.kind() {
1306                 ty::Tuple(inputs)
1307                     if tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some() =>
1308                 {
1309                     tcx.mk_fn_sig(
1310                         inputs.iter(),
1311                         tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0))),
1312                         false,
1313                         hir::Unsafety::Normal,
1314                         abi::Abi::Rust,
1315                     )
1316                 }
1317                 _ => tcx.mk_fn_sig(
1318                     std::iter::once(inputs),
1319                     tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0))),
1320                     false,
1321                     hir::Unsafety::Normal,
1322                     abi::Abi::Rust,
1323                 ),
1324             };
1325             trait_ref.rebind(sig).to_string()
1326         }
1327
1328         let argument_kind = match expected_ref.skip_binder().self_ty().kind() {
1329             ty::Closure(..) => "closure",
1330             ty::Generator(..) => "generator",
1331             _ => "function",
1332         };
1333         let span = self.tcx.sess.source_map().guess_head_span(span);
1334         let mut err = struct_span_err!(
1335             self.tcx.sess,
1336             span,
1337             E0631,
1338             "type mismatch in {} arguments",
1339             argument_kind
1340         );
1341
1342         let found_str = format!("expected signature of `{}`", build_fn_sig_string(self.tcx, found));
1343         err.span_label(span, found_str);
1344
1345         let found_span = found_span.unwrap_or(span);
1346         let expected_str =
1347             format!("found signature of `{}`", build_fn_sig_string(self.tcx, expected_ref));
1348         err.span_label(found_span, expected_str);
1349
1350         err
1351     }
1352
1353     fn suggest_fully_qualified_path(
1354         &self,
1355         err: &mut Diagnostic,
1356         item_def_id: DefId,
1357         span: Span,
1358         trait_ref: DefId,
1359     ) {
1360         if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1361             if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1362                 err.note(&format!(
1363                     "{}s cannot be accessed directly on a `trait`, they can only be \
1364                         accessed through a specific `impl`",
1365                     assoc_item.kind.as_def_kind().descr(item_def_id)
1366                 ));
1367                 err.span_suggestion(
1368                     span,
1369                     "use the fully qualified path to an implementation",
1370                     format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1371                     Applicability::HasPlaceholders,
1372                 );
1373             }
1374         }
1375     }
1376
1377     /// Adds an async-await specific note to the diagnostic when the future does not implement
1378     /// an auto trait because of a captured type.
1379     ///
1380     /// ```text
1381     /// note: future does not implement `Qux` as this value is used across an await
1382     ///   --> $DIR/issue-64130-3-other.rs:17:5
1383     ///    |
1384     /// LL |     let x = Foo;
1385     ///    |         - has type `Foo`
1386     /// LL |     baz().await;
1387     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1388     /// LL | }
1389     ///    | - `x` is later dropped here
1390     /// ```
1391     ///
1392     /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1393     /// is "replaced" with a different message and a more specific error.
1394     ///
1395     /// ```text
1396     /// error: future cannot be sent between threads safely
1397     ///   --> $DIR/issue-64130-2-send.rs:21:5
1398     ///    |
1399     /// LL | fn is_send<T: Send>(t: T) { }
1400     ///    |               ---- required by this bound in `is_send`
1401     /// ...
1402     /// LL |     is_send(bar());
1403     ///    |     ^^^^^^^ future returned by `bar` is not send
1404     ///    |
1405     ///    = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1406     ///            implemented for `Foo`
1407     /// note: future is not send as this value is used across an await
1408     ///   --> $DIR/issue-64130-2-send.rs:15:5
1409     ///    |
1410     /// LL |     let x = Foo;
1411     ///    |         - has type `Foo`
1412     /// LL |     baz().await;
1413     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1414     /// LL | }
1415     ///    | - `x` is later dropped here
1416     /// ```
1417     ///
1418     /// Returns `true` if an async-await specific note was added to the diagnostic.
1419     fn maybe_note_obligation_cause_for_async_await(
1420         &self,
1421         err: &mut Diagnostic,
1422         obligation: &PredicateObligation<'tcx>,
1423     ) -> bool {
1424         debug!(
1425             "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
1426                 obligation.cause.span={:?}",
1427             obligation.predicate, obligation.cause.span
1428         );
1429         let hir = self.tcx.hir();
1430
1431         // Attempt to detect an async-await error by looking at the obligation causes, looking
1432         // for a generator to be present.
1433         //
1434         // When a future does not implement a trait because of a captured type in one of the
1435         // generators somewhere in the call stack, then the result is a chain of obligations.
1436         //
1437         // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1438         // future is passed as an argument to a function C which requires a `Send` type, then the
1439         // chain looks something like this:
1440         //
1441         // - `BuiltinDerivedObligation` with a generator witness (B)
1442         // - `BuiltinDerivedObligation` with a generator (B)
1443         // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1444         // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1445         // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1446         // - `BuiltinDerivedObligation` with a generator witness (A)
1447         // - `BuiltinDerivedObligation` with a generator (A)
1448         // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1449         // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1450         // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1451         // - `BindingObligation` with `impl_send (Send requirement)
1452         //
1453         // The first obligation in the chain is the most useful and has the generator that captured
1454         // the type. The last generator (`outer_generator` below) has information about where the
1455         // bound was introduced. At least one generator should be present for this diagnostic to be
1456         // modified.
1457         let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1458             ty::PredicateKind::Trait(p) => (Some(p), Some(p.self_ty())),
1459             _ => (None, None),
1460         };
1461         let mut generator = None;
1462         let mut outer_generator = None;
1463         let mut next_code = Some(obligation.cause.code());
1464
1465         let mut seen_upvar_tys_infer_tuple = false;
1466
1467         while let Some(code) = next_code {
1468             debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
1469             match code {
1470                 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1471                     next_code = Some(parent_code.as_ref());
1472                 }
1473                 ObligationCauseCode::ImplDerivedObligation(cause) => {
1474                     let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
1475                     debug!(
1476                         "maybe_note_obligation_cause_for_async_await: ImplDerived \
1477                          parent_trait_ref={:?} self_ty.kind={:?}",
1478                         cause.derived.parent_trait_pred,
1479                         ty.kind()
1480                     );
1481
1482                     match *ty.kind() {
1483                         ty::Generator(did, ..) => {
1484                             generator = generator.or(Some(did));
1485                             outer_generator = Some(did);
1486                         }
1487                         ty::GeneratorWitness(..) => {}
1488                         ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1489                             // By introducing a tuple of upvar types into the chain of obligations
1490                             // of a generator, the first non-generator item is now the tuple itself,
1491                             // we shall ignore this.
1492
1493                             seen_upvar_tys_infer_tuple = true;
1494                         }
1495                         _ if generator.is_none() => {
1496                             trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
1497                             target_ty = Some(ty);
1498                         }
1499                         _ => {}
1500                     }
1501
1502                     next_code = Some(cause.derived.parent_code.as_ref());
1503                 }
1504                 ObligationCauseCode::DerivedObligation(derived_obligation)
1505                 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
1506                     let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1507                     debug!(
1508                         "maybe_note_obligation_cause_for_async_await: \
1509                          parent_trait_ref={:?} self_ty.kind={:?}",
1510                         derived_obligation.parent_trait_pred,
1511                         ty.kind()
1512                     );
1513
1514                     match *ty.kind() {
1515                         ty::Generator(did, ..) => {
1516                             generator = generator.or(Some(did));
1517                             outer_generator = Some(did);
1518                         }
1519                         ty::GeneratorWitness(..) => {}
1520                         ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1521                             // By introducing a tuple of upvar types into the chain of obligations
1522                             // of a generator, the first non-generator item is now the tuple itself,
1523                             // we shall ignore this.
1524
1525                             seen_upvar_tys_infer_tuple = true;
1526                         }
1527                         _ if generator.is_none() => {
1528                             trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
1529                             target_ty = Some(ty);
1530                         }
1531                         _ => {}
1532                     }
1533
1534                     next_code = Some(derived_obligation.parent_code.as_ref());
1535                 }
1536                 _ => break,
1537             }
1538         }
1539
1540         // Only continue if a generator was found.
1541         debug!(?generator, ?trait_ref, ?target_ty, "maybe_note_obligation_cause_for_async_await");
1542         let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
1543             return false;
1544         };
1545
1546         let span = self.tcx.def_span(generator_did);
1547
1548         let in_progress_typeck_results = self.in_progress_typeck_results.map(|t| t.borrow());
1549         let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
1550         debug!(
1551             "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
1552              generator_did_root={:?} in_progress_typeck_results.hir_owner={:?} span={:?}",
1553             generator_did,
1554             generator_did_root,
1555             in_progress_typeck_results.as_ref().map(|t| t.hir_owner),
1556             span
1557         );
1558
1559         let generator_body = generator_did
1560             .as_local()
1561             .map(|def_id| hir.local_def_id_to_hir_id(def_id))
1562             .and_then(|hir_id| hir.maybe_body_owned_by(hir_id))
1563             .map(|body_id| hir.body(body_id));
1564         let mut visitor = AwaitsVisitor::default();
1565         if let Some(body) = generator_body {
1566             visitor.visit_body(body);
1567         }
1568         debug!("maybe_note_obligation_cause_for_async_await: awaits = {:?}", visitor.awaits);
1569
1570         // Look for a type inside the generator interior that matches the target type to get
1571         // a span.
1572         let target_ty_erased = self.tcx.erase_regions(target_ty);
1573         let ty_matches = |ty| -> bool {
1574             // Careful: the regions for types that appear in the
1575             // generator interior are not generally known, so we
1576             // want to erase them when comparing (and anyway,
1577             // `Send` and other bounds are generally unaffected by
1578             // the choice of region).  When erasing regions, we
1579             // also have to erase late-bound regions. This is
1580             // because the types that appear in the generator
1581             // interior generally contain "bound regions" to
1582             // represent regions that are part of the suspended
1583             // generator frame. Bound regions are preserved by
1584             // `erase_regions` and so we must also call
1585             // `erase_late_bound_regions`.
1586             let ty_erased = self.tcx.erase_late_bound_regions(ty);
1587             let ty_erased = self.tcx.erase_regions(ty_erased);
1588             let eq = ty_erased == target_ty_erased;
1589             debug!(
1590                 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
1591                     target_ty_erased={:?} eq={:?}",
1592                 ty_erased, target_ty_erased, eq
1593             );
1594             eq
1595         };
1596
1597         let mut interior_or_upvar_span = None;
1598         let mut interior_extra_info = None;
1599
1600         // Get the typeck results from the infcx if the generator is the function we are currently
1601         // type-checking; otherwise, get them by performing a query.  This is needed to avoid
1602         // cycles. If we can't use resolved types because the generator comes from another crate,
1603         // we still provide a targeted error but without all the relevant spans.
1604         let query_typeck_results;
1605         let typeck_results: Option<&TypeckResults<'tcx>> = match &in_progress_typeck_results {
1606             Some(t) if t.hir_owner.to_def_id() == generator_did_root => Some(&t),
1607             _ if generator_did.is_local() => {
1608                 query_typeck_results = self.tcx.typeck(generator_did.expect_local());
1609                 Some(&query_typeck_results)
1610             }
1611             _ => None, // Do not ICE on closure typeck (#66868).
1612         };
1613         if let Some(typeck_results) = typeck_results {
1614             if let Some(upvars) = self.tcx.upvars_mentioned(generator_did) {
1615                 interior_or_upvar_span = upvars.iter().find_map(|(upvar_id, upvar)| {
1616                     let upvar_ty = typeck_results.node_type(*upvar_id);
1617                     let upvar_ty = self.resolve_vars_if_possible(upvar_ty);
1618                     if ty_matches(ty::Binder::dummy(upvar_ty)) {
1619                         Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
1620                     } else {
1621                         None
1622                     }
1623                 });
1624             };
1625
1626             // The generator interior types share the same binders
1627             if let Some(cause) =
1628                 typeck_results.generator_interior_types.as_ref().skip_binder().iter().find(
1629                     |ty::GeneratorInteriorTypeCause { ty, .. }| {
1630                         ty_matches(typeck_results.generator_interior_types.rebind(*ty))
1631                     },
1632                 )
1633             {
1634                 // Check to see if any awaited expressions have the target type.
1635                 let from_awaited_ty = visitor
1636                     .awaits
1637                     .into_iter()
1638                     .map(|id| hir.expect_expr(id))
1639                     .find(|await_expr| {
1640                         ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
1641                     })
1642                     .map(|expr| expr.span);
1643                 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } =
1644                     cause;
1645
1646                 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span));
1647                 interior_extra_info = Some((*scope_span, *yield_span, *expr, from_awaited_ty));
1648             };
1649         } else {
1650             interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span));
1651         }
1652
1653         if let Some(interior_or_upvar_span) = interior_or_upvar_span {
1654             self.note_obligation_cause_for_async_await(
1655                 err,
1656                 interior_or_upvar_span,
1657                 interior_extra_info,
1658                 generator_body,
1659                 outer_generator,
1660                 trait_ref,
1661                 target_ty,
1662                 typeck_results,
1663                 obligation,
1664                 next_code,
1665             );
1666             true
1667         } else {
1668             false
1669         }
1670     }
1671
1672     /// Unconditionally adds the diagnostic note described in
1673     /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1674     fn note_obligation_cause_for_async_await(
1675         &self,
1676         err: &mut Diagnostic,
1677         interior_or_upvar_span: GeneratorInteriorOrUpvar,
1678         interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
1679         inner_generator_body: Option<&hir::Body<'tcx>>,
1680         outer_generator: Option<DefId>,
1681         trait_pred: ty::TraitPredicate<'tcx>,
1682         target_ty: Ty<'tcx>,
1683         typeck_results: Option<&ty::TypeckResults<'tcx>>,
1684         obligation: &PredicateObligation<'tcx>,
1685         next_code: Option<&ObligationCauseCode<'tcx>>,
1686     ) {
1687         let source_map = self.tcx.sess.source_map();
1688
1689         let is_async = inner_generator_body
1690             .and_then(|body| body.generator_kind())
1691             .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1692             .unwrap_or(false);
1693         let (await_or_yield, an_await_or_yield) =
1694             if is_async { ("await", "an await") } else { ("yield", "a yield") };
1695         let future_or_generator = if is_async { "future" } else { "generator" };
1696
1697         // Special case the primary error message when send or sync is the trait that was
1698         // not implemented.
1699         let hir = self.tcx.hir();
1700         let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
1701             self.tcx.get_diagnostic_name(trait_pred.def_id())
1702         {
1703             let (trait_name, trait_verb) =
1704                 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1705
1706             err.clear_code();
1707             err.set_primary_message(format!(
1708                 "{} cannot be {} between threads safely",
1709                 future_or_generator, trait_verb
1710             ));
1711
1712             let original_span = err.span.primary_span().unwrap();
1713             let original_span = self.tcx.sess.source_map().guess_head_span(original_span);
1714             let mut span = MultiSpan::from_span(original_span);
1715
1716             let message = outer_generator
1717                 .and_then(|generator_did| {
1718                     Some(match self.tcx.generator_kind(generator_did).unwrap() {
1719                         GeneratorKind::Gen => format!("generator is not {}", trait_name),
1720                         GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
1721                             .tcx
1722                             .parent(generator_did)
1723                             .and_then(|parent_did| parent_did.as_local())
1724                             .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
1725                             .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
1726                             .map(|name| {
1727                                 format!("future returned by `{}` is not {}", name, trait_name)
1728                             })?,
1729                         GeneratorKind::Async(AsyncGeneratorKind::Block) => {
1730                             format!("future created by async block is not {}", trait_name)
1731                         }
1732                         GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
1733                             format!("future created by async closure is not {}", trait_name)
1734                         }
1735                     })
1736                 })
1737                 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
1738
1739             span.push_span_label(original_span, message);
1740             err.set_span(span);
1741
1742             format!("is not {}", trait_name)
1743         } else {
1744             format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
1745         };
1746
1747         let mut explain_yield = |interior_span: Span,
1748                                  yield_span: Span,
1749                                  scope_span: Option<Span>| {
1750             let mut span = MultiSpan::from_span(yield_span);
1751             if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
1752                 // #70935: If snippet contains newlines, display "the value" instead
1753                 // so that we do not emit complex diagnostics.
1754                 let snippet = &format!("`{}`", snippet);
1755                 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
1756                 // note: future is not `Send` as this value is used across an await
1757                 //   --> $DIR/issue-70935-complex-spans.rs:13:9
1758                 //    |
1759                 // LL |            baz(|| async {
1760                 //    |  ______________-
1761                 //    | |
1762                 //    | |
1763                 // LL | |              foo(tx.clone());
1764                 // LL | |          }).await;
1765                 //    | |          - ^^^^^^ await occurs here, with value maybe used later
1766                 //    | |__________|
1767                 //    |            has type `closure` which is not `Send`
1768                 // note: value is later dropped here
1769                 // LL | |          }).await;
1770                 //    | |                  ^
1771                 //
1772                 span.push_span_label(
1773                     yield_span,
1774                     format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
1775                 );
1776                 span.push_span_label(
1777                     interior_span,
1778                     format!("has type `{}` which {}", target_ty, trait_explanation),
1779                 );
1780                 // If available, use the scope span to annotate the drop location.
1781                 let mut scope_note = None;
1782                 if let Some(scope_span) = scope_span {
1783                     let scope_span = source_map.end_point(scope_span);
1784
1785                     let msg = format!("{} is later dropped here", snippet);
1786                     if source_map.is_multiline(yield_span.between(scope_span)) {
1787                         span.push_span_label(scope_span, msg);
1788                     } else {
1789                         scope_note = Some((scope_span, msg));
1790                     }
1791                 }
1792                 err.span_note(
1793                     span,
1794                     &format!(
1795                         "{} {} as this value is used across {}",
1796                         future_or_generator, trait_explanation, an_await_or_yield
1797                     ),
1798                 );
1799                 if let Some((span, msg)) = scope_note {
1800                     err.span_note(span, &msg);
1801                 }
1802             }
1803         };
1804         match interior_or_upvar_span {
1805             GeneratorInteriorOrUpvar::Interior(interior_span) => {
1806                 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
1807                     if let Some(await_span) = from_awaited_ty {
1808                         // The type causing this obligation is one being awaited at await_span.
1809                         let mut span = MultiSpan::from_span(await_span);
1810                         span.push_span_label(
1811                             await_span,
1812                             format!(
1813                                 "await occurs here on type `{}`, which {}",
1814                                 target_ty, trait_explanation
1815                             ),
1816                         );
1817                         err.span_note(
1818                             span,
1819                             &format!(
1820                                 "future {not_trait} as it awaits another future which {not_trait}",
1821                                 not_trait = trait_explanation
1822                             ),
1823                         );
1824                     } else {
1825                         // Look at the last interior type to get a span for the `.await`.
1826                         debug!(
1827                             "note_obligation_cause_for_async_await generator_interior_types: {:#?}",
1828                             typeck_results.as_ref().map(|t| &t.generator_interior_types)
1829                         );
1830                         explain_yield(interior_span, yield_span, scope_span);
1831                     }
1832
1833                     if let Some(expr_id) = expr {
1834                         let expr = hir.expect_expr(expr_id);
1835                         debug!("target_ty evaluated from {:?}", expr);
1836
1837                         let parent = hir.get_parent_node(expr_id);
1838                         if let Some(hir::Node::Expr(e)) = hir.find(parent) {
1839                             let parent_span = hir.span(parent);
1840                             let parent_did = parent.owner.to_def_id();
1841                             // ```rust
1842                             // impl T {
1843                             //     fn foo(&self) -> i32 {}
1844                             // }
1845                             // T.foo();
1846                             // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
1847                             // ```
1848                             //
1849                             let is_region_borrow = if let Some(typeck_results) = typeck_results {
1850                                 typeck_results
1851                                     .expr_adjustments(expr)
1852                                     .iter()
1853                                     .any(|adj| adj.is_region_borrow())
1854                             } else {
1855                                 false
1856                             };
1857
1858                             // ```rust
1859                             // struct Foo(*const u8);
1860                             // bar(Foo(std::ptr::null())).await;
1861                             //     ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
1862                             // ```
1863                             debug!("parent_def_kind: {:?}", self.tcx.def_kind(parent_did));
1864                             let is_raw_borrow_inside_fn_like_call =
1865                                 match self.tcx.def_kind(parent_did) {
1866                                     DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
1867                                     _ => false,
1868                                 };
1869                             if let Some(typeck_results) = typeck_results {
1870                                 if (typeck_results.is_method_call(e) && is_region_borrow)
1871                                     || is_raw_borrow_inside_fn_like_call
1872                                 {
1873                                     err.span_help(
1874                                         parent_span,
1875                                         "consider moving this into a `let` \
1876                         binding to create a shorter lived borrow",
1877                                     );
1878                                 }
1879                             }
1880                         }
1881                     }
1882                 }
1883             }
1884             GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
1885                 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
1886                 let refers_to_non_sync = match target_ty.kind() {
1887                     ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
1888                         Ok(eval) if !eval.may_apply() => Some(ref_ty),
1889                         _ => None,
1890                     },
1891                     _ => None,
1892                 };
1893
1894                 let (span_label, span_note) = match refers_to_non_sync {
1895                     // if `target_ty` is `&T` and `T` fails to impl `Sync`,
1896                     // include suggestions to make `T: Sync` so that `&T: Send`
1897                     Some(ref_ty) => (
1898                         format!(
1899                             "has type `{}` which {}, because `{}` is not `Sync`",
1900                             target_ty, trait_explanation, ref_ty
1901                         ),
1902                         format!(
1903                             "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
1904                             trait_explanation
1905                         ),
1906                     ),
1907                     None => (
1908                         format!("has type `{}` which {}", target_ty, trait_explanation),
1909                         format!("captured value {}", trait_explanation),
1910                     ),
1911                 };
1912
1913                 let mut span = MultiSpan::from_span(upvar_span);
1914                 span.push_span_label(upvar_span, span_label);
1915                 err.span_note(span, &span_note);
1916             }
1917         }
1918
1919         // Add a note for the item obligation that remains - normally a note pointing to the
1920         // bound that introduced the obligation (e.g. `T: Send`).
1921         debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
1922         self.note_obligation_cause_code(
1923             err,
1924             &obligation.predicate,
1925             obligation.param_env,
1926             next_code.unwrap(),
1927             &mut Vec::new(),
1928             &mut Default::default(),
1929         );
1930     }
1931
1932     fn note_obligation_cause_code<T>(
1933         &self,
1934         err: &mut Diagnostic,
1935         predicate: &T,
1936         param_env: ty::ParamEnv<'tcx>,
1937         cause_code: &ObligationCauseCode<'tcx>,
1938         obligated_types: &mut Vec<Ty<'tcx>>,
1939         seen_requirements: &mut FxHashSet<DefId>,
1940     ) where
1941         T: fmt::Display,
1942     {
1943         let tcx = self.tcx;
1944         match *cause_code {
1945             ObligationCauseCode::ExprAssignable
1946             | ObligationCauseCode::MatchExpressionArm { .. }
1947             | ObligationCauseCode::Pattern { .. }
1948             | ObligationCauseCode::IfExpression { .. }
1949             | ObligationCauseCode::IfExpressionWithNoElse
1950             | ObligationCauseCode::MainFunctionType
1951             | ObligationCauseCode::StartFunctionType
1952             | ObligationCauseCode::IntrinsicType
1953             | ObligationCauseCode::MethodReceiver
1954             | ObligationCauseCode::ReturnNoExpression
1955             | ObligationCauseCode::UnifyReceiver(..)
1956             | ObligationCauseCode::OpaqueType
1957             | ObligationCauseCode::MiscObligation
1958             | ObligationCauseCode::WellFormed(..)
1959             | ObligationCauseCode::MatchImpl(..)
1960             | ObligationCauseCode::ReturnType
1961             | ObligationCauseCode::ReturnValue(_)
1962             | ObligationCauseCode::BlockTailExpression(_)
1963             | ObligationCauseCode::AwaitableExpr(_)
1964             | ObligationCauseCode::ForLoopIterator
1965             | ObligationCauseCode::QuestionMark
1966             | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
1967             | ObligationCauseCode::LetElse
1968             | ObligationCauseCode::BinOp { .. } => {}
1969             ObligationCauseCode::SliceOrArrayElem => {
1970                 err.note("slice and array elements must have `Sized` type");
1971             }
1972             ObligationCauseCode::TupleElem => {
1973                 err.note("only the last element of a tuple may have a dynamically sized type");
1974             }
1975             ObligationCauseCode::ProjectionWf(data) => {
1976                 err.note(&format!("required so that the projection `{}` is well-formed", data,));
1977             }
1978             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1979                 err.note(&format!(
1980                     "required so that reference `{}` does not outlive its referent",
1981                     ref_ty,
1982                 ));
1983             }
1984             ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1985                 err.note(&format!(
1986                     "required so that the lifetime bound of `{}` for `{}` is satisfied",
1987                     region, object_ty,
1988                 ));
1989             }
1990             ObligationCauseCode::ItemObligation(_item_def_id) => {
1991                 // We hold the `DefId` of the item introducing the obligation, but displaying it
1992                 // doesn't add user usable information. It always point at an associated item.
1993             }
1994             ObligationCauseCode::BindingObligation(item_def_id, span) => {
1995                 let item_name = tcx.def_path_str(item_def_id);
1996                 let mut multispan = MultiSpan::from(span);
1997                 if let Some(ident) = tcx.opt_item_name(item_def_id) {
1998                     let sm = tcx.sess.source_map();
1999                     let same_line =
2000                         match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2001                             (Ok(l), Ok(r)) => l.line == r.line,
2002                             _ => true,
2003                         };
2004                     if !ident.span.overlaps(span) && !same_line {
2005                         multispan
2006                             .push_span_label(ident.span, "required by a bound in this".to_string());
2007                     }
2008                 }
2009                 let descr = format!("required by a bound in `{}`", item_name);
2010                 if span != DUMMY_SP {
2011                     let msg = format!("required by this bound in `{}`", item_name);
2012                     multispan.push_span_label(span, msg);
2013                     err.span_note(multispan, &descr);
2014                 } else {
2015                     err.span_note(tcx.def_span(item_def_id), &descr);
2016                 }
2017             }
2018             ObligationCauseCode::ObjectCastObligation(object_ty) => {
2019                 err.note(&format!(
2020                     "required for the cast to the object type `{}`",
2021                     self.ty_to_string(object_ty)
2022                 ));
2023             }
2024             ObligationCauseCode::Coercion { source: _, target } => {
2025                 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2026             }
2027             ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2028                 err.note(
2029                     "the `Copy` trait is required because the repeated element will be copied",
2030                 );
2031
2032                 if is_const_fn {
2033                     err.help(
2034                         "consider creating a new `const` item and initializing it with the result \
2035                         of the function call to be used in the repeat position, like \
2036                         `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2037                     );
2038                 }
2039
2040                 if self.tcx.sess.is_nightly_build() && is_const_fn {
2041                     err.help(
2042                         "create an inline `const` block, see RFC #2920 \
2043                          <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2044                     );
2045                 }
2046             }
2047             ObligationCauseCode::VariableType(hir_id) => {
2048                 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2049                 match self.tcx.hir().find(parent_node) {
2050                     Some(Node::Local(hir::Local {
2051                         init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2052                         ..
2053                     })) => {
2054                         // When encountering an assignment of an unsized trait, like
2055                         // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2056                         // order to use have a slice instead.
2057                         err.span_suggestion_verbose(
2058                             span.shrink_to_lo(),
2059                             "consider borrowing here",
2060                             "&".to_owned(),
2061                             Applicability::MachineApplicable,
2062                         );
2063                         err.note("all local variables must have a statically known size");
2064                     }
2065                     Some(Node::Param(param)) => {
2066                         err.span_suggestion_verbose(
2067                             param.ty_span.shrink_to_lo(),
2068                             "function arguments must have a statically known size, borrowed types \
2069                             always have a known size",
2070                             "&".to_owned(),
2071                             Applicability::MachineApplicable,
2072                         );
2073                     }
2074                     _ => {
2075                         err.note("all local variables must have a statically known size");
2076                     }
2077                 }
2078                 if !self.tcx.features().unsized_locals {
2079                     err.help("unsized locals are gated as an unstable feature");
2080                 }
2081             }
2082             ObligationCauseCode::SizedArgumentType(sp) => {
2083                 if let Some(span) = sp {
2084                     err.span_suggestion_verbose(
2085                         span.shrink_to_lo(),
2086                         "function arguments must have a statically known size, borrowed types \
2087                          always have a known size",
2088                         "&".to_string(),
2089                         Applicability::MachineApplicable,
2090                     );
2091                 } else {
2092                     err.note("all function arguments must have a statically known size");
2093                 }
2094                 if tcx.sess.opts.unstable_features.is_nightly_build()
2095                     && !self.tcx.features().unsized_fn_params
2096                 {
2097                     err.help("unsized fn params are gated as an unstable feature");
2098                 }
2099             }
2100             ObligationCauseCode::SizedReturnType => {
2101                 err.note("the return type of a function must have a statically known size");
2102             }
2103             ObligationCauseCode::SizedYieldType => {
2104                 err.note("the yield type of a generator must have a statically known size");
2105             }
2106             ObligationCauseCode::SizedBoxType => {
2107                 err.note("the type of a box expression must have a statically known size");
2108             }
2109             ObligationCauseCode::AssignmentLhsSized => {
2110                 err.note("the left-hand-side of an assignment must have a statically known size");
2111             }
2112             ObligationCauseCode::TupleInitializerSized => {
2113                 err.note("tuples must have a statically known size to be initialized");
2114             }
2115             ObligationCauseCode::StructInitializerSized => {
2116                 err.note("structs must have a statically known size to be initialized");
2117             }
2118             ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2119                 match *item {
2120                     AdtKind::Struct => {
2121                         if last {
2122                             err.note(
2123                                 "the last field of a packed struct may only have a \
2124                                 dynamically sized type if it does not need drop to be run",
2125                             );
2126                         } else {
2127                             err.note(
2128                                 "only the last field of a struct may have a dynamically sized type",
2129                             );
2130                         }
2131                     }
2132                     AdtKind::Union => {
2133                         err.note("no field of a union may have a dynamically sized type");
2134                     }
2135                     AdtKind::Enum => {
2136                         err.note("no field of an enum variant may have a dynamically sized type");
2137                     }
2138                 }
2139                 err.help("change the field's type to have a statically known size");
2140                 err.span_suggestion(
2141                     span.shrink_to_lo(),
2142                     "borrowed types always have a statically known size",
2143                     "&".to_string(),
2144                     Applicability::MachineApplicable,
2145                 );
2146                 err.multipart_suggestion(
2147                     "the `Box` type always has a statically known size and allocates its contents \
2148                      in the heap",
2149                     vec![
2150                         (span.shrink_to_lo(), "Box<".to_string()),
2151                         (span.shrink_to_hi(), ">".to_string()),
2152                     ],
2153                     Applicability::MachineApplicable,
2154                 );
2155             }
2156             ObligationCauseCode::ConstSized => {
2157                 err.note("constant expressions must have a statically known size");
2158             }
2159             ObligationCauseCode::InlineAsmSized => {
2160                 err.note("all inline asm arguments must have a statically known size");
2161             }
2162             ObligationCauseCode::ConstPatternStructural => {
2163                 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2164             }
2165             ObligationCauseCode::SharedStatic => {
2166                 err.note("shared static variables must have a type that implements `Sync`");
2167             }
2168             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2169                 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2170                 let ty = parent_trait_ref.skip_binder().self_ty();
2171                 if parent_trait_ref.references_error() {
2172                     // NOTE(eddyb) this was `.cancel()`, but `err`
2173                     // is borrowed, so we can't fully defuse it.
2174                     err.downgrade_to_delayed_bug();
2175                     return;
2176                 }
2177
2178                 // If the obligation for a tuple is set directly by a Generator or Closure,
2179                 // then the tuple must be the one containing capture types.
2180                 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2181                     false
2182                 } else {
2183                     if let ObligationCauseCode::BuiltinDerivedObligation(ref data) =
2184                         *data.parent_code
2185                     {
2186                         let parent_trait_ref =
2187                             self.resolve_vars_if_possible(data.parent_trait_pred);
2188                         let ty = parent_trait_ref.skip_binder().self_ty();
2189                         matches!(ty.kind(), ty::Generator(..))
2190                             || matches!(ty.kind(), ty::Closure(..))
2191                     } else {
2192                         false
2193                     }
2194                 };
2195
2196                 // Don't print the tuple of capture types
2197                 if !is_upvar_tys_infer_tuple {
2198                     let msg = format!("required because it appears within the type `{}`", ty);
2199                     match ty.kind() {
2200                         ty::Adt(def, _) => match self.tcx.opt_item_name(def.did()) {
2201                             Some(ident) => err.span_note(ident.span, &msg),
2202                             None => err.note(&msg),
2203                         },
2204                         _ => err.note(&msg),
2205                     };
2206                 }
2207
2208                 obligated_types.push(ty);
2209
2210                 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2211                 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2212                     // #74711: avoid a stack overflow
2213                     ensure_sufficient_stack(|| {
2214                         self.note_obligation_cause_code(
2215                             err,
2216                             &parent_predicate,
2217                             param_env,
2218                             &data.parent_code,
2219                             obligated_types,
2220                             seen_requirements,
2221                         )
2222                     });
2223                 } else {
2224                     ensure_sufficient_stack(|| {
2225                         self.note_obligation_cause_code(
2226                             err,
2227                             &parent_predicate,
2228                             param_env,
2229                             &cause_code.peel_derives(),
2230                             obligated_types,
2231                             seen_requirements,
2232                         )
2233                     });
2234                 }
2235             }
2236             ObligationCauseCode::ImplDerivedObligation(ref data) => {
2237                 let mut parent_trait_pred =
2238                     self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2239                 parent_trait_pred.remap_constness_diag(param_env);
2240                 let parent_def_id = parent_trait_pred.def_id();
2241                 let msg = format!(
2242                     "required because of the requirements on the impl of `{}` for `{}`",
2243                     parent_trait_pred.print_modifiers_and_trait_path(),
2244                     parent_trait_pred.skip_binder().self_ty()
2245                 );
2246                 let mut is_auto_trait = false;
2247                 match self.tcx.hir().get_if_local(data.impl_def_id) {
2248                     Some(Node::Item(hir::Item {
2249                         kind: hir::ItemKind::Trait(is_auto, ..),
2250                         ident,
2251                         ..
2252                     })) => {
2253                         // FIXME: we should do something else so that it works even on crate foreign
2254                         // auto traits.
2255                         is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2256                         err.span_note(ident.span, &msg)
2257                     }
2258                     Some(Node::Item(hir::Item {
2259                         kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2260                         ..
2261                     })) => {
2262                         let mut spans = Vec::with_capacity(2);
2263                         if let Some(trait_ref) = of_trait {
2264                             spans.push(trait_ref.path.span);
2265                         }
2266                         spans.push(self_ty.span);
2267                         err.span_note(spans, &msg)
2268                     }
2269                     _ => err.note(&msg),
2270                 };
2271
2272                 let mut parent_predicate = parent_trait_pred.to_predicate(tcx);
2273                 let mut data = &data.derived;
2274                 let mut count = 0;
2275                 seen_requirements.insert(parent_def_id);
2276                 if is_auto_trait {
2277                     // We don't want to point at the ADT saying "required because it appears within
2278                     // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2279                     while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2280                         &*data.parent_code
2281                     {
2282                         let child_trait_ref =
2283                             self.resolve_vars_if_possible(derived.parent_trait_pred);
2284                         let child_def_id = child_trait_ref.def_id();
2285                         if seen_requirements.insert(child_def_id) {
2286                             break;
2287                         }
2288                         data = derived;
2289                         parent_predicate = child_trait_ref.to_predicate(tcx);
2290                         parent_trait_pred = child_trait_ref;
2291                     }
2292                 }
2293                 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2294                     // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2295                     let child_trait_pred =
2296                         self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2297                     let child_def_id = child_trait_pred.def_id();
2298                     if seen_requirements.insert(child_def_id) {
2299                         break;
2300                     }
2301                     count += 1;
2302                     data = &child.derived;
2303                     parent_predicate = child_trait_pred.to_predicate(tcx);
2304                     parent_trait_pred = child_trait_pred;
2305                 }
2306                 if count > 0 {
2307                     err.note(&format!(
2308                         "{} redundant requirement{} hidden",
2309                         count,
2310                         pluralize!(count)
2311                     ));
2312                     err.note(&format!(
2313                         "required because of the requirements on the impl of `{}` for `{}`",
2314                         parent_trait_pred.print_modifiers_and_trait_path(),
2315                         parent_trait_pred.skip_binder().self_ty()
2316                     ));
2317                 }
2318                 // #74711: avoid a stack overflow
2319                 ensure_sufficient_stack(|| {
2320                     self.note_obligation_cause_code(
2321                         err,
2322                         &parent_predicate,
2323                         param_env,
2324                         &data.parent_code,
2325                         obligated_types,
2326                         seen_requirements,
2327                     )
2328                 });
2329             }
2330             ObligationCauseCode::DerivedObligation(ref data) => {
2331                 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2332                 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2333                 // #74711: avoid a stack overflow
2334                 ensure_sufficient_stack(|| {
2335                     self.note_obligation_cause_code(
2336                         err,
2337                         &parent_predicate,
2338                         param_env,
2339                         &data.parent_code,
2340                         obligated_types,
2341                         seen_requirements,
2342                     )
2343                 });
2344             }
2345             ObligationCauseCode::FunctionArgumentObligation {
2346                 arg_hir_id,
2347                 call_hir_id,
2348                 ref parent_code,
2349             } => {
2350                 let hir = self.tcx.hir();
2351                 if let Some(Node::Expr(expr @ hir::Expr { kind: hir::ExprKind::Block(..), .. })) =
2352                     hir.find(arg_hir_id)
2353                 {
2354                     let in_progress_typeck_results =
2355                         self.in_progress_typeck_results.map(|t| t.borrow());
2356                     let parent_id = hir.get_parent_item(arg_hir_id);
2357                     let typeck_results: &TypeckResults<'tcx> = match &in_progress_typeck_results {
2358                         Some(t) if t.hir_owner == parent_id => t,
2359                         _ => self.tcx.typeck(parent_id),
2360                     };
2361                     let ty = typeck_results.expr_ty_adjusted(expr);
2362                     let span = expr.peel_blocks().span;
2363                     if Some(span) != err.span.primary_span() {
2364                         err.span_label(
2365                             span,
2366                             &if ty.references_error() {
2367                                 String::new()
2368                             } else {
2369                                 format!("this tail expression is of type `{:?}`", ty)
2370                             },
2371                         );
2372                     }
2373                 }
2374                 if let Some(Node::Expr(hir::Expr {
2375                     kind:
2376                         hir::ExprKind::Call(hir::Expr { span, .. }, _)
2377                         | hir::ExprKind::MethodCall(
2378                             hir::PathSegment { ident: Ident { span, .. }, .. },
2379                             ..,
2380                         ),
2381                     ..
2382                 })) = hir.find(call_hir_id)
2383                 {
2384                     if Some(*span) != err.span.primary_span() {
2385                         err.span_label(*span, "required by a bound introduced by this call");
2386                     }
2387                 }
2388                 ensure_sufficient_stack(|| {
2389                     self.note_obligation_cause_code(
2390                         err,
2391                         predicate,
2392                         param_env,
2393                         &parent_code,
2394                         obligated_types,
2395                         seen_requirements,
2396                     )
2397                 });
2398             }
2399             ObligationCauseCode::CompareImplMethodObligation { trait_item_def_id, .. } => {
2400                 let item_name = self.tcx.item_name(trait_item_def_id);
2401                 let msg = format!(
2402                     "the requirement `{}` appears on the impl method `{}` but not on the \
2403                      corresponding trait method",
2404                     predicate, item_name,
2405                 );
2406                 let sp = self
2407                     .tcx
2408                     .opt_item_name(trait_item_def_id)
2409                     .map(|i| i.span)
2410                     .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2411                 let mut assoc_span: MultiSpan = sp.into();
2412                 assoc_span.push_span_label(
2413                     sp,
2414                     format!("this trait method doesn't have the requirement `{}`", predicate),
2415                 );
2416                 if let Some(ident) = self
2417                     .tcx
2418                     .opt_associated_item(trait_item_def_id)
2419                     .and_then(|i| self.tcx.opt_item_name(i.container.id()))
2420                 {
2421                     assoc_span.push_span_label(ident.span, "in this trait".into());
2422                 }
2423                 err.span_note(assoc_span, &msg);
2424             }
2425             ObligationCauseCode::CompareImplTypeObligation { trait_item_def_id, .. } => {
2426                 let item_name = self.tcx.item_name(trait_item_def_id);
2427                 let msg = format!(
2428                     "the requirement `{}` appears on the associated impl type `{}` but not on the \
2429                      corresponding associated trait type",
2430                     predicate, item_name,
2431                 );
2432                 let sp = self.tcx.def_span(trait_item_def_id);
2433                 let mut assoc_span: MultiSpan = sp.into();
2434                 assoc_span.push_span_label(
2435                     sp,
2436                     format!(
2437                         "this trait associated type doesn't have the requirement `{}`",
2438                         predicate,
2439                     ),
2440                 );
2441                 if let Some(ident) = self
2442                     .tcx
2443                     .opt_associated_item(trait_item_def_id)
2444                     .and_then(|i| self.tcx.opt_item_name(i.container.id()))
2445                 {
2446                     assoc_span.push_span_label(ident.span, "in this trait".into());
2447                 }
2448                 err.span_note(assoc_span, &msg);
2449             }
2450             ObligationCauseCode::CompareImplConstObligation => {
2451                 err.note(&format!(
2452                     "the requirement `{}` appears on the associated impl constant \
2453                      but not on the corresponding associated trait constant",
2454                     predicate
2455                 ));
2456             }
2457             ObligationCauseCode::TrivialBound => {
2458                 err.help("see issue #48214");
2459                 if tcx.sess.opts.unstable_features.is_nightly_build() {
2460                     err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2461                 }
2462             }
2463         }
2464     }
2465
2466     fn suggest_new_overflow_limit(&self, err: &mut Diagnostic) {
2467         let suggested_limit = match self.tcx.recursion_limit() {
2468             Limit(0) => Limit(2),
2469             limit => limit * 2,
2470         };
2471         err.help(&format!(
2472             "consider increasing the recursion limit by adding a \
2473              `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
2474             suggested_limit,
2475             self.tcx.crate_name(LOCAL_CRATE),
2476         ));
2477     }
2478
2479     fn suggest_await_before_try(
2480         &self,
2481         err: &mut Diagnostic,
2482         obligation: &PredicateObligation<'tcx>,
2483         trait_pred: ty::PolyTraitPredicate<'tcx>,
2484         span: Span,
2485     ) {
2486         debug!(
2487             "suggest_await_before_try: obligation={:?}, span={:?}, trait_pred={:?}, trait_pred_self_ty={:?}",
2488             obligation,
2489             span,
2490             trait_pred,
2491             trait_pred.self_ty()
2492         );
2493         let body_hir_id = obligation.cause.body_id;
2494         let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2495
2496         if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(item_id) {
2497             let body = self.tcx.hir().body(body_id);
2498             if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2499                 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2500
2501                 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
2502
2503                 // Do not check on infer_types to avoid panic in evaluate_obligation.
2504                 if self_ty.has_infer_types() {
2505                     return;
2506                 }
2507                 let self_ty = self.tcx.erase_regions(self_ty);
2508
2509                 let impls_future = self.type_implements_trait(
2510                     future_trait,
2511                     self_ty.skip_binder(),
2512                     ty::List::empty(),
2513                     obligation.param_env,
2514                 );
2515
2516                 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2517                 // `<T as Future>::Output`
2518                 let projection_ty = ty::ProjectionTy {
2519                     // `T`
2520                     substs: self.tcx.mk_substs_trait(
2521                         trait_pred.self_ty().skip_binder(),
2522                         &self.fresh_substs_for_item(span, item_def_id)[1..],
2523                     ),
2524                     // `Future::Output`
2525                     item_def_id,
2526                 };
2527
2528                 let mut selcx = SelectionContext::new(self);
2529
2530                 let mut obligations = vec![];
2531                 let normalized_ty = normalize_projection_type(
2532                     &mut selcx,
2533                     obligation.param_env,
2534                     projection_ty,
2535                     obligation.cause.clone(),
2536                     0,
2537                     &mut obligations,
2538                 );
2539
2540                 debug!(
2541                     "suggest_await_before_try: normalized_projection_type {:?}",
2542                     self.resolve_vars_if_possible(normalized_ty)
2543                 );
2544                 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2545                     obligation.param_env,
2546                     trait_pred,
2547                     normalized_ty.ty().unwrap(),
2548                 );
2549                 debug!("suggest_await_before_try: try_trait_obligation {:?}", try_obligation);
2550                 if self.predicate_may_hold(&try_obligation)
2551                     && impls_future.must_apply_modulo_regions()
2552                     && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2553                     && snippet.ends_with('?')
2554                 {
2555                     err.span_suggestion_verbose(
2556                         span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
2557                         "consider `await`ing on the `Future`",
2558                         ".await".to_string(),
2559                         Applicability::MaybeIncorrect,
2560                     );
2561                 }
2562             }
2563         }
2564     }
2565
2566     fn suggest_floating_point_literal(
2567         &self,
2568         obligation: &PredicateObligation<'tcx>,
2569         err: &mut Diagnostic,
2570         trait_ref: &ty::PolyTraitRef<'tcx>,
2571     ) {
2572         let rhs_span = match obligation.cause.code() {
2573             ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit } if *is_lit => span,
2574             _ => return,
2575         };
2576         match (
2577             trait_ref.skip_binder().self_ty().kind(),
2578             trait_ref.skip_binder().substs.type_at(1).kind(),
2579         ) {
2580             (ty::Float(_), ty::Infer(InferTy::IntVar(_))) => {
2581                 err.span_suggestion_verbose(
2582                     rhs_span.shrink_to_hi(),
2583                     "consider using a floating-point literal by writing it with `.0`",
2584                     String::from(".0"),
2585                     Applicability::MaybeIncorrect,
2586                 );
2587             }
2588             _ => {}
2589         }
2590     }
2591 }
2592
2593 /// Collect all the returned expressions within the input expression.
2594 /// Used to point at the return spans when we want to suggest some change to them.
2595 #[derive(Default)]
2596 pub struct ReturnsVisitor<'v> {
2597     pub returns: Vec<&'v hir::Expr<'v>>,
2598     in_block_tail: bool,
2599 }
2600
2601 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
2602     fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2603         // Visit every expression to detect `return` paths, either through the function's tail
2604         // expression or `return` statements. We walk all nodes to find `return` statements, but
2605         // we only care about tail expressions when `in_block_tail` is `true`, which means that
2606         // they're in the return path of the function body.
2607         match ex.kind {
2608             hir::ExprKind::Ret(Some(ex)) => {
2609                 self.returns.push(ex);
2610             }
2611             hir::ExprKind::Block(block, _) if self.in_block_tail => {
2612                 self.in_block_tail = false;
2613                 for stmt in block.stmts {
2614                     hir::intravisit::walk_stmt(self, stmt);
2615                 }
2616                 self.in_block_tail = true;
2617                 if let Some(expr) = block.expr {
2618                     self.visit_expr(expr);
2619                 }
2620             }
2621             hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
2622                 self.visit_expr(then);
2623                 if let Some(el) = else_opt {
2624                     self.visit_expr(el);
2625                 }
2626             }
2627             hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
2628                 for arm in arms {
2629                     self.visit_expr(arm.body);
2630                 }
2631             }
2632             // We need to walk to find `return`s in the entire body.
2633             _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
2634             _ => self.returns.push(ex),
2635         }
2636     }
2637
2638     fn visit_body(&mut self, body: &'v hir::Body<'v>) {
2639         assert!(!self.in_block_tail);
2640         if body.generator_kind().is_none() {
2641             if let hir::ExprKind::Block(block, None) = body.value.kind {
2642                 if block.expr.is_some() {
2643                     self.in_block_tail = true;
2644                 }
2645             }
2646         }
2647         hir::intravisit::walk_body(self, body);
2648     }
2649 }
2650
2651 /// Collect all the awaited expressions within the input expression.
2652 #[derive(Default)]
2653 struct AwaitsVisitor {
2654     awaits: Vec<hir::HirId>,
2655 }
2656
2657 impl<'v> Visitor<'v> for AwaitsVisitor {
2658     fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2659         if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
2660             self.awaits.push(id)
2661         }
2662         hir::intravisit::walk_expr(self, ex)
2663     }
2664 }
2665
2666 pub trait NextTypeParamName {
2667     fn next_type_param_name(&self, name: Option<&str>) -> String;
2668 }
2669
2670 impl NextTypeParamName for &[hir::GenericParam<'_>] {
2671     fn next_type_param_name(&self, name: Option<&str>) -> String {
2672         // This is the list of possible parameter names that we might suggest.
2673         let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
2674         let name = name.as_deref();
2675         let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
2676         let used_names = self
2677             .iter()
2678             .filter_map(|p| match p.name {
2679                 hir::ParamName::Plain(ident) => Some(ident.name),
2680                 _ => None,
2681             })
2682             .collect::<Vec<_>>();
2683
2684         possible_names
2685             .iter()
2686             .find(|n| !used_names.contains(&Symbol::intern(n)))
2687             .unwrap_or(&"ParamName")
2688             .to_string()
2689     }
2690 }
2691
2692 fn suggest_trait_object_return_type_alternatives(
2693     err: &mut Diagnostic,
2694     ret_ty: Span,
2695     trait_obj: &str,
2696     is_object_safe: bool,
2697 ) {
2698     err.span_suggestion(
2699         ret_ty,
2700         "use some type `T` that is `T: Sized` as the return type if all return paths have the \
2701             same type",
2702         "T".to_string(),
2703         Applicability::MaybeIncorrect,
2704     );
2705     err.span_suggestion(
2706         ret_ty,
2707         &format!(
2708             "use `impl {}` as the return type if all return paths have the same type but you \
2709                 want to expose only the trait in the signature",
2710             trait_obj,
2711         ),
2712         format!("impl {}", trait_obj),
2713         Applicability::MaybeIncorrect,
2714     );
2715     if is_object_safe {
2716         err.span_suggestion(
2717             ret_ty,
2718             &format!(
2719                 "use a boxed trait object if all return paths implement trait `{}`",
2720                 trait_obj,
2721             ),
2722             format!("Box<dyn {}>", trait_obj),
2723             Applicability::MaybeIncorrect,
2724         );
2725     }
2726 }