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