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