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