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