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