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