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