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