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