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