Skip to main content

rustc_trait_selection/error_reporting/traits/
suggestions.rs

1// ignore-tidy-filelength
2
3use std::borrow::Cow;
4use std::path::PathBuf;
5use std::{debug_assert_matches, iter};
6
7use itertools::{EitherOrBoth, Itertools};
8use rustc_abi::ExternAbi;
9use rustc_data_structures::fx::FxHashSet;
10use rustc_data_structures::stack::ensure_sufficient_stack;
11use rustc_errors::codes::*;
12use rustc_errors::{
13    Applicability, Diag, EmissionGuarantee, MultiSpan, Style, SuggestionStyle, pluralize,
14    struct_span_code_err,
15};
16use rustc_hir::def::{CtorOf, DefKind, Res};
17use rustc_hir::def_id::DefId;
18use rustc_hir::intravisit::{Visitor, VisitorExt};
19use rustc_hir::lang_items::LangItem;
20use rustc_hir::{
21    self as hir, AmbigArg, CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, HirId, Node,
22    expr_needs_parens,
23};
24use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferCtxt, InferOk};
25use rustc_infer::traits::ImplSource;
26use rustc_middle::middle::privacy::Level;
27use rustc_middle::traits::IsConstable;
28use rustc_middle::ty::adjustment::{Adjust, DerefAdjustKind};
29use rustc_middle::ty::error::TypeError;
30use rustc_middle::ty::print::{
31    PrintPolyTraitPredicateExt as _, PrintPolyTraitRefExt, PrintTraitPredicateExt as _,
32    PrintTraitRefExt as _, with_forced_trimmed_paths, with_no_trimmed_paths,
33    with_types_for_suggestion,
34};
35use rustc_middle::ty::{
36    self, AdtKind, GenericArgs, InferTy, IsSuggestable, Ty, TyCtxt, TypeFoldable, TypeFolder,
37    TypeSuperFoldable, TypeSuperVisitable, TypeVisitableExt, TypeVisitor, TypeckResults,
38    Unnormalized, Upcast, suggest_arbitrary_trait_bound, suggest_constraining_type_param,
39};
40use rustc_middle::{bug, span_bug};
41use rustc_span::def_id::LocalDefId;
42use rustc_span::{
43    BytePos, DUMMY_SP, DesugaringKind, ExpnKind, Ident, MacroKind, Span, Symbol, kw, sym,
44};
45use tracing::{debug, instrument};
46
47use super::{
48    DefIdOrName, FindExprBySpan, ImplCandidate, Obligation, ObligationCause, ObligationCauseCode,
49    PredicateObligation,
50};
51use crate::diagnostics;
52use crate::error_reporting::TypeErrCtxt;
53use crate::infer::InferCtxtExt as _;
54use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
55use crate::traits::{ImplDerivedCause, NormalizeExt, ObligationCtxt, SelectionContext};
56
57#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CoroutineInteriorOrUpvar {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            CoroutineInteriorOrUpvar::Interior(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "Interior", __self_0, &__self_1),
            CoroutineInteriorOrUpvar::Upvar(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Upvar",
                    &__self_0),
        }
    }
}Debug)]
58pub enum CoroutineInteriorOrUpvar {
59    // span of interior type
60    Interior(Span, Option<(Span, Option<Span>)>),
61    // span of upvar
62    Upvar(Span),
63}
64
65// This type provides a uniform interface to retrieve data on coroutines, whether it originated from
66// the local crate being compiled or from a foreign crate.
67#[derive(#[automatically_derived]
impl<'a, 'tcx> ::core::fmt::Debug for CoroutineData<'a, 'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "CoroutineData",
            &&self.0)
    }
}Debug)]
68struct CoroutineData<'a, 'tcx>(&'a TypeckResults<'tcx>);
69
70impl<'a, 'tcx> CoroutineData<'a, 'tcx> {
71    /// Try to get information about variables captured by the coroutine that matches a type we are
72    /// looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
73    /// meet an obligation
74    fn try_get_upvar_span<F>(
75        &self,
76        infer_context: &InferCtxt<'tcx>,
77        coroutine_did: DefId,
78        ty_matches: F,
79    ) -> Option<CoroutineInteriorOrUpvar>
80    where
81        F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
82    {
83        infer_context.tcx.upvars_mentioned(coroutine_did).and_then(|upvars| {
84            upvars.iter().find_map(|(upvar_id, upvar)| {
85                let upvar_ty = self.0.node_type(*upvar_id);
86                let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
87                ty_matches(ty::Binder::dummy(upvar_ty))
88                    .then(|| CoroutineInteriorOrUpvar::Upvar(upvar.span))
89            })
90        })
91    }
92
93    /// Try to get the span of a type being awaited on that matches the type we are looking with the
94    /// `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
95    /// obligation
96    fn get_from_await_ty<F>(
97        &self,
98        visitor: AwaitsVisitor,
99        tcx: TyCtxt<'tcx>,
100        ty_matches: F,
101    ) -> Option<Span>
102    where
103        F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
104    {
105        visitor
106            .awaits
107            .into_iter()
108            .map(|id| tcx.hir_expect_expr(id))
109            .find(|await_expr| ty_matches(ty::Binder::dummy(self.0.expr_ty_adjusted(await_expr))))
110            .map(|expr| expr.span)
111    }
112}
113
114fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
115    (
116        generics.tail_span_for_predicate_suggestion(),
117        {
    let _guard =
        ::rustc_middle::ty::print::pretty::RtnModeHelper::with(RtnMode::ForSuggestion);
    ::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("{0} {1}",
                    generics.add_where_or_trailing_comma(), pred))
        })
}with_types_for_suggestion!(format!("{} {}", generics.add_where_or_trailing_comma(), pred)),
118    )
119}
120
121/// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
122/// it can also be an `impl Trait` param that needs to be decomposed to a type
123/// param for cleaner code.
124pub fn suggest_restriction<'tcx, G: EmissionGuarantee>(
125    tcx: TyCtxt<'tcx>,
126    item_id: LocalDefId,
127    hir_generics: &hir::Generics<'tcx>,
128    msg: &str,
129    err: &mut Diag<'_, G>,
130    fn_sig: Option<&hir::FnSig<'_>>,
131    projection: Option<ty::ProjectionAliasTy<'_>>,
132    trait_pred: ty::PolyTraitPredicate<'tcx>,
133    // When we are dealing with a trait, `super_traits` will be `Some`:
134    // Given `trait T: A + B + C {}`
135    //              -  ^^^^^^^^^ GenericBounds
136    //              |
137    //              &Ident
138    super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
139) {
140    if hir_generics.where_clause_span.from_expansion()
141        || hir_generics.where_clause_span.desugaring_kind().is_some()
142        || projection.is_some_and(|projection| {
143            (tcx.is_impl_trait_in_trait(projection.kind) && !tcx.features().return_type_notation())
144                || tcx.lookup_stability(projection.kind).is_some_and(|stab| stab.is_unstable())
145        })
146    {
147        return;
148    }
149    let generics = tcx.generics_of(item_id);
150    // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
151    if let Some((param, bound_str, fn_sig)) =
152        fn_sig.zip(projection).and_then(|(sig, p)| match *p.projection_self_ty().kind() {
153            // Shenanigans to get the `Trait` from the `impl Trait`.
154            ty::Param(param) => {
155                let param_def = generics.type_param(param, tcx);
156                if param_def.kind.is_synthetic() {
157                    let bound_str =
158                        param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
159                    return Some((param_def, bound_str, sig));
160                }
161                None
162            }
163            _ => None,
164        })
165    {
166        let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
167        let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
168            tcx,
169            param,
170            replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
171                .to_ty(tcx),
172        });
173        if !trait_pred.is_suggestable(tcx, false) {
174            return;
175        }
176        // We know we have an `impl Trait` that doesn't satisfy a required projection.
177
178        // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
179        // types. There should be at least one, but there might be *more* than one. In that
180        // case we could just ignore it and try to identify which one needs the restriction,
181        // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
182        // where `T: Trait`.
183        let mut ty_spans = ::alloc::vec::Vec::new()vec![];
184        for input in fn_sig.decl.inputs {
185            ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
186                .visit_ty_unambig(input);
187        }
188        // The type param `T: Trait` we will suggest to introduce.
189        let type_param = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", type_param_name,
                bound_str))
    })format!("{type_param_name}: {bound_str}");
190
191        let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [if let Some(span) = hir_generics.span_for_param_suggestion() {
                    (span,
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!(", {0}", type_param))
                            }))
                } else {
                    (hir_generics.span,
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("<{0}>", type_param))
                            }))
                },
                predicate_constraint(hir_generics, trait_pred.upcast(tcx))]))vec![
192            if let Some(span) = hir_generics.span_for_param_suggestion() {
193                (span, format!(", {type_param}"))
194            } else {
195                (hir_generics.span, format!("<{type_param}>"))
196            },
197            // `fn foo(t: impl Trait)`
198            //                       ^ suggest `where <T as Trait>::A: Bound`
199            predicate_constraint(hir_generics, trait_pred.upcast(tcx)),
200        ];
201        sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
202
203        // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
204        // FIXME: we should suggest `fn foo(t: impl Trait<A: Bound>)` instead.
205        err.multipart_suggestion(
206            "introduce a type parameter with a trait bound instead of using `impl Trait`",
207            sugg,
208            Applicability::MaybeIncorrect,
209        );
210    } else {
211        if !trait_pred.is_suggestable(tcx, false) {
212            return;
213        }
214        // Trivial case: `T` needs an extra bound: `T: Bound`.
215        let (sp, suggestion) = match (
216            hir_generics
217                .params
218                .iter()
219                .find(|p| !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
    hir::GenericParamKind::Type { synthetic: true, .. } => true,
    _ => false,
}matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
220            super_traits,
221        ) {
222            (_, None) => predicate_constraint(hir_generics, trait_pred.upcast(tcx)),
223            (None, Some((ident, []))) => (
224                ident.span.shrink_to_hi(),
225                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(": {0}",
                trait_pred.print_modifiers_and_trait_path()))
    })format!(": {}", trait_pred.print_modifiers_and_trait_path()),
226            ),
227            (_, Some((_, [.., bounds]))) => (
228                bounds.span().shrink_to_hi(),
229                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" + {0}",
                trait_pred.print_modifiers_and_trait_path()))
    })format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
230            ),
231            (Some(_), Some((_, []))) => (
232                hir_generics.span.shrink_to_hi(),
233                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(": {0}",
                trait_pred.print_modifiers_and_trait_path()))
    })format!(": {}", trait_pred.print_modifiers_and_trait_path()),
234            ),
235        };
236
237        err.span_suggestion_verbose(
238            sp,
239            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider further restricting {0}",
                msg))
    })format!("consider further restricting {msg}"),
240            suggestion,
241            Applicability::MachineApplicable,
242        );
243    }
244}
245
246/// A single layer of `&` peeled from an expression, used by
247/// [`TypeErrCtxt::peel_expr_refs`].
248struct PeeledRef<'tcx> {
249    /// The span covering the `&` (and any whitespace/mutability keyword) to remove.
250    span: Span,
251    /// The type after peeling this layer (and all prior layers).
252    peeled_ty: Ty<'tcx>,
253}
254
255impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
256    pub fn note_field_shadowed_by_private_candidate_in_cause(
257        &self,
258        err: &mut Diag<'_>,
259        cause: &ObligationCause<'tcx>,
260        param_env: ty::ParamEnv<'tcx>,
261    ) {
262        let mut hir_ids = FxHashSet::default();
263        // Walk the parent chain so we can recover
264        // the source expression from whichever layer carries them.
265        let mut next_code = Some(cause.code());
266        while let Some(cause_code) = next_code {
267            match cause_code {
268                ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. } => {
269                    hir_ids.insert(*lhs_hir_id);
270                    hir_ids.insert(*rhs_hir_id);
271                }
272                ObligationCauseCode::FunctionArg { arg_hir_id, .. }
273                | ObligationCauseCode::ReturnValue(arg_hir_id)
274                | ObligationCauseCode::AwaitableExpr(arg_hir_id)
275                | ObligationCauseCode::BlockTailExpression(arg_hir_id, _)
276                | ObligationCauseCode::UnOp { hir_id: arg_hir_id } => {
277                    hir_ids.insert(*arg_hir_id);
278                }
279                ObligationCauseCode::OpaqueReturnType(Some((_, hir_id))) => {
280                    hir_ids.insert(*hir_id);
281                }
282                _ => {}
283            }
284            next_code = cause_code.parent();
285        }
286
287        if !cause.span.is_dummy()
288            && let Some(body) = self.tcx.hir_maybe_body_owned_by(cause.body_def_id)
289        {
290            let mut expr_finder = FindExprBySpan::new(cause.span, self.tcx);
291            expr_finder.visit_body(body);
292            if let Some(expr) = expr_finder.result {
293                hir_ids.insert(expr.hir_id);
294            }
295        }
296
297        // we will sort immediately by source order before emitting any diagnostics
298        #[allow(rustc::potential_query_instability)]
299        let mut hir_ids: Vec<_> = hir_ids.into_iter().collect();
300        let source_map = self.tcx.sess.source_map();
301        hir_ids.sort_by_cached_key(|hir_id| {
302            let span = self.tcx.hir_span(*hir_id);
303            let lo = source_map.lookup_byte_offset(span.lo());
304            let hi = source_map.lookup_byte_offset(span.hi());
305            (lo.sf.name.prefer_remapped_unconditionally().to_string(), lo.pos.0, hi.pos.0)
306        });
307
308        for hir_id in hir_ids {
309            self.note_field_shadowed_by_private_candidate(err, hir_id, param_env);
310        }
311    }
312
313    pub fn note_field_shadowed_by_private_candidate(
314        &self,
315        err: &mut Diag<'_>,
316        hir_id: hir::HirId,
317        param_env: ty::ParamEnv<'tcx>,
318    ) {
319        let Some(typeck_results) = &self.typeck_results else {
320            return;
321        };
322        let Node::Expr(expr) = self.tcx.hir_node(hir_id) else {
323            return;
324        };
325        let hir::ExprKind::Field(base_expr, field_ident) = expr.kind else {
326            return;
327        };
328
329        let Some(base_ty) = typeck_results.expr_ty_opt(base_expr) else {
330            return;
331        };
332        let base_ty = self.resolve_vars_if_possible(base_ty);
333        if base_ty.references_error() {
334            return;
335        }
336
337        let mut private_candidate: Option<(Ty<'tcx>, Ty<'tcx>, Span)> = None;
338
339        for (deref_base_ty, _) in (self.autoderef_steps)(base_ty) {
340            let ty::Adt(base_def, args) = deref_base_ty.kind() else {
341                continue;
342            };
343
344            if base_def.is_enum() {
345                continue;
346            }
347
348            let (adjusted_ident, def_scope) = self.tcx.adjust_ident_and_get_scope(
349                field_ident,
350                base_def.did(),
351                typeck_results.hir_owner.def_id,
352            );
353
354            let Some((_, field_def)) =
355                base_def.non_enum_variant().fields.iter_enumerated().find(|(_, field)| {
356                    field.ident(self.tcx).normalize_to_macros_2_0() == adjusted_ident
357                })
358            else {
359                continue;
360            };
361            let field_span = self
362                .tcx
363                .def_ident_span(field_def.did)
364                .unwrap_or_else(|| self.tcx.def_span(field_def.did));
365
366            if field_def.vis.is_accessible_from(def_scope, self.tcx) {
367                let accessible_field_ty = field_def.ty(self.tcx, args).skip_norm_wip();
368                if let Some((private_base_ty, private_field_ty, private_field_span)) =
369                    private_candidate
370                    && !self.can_eq(param_env, private_field_ty, accessible_field_ty)
371                {
372                    let private_struct_span = match private_base_ty.kind() {
373                        ty::Adt(private_base_def, _) => self
374                            .tcx
375                            .def_ident_span(private_base_def.did())
376                            .unwrap_or_else(|| self.tcx.def_span(private_base_def.did())),
377                        _ => DUMMY_SP,
378                    };
379                    let accessible_struct_span = self
380                        .tcx
381                        .def_ident_span(base_def.did())
382                        .unwrap_or_else(|| self.tcx.def_span(base_def.did()));
383                    let deref_impl_span = (typeck_results
384                        .expr_adjustments(base_expr)
385                        .iter()
386                        .filter(|adj| {
387                            #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
    Adjust::Deref(DerefAdjustKind::Overloaded(_)) => true,
    _ => false,
}matches!(adj.kind, Adjust::Deref(DerefAdjustKind::Overloaded(_)))
388                        })
389                        .count()
390                        == 1)
391                        .then(|| {
392                            self.probe(|_| {
393                                let deref_trait_did =
394                                    self.tcx.require_lang_item(LangItem::Deref, DUMMY_SP);
395                                let trait_ref =
396                                    ty::TraitRef::new(self.tcx, deref_trait_did, [private_base_ty]);
397                                let obligation: Obligation<'tcx, ty::Predicate<'tcx>> =
398                                    Obligation::new(
399                                        self.tcx,
400                                        ObligationCause::dummy(),
401                                        param_env,
402                                        trait_ref,
403                                    );
404                                let Ok(Some(ImplSource::UserDefined(impl_data))) =
405                                    SelectionContext::new(self)
406                                        .select(&obligation.with(self.tcx, trait_ref))
407                                else {
408                                    return None;
409                                };
410                                Some(self.tcx.def_span(impl_data.impl_def_id))
411                            })
412                        })
413                        .flatten();
414
415                    let mut note_spans: MultiSpan = private_struct_span.into();
416                    if private_struct_span != DUMMY_SP {
417                        note_spans.push_span_label(private_struct_span, "in this struct");
418                    }
419                    if private_field_span != DUMMY_SP {
420                        note_spans.push_span_label(
421                            private_field_span,
422                            "if this field wasn't private, it would be accessible",
423                        );
424                    }
425                    if accessible_struct_span != DUMMY_SP {
426                        note_spans.push_span_label(
427                            accessible_struct_span,
428                            "this struct is accessible through auto-deref",
429                        );
430                    }
431                    if field_span != DUMMY_SP {
432                        note_spans
433                            .push_span_label(field_span, "this is the field that was accessed");
434                    }
435                    if let Some(deref_impl_span) = deref_impl_span
436                        && deref_impl_span != DUMMY_SP
437                    {
438                        note_spans.push_span_label(
439                            deref_impl_span,
440                            "the field was accessed through this `Deref`",
441                        );
442                    }
443
444                    err.span_note(
445                        note_spans,
446                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("there is a field `{0}` on `{1}` with type `{2}` but it is private; `{0}` from `{3}` was accessed through auto-deref instead",
                field_ident, private_base_ty, private_field_ty,
                deref_base_ty))
    })format!(
447                            "there is a field `{field_ident}` on `{private_base_ty}` with type `{private_field_ty}` but it is private; `{field_ident}` from `{deref_base_ty}` was accessed through auto-deref instead"
448                        ),
449                    );
450                }
451
452                // we finally get to the accessible field,
453                // so we can return early without checking the rest of the autoderef candidates
454                return;
455            }
456
457            private_candidate.get_or_insert((
458                deref_base_ty,
459                field_def.ty(self.tcx, args).skip_norm_wip(),
460                field_span,
461            ));
462        }
463    }
464
465    pub fn suggest_restricting_param_bound(
466        &self,
467        err: &mut Diag<'_>,
468        trait_pred: ty::PolyTraitPredicate<'tcx>,
469        associated_ty: Option<(&'static str, Ty<'tcx>)>,
470        mut body_def_id: LocalDefId,
471    ) {
472        if trait_pred.skip_binder().polarity != ty::PredicatePolarity::Positive {
473            return;
474        }
475
476        let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
477
478        let self_ty = trait_pred.skip_binder().self_ty();
479        let (param_ty, projection) = match *self_ty.kind() {
480            ty::Param(_) => (true, None),
481            ty::Alias(_, alias) => {
482                if let Some(projection) = alias.try_to_projection() {
483                    (false, Some(projection))
484                } else {
485                    (false, None)
486                }
487            }
488            _ => (false, None),
489        };
490
491        let mut finder = ParamFinder { .. };
492        finder.visit_binder(&trait_pred);
493
494        // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
495        //        don't suggest `T: Sized + ?Sized`.
496        loop {
497            let node = self.tcx.hir_node_by_def_id(body_def_id);
498            match node {
499                hir::Node::Item(hir::Item {
500                    kind: hir::ItemKind::Trait { ident, generics, bounds, .. },
501                    ..
502                }) if self_ty == self.tcx.types.self_param => {
503                    if !param_ty { ::core::panicking::panic("assertion failed: param_ty") };assert!(param_ty);
504                    // Restricting `Self` for a single method.
505                    suggest_restriction(
506                        self.tcx,
507                        body_def_id,
508                        generics,
509                        "`Self`",
510                        err,
511                        None,
512                        projection,
513                        trait_pred,
514                        Some((&ident, bounds)),
515                    );
516                    return;
517                }
518
519                hir::Node::TraitItem(hir::TraitItem {
520                    generics,
521                    kind: hir::TraitItemKind::Fn(..),
522                    ..
523                }) if self_ty == self.tcx.types.self_param => {
524                    if !param_ty { ::core::panicking::panic("assertion failed: param_ty") };assert!(param_ty);
525                    // Restricting `Self` for a single method.
526                    suggest_restriction(
527                        self.tcx,
528                        body_def_id,
529                        generics,
530                        "`Self`",
531                        err,
532                        None,
533                        projection,
534                        trait_pred,
535                        None,
536                    );
537                    return;
538                }
539
540                hir::Node::TraitItem(hir::TraitItem {
541                    generics,
542                    kind: hir::TraitItemKind::Fn(fn_sig, ..),
543                    ..
544                })
545                | hir::Node::ImplItem(hir::ImplItem {
546                    generics,
547                    kind: hir::ImplItemKind::Fn(fn_sig, ..),
548                    ..
549                })
550                | hir::Node::Item(hir::Item {
551                    kind: hir::ItemKind::Fn { sig: fn_sig, generics, .. },
552                    ..
553                }) if projection.is_some() => {
554                    // Missing restriction on associated type of type parameter (unmet projection).
555                    suggest_restriction(
556                        self.tcx,
557                        body_def_id,
558                        generics,
559                        "the associated type",
560                        err,
561                        Some(fn_sig),
562                        projection,
563                        trait_pred,
564                        None,
565                    );
566                    return;
567                }
568                hir::Node::Item(hir::Item {
569                    kind:
570                        hir::ItemKind::Trait { generics, .. }
571                        | hir::ItemKind::Impl(hir::Impl { generics, .. }),
572                    ..
573                }) if projection.is_some() => {
574                    // Missing restriction on associated type of type parameter (unmet projection).
575                    suggest_restriction(
576                        self.tcx,
577                        body_def_id,
578                        generics,
579                        "the associated type",
580                        err,
581                        None,
582                        projection,
583                        trait_pred,
584                        None,
585                    );
586                    return;
587                }
588
589                hir::Node::Item(hir::Item {
590                    kind:
591                        hir::ItemKind::Struct(_, generics, _)
592                        | hir::ItemKind::Enum(_, generics, _)
593                        | hir::ItemKind::Union(_, generics, _)
594                        | hir::ItemKind::Trait { generics, .. }
595                        | hir::ItemKind::Impl(hir::Impl { generics, .. })
596                        | hir::ItemKind::Fn { generics, .. }
597                        | hir::ItemKind::TyAlias(_, generics, _)
598                        | hir::ItemKind::Const(_, generics, _, _)
599                        | hir::ItemKind::TraitAlias(_, _, generics, _),
600                    ..
601                })
602                | hir::Node::TraitItem(hir::TraitItem { generics, .. })
603                | hir::Node::ImplItem(hir::ImplItem { generics, .. })
604                    if param_ty =>
605                {
606                    // We skip the 0'th arg (self) because we do not want
607                    // to consider the predicate as not suggestible if the
608                    // self type is an arg position `impl Trait` -- instead,
609                    // we handle that by adding ` + Bound` below.
610                    // FIXME(compiler-errors): It would be nice to do the same
611                    // this that we do in `suggest_restriction` and pull the
612                    // `impl Trait` into a new generic if it shows up somewhere
613                    // else in the predicate.
614                    if !trait_pred.skip_binder().trait_ref.args[1..]
615                        .iter()
616                        .all(|g| g.is_suggestable(self.tcx, false))
617                    {
618                        return;
619                    }
620                    // Missing generic type parameter bound.
621                    let param_name = self_ty.to_string();
622                    let mut constraint = {
    let _guard = NoTrimmedGuard::new();
    trait_pred.print_modifiers_and_trait_path().to_string()
}with_no_trimmed_paths!(
623                        trait_pred.print_modifiers_and_trait_path().to_string()
624                    );
625
626                    if let Some((name, term)) = associated_ty {
627                        // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
628                        // That should be extracted into a helper function.
629                        if let Some(stripped) = constraint.strip_suffix('>') {
630                            constraint = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, {1} = {2}>", stripped, name,
                term))
    })format!("{stripped}, {name} = {term}>");
631                        } else {
632                            constraint.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0} = {1}>", name, term))
    })format!("<{name} = {term}>"));
633                        }
634                    }
635
636                    if suggest_constraining_type_param(
637                        self.tcx,
638                        generics,
639                        err,
640                        &param_name,
641                        &constraint,
642                        Some(trait_pred.def_id()),
643                        None,
644                    ) {
645                        return;
646                    }
647                }
648
649                hir::Node::TraitItem(hir::TraitItem {
650                    generics,
651                    kind: hir::TraitItemKind::Fn(..),
652                    ..
653                })
654                | hir::Node::ImplItem(hir::ImplItem {
655                    generics,
656                    impl_kind: hir::ImplItemImplKind::Inherent { .. },
657                    kind: hir::ImplItemKind::Fn(..),
658                    ..
659                }) if finder.can_suggest_bound(generics) => {
660                    // Missing generic type parameter bound.
661                    suggest_arbitrary_trait_bound(
662                        self.tcx,
663                        generics,
664                        err,
665                        trait_pred,
666                        associated_ty,
667                    );
668                }
669                hir::Node::Item(hir::Item {
670                    kind:
671                        hir::ItemKind::Struct(_, generics, _)
672                        | hir::ItemKind::Enum(_, generics, _)
673                        | hir::ItemKind::Union(_, generics, _)
674                        | hir::ItemKind::Trait { generics, .. }
675                        | hir::ItemKind::Impl(hir::Impl { generics, .. })
676                        | hir::ItemKind::Fn { generics, .. }
677                        | hir::ItemKind::TyAlias(_, generics, _)
678                        | hir::ItemKind::Const(_, generics, _, _)
679                        | hir::ItemKind::TraitAlias(_, _, generics, _),
680                    ..
681                }) if finder.can_suggest_bound(generics) => {
682                    // Missing generic type parameter bound.
683                    if suggest_arbitrary_trait_bound(
684                        self.tcx,
685                        generics,
686                        err,
687                        trait_pred,
688                        associated_ty,
689                    ) {
690                        return;
691                    }
692                }
693                hir::Node::Crate(..) => return,
694
695                _ => {}
696            }
697            body_def_id = self.tcx.local_parent(body_def_id);
698        }
699    }
700
701    /// Provide a suggestion to dereference arguments to functions and binary operators, if that
702    /// would satisfy trait bounds.
703    pub(super) fn suggest_dereferences(
704        &self,
705        obligation: &PredicateObligation<'tcx>,
706        err: &mut Diag<'_>,
707        trait_pred: ty::PolyTraitPredicate<'tcx>,
708    ) -> bool {
709        let mut code = obligation.cause.code();
710        if let ObligationCauseCode::FunctionArg { arg_hir_id, call_hir_id, .. } = code
711            && let Some(typeck_results) = &self.typeck_results
712            && let hir::Node::Expr(expr) = self.tcx.hir_node(*arg_hir_id)
713            && let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
714        {
715            // Suggest dereferencing the argument to a function/method call if possible
716
717            // Get the root obligation, since the leaf obligation we have may be unhelpful (#87437)
718            let mut real_trait_pred = trait_pred;
719            while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
720                code = parent_code;
721                if let Some(parent_trait_pred) = parent_trait_pred {
722                    real_trait_pred = parent_trait_pred;
723                }
724            }
725
726            // We `instantiate_bound_regions_with_erased` here because `make_subregion` does not handle
727            // `ReBound`, and we don't particularly care about the regions.
728            let real_ty = self.tcx.instantiate_bound_regions_with_erased(real_trait_pred.self_ty());
729            if !self.can_eq(obligation.param_env, real_ty, arg_ty) {
730                return false;
731            }
732
733            // Potentially, we'll want to place our dereferences under a `&`. We don't try this for
734            // `&mut`, since we can't be sure users will get the side-effects they want from it.
735            // If this doesn't work, we'll try removing the `&` in `suggest_remove_reference`.
736            // FIXME(dianne): this misses the case where users need both to deref and remove `&`s.
737            // This method could be combined with `TypeErrCtxt::suggest_remove_reference` to handle
738            // that, similar to what `FnCtxt::suggest_deref_or_ref` does.
739            let (is_under_ref, base_ty, span) = match expr.kind {
740                hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, subexpr)
741                    if let &ty::Ref(region, base_ty, hir::Mutability::Not) = real_ty.kind() =>
742                {
743                    (Some(region), base_ty, subexpr.span)
744                }
745                // Don't suggest `*&mut`, etc.
746                hir::ExprKind::AddrOf(..) => return false,
747                _ => (None, real_ty, obligation.cause.span),
748            };
749
750            let autoderef = (self.autoderef_steps)(base_ty);
751            let mut is_boxed = base_ty.is_box();
752            if let Some(steps) = autoderef.into_iter().position(|(mut ty, obligations)| {
753                // Ensure one of the following for dereferencing to be valid: we're passing by
754                // reference, `ty` is `Copy`, or we're moving out of a (potentially nested) `Box`.
755                let can_deref = is_under_ref.is_some()
756                    || self.type_is_copy_modulo_regions(obligation.param_env, ty)
757                    || ty.is_numeric() // for inference vars (presumably but not provably `Copy`)
758                    || is_boxed && self.type_is_sized_modulo_regions(obligation.param_env, ty);
759                is_boxed &= ty.is_box();
760
761                // Re-add the `&` if necessary
762                if let Some(region) = is_under_ref {
763                    ty = Ty::new_ref(self.tcx, region, ty, hir::Mutability::Not);
764                }
765
766                // Remapping bound vars here
767                let real_trait_pred_and_ty =
768                    real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
769                let obligation = self.mk_trait_obligation_with_new_self_ty(
770                    obligation.param_env,
771                    real_trait_pred_and_ty,
772                );
773
774                can_deref
775                    && obligations
776                        .iter()
777                        .chain([&obligation])
778                        .all(|obligation| self.predicate_may_hold(obligation))
779            }) && steps > 0
780            {
781                if span.in_external_macro(self.tcx.sess.source_map()) {
782                    return false;
783                }
784                let derefs = "*".repeat(steps);
785                let msg = "consider dereferencing here";
786
787                let call_node = self.tcx.hir_node(*call_hir_id);
788                let is_receiver = #[allow(non_exhaustive_omitted_patterns)] match call_node {
    Node::Expr(hir::Expr {
        kind: hir::ExprKind::MethodCall(_, receiver_expr, ..), .. }) if
        receiver_expr.hir_id == *arg_hir_id => true,
    _ => false,
}matches!(
789                    call_node,
790                    Node::Expr(hir::Expr {
791                        kind: hir::ExprKind::MethodCall(_, receiver_expr, ..),
792                        ..
793                    })
794                    if receiver_expr.hir_id == *arg_hir_id
795                );
796                if is_receiver {
797                    err.multipart_suggestion(
798                        msg,
799                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("({0}", derefs))
                        })), (span.shrink_to_hi(), ")".to_string())]))vec![
800                            (span.shrink_to_lo(), format!("({derefs}")),
801                            (span.shrink_to_hi(), ")".to_string()),
802                        ],
803                        Applicability::MachineApplicable,
804                    )
805                } else {
806                    err.span_suggestion_verbose(
807                        span.shrink_to_lo(),
808                        msg,
809                        derefs,
810                        Applicability::MachineApplicable,
811                    )
812                };
813                return true;
814            }
815        } else if let (
816            ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. },
817            predicate,
818        ) = code.peel_derives_with_predicate()
819            && let Some(typeck_results) = &self.typeck_results
820            && let hir::Node::Expr(lhs) = self.tcx.hir_node(*lhs_hir_id)
821            && let hir::Node::Expr(rhs) = self.tcx.hir_node(*rhs_hir_id)
822            && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs)
823            && let trait_pred = predicate.unwrap_or(trait_pred)
824            // Only run this code on binary operators
825            && hir::lang_items::BINARY_OPERATORS
826                .iter()
827                .filter_map(|&op| self.tcx.lang_items().get(op))
828                .any(|op| {
829                    op == trait_pred.skip_binder().trait_ref.def_id
830                })
831        {
832            // Suggest dereferencing the LHS, RHS, or both terms of a binop if possible
833            let trait_pred = predicate.unwrap_or(trait_pred);
834            let lhs_ty = self.tcx.instantiate_bound_regions_with_erased(trait_pred.self_ty());
835            let lhs_autoderef = (self.autoderef_steps)(lhs_ty);
836            let rhs_autoderef = (self.autoderef_steps)(rhs_ty);
837            let first_lhs = lhs_autoderef.first().unwrap().clone();
838            let first_rhs = rhs_autoderef.first().unwrap().clone();
839            let mut autoderefs = lhs_autoderef
840                .into_iter()
841                .enumerate()
842                .rev()
843                .zip_longest(rhs_autoderef.into_iter().enumerate().rev())
844                .map(|t| match t {
845                    EitherOrBoth::Both(a, b) => (a, b),
846                    EitherOrBoth::Left(a) => (a, (0, first_rhs.clone())),
847                    EitherOrBoth::Right(b) => ((0, first_lhs.clone()), b),
848                })
849                .rev();
850            if let Some((lsteps, rsteps)) =
851                autoderefs.find_map(|((lsteps, (l_ty, _)), (rsteps, (r_ty, _)))| {
852                    // Create a new predicate with the dereferenced LHS and RHS
853                    // We simultaneously dereference both sides rather than doing them
854                    // one at a time to account for cases such as &Box<T> == &&T
855                    let trait_pred_and_ty = trait_pred.map_bound(|inner| {
856                        (
857                            ty::TraitPredicate {
858                                trait_ref: ty::TraitRef::new_from_args(
859                                    self.tcx,
860                                    inner.trait_ref.def_id,
861                                    self.tcx.mk_args(
862                                        &[&[l_ty.into(), r_ty.into()], &inner.trait_ref.args[2..]]
863                                            .concat(),
864                                    ),
865                                ),
866                                ..inner
867                            },
868                            l_ty,
869                        )
870                    });
871                    let obligation = self.mk_trait_obligation_with_new_self_ty(
872                        obligation.param_env,
873                        trait_pred_and_ty,
874                    );
875                    self.predicate_may_hold(&obligation).then_some(match (lsteps, rsteps) {
876                        (_, 0) => (Some(lsteps), None),
877                        (0, _) => (None, Some(rsteps)),
878                        _ => (Some(lsteps), Some(rsteps)),
879                    })
880                })
881            {
882                let make_sugg = |mut expr: &Expr<'_>, mut steps| {
883                    if expr.span.in_external_macro(self.tcx.sess.source_map()) {
884                        return None;
885                    }
886                    let mut prefix_span = expr.span.shrink_to_lo();
887                    let mut msg = "consider dereferencing here";
888                    if let hir::ExprKind::AddrOf(_, _, inner) = expr.kind {
889                        msg = "consider removing the borrow and dereferencing instead";
890                        if let hir::ExprKind::AddrOf(..) = inner.kind {
891                            msg = "consider removing the borrows and dereferencing instead";
892                        }
893                    }
894                    while let hir::ExprKind::AddrOf(_, _, inner) = expr.kind
895                        && steps > 0
896                    {
897                        prefix_span = prefix_span.with_hi(inner.span.lo());
898                        expr = inner;
899                        steps -= 1;
900                    }
901                    // Empty suggestions with empty spans ICE with debug assertions
902                    if steps == 0 {
903                        return Some((
904                            msg.trim_end_matches(" and dereferencing instead"),
905                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(prefix_span, String::new())]))vec![(prefix_span, String::new())],
906                        ));
907                    }
908                    let derefs = "*".repeat(steps);
909                    let needs_parens = steps > 0 && expr_needs_parens(expr);
910                    let mut suggestion = if needs_parens {
911                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0}(", derefs))
                        })), (expr.span.shrink_to_hi(), ")".to_string())]))vec![
912                            (
913                                expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
914                                format!("{derefs}("),
915                            ),
916                            (expr.span.shrink_to_hi(), ")".to_string()),
917                        ]
918                    } else {
919                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0}", derefs))
                        }))]))vec![(
920                            expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
921                            format!("{derefs}"),
922                        )]
923                    };
924                    // Empty suggestions with empty spans ICE with debug assertions
925                    if !prefix_span.is_empty() {
926                        suggestion.push((prefix_span, String::new()));
927                    }
928                    Some((msg, suggestion))
929                };
930
931                if let Some(lsteps) = lsteps
932                    && let Some(rsteps) = rsteps
933                    && lsteps > 0
934                    && rsteps > 0
935                {
936                    let Some((_, mut suggestion)) = make_sugg(lhs, lsteps) else {
937                        return false;
938                    };
939                    let Some((_, mut rhs_suggestion)) = make_sugg(rhs, rsteps) else {
940                        return false;
941                    };
942                    suggestion.append(&mut rhs_suggestion);
943                    err.multipart_suggestion(
944                        "consider dereferencing both sides of the expression",
945                        suggestion,
946                        Applicability::MachineApplicable,
947                    );
948                    return true;
949                } else if let Some(lsteps) = lsteps
950                    && lsteps > 0
951                {
952                    let Some((msg, suggestion)) = make_sugg(lhs, lsteps) else {
953                        return false;
954                    };
955                    err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
956                    return true;
957                } else if let Some(rsteps) = rsteps
958                    && rsteps > 0
959                {
960                    let Some((msg, suggestion)) = make_sugg(rhs, rsteps) else {
961                        return false;
962                    };
963                    err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
964                    return true;
965                }
966            }
967        }
968        false
969    }
970
971    /// Given a closure's `DefId`, return the given name of the closure.
972    ///
973    /// This doesn't account for reassignments, but it's only used for suggestions.
974    fn get_closure_name(
975        &self,
976        def_id: DefId,
977        err: &mut Diag<'_>,
978        msg: Cow<'static, str>,
979    ) -> Option<Symbol> {
980        let get_name = |err: &mut Diag<'_>, kind: &hir::PatKind<'_>| -> Option<Symbol> {
981            // Get the local name of this closure. This can be inaccurate because
982            // of the possibility of reassignment, but this should be good enough.
983            match &kind {
984                hir::PatKind::Binding(hir::BindingMode::NONE, _, ident, None) => Some(ident.name),
985                _ => {
986                    err.note(msg);
987                    None
988                }
989            }
990        };
991
992        let hir_id = self.tcx.local_def_id_to_hir_id(def_id.as_local()?);
993        match self.tcx.parent_hir_node(hir_id) {
994            hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Let(local), .. }) => {
995                get_name(err, &local.pat.kind)
996            }
997            // Different to previous arm because one is `&hir::Local` and the other
998            // is `Box<hir::Local>`.
999            hir::Node::LetStmt(local) => get_name(err, &local.pat.kind),
1000            _ => None,
1001        }
1002    }
1003
1004    /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
1005    /// evaluate to a type that *would* satisfy the trait bound. If it would, suggest calling
1006    /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
1007    pub(super) fn suggest_fn_call(
1008        &self,
1009        obligation: &PredicateObligation<'tcx>,
1010        err: &mut Diag<'_>,
1011        trait_pred: ty::PolyTraitPredicate<'tcx>,
1012    ) -> bool {
1013        // It doesn't make sense to make this suggestion outside of typeck...
1014        // (also autoderef will ICE...)
1015        if self.typeck_results.is_none() {
1016            return false;
1017        }
1018
1019        if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) =
1020            obligation.predicate.kind().skip_binder()
1021            && self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Sized)
1022        {
1023            // Don't suggest calling to turn an unsized type into a sized type
1024            return false;
1025        }
1026
1027        let self_ty = self.instantiate_binder_with_fresh_vars(
1028            DUMMY_SP,
1029            BoundRegionConversionTime::FnCall,
1030            trait_pred.self_ty(),
1031        );
1032
1033        let Some((def_id_or_name, output, inputs)) =
1034            self.extract_callable_info(obligation.cause.body_def_id, obligation.param_env, self_ty)
1035        else {
1036            return false;
1037        };
1038
1039        // Remapping bound vars here
1040        let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
1041
1042        let new_obligation =
1043            self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
1044        if !self.predicate_must_hold_modulo_regions(&new_obligation) {
1045            return false;
1046        }
1047
1048        // If this is a zero-argument async closure directly passed as an argument
1049        // and the expected type is `Future`, suggest using `async {}` block instead
1050        // of `async || {}`
1051        if let ty::CoroutineClosure(def_id, args) = *self_ty.kind()
1052            && let sig = args.as_coroutine_closure().coroutine_closure_sig().skip_binder()
1053            && let ty::Tuple(inputs) = *sig.tupled_inputs_ty.kind()
1054            && inputs.is_empty()
1055            && self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Future)
1056            && let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1057            && let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) =
1058                self.tcx.hir_node(*arg_hir_id)
1059            && let Some(hir::Node::Expr(hir::Expr {
1060                kind: hir::ExprKind::Closure(closure), ..
1061            })) = self.tcx.hir_get_if_local(def_id)
1062            && let hir::ClosureKind::CoroutineClosure(CoroutineDesugaring::Async) = closure.kind
1063            && let Some(arg_span) = closure.fn_arg_span
1064            && obligation.cause.span.contains(arg_span)
1065        {
1066            let mut body = self.tcx.hir_body(closure.body).value;
1067            let peeled = body.peel_blocks().peel_drop_temps();
1068            if let hir::ExprKind::Closure(inner) = peeled.kind {
1069                body = self.tcx.hir_body(inner.body).value;
1070            }
1071            if !#[allow(non_exhaustive_omitted_patterns)] match body.peel_blocks().peel_drop_temps().kind
    {
    hir::ExprKind::Block(..) => true,
    _ => false,
}matches!(body.peel_blocks().peel_drop_temps().kind, hir::ExprKind::Block(..)) {
1072                return false;
1073            }
1074
1075            let sm = self.tcx.sess.source_map();
1076            let removal_span = if let Ok(snippet) =
1077                sm.span_to_snippet(arg_span.with_hi(arg_span.hi() + rustc_span::BytePos(1)))
1078                && snippet.ends_with(' ')
1079            {
1080                // There's a space after `||`, include it in the removal
1081                arg_span.with_hi(arg_span.hi() + rustc_span::BytePos(1))
1082            } else {
1083                arg_span
1084            };
1085            err.span_suggestion_verbose(
1086                removal_span,
1087                "use `async {}` instead of `async || {}` to introduce an async block",
1088                "",
1089                Applicability::MachineApplicable,
1090            );
1091            return true;
1092        }
1093
1094        // Get the name of the callable and the arguments to be used in the suggestion.
1095        let msg = match def_id_or_name {
1096            DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
1097                DefKind::Ctor(CtorOf::Struct, _) => {
1098                    Cow::from("use parentheses to construct this tuple struct")
1099                }
1100                DefKind::Ctor(CtorOf::Variant, _) => {
1101                    Cow::from("use parentheses to construct this tuple variant")
1102                }
1103                kind => Cow::from(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use parentheses to call this {0}",
                self.tcx.def_kind_descr(kind, def_id)))
    })format!(
1104                    "use parentheses to call this {}",
1105                    self.tcx.def_kind_descr(kind, def_id)
1106                )),
1107            },
1108            DefIdOrName::Name(name) => Cow::from(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use parentheses to call this {0}",
                name))
    })format!("use parentheses to call this {name}")),
1109        };
1110
1111        let args = inputs
1112            .into_iter()
1113            .map(|ty| {
1114                if ty.is_suggestable(self.tcx, false) {
1115                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("/* {0} */", ty))
    })format!("/* {ty} */")
1116                } else {
1117                    "/* value */".to_string()
1118                }
1119            })
1120            .collect::<Vec<_>>()
1121            .join(", ");
1122
1123        if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1124            && obligation.cause.span.can_be_used_for_suggestions()
1125        {
1126            let span = obligation.cause.span;
1127
1128            let arg_expr = match self.tcx.hir_node(*arg_hir_id) {
1129                hir::Node::Expr(expr) => Some(expr),
1130                _ => None,
1131            };
1132
1133            let is_closure_expr =
1134                arg_expr.is_some_and(|expr| #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    hir::ExprKind::Closure(..) => true,
    _ => false,
}matches!(expr.kind, hir::ExprKind::Closure(..)));
1135
1136            // If the user wrote `|| {}()`, suggesting to call the closure would produce `(|| {}())()`,
1137            // which doesn't help and is often outright wrong.
1138            if args.is_empty()
1139                && let Some(expr) = arg_expr
1140                && let hir::ExprKind::Closure(closure) = expr.kind
1141            {
1142                let mut body = self.tcx.hir_body(closure.body).value;
1143
1144                // Async closures desugar to a closure returning a coroutine
1145                if let hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) =
1146                    closure.kind
1147                {
1148                    let peeled = body.peel_blocks().peel_drop_temps();
1149                    if let hir::ExprKind::Closure(inner) = peeled.kind {
1150                        body = self.tcx.hir_body(inner.body).value;
1151                    }
1152                }
1153
1154                let peeled_body = body.peel_blocks().peel_drop_temps();
1155                if let hir::ExprKind::Call(callee, call_args) = peeled_body.kind
1156                    && call_args.is_empty()
1157                    && let hir::ExprKind::Block(..) = callee.peel_blocks().peel_drop_temps().kind
1158                {
1159                    return false;
1160                }
1161            }
1162
1163            if is_closure_expr {
1164                err.multipart_suggestions(
1165                    msg,
1166                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                        [(span.shrink_to_lo(), "(".to_string()),
                                (span.shrink_to_hi(),
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!(")({0})", args))
                                        }))]))]))vec![vec![
1167                        (span.shrink_to_lo(), "(".to_string()),
1168                        (span.shrink_to_hi(), format!(")({args})")),
1169                    ]],
1170                    Applicability::HasPlaceholders,
1171                );
1172            } else {
1173                err.span_suggestion_verbose(
1174                    span.shrink_to_hi(),
1175                    msg,
1176                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0})", args))
    })format!("({args})"),
1177                    Applicability::HasPlaceholders,
1178                );
1179            }
1180        } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
1181            let name = match self.tcx.hir_get_if_local(def_id) {
1182                Some(hir::Node::Expr(hir::Expr {
1183                    kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
1184                    ..
1185                })) => {
1186                    err.span_label(*fn_decl_span, "consider calling this closure");
1187                    let Some(name) = self.get_closure_name(def_id, err, msg.clone()) else {
1188                        return false;
1189                    };
1190                    name.to_string()
1191                }
1192                Some(hir::Node::Item(hir::Item {
1193                    kind: hir::ItemKind::Fn { ident, .. }, ..
1194                })) => {
1195                    err.span_label(ident.span, "consider calling this function");
1196                    ident.to_string()
1197                }
1198                Some(hir::Node::Ctor(..)) => {
1199                    let name = self.tcx.def_path_str(def_id);
1200                    err.span_label(
1201                        self.tcx.def_span(def_id),
1202                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider calling the constructor for `{0}`",
                name))
    })format!("consider calling the constructor for `{name}`"),
1203                    );
1204                    name
1205                }
1206                _ => return false,
1207            };
1208            err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: `{1}({2})`", msg, name, args))
    })format!("{msg}: `{name}({args})`"));
1209        }
1210        true
1211    }
1212
1213    pub(super) fn suggest_cast_to_fn_pointer(
1214        &self,
1215        obligation: &PredicateObligation<'tcx>,
1216        err: &mut Diag<'_>,
1217        leaf_trait_predicate: ty::PolyTraitPredicate<'tcx>,
1218        main_trait_predicate: ty::PolyTraitPredicate<'tcx>,
1219        span: Span,
1220    ) -> bool {
1221        let &[candidate] = &self.find_similar_impl_candidates(leaf_trait_predicate)[..] else {
1222            return false;
1223        };
1224        let candidate = candidate.trait_ref;
1225
1226        if !#[allow(non_exhaustive_omitted_patterns)] match (candidate.self_ty().kind(),
        main_trait_predicate.self_ty().skip_binder().kind()) {
    (ty::FnPtr(..), ty::FnDef(..)) => true,
    _ => false,
}matches!(
1227            (candidate.self_ty().kind(), main_trait_predicate.self_ty().skip_binder().kind(),),
1228            (ty::FnPtr(..), ty::FnDef(..))
1229        ) {
1230            return false;
1231        }
1232
1233        let parenthesized_cast = |span: Span| {
1234            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(), "(".to_string()),
                (span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(" as {0})",
                                    candidate.self_ty()))
                        }))]))vec![
1235                (span.shrink_to_lo(), "(".to_string()),
1236                (span.shrink_to_hi(), format!(" as {})", candidate.self_ty())),
1237            ]
1238        };
1239        // Wrap method receivers and `&`-references in parens.
1240        let suggestion = if self.tcx.sess.source_map().span_followed_by(span, ".").is_some() {
1241            parenthesized_cast(span)
1242        } else if let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id) {
1243            let mut expr_finder = FindExprBySpan::new(span, self.tcx);
1244            expr_finder.visit_expr(body.value);
1245            if let Some(expr) = expr_finder.result
1246                && let hir::ExprKind::AddrOf(_, _, expr) = expr.kind
1247            {
1248                parenthesized_cast(expr.span)
1249            } else {
1250                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(" as {0}",
                                    candidate.self_ty()))
                        }))]))vec![(span.shrink_to_hi(), format!(" as {}", candidate.self_ty()))]
1251            }
1252        } else {
1253            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(" as {0}",
                                    candidate.self_ty()))
                        }))]))vec![(span.shrink_to_hi(), format!(" as {}", candidate.self_ty()))]
1254        };
1255
1256        let trait_ = self.tcx.short_string(candidate.print_trait_sugared(), err.long_ty_path());
1257        let self_ty = self.tcx.short_string(candidate.self_ty(), err.long_ty_path());
1258        err.multipart_suggestion(
1259            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the trait `{0}` is implemented for fn pointer `{1}`, try casting using `as`",
                trait_, self_ty))
    })format!(
1260                "the trait `{trait_}` is implemented for fn pointer \
1261                 `{self_ty}`, try casting using `as`",
1262            ),
1263            suggestion,
1264            Applicability::MaybeIncorrect,
1265        );
1266        true
1267    }
1268
1269    pub(super) fn check_for_binding_assigned_block_without_tail_expression(
1270        &self,
1271        obligation: &PredicateObligation<'tcx>,
1272        err: &mut Diag<'_>,
1273        trait_pred: ty::PolyTraitPredicate<'tcx>,
1274    ) {
1275        let mut span = obligation.cause.span;
1276        while span.from_expansion() {
1277            // Remove all the desugaring and macro contexts.
1278            span.remove_mark();
1279        }
1280        let mut expr_finder = FindExprBySpan::new(span, self.tcx);
1281        let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id) else {
1282            return;
1283        };
1284        expr_finder.visit_expr(body.value);
1285        let Some(expr) = expr_finder.result else {
1286            return;
1287        };
1288        let Some(typeck) = &self.typeck_results else {
1289            return;
1290        };
1291        let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else {
1292            return;
1293        };
1294        if !ty.is_unit() {
1295            return;
1296        };
1297        let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else {
1298            return;
1299        };
1300        let Res::Local(hir_id) = path.res else {
1301            return;
1302        };
1303        let hir::Node::Pat(pat) = self.tcx.hir_node(hir_id) else {
1304            return;
1305        };
1306        let hir::Node::LetStmt(hir::LetStmt { ty: None, init: Some(init), .. }) =
1307            self.tcx.parent_hir_node(pat.hir_id)
1308        else {
1309            return;
1310        };
1311        let hir::ExprKind::Block(block, None) = init.kind else {
1312            return;
1313        };
1314        if block.expr.is_some() {
1315            return;
1316        }
1317        let [.., stmt] = block.stmts else {
1318            err.span_label(block.span, "this empty block is missing a tail expression");
1319            return;
1320        };
1321        // FIXME expr and stmt have the same span if expr comes from expansion
1322        // cc: https://github.com/rust-lang/rust/pull/147416#discussion_r2499407523
1323        if stmt.span.from_expansion() {
1324            return;
1325        }
1326        let hir::StmtKind::Semi(tail_expr) = stmt.kind else {
1327            return;
1328        };
1329        let Some(ty) = typeck.expr_ty_opt(tail_expr) else {
1330            err.span_label(block.span, "this block is missing a tail expression");
1331            return;
1332        };
1333        let ty = self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(ty));
1334        let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, ty));
1335
1336        let new_obligation =
1337            self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
1338        if !#[allow(non_exhaustive_omitted_patterns)] match tail_expr.kind {
    hir::ExprKind::Err(_) => true,
    _ => false,
}matches!(tail_expr.kind, hir::ExprKind::Err(_))
1339            && self.predicate_must_hold_modulo_regions(&new_obligation)
1340        {
1341            err.span_suggestion_short(
1342                stmt.span.with_lo(tail_expr.span.hi()),
1343                "remove this semicolon",
1344                "",
1345                Applicability::MachineApplicable,
1346            );
1347        } else {
1348            err.span_label(block.span, "this block is missing a tail expression");
1349        }
1350    }
1351
1352    pub(super) fn suggest_add_clone_to_arg(
1353        &self,
1354        obligation: &PredicateObligation<'tcx>,
1355        err: &mut Diag<'_>,
1356        trait_pred: ty::PolyTraitPredicate<'tcx>,
1357    ) -> bool {
1358        let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
1359        self.enter_forall(self_ty, |ty: Ty<'_>| {
1360            let Some(generics) = self.tcx.hir_get_generics(obligation.cause.body_def_id) else {
1361                return false;
1362            };
1363            let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false };
1364            let ty::Param(param) = inner_ty.kind() else { return false };
1365            let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1366            else {
1367                return false;
1368            };
1369
1370            let clone_trait = self.tcx.require_lang_item(LangItem::Clone, obligation.cause.span);
1371            let has_clone = |ty| {
1372                self.type_implements_trait(clone_trait, [ty], obligation.param_env)
1373                    .must_apply_modulo_regions()
1374            };
1375
1376            let existing_clone_call = match self.tcx.hir_node(*arg_hir_id) {
1377                // It's just a variable. Propose cloning it.
1378                Node::Expr(Expr { kind: hir::ExprKind::Path(_), .. }) => None,
1379                // It's already a call to `clone()`. We might be able to suggest
1380                // adding a `+ Clone` bound, though.
1381                Node::Expr(Expr {
1382                    kind:
1383                        hir::ExprKind::MethodCall(
1384                            hir::PathSegment { ident, .. },
1385                            _receiver,
1386                            [],
1387                            call_span,
1388                        ),
1389                    hir_id,
1390                    ..
1391                }) if ident.name == sym::clone
1392                    && !call_span.from_expansion()
1393                    && !has_clone(*inner_ty) =>
1394                {
1395                    // We only care about method calls corresponding to the real `Clone` trait.
1396                    let Some(typeck_results) = self.typeck_results.as_ref() else { return false };
1397                    let Some((DefKind::AssocFn, did)) = typeck_results.type_dependent_def(*hir_id)
1398                    else {
1399                        return false;
1400                    };
1401                    if self.tcx.trait_of_assoc(did) != Some(clone_trait) {
1402                        return false;
1403                    }
1404                    Some(ident.span)
1405                }
1406                _ => return false,
1407            };
1408
1409            let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1410                obligation.param_env,
1411                trait_pred.map_bound(|trait_pred| (trait_pred, *inner_ty)),
1412            );
1413
1414            if self.predicate_may_hold(&new_obligation) && has_clone(ty) {
1415                if !has_clone(param.to_ty(self.tcx)) {
1416                    suggest_constraining_type_param(
1417                        self.tcx,
1418                        generics,
1419                        err,
1420                        param.name.as_str(),
1421                        "Clone",
1422                        Some(clone_trait),
1423                        None,
1424                    );
1425                }
1426                if let Some(existing_clone_call) = existing_clone_call {
1427                    err.span_note(
1428                        existing_clone_call,
1429                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this `clone()` copies the reference, which does not do anything, because `{0}` does not implement `Clone`",
                inner_ty))
    })format!(
1430                            "this `clone()` copies the reference, \
1431                            which does not do anything, \
1432                            because `{inner_ty}` does not implement `Clone`"
1433                        ),
1434                    );
1435                } else {
1436                    err.span_suggestion_verbose(
1437                        obligation.cause.span.shrink_to_hi(),
1438                        "consider using clone here",
1439                        ".clone()".to_string(),
1440                        Applicability::MaybeIncorrect,
1441                    );
1442                }
1443                return true;
1444            }
1445            false
1446        })
1447    }
1448
1449    /// Extracts information about a callable type for diagnostics. This is a
1450    /// heuristic -- it doesn't necessarily mean that a type is always callable,
1451    /// because the callable type must also be well-formed to be called.
1452    pub fn extract_callable_info(
1453        &self,
1454        body_def_id: LocalDefId,
1455        param_env: ty::ParamEnv<'tcx>,
1456        found: Ty<'tcx>,
1457    ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
1458        // Autoderef is useful here because sometimes we box callables, etc.
1459        let Some((def_id_or_name, output, inputs)) =
1460            (self.autoderef_steps)(found).into_iter().find_map(|(found, _)| match *found.kind() {
1461                ty::FnPtr(sig_tys, _) => Some((
1462                    DefIdOrName::Name("function pointer"),
1463                    sig_tys.output(),
1464                    sig_tys.inputs(),
1465                )),
1466                ty::FnDef(def_id, _) => {
1467                    let fn_sig = found.fn_sig(self.tcx);
1468                    Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
1469                }
1470                ty::Closure(def_id, args) => {
1471                    let fn_sig = args.as_closure().sig();
1472                    Some((
1473                        DefIdOrName::DefId(def_id),
1474                        fn_sig.output(),
1475                        fn_sig.inputs().map_bound(|inputs| inputs[0].tuple_fields().as_slice()),
1476                    ))
1477                }
1478                ty::CoroutineClosure(def_id, args) => {
1479                    let sig_parts = args.as_coroutine_closure().coroutine_closure_sig();
1480                    Some((
1481                        DefIdOrName::DefId(def_id),
1482                        sig_parts.map_bound(|sig| {
1483                            sig.to_coroutine(
1484                                self.tcx,
1485                                args.as_coroutine_closure().parent_args(),
1486                                // Just use infer vars here, since we  don't really care
1487                                // what these types are, just that we're returning a coroutine.
1488                                self.next_ty_var(DUMMY_SP),
1489                                self.tcx.coroutine_for_closure(def_id),
1490                                self.next_ty_var(DUMMY_SP),
1491                            )
1492                        }),
1493                        sig_parts.map_bound(|sig| sig.tupled_inputs_ty.tuple_fields().as_slice()),
1494                    ))
1495                }
1496                ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
1497                    self.tcx
1498                        .item_self_bounds(def_id)
1499                        .instantiate(self.tcx, args)
1500                        .skip_norm_wip()
1501                        .iter()
1502                        .find_map(|pred| {
1503                            if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder()
1504                            && self
1505                                .tcx
1506                                .is_lang_item(proj.def_id(), LangItem::FnOnceOutput)
1507                            // args tuple will always be args[1]
1508                            && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1509                            {
1510                                Some((
1511                                    DefIdOrName::DefId(def_id),
1512                                    pred.kind().rebind(proj.term.expect_type()),
1513                                    pred.kind().rebind(args.as_slice()),
1514                                ))
1515                            } else {
1516                                None
1517                            }
1518                        })
1519                }
1520                ty::Dynamic(data, _) => data.iter().find_map(|pred| {
1521                    if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
1522                        && self.tcx.is_lang_item(proj.def_id, LangItem::FnOnceOutput)
1523                        // for existential projection, args are shifted over by 1
1524                        && let ty::Tuple(args) = proj.args.type_at(0).kind()
1525                    {
1526                        Some((
1527                            DefIdOrName::Name("trait object"),
1528                            pred.rebind(proj.term.expect_type()),
1529                            pred.rebind(args.as_slice()),
1530                        ))
1531                    } else {
1532                        None
1533                    }
1534                }),
1535                ty::Param(param) => {
1536                    let generics = self.tcx.generics_of(body_def_id);
1537                    let name = if generics.count() > param.index as usize
1538                        && let def = generics.param_at(param.index as usize, self.tcx)
1539                        && #[allow(non_exhaustive_omitted_patterns)] match def.kind {
    ty::GenericParamDefKind::Type { .. } => true,
    _ => false,
}matches!(def.kind, ty::GenericParamDefKind::Type { .. })
1540                        && def.name == param.name
1541                    {
1542                        DefIdOrName::DefId(def.def_id)
1543                    } else {
1544                        DefIdOrName::Name("type parameter")
1545                    };
1546                    param_env.caller_bounds().iter().find_map(|clause| {
1547                        if let ty::ClauseKind::Projection(proj) = clause.kind().skip_binder()
1548                            && self
1549                                .tcx
1550                                .is_lang_item(proj.def_id(), LangItem::FnOnceOutput)
1551                            && proj.projection_term.self_ty() == found
1552                            // args tuple will always be args[1]
1553                            && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1554                        {
1555                            Some((
1556                                name,
1557                                clause.kind().rebind(proj.term.expect_type()),
1558                                clause.kind().rebind(args.as_slice()),
1559                            ))
1560                        } else {
1561                            None
1562                        }
1563                    })
1564                }
1565                _ => None,
1566            })
1567        else {
1568            return None;
1569        };
1570
1571        let output = self.instantiate_binder_with_fresh_vars(
1572            DUMMY_SP,
1573            BoundRegionConversionTime::FnCall,
1574            output,
1575        );
1576        let inputs = inputs
1577            .skip_binder()
1578            .iter()
1579            .map(|ty| {
1580                self.instantiate_binder_with_fresh_vars(
1581                    DUMMY_SP,
1582                    BoundRegionConversionTime::FnCall,
1583                    inputs.rebind(*ty),
1584                )
1585            })
1586            .collect();
1587
1588        // We don't want to register any extra obligations, which should be
1589        // implied by wf, but also because that would possibly result in
1590        // erroneous errors later on.
1591        let InferOk { value: output, obligations: _ } =
1592            self.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(output));
1593
1594        if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
1595    }
1596
1597    pub(super) fn where_clause_expr_matches_failed_self_ty(
1598        &self,
1599        obligation: &PredicateObligation<'tcx>,
1600        old_self_ty: Ty<'tcx>,
1601    ) -> bool {
1602        let ObligationCauseCode::WhereClauseInExpr(..) = obligation.cause.code() else {
1603            return true;
1604        };
1605        let (Some(typeck_results), Some(body)) = (
1606            self.typeck_results.as_ref(),
1607            self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id),
1608        ) else {
1609            return true;
1610        };
1611
1612        let mut expr_finder = FindExprBySpan::new(obligation.cause.span, self.tcx);
1613        expr_finder.visit_expr(body.value);
1614        let Some(expr) = expr_finder.result else {
1615            return true;
1616        };
1617
1618        let inner_old_self_ty = match old_self_ty.kind() {
1619            ty::Ref(_, inner_ty, _) => Some(*inner_ty),
1620            _ => None,
1621        };
1622
1623        typeck_results.expr_ty_adjusted_opt(expr).is_some_and(|expr_ty| {
1624            self.can_eq(obligation.param_env, expr_ty, old_self_ty)
1625                || inner_old_self_ty
1626                    .is_some_and(|inner_ty| self.can_eq(obligation.param_env, expr_ty, inner_ty))
1627        })
1628    }
1629
1630    pub(super) fn suggest_add_reference_to_arg(
1631        &self,
1632        obligation: &PredicateObligation<'tcx>,
1633        err: &mut Diag<'_>,
1634        poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
1635        has_custom_message: bool,
1636    ) -> bool {
1637        let span = obligation.cause.span;
1638        let param_env = obligation.param_env;
1639
1640        let mk_result = |trait_pred_and_new_ty| {
1641            let obligation =
1642                self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1643            self.predicate_must_hold_modulo_regions(&obligation)
1644        };
1645
1646        let code = match obligation.cause.code() {
1647            ObligationCauseCode::FunctionArg { parent_code, .. } => parent_code,
1648            // FIXME(compiler-errors): This is kind of a mess, but required for obligations
1649            // that come from a path expr to affect the *call* expr.
1650            c @ ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, _)
1651                if self.tcx.hir_span(*hir_id).lo() == span.lo() =>
1652            {
1653                // `hir_id` corresponds to the HIR node that introduced a `where`-clause obligation.
1654                // If that obligation comes from a type in an associated method call, we need
1655                // special handling here.
1656                if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(*hir_id)
1657                    && let hir::ExprKind::Call(base, _) = expr.kind
1658                    && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, segment)) = base.kind
1659                    && let hir::Node::Expr(outer) = self.tcx.parent_hir_node(expr.hir_id)
1660                    && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mtbl, _) = outer.kind
1661                    && ty.span == span
1662                {
1663                    // We've encountered something like `&str::from("")`, where the intended code
1664                    // was likely `<&str>::from("")`. The former is interpreted as "call method
1665                    // `from` on `str` and borrow the result", while the latter means "call method
1666                    // `from` on `&str`".
1667
1668                    let trait_pred_and_imm_ref = poly_trait_pred.map_bound(|p| {
1669                        (p, Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, p.self_ty()))
1670                    });
1671                    let trait_pred_and_mut_ref = poly_trait_pred.map_bound(|p| {
1672                        (p, Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, p.self_ty()))
1673                    });
1674
1675                    let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1676                    let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1677                    let sugg_msg = |pre: &str| {
1678                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you likely meant to call the associated function `{0}` for type `&{2}{1}`, but the code as written calls associated function `{0}` on type `{1}`",
                segment.ident, poly_trait_pred.self_ty(), pre))
    })format!(
1679                            "you likely meant to call the associated function `{FN}` for type \
1680                             `&{pre}{TY}`, but the code as written calls associated function `{FN}` on \
1681                             type `{TY}`",
1682                            FN = segment.ident,
1683                            TY = poly_trait_pred.self_ty(),
1684                        )
1685                    };
1686                    match (imm_ref_self_ty_satisfies_pred, mut_ref_self_ty_satisfies_pred, mtbl) {
1687                        (true, _, hir::Mutability::Not) | (_, true, hir::Mutability::Mut) => {
1688                            err.multipart_suggestion(
1689                                sugg_msg(mtbl.prefix_str()),
1690                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(outer.span.shrink_to_lo(), "<".to_string()),
                (span.shrink_to_hi(), ">".to_string())]))vec![
1691                                    (outer.span.shrink_to_lo(), "<".to_string()),
1692                                    (span.shrink_to_hi(), ">".to_string()),
1693                                ],
1694                                Applicability::MachineApplicable,
1695                            );
1696                        }
1697                        (true, _, hir::Mutability::Mut) => {
1698                            // There's an associated function found on the immutable borrow of the
1699                            err.multipart_suggestion(
1700                                sugg_msg("mut "),
1701                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(outer.span.shrink_to_lo().until(span), "<&".to_string()),
                (span.shrink_to_hi(), ">".to_string())]))vec![
1702                                    (outer.span.shrink_to_lo().until(span), "<&".to_string()),
1703                                    (span.shrink_to_hi(), ">".to_string()),
1704                                ],
1705                                Applicability::MachineApplicable,
1706                            );
1707                        }
1708                        (_, true, hir::Mutability::Not) => {
1709                            err.multipart_suggestion(
1710                                sugg_msg(""),
1711                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(outer.span.shrink_to_lo().until(span), "<&mut ".to_string()),
                (span.shrink_to_hi(), ">".to_string())]))vec![
1712                                    (outer.span.shrink_to_lo().until(span), "<&mut ".to_string()),
1713                                    (span.shrink_to_hi(), ">".to_string()),
1714                                ],
1715                                Applicability::MachineApplicable,
1716                            );
1717                        }
1718                        _ => {}
1719                    }
1720                    // If we didn't return early here, we would instead suggest `&&str::from("")`.
1721                    return false;
1722                }
1723                c
1724            }
1725            c if #[allow(non_exhaustive_omitted_patterns)] match span.ctxt().outer_expn_data().kind
    {
    ExpnKind::Desugaring(DesugaringKind::ForLoop) => true,
    _ => false,
}matches!(
1726                span.ctxt().outer_expn_data().kind,
1727                ExpnKind::Desugaring(DesugaringKind::ForLoop)
1728            ) =>
1729            {
1730                c
1731            }
1732            _ => return false,
1733        };
1734
1735        // List of traits for which it would be nonsensical to suggest borrowing.
1736        // For instance, immutable references are always Copy, so suggesting to
1737        // borrow would always succeed, but it's probably not what the user wanted.
1738        let mut never_suggest_borrow: Vec<_> =
1739            [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1740                .iter()
1741                .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1742                .collect();
1743
1744        if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1745            never_suggest_borrow.push(def_id);
1746        }
1747
1748        // Try to apply the original trait bound by borrowing.
1749        let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1750                                 blacklist: &[DefId]|
1751         -> bool {
1752            if blacklist.contains(&old_pred.def_id()) {
1753                return false;
1754            }
1755            // We map bounds to `&T` and `&mut T`
1756            let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1757                (
1758                    trait_pred,
1759                    Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1760                )
1761            });
1762            let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1763                (
1764                    trait_pred,
1765                    Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1766                )
1767            });
1768
1769            let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1770            let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1771
1772            let (ref_inner_ty_satisfies_pred, ref_inner_ty_is_mut) =
1773                if let ObligationCauseCode::WhereClauseInExpr(..) = obligation.cause.code()
1774                    && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1775                {
1776                    (
1777                        mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1778                        mutability.is_mut(),
1779                    )
1780                } else {
1781                    (false, false)
1782                };
1783
1784            let is_immut = imm_ref_self_ty_satisfies_pred
1785                || (ref_inner_ty_satisfies_pred && !ref_inner_ty_is_mut);
1786            let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_is_mut;
1787            if !is_immut && !is_mut {
1788                return false;
1789            }
1790            let Ok(_snippet) = self.tcx.sess.source_map().span_to_snippet(span) else {
1791                return false;
1792            };
1793            // We don't want a borrowing suggestion on the fields in structs
1794            // ```
1795            // #[derive(Clone)]
1796            // struct Foo {
1797            //     the_foos: Vec<Foo>
1798            // }
1799            // ```
1800            if !#[allow(non_exhaustive_omitted_patterns)] match span.ctxt().outer_expn_data().kind
    {
    ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => true,
    _ => false,
}matches!(
1801                span.ctxt().outer_expn_data().kind,
1802                ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1803            ) {
1804                return false;
1805            }
1806            // We have a very specific type of error, where just borrowing this argument
1807            // might solve the problem. In cases like this, the important part is the
1808            // original type obligation, not the last one that failed, which is arbitrary.
1809            // Because of this, we modify the error to refer to the original obligation and
1810            // return early in the caller.
1811
1812            let mut label = || {
1813                // Special case `Sized` as `old_pred` will be the trait itself instead of
1814                // `Sized` when the trait bound is the source of the error.
1815                let is_sized = match obligation.predicate.kind().skip_binder() {
1816                    ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) => {
1817                        self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Sized)
1818                    }
1819                    _ => false,
1820                };
1821
1822                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the trait bound `{0}` is not satisfied",
                self.tcx.short_string(old_pred, err.long_ty_path())))
    })format!(
1823                    "the trait bound `{}` is not satisfied",
1824                    self.tcx.short_string(old_pred, err.long_ty_path()),
1825                );
1826                let self_ty_str = self.tcx.short_string(old_pred.self_ty(), err.long_ty_path());
1827                let trait_path = self
1828                    .tcx
1829                    .short_string(old_pred.print_modifiers_and_trait_path(), err.long_ty_path());
1830
1831                if has_custom_message {
1832                    let msg = if is_sized {
1833                        "the trait bound `Sized` is not satisfied".into()
1834                    } else {
1835                        msg
1836                    };
1837                    err.note(msg);
1838                } else {
1839                    err.messages = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(rustc_errors::DiagMessage::from(msg), Style::NoStyle)]))vec![(rustc_errors::DiagMessage::from(msg), Style::NoStyle)];
1840                }
1841                if is_sized {
1842                    err.span_label(
1843                        span,
1844                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the trait `Sized` is not implemented for `{0}`",
                self_ty_str))
    })format!("the trait `Sized` is not implemented for `{self_ty_str}`"),
1845                    );
1846                } else {
1847                    err.span_label(
1848                        span,
1849                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the trait `{0}` is not implemented for `{1}`",
                trait_path, self_ty_str))
    })format!("the trait `{trait_path}` is not implemented for `{self_ty_str}`"),
1850                    );
1851                }
1852            };
1853
1854            let mut sugg_prefixes = ::alloc::vec::Vec::new()vec![];
1855            if is_immut {
1856                sugg_prefixes.push("&");
1857            }
1858            if is_mut {
1859                sugg_prefixes.push("&mut ");
1860            }
1861            let sugg_msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider{0} borrowing here",
                if is_mut && !is_immut { " mutably" } else { "" }))
    })format!(
1862                "consider{} borrowing here",
1863                if is_mut && !is_immut { " mutably" } else { "" },
1864            );
1865
1866            // Issue #104961, we need to add parentheses properly for compound expressions
1867            // for example, `x.starts_with("hi".to_string() + "you")`
1868            // should be `x.starts_with(&("hi".to_string() + "you"))`
1869            let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id) else {
1870                return false;
1871            };
1872            let mut expr_finder = FindExprBySpan::new(span, self.tcx);
1873            expr_finder.visit_expr(body.value);
1874
1875            if let Some(ty) = expr_finder.ty_result {
1876                if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(ty.hir_id)
1877                    && let hir::ExprKind::Path(hir::QPath::TypeRelative(_, _)) = expr.kind
1878                    && ty.span == span
1879                {
1880                    // We've encountered something like `str::from("")`, where the intended code
1881                    // was likely `<&str>::from("")`. #143393.
1882                    label();
1883                    err.multipart_suggestions(
1884                        sugg_msg,
1885                        sugg_prefixes.into_iter().map(|sugg_prefix| {
1886                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("<{0}", sugg_prefix))
                        })), (span.shrink_to_hi(), ">".to_string())]))vec![
1887                                (span.shrink_to_lo(), format!("<{sugg_prefix}")),
1888                                (span.shrink_to_hi(), ">".to_string()),
1889                            ]
1890                        }),
1891                        Applicability::MaybeIncorrect,
1892                    );
1893                    return true;
1894                }
1895                return false;
1896            }
1897            let Some(expr) = expr_finder.result else {
1898                return false;
1899            };
1900            if let hir::ExprKind::AddrOf(_, _, _) = expr.kind {
1901                return false;
1902            }
1903            let old_self_ty = old_pred.skip_binder().self_ty();
1904            if !old_self_ty.has_escaping_bound_vars()
1905                && !self.where_clause_expr_matches_failed_self_ty(
1906                    obligation,
1907                    self.tcx.instantiate_bound_regions_with_erased(old_pred.self_ty()),
1908                )
1909            {
1910                return false;
1911            }
1912            let needs_parens_post = expr_needs_parens(expr);
1913            let needs_parens_pre = match self.tcx.parent_hir_node(expr.hir_id) {
1914                Node::Expr(e)
1915                    if let hir::ExprKind::MethodCall(_, base, _, _) = e.kind
1916                        && base.hir_id == expr.hir_id =>
1917                {
1918                    true
1919                }
1920                _ => false,
1921            };
1922
1923            label();
1924            let suggestions = sugg_prefixes.into_iter().map(|sugg_prefix| {
1925                match (needs_parens_pre, needs_parens_post) {
1926                    (false, false) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(), sugg_prefix.to_string())]))vec![(span.shrink_to_lo(), sugg_prefix.to_string())],
1927                    // We have something like `foo.bar()`, where we want to bororw foo, so we need
1928                    // to suggest `(&mut foo).bar()`.
1929                    (false, true) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0}(", sugg_prefix))
                        })), (span.shrink_to_hi(), ")".to_string())]))vec![
1930                        (span.shrink_to_lo(), format!("{sugg_prefix}(")),
1931                        (span.shrink_to_hi(), ")".to_string()),
1932                    ],
1933                    // Issue #109436, we need to add parentheses properly for method calls
1934                    // for example, `foo.into()` should be `(&foo).into()`
1935                    (true, false) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("({0}", sugg_prefix))
                        })), (span.shrink_to_hi(), ")".to_string())]))vec![
1936                        (span.shrink_to_lo(), format!("({sugg_prefix}")),
1937                        (span.shrink_to_hi(), ")".to_string()),
1938                    ],
1939                    (true, true) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("({0}(", sugg_prefix))
                        })), (span.shrink_to_hi(), "))".to_string())]))vec![
1940                        (span.shrink_to_lo(), format!("({sugg_prefix}(")),
1941                        (span.shrink_to_hi(), "))".to_string()),
1942                    ],
1943                }
1944            });
1945            err.multipart_suggestions(sugg_msg, suggestions, Applicability::MaybeIncorrect);
1946            return true;
1947        };
1948
1949        if let ObligationCauseCode::ImplDerived(cause) = &*code {
1950            try_borrowing(cause.derived.parent_trait_pred, &[])
1951        } else if let ObligationCauseCode::WhereClause(..)
1952        | ObligationCauseCode::WhereClauseInExpr(..) = code
1953        {
1954            try_borrowing(poly_trait_pred, &never_suggest_borrow)
1955        } else {
1956            false
1957        }
1958    }
1959
1960    // Suggest borrowing the type
1961    pub(super) fn suggest_borrowing_for_object_cast(
1962        &self,
1963        err: &mut Diag<'_>,
1964        obligation: &PredicateObligation<'tcx>,
1965        self_ty: Ty<'tcx>,
1966        target_ty: Ty<'tcx>,
1967    ) {
1968        let ty::Ref(_, object_ty, hir::Mutability::Not) = target_ty.kind() else {
1969            return;
1970        };
1971        let ty::Dynamic(predicates, _) = object_ty.kind() else {
1972            return;
1973        };
1974        let self_ref_ty = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, self_ty);
1975
1976        for predicate in predicates.iter() {
1977            if !self.predicate_must_hold_modulo_regions(
1978                &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1979            ) {
1980                return;
1981            }
1982        }
1983
1984        err.span_suggestion_verbose(
1985            obligation.cause.span.shrink_to_lo(),
1986            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider borrowing the value, since `&{0}` can be coerced into `{1}`",
                self_ty, target_ty))
    })format!(
1987                "consider borrowing the value, since `&{self_ty}` can be coerced into `{target_ty}`"
1988            ),
1989            "&",
1990            Applicability::MaybeIncorrect,
1991        );
1992    }
1993
1994    /// Peel `&`-borrows from an expression, following through untyped let-bindings.
1995    /// Returns a list of removable `&` layers (each with the span to remove and the
1996    /// resulting type), plus an optional terminal [`hir::Param`] when the chain ends
1997    /// at a function parameter (including async-fn desugared parameters).
1998    fn peel_expr_refs(
1999        &self,
2000        mut expr: &'tcx hir::Expr<'tcx>,
2001        mut ty: Ty<'tcx>,
2002    ) -> (Vec<PeeledRef<'tcx>>, Option<&'tcx hir::Param<'tcx>>) {
2003        let mut refs = Vec::new();
2004        'outer: loop {
2005            while let hir::ExprKind::AddrOf(_, _, borrowed) = expr.kind {
2006                let span =
2007                    if let Some(borrowed_span) = borrowed.span.find_ancestor_inside(expr.span) {
2008                        expr.span.until(borrowed_span)
2009                    } else {
2010                        break 'outer;
2011                    };
2012
2013                // Double check that the span actually corresponds to a borrow,
2014                // rather than some macro garbage.
2015                // The span may include leading parens from parenthesized expressions
2016                // (e.g., `(&expr)` where HIR removes the Paren but keeps the span).
2017                // In that case, trim the span to start at the `&`.
2018                let span = match self.tcx.sess.source_map().span_to_snippet(span) {
2019                    Ok(ref snippet) if snippet.starts_with("&") => span,
2020                    Ok(ref snippet) if let Some(amp) = snippet.find('&') => {
2021                        span.with_lo(span.lo() + BytePos(amp as u32))
2022                    }
2023                    _ => break 'outer,
2024                };
2025
2026                let ty::Ref(_, inner_ty, _) = ty.kind() else {
2027                    break 'outer;
2028                };
2029                ty = *inner_ty;
2030                refs.push(PeeledRef { span, peeled_ty: ty });
2031                expr = borrowed;
2032            }
2033            if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
2034                && let Res::Local(hir_id) = path.res
2035                && let hir::Node::Pat(binding) = self.tcx.hir_node(hir_id)
2036            {
2037                match self.tcx.parent_hir_node(binding.hir_id) {
2038                    // Untyped let-binding: follow to its initializer.
2039                    hir::Node::LetStmt(local)
2040                        if local.ty.is_none()
2041                            && let Some(init) = local.init =>
2042                    {
2043                        expr = init;
2044                        continue;
2045                    }
2046                    // Async fn desugared parameter: `let x = __arg0;` with AsyncFn source.
2047                    // Follow to the original parameter.
2048                    hir::Node::LetStmt(local)
2049                        if #[allow(non_exhaustive_omitted_patterns)] match local.source {
    hir::LocalSource::AsyncFn => true,
    _ => false,
}matches!(local.source, hir::LocalSource::AsyncFn)
2050                            && let Some(init) = local.init
2051                            && let hir::ExprKind::Path(hir::QPath::Resolved(None, arg_path)) =
2052                                init.kind
2053                            && let Res::Local(arg_hir_id) = arg_path.res
2054                            && let hir::Node::Pat(arg_binding) = self.tcx.hir_node(arg_hir_id)
2055                            && let hir::Node::Param(param) =
2056                                self.tcx.parent_hir_node(arg_binding.hir_id) =>
2057                    {
2058                        return (refs, Some(param));
2059                    }
2060                    // Direct parameter reference.
2061                    hir::Node::Param(param) => {
2062                        return (refs, Some(param));
2063                    }
2064                    _ => break 'outer,
2065                }
2066            } else {
2067                break 'outer;
2068            }
2069        }
2070        (refs, None)
2071    }
2072
2073    /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
2074    /// suggest removing these references until we reach a type that implements the trait.
2075    pub(super) fn suggest_remove_reference(
2076        &self,
2077        obligation: &PredicateObligation<'tcx>,
2078        err: &mut Diag<'_>,
2079        trait_pred: ty::PolyTraitPredicate<'tcx>,
2080    ) -> bool {
2081        let mut span = obligation.cause.span;
2082        let mut trait_pred = trait_pred;
2083        let mut code = obligation.cause.code();
2084        while let Some((c, Some(parent_trait_pred))) = code.parent_with_predicate() {
2085            // We want the root obligation, in order to detect properly handle
2086            // `for _ in &mut &mut vec![] {}`.
2087            code = c;
2088            trait_pred = parent_trait_pred;
2089        }
2090        while span.desugaring_kind().is_some() {
2091            // Remove all the hir desugaring contexts while maintaining the macro contexts.
2092            span.remove_mark();
2093        }
2094        let mut expr_finder = super::FindExprBySpan::new(span, self.tcx);
2095        let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id) else {
2096            return false;
2097        };
2098        expr_finder.visit_expr(body.value);
2099        let mut maybe_suggest = |suggested_ty, count, suggestions| {
2100            // Remapping bound vars here
2101            let trait_pred_and_suggested_ty =
2102                trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
2103
2104            let new_obligation = self.mk_trait_obligation_with_new_self_ty(
2105                obligation.param_env,
2106                trait_pred_and_suggested_ty,
2107            );
2108
2109            if self.predicate_may_hold(&new_obligation) {
2110                let msg = if count == 1 {
2111                    "consider removing the leading `&`-reference".to_string()
2112                } else {
2113                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider removing {0} leading `&`-references",
                count))
    })format!("consider removing {count} leading `&`-references")
2114                };
2115
2116                err.multipart_suggestion(msg, suggestions, Applicability::MachineApplicable);
2117                true
2118            } else {
2119                false
2120            }
2121        };
2122
2123        // Maybe suggest removal of borrows from types in type parameters, like in
2124        // `src/test/ui/not-panic/not-panic-safe.rs`.
2125        let mut count = 0;
2126        let mut suggestions = ::alloc::vec::Vec::new()vec![];
2127        // Skipping binder here, remapping below
2128        let mut suggested_ty = trait_pred.self_ty().skip_binder();
2129        if let Some(mut hir_ty) = expr_finder.ty_result {
2130            while let hir::TyKind::Ref(_, mut_ty) = &hir_ty.kind {
2131                count += 1;
2132                let span = hir_ty.span.until(mut_ty.ty.span);
2133                suggestions.push((span, String::new()));
2134
2135                let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
2136                    break;
2137                };
2138                suggested_ty = *inner_ty;
2139
2140                hir_ty = mut_ty.ty;
2141
2142                if maybe_suggest(suggested_ty, count, suggestions.clone()) {
2143                    return true;
2144                }
2145            }
2146        }
2147
2148        // Maybe suggest removal of borrows from expressions, like in `for i in &&&foo {}`.
2149        let Some(expr) = expr_finder.result else {
2150            return false;
2151        };
2152        // Skipping binder here, remapping below
2153        let suggested_ty = trait_pred.self_ty().skip_binder();
2154        let (peeled_refs, _) = self.peel_expr_refs(expr, suggested_ty);
2155        for (i, peeled) in peeled_refs.iter().enumerate() {
2156            let suggestions: Vec<_> =
2157                peeled_refs[..=i].iter().map(|r| (r.span, String::new())).collect();
2158            if maybe_suggest(peeled.peeled_ty, i + 1, suggestions) {
2159                return true;
2160            }
2161        }
2162        false
2163    }
2164
2165    /// Suggest removing `&` from a function parameter type like `&impl Future`.
2166    fn suggest_remove_ref_from_param(&self, param: &hir::Param<'_>, err: &mut Diag<'_>) -> bool {
2167        if let Some(decl) = self.tcx.parent_hir_node(param.hir_id).fn_decl()
2168            && let Some(input_ty) = decl.inputs.iter().find(|t| param.ty_span.contains(t.span))
2169            && let hir::TyKind::Ref(_, mut_ty) = input_ty.kind
2170        {
2171            let ref_span = input_ty.span.until(mut_ty.ty.span);
2172            match self.tcx.sess.source_map().span_to_snippet(ref_span) {
2173                Ok(snippet) if snippet.starts_with("&") => {
2174                    err.span_suggestion_verbose(
2175                        ref_span,
2176                        "consider removing the `&` from the parameter type",
2177                        "",
2178                        Applicability::MaybeIncorrect,
2179                    );
2180                    return true;
2181                }
2182                _ => {}
2183            }
2184        }
2185        false
2186    }
2187
2188    pub(super) fn suggest_remove_await(
2189        &self,
2190        obligation: &PredicateObligation<'tcx>,
2191        err: &mut Diag<'_>,
2192    ) {
2193        if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives()
2194            && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
2195        {
2196            // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
2197            // and if not maybe suggest doing something else? If we kept the expression around we
2198            // could also check if it is an fn call (very likely) and suggest changing *that*, if
2199            // it is from the local crate.
2200
2201            // If the type is `&..&T` where `T: Future`, suggest removing `&`
2202            // instead of removing `.await`.
2203            if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2204                obligation.predicate.kind().skip_binder()
2205            {
2206                let self_ty = pred.self_ty();
2207                let future_trait =
2208                    self.tcx.require_lang_item(LangItem::Future, obligation.cause.span);
2209
2210                // Peel through references to check if there's a Future underneath.
2211                let has_future = {
2212                    let mut ty = self_ty;
2213                    loop {
2214                        match *ty.kind() {
2215                            ty::Ref(_, inner_ty, _)
2216                                if !#[allow(non_exhaustive_omitted_patterns)] match inner_ty.kind() {
    ty::Dynamic(..) => true,
    _ => false,
}matches!(inner_ty.kind(), ty::Dynamic(..)) =>
2217                            {
2218                                if self
2219                                    .type_implements_trait(
2220                                        future_trait,
2221                                        [inner_ty],
2222                                        obligation.param_env,
2223                                    )
2224                                    .must_apply_modulo_regions()
2225                                {
2226                                    break true;
2227                                }
2228                                ty = inner_ty;
2229                            }
2230                            _ => break false,
2231                        }
2232                    }
2233                };
2234
2235                if has_future {
2236                    let (peeled_refs, terminal_param) = self.peel_expr_refs(expr, self_ty);
2237
2238                    // Try removing `&`s from the expression.
2239                    for (i, peeled) in peeled_refs.iter().enumerate() {
2240                        if self
2241                            .type_implements_trait(
2242                                future_trait,
2243                                [peeled.peeled_ty],
2244                                obligation.param_env,
2245                            )
2246                            .must_apply_modulo_regions()
2247                        {
2248                            let count = i + 1;
2249                            let msg = if count == 1 {
2250                                "consider removing the leading `&`-reference".to_string()
2251                            } else {
2252                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider removing {0} leading `&`-references",
                count))
    })format!("consider removing {count} leading `&`-references")
2253                            };
2254                            let suggestions: Vec<_> =
2255                                peeled_refs[..=i].iter().map(|r| (r.span, String::new())).collect();
2256                            err.multipart_suggestion(
2257                                msg,
2258                                suggestions,
2259                                Applicability::MachineApplicable,
2260                            );
2261                            return;
2262                        }
2263                    }
2264
2265                    // Try removing `&` from the parameter type, but only when there's
2266                    // no `&` in the expression itself (otherwise removing from the param
2267                    // alone wouldn't fix the error).
2268                    if peeled_refs.is_empty()
2269                        && let Some(param) = terminal_param
2270                        && self.suggest_remove_ref_from_param(param, err)
2271                    {
2272                        return;
2273                    }
2274
2275                    // Fallback: emit a help message when we can't provide a specific span.
2276                    err.help(
2277                        "a reference to a future is not a future; \
2278                     consider removing the leading `&`-reference",
2279                    );
2280                    return;
2281                }
2282            }
2283
2284            // use nth(1) to skip one layer of desugaring from `IntoIter::into_iter`
2285            if let Some((_, hir::Node::Expr(await_expr))) = self.tcx.hir_parent_iter(*hir_id).nth(1)
2286                && let Some(expr_span) = expr.span.find_ancestor_inside_same_ctxt(await_expr.span)
2287            {
2288                let removal_span = self
2289                    .tcx
2290                    .sess
2291                    .source_map()
2292                    .span_extend_while_whitespace(expr_span)
2293                    .shrink_to_hi()
2294                    .to(await_expr.span.shrink_to_hi());
2295                err.span_suggestion_verbose(
2296                    removal_span,
2297                    "remove the `.await`",
2298                    "",
2299                    Applicability::MachineApplicable,
2300                );
2301            } else {
2302                err.span_label(obligation.cause.span, "remove the `.await`");
2303            }
2304            // FIXME: account for associated `async fn`s.
2305            if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
2306                if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2307                    obligation.predicate.kind().skip_binder()
2308                {
2309                    err.span_label(*span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this call returns `{0}`",
                pred.self_ty()))
    })format!("this call returns `{}`", pred.self_ty()));
2310                }
2311                if let Some(typeck_results) = &self.typeck_results
2312                    && let ty = typeck_results.expr_ty_adjusted(base)
2313                    && let ty::FnDef(def_id, _args) = ty.kind()
2314                    && let Some(hir::Node::Item(item)) = self.tcx.hir_get_if_local(*def_id)
2315                {
2316                    let (ident, _, _, _) = item.expect_fn();
2317                    let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("alternatively, consider making `fn {0}` asynchronous",
                ident))
    })format!("alternatively, consider making `fn {ident}` asynchronous");
2318                    if item.vis_span.is_empty() {
2319                        err.span_suggestion_verbose(
2320                            item.span.shrink_to_lo(),
2321                            msg,
2322                            "async ",
2323                            Applicability::MaybeIncorrect,
2324                        );
2325                    } else {
2326                        err.span_suggestion_verbose(
2327                            item.vis_span.shrink_to_hi(),
2328                            msg,
2329                            " async",
2330                            Applicability::MaybeIncorrect,
2331                        );
2332                    }
2333                }
2334            }
2335        }
2336    }
2337
2338    /// Check if the trait bound is implemented for a different mutability and note it in the
2339    /// final error.
2340    pub(super) fn suggest_change_mut(
2341        &self,
2342        obligation: &PredicateObligation<'tcx>,
2343        err: &mut Diag<'_>,
2344        trait_pred: ty::PolyTraitPredicate<'tcx>,
2345    ) {
2346        let points_at_arg =
2347            #[allow(non_exhaustive_omitted_patterns)] match obligation.cause.code() {
    ObligationCauseCode::FunctionArg { .. } => true,
    _ => false,
}matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. },);
2348
2349        let span = obligation.cause.span;
2350        if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2351            let refs_number =
2352                snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
2353            if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
2354                // Do not suggest removal of borrow from type arguments.
2355                return;
2356            }
2357            let trait_pred = self.resolve_vars_if_possible(trait_pred);
2358            if trait_pred.has_non_region_infer() {
2359                // Do not ICE while trying to find if a reborrow would succeed on a trait with
2360                // unresolved bindings.
2361                return;
2362            }
2363
2364            // Skipping binder here, remapping below
2365            if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
2366            {
2367                let suggested_ty = match mutability {
2368                    hir::Mutability::Mut => Ty::new_imm_ref(self.tcx, region, t_type),
2369                    hir::Mutability::Not => Ty::new_mut_ref(self.tcx, region, t_type),
2370                };
2371
2372                // Remapping bound vars here
2373                let trait_pred_and_suggested_ty =
2374                    trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
2375
2376                let new_obligation = self.mk_trait_obligation_with_new_self_ty(
2377                    obligation.param_env,
2378                    trait_pred_and_suggested_ty,
2379                );
2380                let suggested_ty_would_satisfy_obligation = self
2381                    .evaluate_obligation_no_overflow(&new_obligation)
2382                    .must_apply_modulo_regions();
2383                if suggested_ty_would_satisfy_obligation {
2384                    let sp = self
2385                        .tcx
2386                        .sess
2387                        .source_map()
2388                        .span_take_while(span, |c| c.is_whitespace() || *c == '&');
2389                    if points_at_arg && mutability.is_not() && refs_number > 0 {
2390                        // If we have a call like foo(&mut buf), then don't suggest foo(&mut mut buf)
2391                        if snippet
2392                            .trim_start_matches(|c: char| c.is_whitespace() || c == '&')
2393                            .starts_with("mut")
2394                        {
2395                            return;
2396                        }
2397                        err.span_suggestion_verbose(
2398                            sp,
2399                            "consider changing this borrow's mutability",
2400                            "&mut ",
2401                            Applicability::MachineApplicable,
2402                        );
2403                    } else {
2404                        err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is implemented for `{1}`, but not for `{2}`",
                trait_pred.print_modifiers_and_trait_path(), suggested_ty,
                trait_pred.skip_binder().self_ty()))
    })format!(
2405                            "`{}` is implemented for `{}`, but not for `{}`",
2406                            trait_pred.print_modifiers_and_trait_path(),
2407                            suggested_ty,
2408                            trait_pred.skip_binder().self_ty(),
2409                        ));
2410                    }
2411                }
2412            }
2413        }
2414    }
2415
2416    pub(super) fn suggest_semicolon_removal(
2417        &self,
2418        obligation: &PredicateObligation<'tcx>,
2419        err: &mut Diag<'_>,
2420        span: Span,
2421        trait_pred: ty::PolyTraitPredicate<'tcx>,
2422    ) -> bool {
2423        let node = self.tcx.hir_node_by_def_id(obligation.cause.body_def_id);
2424        if let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn {sig, body: body_id, .. }, .. }) = node
2425            && let hir::ExprKind::Block(blk, _) = &self.tcx.hir_body(*body_id).value.kind
2426            && sig.decl.output.span().overlaps(span)
2427            && blk.expr.is_none()
2428            && trait_pred.self_ty().skip_binder().is_unit()
2429            && let Some(stmt) = blk.stmts.last()
2430            && let hir::StmtKind::Semi(expr) = stmt.kind
2431            // Only suggest this if the expression behind the semicolon implements the predicate
2432            && let Some(typeck_results) = &self.typeck_results
2433            && let Some(ty) = typeck_results.expr_ty_opt(expr)
2434            && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
2435                obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
2436            ))
2437        {
2438            err.span_label(
2439                expr.span,
2440                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this expression has type `{0}`, which implements `{1}`",
                ty, trait_pred.print_modifiers_and_trait_path()))
    })format!(
2441                    "this expression has type `{}`, which implements `{}`",
2442                    ty,
2443                    trait_pred.print_modifiers_and_trait_path()
2444                ),
2445            );
2446            err.span_suggestion(
2447                self.tcx.sess.source_map().end_point(stmt.span),
2448                "remove this semicolon",
2449                "",
2450                Applicability::MachineApplicable,
2451            );
2452            return true;
2453        }
2454        false
2455    }
2456
2457    pub(super) fn suggest_borrow_for_unsized_closure_return<G: EmissionGuarantee>(
2458        &self,
2459        body_def_id: LocalDefId,
2460        err: &mut Diag<'_, G>,
2461        predicate: ty::Predicate<'tcx>,
2462    ) {
2463        let Some(pred) = predicate.as_trait_clause() else {
2464            return;
2465        };
2466        if !self.tcx.is_lang_item(pred.def_id(), LangItem::Sized) {
2467            return;
2468        }
2469
2470        let Some(span) = err.span.primary_span() else {
2471            return;
2472        };
2473        let Some(body_id) = self.tcx.hir_node_by_def_id(body_def_id).body_id() else {
2474            return;
2475        };
2476        let body = self.tcx.hir_body(body_id);
2477        let mut expr_finder = FindExprBySpan::new(span, self.tcx);
2478        expr_finder.visit_expr(body.value);
2479        let Some(expr) = expr_finder.result else {
2480            return;
2481        };
2482
2483        let closure = match expr.kind {
2484            hir::ExprKind::Call(_, args) => args.iter().find_map(|arg| match arg.kind {
2485                hir::ExprKind::Closure(closure) => Some(closure),
2486                _ => None,
2487            }),
2488            hir::ExprKind::MethodCall(_, _, args, _) => {
2489                args.iter().find_map(|arg| match arg.kind {
2490                    hir::ExprKind::Closure(closure) => Some(closure),
2491                    _ => None,
2492                })
2493            }
2494            _ => None,
2495        };
2496        let Some(closure) = closure else {
2497            return;
2498        };
2499        if !#[allow(non_exhaustive_omitted_patterns)] match closure.fn_decl.output {
    hir::FnRetTy::DefaultReturn(_) => true,
    _ => false,
}matches!(closure.fn_decl.output, hir::FnRetTy::DefaultReturn(_)) {
2500            return;
2501        }
2502
2503        err.span_suggestion_verbose(
2504            self.tcx.hir_body(closure.body).value.span.shrink_to_lo(),
2505            "consider borrowing the value",
2506            "&",
2507            Applicability::MaybeIncorrect,
2508        );
2509    }
2510
2511    pub(super) fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
2512        let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig, .. }, .. }) =
2513            self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
2514        else {
2515            return None;
2516        };
2517
2518        if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
2519    }
2520
2521    /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
2522    /// applicable and signal that the error has been expanded appropriately and needs to be
2523    /// emitted.
2524    pub(super) fn suggest_impl_trait(
2525        &self,
2526        err: &mut Diag<'_>,
2527        obligation: &PredicateObligation<'tcx>,
2528        trait_pred: ty::PolyTraitPredicate<'tcx>,
2529    ) -> bool {
2530        let ObligationCauseCode::SizedReturnType = obligation.cause.code() else {
2531            return false;
2532        };
2533        let ty::Dynamic(_, _) = trait_pred.self_ty().skip_binder().kind() else {
2534            return false;
2535        };
2536        if let Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig: fn_sig, .. }, .. })
2537        | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(fn_sig, _), .. })
2538        | Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(fn_sig, _), .. }) =
2539            self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
2540            && let hir::FnRetTy::Return(ty) = fn_sig.decl.output
2541            && let hir::TyKind::Path(qpath) = ty.kind
2542            && let hir::QPath::Resolved(None, path) = qpath
2543            && let Res::Def(DefKind::TyAlias, def_id) = path.res
2544        {
2545            // Do not suggest
2546            // type T = dyn Trait;
2547            // fn foo() -> impl T { .. }
2548            err.span_note(self.tcx.def_span(def_id), "this type alias is unsized");
2549            err.multipart_suggestion(
2550                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider boxing the return type, and wrapping all of the returned values in `Box::new`"))
    })format!(
2551                    "consider boxing the return type, and wrapping all of the returned values in \
2552                    `Box::new`",
2553                ),
2554                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(ty.span.shrink_to_lo(), "Box<".to_string()),
                (ty.span.shrink_to_hi(), ">".to_string())]))vec![
2555                    (ty.span.shrink_to_lo(), "Box<".to_string()),
2556                    (ty.span.shrink_to_hi(), ">".to_string()),
2557                ],
2558                Applicability::MaybeIncorrect,
2559            );
2560            return false;
2561        }
2562
2563        err.code(E0746);
2564        err.primary_message("return type cannot be a trait object without pointer indirection");
2565        err.children.clear();
2566
2567        let mut span = obligation.cause.span;
2568        let mut is_async_fn_return = false;
2569        if let DefKind::Closure = self.tcx.def_kind(obligation.cause.body_def_id)
2570            && let parent = self.tcx.local_parent(obligation.cause.body_def_id)
2571            && let DefKind::Fn | DefKind::AssocFn = self.tcx.def_kind(parent)
2572            && self.tcx.asyncness(parent).is_async()
2573            && let Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig: fn_sig, .. }, .. })
2574            | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(fn_sig, _), .. })
2575            | Node::TraitItem(hir::TraitItem {
2576                kind: hir::TraitItemKind::Fn(fn_sig, _), ..
2577            }) = self.tcx.hir_node_by_def_id(parent)
2578        {
2579            // Do not suggest (#147894)
2580            // async fn foo() -> dyn Display impl { .. }
2581            // and
2582            // async fn foo() -> dyn Display Box<dyn { .. }>
2583            span = fn_sig.decl.output.span();
2584            is_async_fn_return = true;
2585            err.span(span);
2586        }
2587        let body = self.tcx.hir_body_owned_by(obligation.cause.body_def_id);
2588
2589        if !is_async_fn_return
2590            && let Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) =
2591                self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
2592            && #[allow(non_exhaustive_omitted_patterns)] match closure.fn_decl.output {
    hir::FnRetTy::DefaultReturn(_) => true,
    _ => false,
}matches!(closure.fn_decl.output, hir::FnRetTy::DefaultReturn(_))
2593        {
2594            return true;
2595        }
2596
2597        let mut visitor = ReturnsVisitor::default();
2598        visitor.visit_body(&body);
2599
2600        let (pre, impl_span) = if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span)
2601            && snip.starts_with("dyn ")
2602        {
2603            ("", span.with_hi(span.lo() + BytePos(4)))
2604        } else {
2605            ("dyn ", span.shrink_to_lo())
2606        };
2607
2608        err.span_suggestion_verbose(
2609            impl_span,
2610            "consider returning an `impl Trait` instead of a `dyn Trait`",
2611            "impl ",
2612            Applicability::MaybeIncorrect,
2613        );
2614
2615        let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("Box<{0}", pre))
                        })), (span.shrink_to_hi(), ">".to_string())]))vec![
2616            (span.shrink_to_lo(), format!("Box<{pre}")),
2617            (span.shrink_to_hi(), ">".to_string()),
2618        ];
2619        sugg.extend(visitor.returns.into_iter().flat_map(|expr| {
2620            let span =
2621                expr.span.find_ancestor_in_same_ctxt(obligation.cause.span).unwrap_or(expr.span);
2622            if !span.can_be_used_for_suggestions() {
2623                ::alloc::vec::Vec::new()vec![]
2624            } else if let hir::ExprKind::Call(path, ..) = expr.kind
2625                && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, method)) = path.kind
2626                && method.ident.name == sym::new
2627                && let hir::TyKind::Path(hir::QPath::Resolved(.., box_path)) = ty.kind
2628                && box_path
2629                    .res
2630                    .opt_def_id()
2631                    .is_some_and(|def_id| self.tcx.is_lang_item(def_id, LangItem::OwnedBox))
2632            {
2633                // Don't box `Box::new`
2634                ::alloc::vec::Vec::new()vec![]
2635            } else {
2636                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(), "Box::new(".to_string()),
                (span.shrink_to_hi(), ")".to_string())]))vec![
2637                    (span.shrink_to_lo(), "Box::new(".to_string()),
2638                    (span.shrink_to_hi(), ")".to_string()),
2639                ]
2640            }
2641        }));
2642
2643        err.multipart_suggestion(
2644            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("alternatively, box the return type, and wrap all of the returned values in `Box::new`"))
    })format!(
2645                "alternatively, box the return type, and wrap all of the returned values in \
2646                 `Box::new`",
2647            ),
2648            sugg,
2649            Applicability::MaybeIncorrect,
2650        );
2651
2652        true
2653    }
2654
2655    pub(super) fn report_closure_arg_mismatch(
2656        &self,
2657        span: Span,
2658        found_span: Option<Span>,
2659        found: ty::TraitRef<'tcx>,
2660        expected: ty::TraitRef<'tcx>,
2661        cause: &ObligationCauseCode<'tcx>,
2662        found_node: Option<Node<'_>>,
2663        param_env: ty::ParamEnv<'tcx>,
2664    ) -> Diag<'a> {
2665        pub(crate) fn build_fn_sig_ty<'tcx>(
2666            infcx: &InferCtxt<'tcx>,
2667            trait_ref: ty::TraitRef<'tcx>,
2668        ) -> Ty<'tcx> {
2669            let inputs = trait_ref.args.type_at(1);
2670            let sig = match inputs.kind() {
2671                ty::Tuple(inputs) if infcx.tcx.is_callable_trait(trait_ref.def_id) => {
2672                    infcx.tcx.mk_fn_sig_safe_rust_abi(*inputs, infcx.next_ty_var(DUMMY_SP))
2673                }
2674                _ => infcx.tcx.mk_fn_sig_safe_rust_abi([inputs], infcx.next_ty_var(DUMMY_SP)),
2675            };
2676
2677            Ty::new_fn_ptr(infcx.tcx, ty::Binder::dummy(sig))
2678        }
2679
2680        let argument_kind = match expected.self_ty().kind() {
2681            ty::Closure(..) => "closure",
2682            ty::Coroutine(..) => "coroutine",
2683            _ => "function",
2684        };
2685        let mut err = {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("type mismatch in {0} arguments",
                            argument_kind))
                })).with_code(E0631)
}struct_span_code_err!(
2686            self.dcx(),
2687            span,
2688            E0631,
2689            "type mismatch in {argument_kind} arguments",
2690        );
2691
2692        err.span_label(span, "expected due to this");
2693
2694        let found_span = found_span.unwrap_or(span);
2695        err.span_label(found_span, "found signature defined here");
2696
2697        let expected = build_fn_sig_ty(self, expected);
2698        let found = build_fn_sig_ty(self, found);
2699
2700        let (expected_str, found_str) = self.cmp(expected, found);
2701
2702        let signature_kind = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} signature", argument_kind))
    })format!("{argument_kind} signature");
2703        err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
2704
2705        self.note_conflicting_fn_args(&mut err, cause, expected, found, param_env);
2706        self.note_conflicting_closure_bounds(cause, &mut err);
2707
2708        if let Some(found_node) = found_node {
2709            hint_missing_borrow(self, param_env, span, found, expected, found_node, &mut err);
2710        }
2711
2712        err
2713    }
2714
2715    fn note_conflicting_fn_args(
2716        &self,
2717        err: &mut Diag<'_>,
2718        cause: &ObligationCauseCode<'tcx>,
2719        expected: Ty<'tcx>,
2720        found: Ty<'tcx>,
2721        param_env: ty::ParamEnv<'tcx>,
2722    ) {
2723        let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = cause else {
2724            return;
2725        };
2726        let ty::FnPtr(sig_tys, hdr) = expected.kind() else {
2727            return;
2728        };
2729        let expected = sig_tys.with(*hdr);
2730        let ty::FnPtr(sig_tys, hdr) = found.kind() else {
2731            return;
2732        };
2733        let found = sig_tys.with(*hdr);
2734        let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) else {
2735            return;
2736        };
2737        let hir::ExprKind::Path(path) = arg.kind else {
2738            return;
2739        };
2740        let expected_inputs = self.tcx.instantiate_bound_regions_with_erased(expected).inputs();
2741        let found_inputs = self.tcx.instantiate_bound_regions_with_erased(found).inputs();
2742        let both_tys = expected_inputs.iter().copied().zip(found_inputs.iter().copied());
2743
2744        let arg_expr = |infcx: &InferCtxt<'tcx>, name, expected: Ty<'tcx>, found: Ty<'tcx>| {
2745            let (expected_ty, expected_refs) = get_deref_type_and_refs(expected);
2746            let (found_ty, found_refs) = get_deref_type_and_refs(found);
2747
2748            if infcx.can_eq(param_env, found_ty, expected_ty) {
2749                if found_refs.len() == expected_refs.len()
2750                    && found_refs.iter().eq(expected_refs.iter())
2751                {
2752                    name
2753                } else if found_refs.len() > expected_refs.len() {
2754                    let refs = &found_refs[..found_refs.len() - expected_refs.len()];
2755                    if found_refs[..expected_refs.len()].iter().eq(expected_refs.iter()) {
2756                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}",
                refs.iter().map(|mutbl|
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("&{0}",
                                                mutbl.prefix_str()))
                                    })).collect::<Vec<_>>().join(""), name))
    })format!(
2757                            "{}{name}",
2758                            refs.iter()
2759                                .map(|mutbl| format!("&{}", mutbl.prefix_str()))
2760                                .collect::<Vec<_>>()
2761                                .join(""),
2762                        )
2763                    } else {
2764                        // The refs have different mutability.
2765                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}*{1}",
                refs.iter().map(|mutbl|
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("&{0}",
                                                mutbl.prefix_str()))
                                    })).collect::<Vec<_>>().join(""), name))
    })format!(
2766                            "{}*{name}",
2767                            refs.iter()
2768                                .map(|mutbl| format!("&{}", mutbl.prefix_str()))
2769                                .collect::<Vec<_>>()
2770                                .join(""),
2771                        )
2772                    }
2773                } else if expected_refs.len() > found_refs.len() {
2774                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}",
                (0..(expected_refs.len() -
                                            found_refs.len())).map(|_|
                                "*").collect::<Vec<_>>().join(""), name))
    })format!(
2775                        "{}{name}",
2776                        (0..(expected_refs.len() - found_refs.len()))
2777                            .map(|_| "*")
2778                            .collect::<Vec<_>>()
2779                            .join(""),
2780                    )
2781                } else {
2782                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}",
                found_refs.iter().map(|mutbl|
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("&{0}",
                                                    mutbl.prefix_str()))
                                        })).chain(found_refs.iter().map(|_|
                                    "*".to_string())).collect::<Vec<_>>().join(""), name))
    })format!(
2783                        "{}{name}",
2784                        found_refs
2785                            .iter()
2786                            .map(|mutbl| format!("&{}", mutbl.prefix_str()))
2787                            .chain(found_refs.iter().map(|_| "*".to_string()))
2788                            .collect::<Vec<_>>()
2789                            .join(""),
2790                    )
2791                }
2792            } else {
2793                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("/* {0} */", found))
    })format!("/* {found} */")
2794            }
2795        };
2796        let args_have_same_underlying_type = both_tys.clone().all(|(expected, found)| {
2797            let (expected_ty, _) = get_deref_type_and_refs(expected);
2798            let (found_ty, _) = get_deref_type_and_refs(found);
2799            self.can_eq(param_env, found_ty, expected_ty)
2800        });
2801        let (closure_names, call_names): (Vec<_>, Vec<_>) = if args_have_same_underlying_type
2802            && !expected_inputs.is_empty()
2803            && expected_inputs.len() == found_inputs.len()
2804            && let Some(typeck) = &self.typeck_results
2805            && let Res::Def(res_kind, fn_def_id) = typeck.qpath_res(&path, *arg_hir_id)
2806            && res_kind.is_fn_like()
2807        {
2808            let closure: Vec<_> = self
2809                .tcx
2810                .fn_arg_idents(fn_def_id)
2811                .iter()
2812                .enumerate()
2813                .map(|(i, ident)| {
2814                    if let Some(ident) = ident
2815                        && !#[allow(non_exhaustive_omitted_patterns)] match ident {
    Ident { name: kw::Underscore | kw::SelfLower, .. } => true,
    _ => false,
}matches!(ident, Ident { name: kw::Underscore | kw::SelfLower, .. })
2816                    {
2817                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", ident))
    })format!("{ident}")
2818                    } else {
2819                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("arg{0}", i))
    })format!("arg{i}")
2820                    }
2821                })
2822                .collect();
2823            let args = closure
2824                .iter()
2825                .zip(both_tys)
2826                .map(|(name, (expected, found))| {
2827                    arg_expr(self.infcx, name.to_owned(), expected, found)
2828                })
2829                .collect();
2830            (closure, args)
2831        } else {
2832            let closure_args = expected_inputs
2833                .iter()
2834                .enumerate()
2835                .map(|(i, _)| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("arg{0}", i))
    })format!("arg{i}"))
2836                .collect::<Vec<_>>();
2837            let call_args = both_tys
2838                .enumerate()
2839                .map(|(i, (expected, found))| {
2840                    arg_expr(self.infcx, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("arg{0}", i))
    })format!("arg{i}"), expected, found)
2841                })
2842                .collect::<Vec<_>>();
2843            (closure_args, call_args)
2844        };
2845        let closure_names: Vec<_> = closure_names
2846            .into_iter()
2847            .zip(expected_inputs.iter())
2848            .map(|(name, ty)| {
2849                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}{0}",
                if ty.has_infer_types() {
                    String::new()
                } else if ty.references_error() {
                    ": /* type */".to_string()
                } else {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(": {0}", ty))
                        })
                }, name))
    })format!(
2850                    "{name}{}",
2851                    if ty.has_infer_types() {
2852                        String::new()
2853                    } else if ty.references_error() {
2854                        ": /* type */".to_string()
2855                    } else {
2856                        format!(": {ty}")
2857                    }
2858                )
2859            })
2860            .collect();
2861        err.multipart_suggestion(
2862            "consider wrapping the function in a closure",
2863            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(arg.span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("|{0}| ",
                                    closure_names.join(", ")))
                        })),
                (arg.span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("({0})",
                                    call_names.join(", ")))
                        }))]))vec![
2864                (arg.span.shrink_to_lo(), format!("|{}| ", closure_names.join(", "))),
2865                (arg.span.shrink_to_hi(), format!("({})", call_names.join(", "))),
2866            ],
2867            Applicability::MaybeIncorrect,
2868        );
2869    }
2870
2871    // Add a note if there are two `Fn`-family bounds that have conflicting argument
2872    // requirements, which will always cause a closure to have a type error.
2873    fn note_conflicting_closure_bounds(
2874        &self,
2875        cause: &ObligationCauseCode<'tcx>,
2876        err: &mut Diag<'_>,
2877    ) {
2878        // First, look for an `WhereClauseInExpr`, which means we can get
2879        // the uninstantiated predicate list of the called function. And check
2880        // that the predicate that we failed to satisfy is a `Fn`-like trait.
2881        if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = *cause
2882            && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
2883            && let Some(pred) = predicates.predicates.get(idx).map(|p| p.as_ref().skip_norm_wip())
2884            && let ty::ClauseKind::Trait(trait_pred) = pred.kind().skip_binder()
2885            && self.tcx.is_fn_trait(trait_pred.def_id())
2886        {
2887            let expected_self =
2888                self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.self_ty()));
2889            let expected_args =
2890                self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.trait_ref.args));
2891
2892            // Find another predicate whose self-type is equal to the expected self type,
2893            // but whose args don't match.
2894            let other_pred = predicates.into_iter().enumerate().find(|&(other_idx, (pred, _))| {
2895                let pred = pred.skip_norm_wip();
2896                match pred.kind().skip_binder() {
2897                    ty::ClauseKind::Trait(trait_pred)
2898                        if self.tcx.is_fn_trait(trait_pred.def_id())
2899                            && other_idx != idx
2900                            // Make sure that the self type matches
2901                            // (i.e. constraining this closure)
2902                            && expected_self
2903                                == self.tcx.anonymize_bound_vars(
2904                                    pred.kind().rebind(trait_pred.self_ty()),
2905                                )
2906                            // But the args don't match (i.e. incompatible args)
2907                            && expected_args
2908                                != self.tcx.anonymize_bound_vars(
2909                                    pred.kind().rebind(trait_pred.trait_ref.args),
2910                                ) =>
2911                    {
2912                        true
2913                    }
2914                    _ => false,
2915                }
2916            });
2917            // If we found one, then it's very likely the cause of the error.
2918            if let Some((_, (_, other_pred_span))) = other_pred {
2919                err.span_note(
2920                    other_pred_span,
2921                    "closure inferred to have a different signature due to this bound",
2922                );
2923            }
2924        }
2925    }
2926
2927    pub(super) fn suggest_fully_qualified_path(
2928        &self,
2929        err: &mut Diag<'_>,
2930        item_def_id: DefId,
2931        span: Span,
2932        trait_ref: DefId,
2933    ) {
2934        if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id)
2935            && let ty::AssocKind::Const { .. } | ty::AssocKind::Type { .. } = assoc_item.kind
2936        {
2937            err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}s cannot be accessed directly on a `trait`, they can only be accessed through a specific `impl`",
                self.tcx.def_kind_descr(assoc_item.as_def_kind(),
                    item_def_id)))
    })format!(
2938                "{}s cannot be accessed directly on a `trait`, they can only be \
2939                        accessed through a specific `impl`",
2940                self.tcx.def_kind_descr(assoc_item.as_def_kind(), item_def_id)
2941            ));
2942
2943            if !assoc_item.is_impl_trait_in_trait() {
2944                err.span_suggestion_verbose(
2945                    span,
2946                    "use the fully qualified path to an implementation",
2947                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<Type as {0}>::{1}",
                self.tcx.def_path_str(trait_ref), assoc_item.name()))
    })format!(
2948                        "<Type as {}>::{}",
2949                        self.tcx.def_path_str(trait_ref),
2950                        assoc_item.name()
2951                    ),
2952                    Applicability::HasPlaceholders,
2953                );
2954            }
2955        }
2956    }
2957
2958    /// Adds an async-await specific note to the diagnostic when the future does not implement
2959    /// an auto trait because of a captured type.
2960    ///
2961    /// ```text
2962    /// note: future does not implement `Qux` as this value is used across an await
2963    ///   --> $DIR/issue-64130-3-other.rs:17:5
2964    ///    |
2965    /// LL |     let x = Foo;
2966    ///    |         - has type `Foo`
2967    /// LL |     baz().await;
2968    ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2969    /// LL | }
2970    ///    | - `x` is later dropped here
2971    /// ```
2972    ///
2973    /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
2974    /// is "replaced" with a different message and a more specific error.
2975    ///
2976    /// ```text
2977    /// error: future cannot be sent between threads safely
2978    ///   --> $DIR/issue-64130-2-send.rs:21:5
2979    ///    |
2980    /// LL | fn is_send<T: Send>(t: T) { }
2981    ///    |               ---- required by this bound in `is_send`
2982    /// ...
2983    /// LL |     is_send(bar());
2984    ///    |     ^^^^^^^ future returned by `bar` is not send
2985    ///    |
2986    ///    = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
2987    ///            implemented for `Foo`
2988    /// note: future is not send as this value is used across an await
2989    ///   --> $DIR/issue-64130-2-send.rs:15:5
2990    ///    |
2991    /// LL |     let x = Foo;
2992    ///    |         - has type `Foo`
2993    /// LL |     baz().await;
2994    ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2995    /// LL | }
2996    ///    | - `x` is later dropped here
2997    /// ```
2998    ///
2999    /// Returns `true` if an async-await specific note was added to the diagnostic.
3000    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("maybe_note_obligation_cause_for_async_await",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3000u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["obligation.predicate",
                                                    "obligation.cause.span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&obligation.predicate)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&obligation.cause.span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: bool = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (mut trait_ref, mut target_ty) =
                match obligation.predicate.kind().skip_binder() {
                    ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) =>
                        (Some(p), Some(p.self_ty())),
                    _ => (None, None),
                };
            let mut coroutine = None;
            let mut outer_coroutine = None;
            let mut next_code = Some(obligation.cause.code());
            let mut seen_upvar_tys_infer_tuple = false;
            while let Some(code) = next_code {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3039",
                                        "rustc_trait_selection::error_reporting::traits::suggestions",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                        ::tracing_core::__macro_support::Option::Some(3039u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                        ::tracing_core::field::FieldSet::new(&["code"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&code) as
                                                            &dyn Value))])
                            });
                    } else { ; }
                };
                match code {
                    ObligationCauseCode::FunctionArg { parent_code, .. } => {
                        next_code = Some(parent_code);
                    }
                    ObligationCauseCode::ImplDerived(cause) => {
                        let ty =
                            cause.derived.parent_trait_pred.skip_binder().self_ty();
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3046",
                                                "rustc_trait_selection::error_reporting::traits::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(3046u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&["message",
                                                                "parent_trait_ref", "self_ty.kind"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("ImplDerived")
                                                                    as &dyn Value)),
                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&cause.derived.parent_trait_pred)
                                                                    as &dyn Value)),
                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&ty.kind())
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        match *ty.kind() {
                            ty::Coroutine(did, ..) | ty::CoroutineWitness(did, _) => {
                                coroutine = coroutine.or(Some(did));
                                outer_coroutine = Some(did);
                            }
                            ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
                                seen_upvar_tys_infer_tuple = true;
                            }
                            _ if coroutine.is_none() => {
                                trait_ref =
                                    Some(cause.derived.parent_trait_pred.skip_binder());
                                target_ty = Some(ty);
                            }
                            _ => {}
                        }
                        next_code = Some(&cause.derived.parent_code);
                    }
                    ObligationCauseCode::WellFormedDerived(derived_obligation) |
                        ObligationCauseCode::BuiltinDerived(derived_obligation) => {
                        let ty =
                            derived_obligation.parent_trait_pred.skip_binder().self_ty();
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3076",
                                                "rustc_trait_selection::error_reporting::traits::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(3076u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&["parent_trait_ref",
                                                                "self_ty.kind"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&derived_obligation.parent_trait_pred)
                                                                    as &dyn Value)),
                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&ty.kind())
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        match *ty.kind() {
                            ty::Coroutine(did, ..) | ty::CoroutineWitness(did, ..) => {
                                coroutine = coroutine.or(Some(did));
                                outer_coroutine = Some(did);
                            }
                            ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
                                seen_upvar_tys_infer_tuple = true;
                            }
                            _ if coroutine.is_none() => {
                                trait_ref =
                                    Some(derived_obligation.parent_trait_pred.skip_binder());
                                target_ty = Some(ty);
                            }
                            _ => {}
                        }
                        next_code = Some(&derived_obligation.parent_code);
                    }
                    _ => break,
                }
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3107",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3107u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["coroutine",
                                                    "trait_ref", "target_ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&coroutine)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&trait_ref)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&target_ty)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let (Some(coroutine_did), Some(trait_ref), Some(target_ty)) =
                (coroutine, trait_ref, target_ty) else { return false; };
            let span = self.tcx.def_span(coroutine_did);
            let coroutine_did_root =
                self.tcx.typeck_root_def_id(coroutine_did);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3117",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3117u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["coroutine_did",
                                                    "coroutine_did_root", "typeck_results.hir_owner", "span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&coroutine_did)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&coroutine_did_root)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&self.typeck_results.as_ref().map(|t|
                                                                            t.hir_owner)) as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&span) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            let coroutine_body =
                coroutine_did.as_local().and_then(|def_id|
                        self.tcx.hir_maybe_body_owned_by(def_id));
            let mut visitor = AwaitsVisitor::default();
            if let Some(body) = coroutine_body { visitor.visit_body(&body); }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3130",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3130u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["awaits"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&visitor.awaits)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let target_ty_erased =
                self.tcx.erase_and_anonymize_regions(target_ty);
            let ty_matches =
                |ty| -> bool
                    {
                        let ty_erased =
                            self.tcx.instantiate_bound_regions_with_erased(ty);
                        let ty_erased =
                            self.tcx.erase_and_anonymize_regions(ty_erased);
                        let eq = ty_erased == target_ty_erased;
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3151",
                                                "rustc_trait_selection::error_reporting::traits::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(3151u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&["ty_erased",
                                                                "target_ty_erased", "eq"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&ty_erased)
                                                                    as &dyn Value)),
                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&target_ty_erased)
                                                                    as &dyn Value)),
                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&eq) as
                                                                    &dyn Value))])
                                    });
                            } else { ; }
                        };
                        eq
                    };
            let coroutine_data =
                match &self.typeck_results {
                    Some(t) if t.hir_owner.to_def_id() == coroutine_did_root =>
                        CoroutineData(t),
                    _ if coroutine_did.is_local() => {
                        CoroutineData(self.tcx.typeck(coroutine_did.expect_local()))
                    }
                    _ => return false,
                };
            let coroutine_within_in_progress_typeck =
                match &self.typeck_results {
                    Some(t) => t.hir_owner.to_def_id() == coroutine_did_root,
                    _ => false,
                };
            let mut interior_or_upvar_span = None;
            let from_awaited_ty =
                coroutine_data.get_from_await_ty(visitor, self.tcx,
                    ty_matches);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3175",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3175u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["from_awaited_ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&from_awaited_ty)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            if coroutine_did.is_local() &&
                        !coroutine_within_in_progress_typeck &&
                    let Some(coroutine_info) =
                        self.tcx.mir_coroutine_witnesses(coroutine_did) {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3183",
                                        "rustc_trait_selection::error_reporting::traits::suggestions",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                        ::tracing_core::__macro_support::Option::Some(3183u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                        ::tracing_core::field::FieldSet::new(&["coroutine_info"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&coroutine_info)
                                                            as &dyn Value))])
                            });
                    } else { ; }
                };
                'find_source:
                    for (variant, source_info) in
                    coroutine_info.variant_fields.iter().zip(&coroutine_info.variant_source_info)
                    {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3187",
                                            "rustc_trait_selection::error_reporting::traits::suggestions",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                            ::tracing_core::__macro_support::Option::Some(3187u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                            ::tracing_core::field::FieldSet::new(&["variant"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&variant) as
                                                                &dyn Value))])
                                });
                        } else { ; }
                    };
                    for &local in variant {
                        let decl = &coroutine_info.field_tys[local];
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3190",
                                                "rustc_trait_selection::error_reporting::traits::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(3190u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&["decl"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&decl) as
                                                                    &dyn Value))])
                                    });
                            } else { ; }
                        };
                        if ty_matches(ty::Binder::dummy(decl.ty)) &&
                                !decl.ignore_for_traits {
                            interior_or_upvar_span =
                                Some(CoroutineInteriorOrUpvar::Interior(decl.source_info.span,
                                        Some((source_info.span, from_awaited_ty))));
                            break 'find_source;
                        }
                    }
                }
            }
            if interior_or_upvar_span.is_none() {
                interior_or_upvar_span =
                    coroutine_data.try_get_upvar_span(self, coroutine_did,
                        ty_matches);
            }
            if interior_or_upvar_span.is_none() && !coroutine_did.is_local() {
                interior_or_upvar_span =
                    Some(CoroutineInteriorOrUpvar::Interior(span, None));
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3211",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3211u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["interior_or_upvar_span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&interior_or_upvar_span)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            if let Some(interior_or_upvar_span) = interior_or_upvar_span {
                let is_async = self.tcx.coroutine_is_async(coroutine_did);
                self.note_obligation_cause_for_async_await(err,
                    interior_or_upvar_span, is_async, outer_coroutine,
                    trait_ref, target_ty, obligation, next_code);
                true
            } else { false }
        }
    }
}#[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
3001    pub fn maybe_note_obligation_cause_for_async_await<G: EmissionGuarantee>(
3002        &self,
3003        err: &mut Diag<'_, G>,
3004        obligation: &PredicateObligation<'tcx>,
3005    ) -> bool {
3006        // Attempt to detect an async-await error by looking at the obligation causes, looking
3007        // for a coroutine to be present.
3008        //
3009        // When a future does not implement a trait because of a captured type in one of the
3010        // coroutines somewhere in the call stack, then the result is a chain of obligations.
3011        //
3012        // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
3013        // future is passed as an argument to a function C which requires a `Send` type, then the
3014        // chain looks something like this:
3015        //
3016        // - `BuiltinDerivedObligation` with a coroutine witness (B)
3017        // - `BuiltinDerivedObligation` with a coroutine (B)
3018        // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
3019        // - `BuiltinDerivedObligation` with a coroutine witness (A)
3020        // - `BuiltinDerivedObligation` with a coroutine (A)
3021        // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
3022        // - `BindingObligation` with `impl_send` (Send requirement)
3023        //
3024        // The first obligation in the chain is the most useful and has the coroutine that captured
3025        // the type. The last coroutine (`outer_coroutine` below) has information about where the
3026        // bound was introduced. At least one coroutine should be present for this diagnostic to be
3027        // modified.
3028        let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
3029            ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) => (Some(p), Some(p.self_ty())),
3030            _ => (None, None),
3031        };
3032        let mut coroutine = None;
3033        let mut outer_coroutine = None;
3034        let mut next_code = Some(obligation.cause.code());
3035
3036        let mut seen_upvar_tys_infer_tuple = false;
3037
3038        while let Some(code) = next_code {
3039            debug!(?code);
3040            match code {
3041                ObligationCauseCode::FunctionArg { parent_code, .. } => {
3042                    next_code = Some(parent_code);
3043                }
3044                ObligationCauseCode::ImplDerived(cause) => {
3045                    let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
3046                    debug!(
3047                        parent_trait_ref = ?cause.derived.parent_trait_pred,
3048                        self_ty.kind = ?ty.kind(),
3049                        "ImplDerived",
3050                    );
3051
3052                    match *ty.kind() {
3053                        ty::Coroutine(did, ..) | ty::CoroutineWitness(did, _) => {
3054                            coroutine = coroutine.or(Some(did));
3055                            outer_coroutine = Some(did);
3056                        }
3057                        ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
3058                            // By introducing a tuple of upvar types into the chain of obligations
3059                            // of a coroutine, the first non-coroutine item is now the tuple itself,
3060                            // we shall ignore this.
3061
3062                            seen_upvar_tys_infer_tuple = true;
3063                        }
3064                        _ if coroutine.is_none() => {
3065                            trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
3066                            target_ty = Some(ty);
3067                        }
3068                        _ => {}
3069                    }
3070
3071                    next_code = Some(&cause.derived.parent_code);
3072                }
3073                ObligationCauseCode::WellFormedDerived(derived_obligation)
3074                | ObligationCauseCode::BuiltinDerived(derived_obligation) => {
3075                    let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
3076                    debug!(
3077                        parent_trait_ref = ?derived_obligation.parent_trait_pred,
3078                        self_ty.kind = ?ty.kind(),
3079                    );
3080
3081                    match *ty.kind() {
3082                        ty::Coroutine(did, ..) | ty::CoroutineWitness(did, ..) => {
3083                            coroutine = coroutine.or(Some(did));
3084                            outer_coroutine = Some(did);
3085                        }
3086                        ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
3087                            // By introducing a tuple of upvar types into the chain of obligations
3088                            // of a coroutine, the first non-coroutine item is now the tuple itself,
3089                            // we shall ignore this.
3090
3091                            seen_upvar_tys_infer_tuple = true;
3092                        }
3093                        _ if coroutine.is_none() => {
3094                            trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
3095                            target_ty = Some(ty);
3096                        }
3097                        _ => {}
3098                    }
3099
3100                    next_code = Some(&derived_obligation.parent_code);
3101                }
3102                _ => break,
3103            }
3104        }
3105
3106        // Only continue if a coroutine was found.
3107        debug!(?coroutine, ?trait_ref, ?target_ty);
3108        let (Some(coroutine_did), Some(trait_ref), Some(target_ty)) =
3109            (coroutine, trait_ref, target_ty)
3110        else {
3111            return false;
3112        };
3113
3114        let span = self.tcx.def_span(coroutine_did);
3115
3116        let coroutine_did_root = self.tcx.typeck_root_def_id(coroutine_did);
3117        debug!(
3118            ?coroutine_did,
3119            ?coroutine_did_root,
3120            typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
3121            ?span,
3122        );
3123
3124        let coroutine_body =
3125            coroutine_did.as_local().and_then(|def_id| self.tcx.hir_maybe_body_owned_by(def_id));
3126        let mut visitor = AwaitsVisitor::default();
3127        if let Some(body) = coroutine_body {
3128            visitor.visit_body(&body);
3129        }
3130        debug!(awaits = ?visitor.awaits);
3131
3132        // Look for a type inside the coroutine interior that matches the target type to get
3133        // a span.
3134        let target_ty_erased = self.tcx.erase_and_anonymize_regions(target_ty);
3135        let ty_matches = |ty| -> bool {
3136            // Careful: the regions for types that appear in the
3137            // coroutine interior are not generally known, so we
3138            // want to erase them when comparing (and anyway,
3139            // `Send` and other bounds are generally unaffected by
3140            // the choice of region). When erasing regions, we
3141            // also have to erase late-bound regions. This is
3142            // because the types that appear in the coroutine
3143            // interior generally contain "bound regions" to
3144            // represent regions that are part of the suspended
3145            // coroutine frame. Bound regions are preserved by
3146            // `erase_and_anonymize_regions` and so we must also call
3147            // `instantiate_bound_regions_with_erased`.
3148            let ty_erased = self.tcx.instantiate_bound_regions_with_erased(ty);
3149            let ty_erased = self.tcx.erase_and_anonymize_regions(ty_erased);
3150            let eq = ty_erased == target_ty_erased;
3151            debug!(?ty_erased, ?target_ty_erased, ?eq);
3152            eq
3153        };
3154
3155        // Get the typeck results from the infcx if the coroutine is the function we are currently
3156        // type-checking; otherwise, get them by performing a query. This is needed to avoid
3157        // cycles. If we can't use resolved types because the coroutine comes from another crate,
3158        // we still provide a targeted error but without all the relevant spans.
3159        let coroutine_data = match &self.typeck_results {
3160            Some(t) if t.hir_owner.to_def_id() == coroutine_did_root => CoroutineData(t),
3161            _ if coroutine_did.is_local() => {
3162                CoroutineData(self.tcx.typeck(coroutine_did.expect_local()))
3163            }
3164            _ => return false,
3165        };
3166
3167        let coroutine_within_in_progress_typeck = match &self.typeck_results {
3168            Some(t) => t.hir_owner.to_def_id() == coroutine_did_root,
3169            _ => false,
3170        };
3171
3172        let mut interior_or_upvar_span = None;
3173
3174        let from_awaited_ty = coroutine_data.get_from_await_ty(visitor, self.tcx, ty_matches);
3175        debug!(?from_awaited_ty);
3176
3177        // Avoid disclosing internal information to downstream crates.
3178        if coroutine_did.is_local()
3179            // Try to avoid cycles.
3180            && !coroutine_within_in_progress_typeck
3181            && let Some(coroutine_info) = self.tcx.mir_coroutine_witnesses(coroutine_did)
3182        {
3183            debug!(?coroutine_info);
3184            'find_source: for (variant, source_info) in
3185                coroutine_info.variant_fields.iter().zip(&coroutine_info.variant_source_info)
3186            {
3187                debug!(?variant);
3188                for &local in variant {
3189                    let decl = &coroutine_info.field_tys[local];
3190                    debug!(?decl);
3191                    if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.ignore_for_traits {
3192                        interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(
3193                            decl.source_info.span,
3194                            Some((source_info.span, from_awaited_ty)),
3195                        ));
3196                        break 'find_source;
3197                    }
3198                }
3199            }
3200        }
3201
3202        if interior_or_upvar_span.is_none() {
3203            interior_or_upvar_span =
3204                coroutine_data.try_get_upvar_span(self, coroutine_did, ty_matches);
3205        }
3206
3207        if interior_or_upvar_span.is_none() && !coroutine_did.is_local() {
3208            interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(span, None));
3209        }
3210
3211        debug!(?interior_or_upvar_span);
3212        if let Some(interior_or_upvar_span) = interior_or_upvar_span {
3213            let is_async = self.tcx.coroutine_is_async(coroutine_did);
3214            self.note_obligation_cause_for_async_await(
3215                err,
3216                interior_or_upvar_span,
3217                is_async,
3218                outer_coroutine,
3219                trait_ref,
3220                target_ty,
3221                obligation,
3222                next_code,
3223            );
3224            true
3225        } else {
3226            false
3227        }
3228    }
3229
3230    /// Unconditionally adds the diagnostic note described in
3231    /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
3232    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("note_obligation_cause_for_async_await",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3232u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let source_map = self.tcx.sess.source_map();
            let (await_or_yield, an_await_or_yield) =
                if is_async {
                    ("await", "an await")
                } else { ("yield", "a yield") };
            let future_or_coroutine =
                if is_async { "future" } else { "coroutine" };
            let trait_explanation =
                if let Some(name @ (sym::Send | sym::Sync)) =
                        self.tcx.get_diagnostic_name(trait_pred.def_id()) {
                    let (trait_name, trait_verb) =
                        if name == sym::Send {
                            ("`Send`", "sent")
                        } else { ("`Sync`", "shared") };
                    err.code = None;
                    err.primary_message(::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("{0} cannot be {1} between threads safely",
                                        future_or_coroutine, trait_verb))
                            }));
                    let original_span = err.span.primary_span().unwrap();
                    let mut span = MultiSpan::from_span(original_span);
                    let message =
                        outer_coroutine.and_then(|coroutine_did|
                                    {
                                        Some(match self.tcx.coroutine_kind(coroutine_did).unwrap() {
                                                CoroutineKind::Coroutine(_) =>
                                                    ::alloc::__export::must_use({
                                                            ::alloc::fmt::format(format_args!("coroutine is not {0}",
                                                                    trait_name))
                                                        }),
                                                CoroutineKind::Desugared(CoroutineDesugaring::Async,
                                                    CoroutineSource::Fn) =>
                                                    self.tcx.parent(coroutine_did).as_local().map(|parent_did|
                                                                        self.tcx.local_def_id_to_hir_id(parent_did)).and_then(|parent_hir_id|
                                                                    self.tcx.hir_opt_name(parent_hir_id)).map(|name|
                                                                {
                                                                    ::alloc::__export::must_use({
                                                                            ::alloc::fmt::format(format_args!("future returned by `{0}` is not {1}",
                                                                                    name, trait_name))
                                                                        })
                                                                })?,
                                                CoroutineKind::Desugared(CoroutineDesugaring::Async,
                                                    CoroutineSource::Block) => {
                                                    ::alloc::__export::must_use({
                                                            ::alloc::fmt::format(format_args!("future created by async block is not {0}",
                                                                    trait_name))
                                                        })
                                                }
                                                CoroutineKind::Desugared(CoroutineDesugaring::Async,
                                                    CoroutineSource::Closure) => {
                                                    ::alloc::__export::must_use({
                                                            ::alloc::fmt::format(format_args!("future created by async closure is not {0}",
                                                                    trait_name))
                                                        })
                                                }
                                                CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen,
                                                    CoroutineSource::Fn) =>
                                                    self.tcx.parent(coroutine_did).as_local().map(|parent_did|
                                                                        self.tcx.local_def_id_to_hir_id(parent_did)).and_then(|parent_hir_id|
                                                                    self.tcx.hir_opt_name(parent_hir_id)).map(|name|
                                                                {
                                                                    ::alloc::__export::must_use({
                                                                            ::alloc::fmt::format(format_args!("async iterator returned by `{0}` is not {1}",
                                                                                    name, trait_name))
                                                                        })
                                                                })?,
                                                CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen,
                                                    CoroutineSource::Block) => {
                                                    ::alloc::__export::must_use({
                                                            ::alloc::fmt::format(format_args!("async iterator created by async gen block is not {0}",
                                                                    trait_name))
                                                        })
                                                }
                                                CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen,
                                                    CoroutineSource::Closure) => {
                                                    ::alloc::__export::must_use({
                                                            ::alloc::fmt::format(format_args!("async iterator created by async gen closure is not {0}",
                                                                    trait_name))
                                                        })
                                                }
                                                CoroutineKind::Desugared(CoroutineDesugaring::Gen,
                                                    CoroutineSource::Fn) => {
                                                    self.tcx.parent(coroutine_did).as_local().map(|parent_did|
                                                                        self.tcx.local_def_id_to_hir_id(parent_did)).and_then(|parent_hir_id|
                                                                    self.tcx.hir_opt_name(parent_hir_id)).map(|name|
                                                                {
                                                                    ::alloc::__export::must_use({
                                                                            ::alloc::fmt::format(format_args!("iterator returned by `{0}` is not {1}",
                                                                                    name, trait_name))
                                                                        })
                                                                })?
                                                }
                                                CoroutineKind::Desugared(CoroutineDesugaring::Gen,
                                                    CoroutineSource::Block) => {
                                                    ::alloc::__export::must_use({
                                                            ::alloc::fmt::format(format_args!("iterator created by gen block is not {0}",
                                                                    trait_name))
                                                        })
                                                }
                                                CoroutineKind::Desugared(CoroutineDesugaring::Gen,
                                                    CoroutineSource::Closure) => {
                                                    ::alloc::__export::must_use({
                                                            ::alloc::fmt::format(format_args!("iterator created by gen closure is not {0}",
                                                                    trait_name))
                                                        })
                                                }
                                            })
                                    }).unwrap_or_else(||
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("{0} is not {1}",
                                                future_or_coroutine, trait_name))
                                    }));
                    span.push_span_label(original_span, message);
                    err.span(span);
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("is not {0}", trait_name))
                        })
                } else {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("does not implement `{0}`",
                                    trait_pred.print_modifiers_and_trait_path()))
                        })
                };
            let mut explain_yield =
                |interior_span: Span, yield_span: Span|
                    {
                        let mut span = MultiSpan::from_span(yield_span);
                        let snippet =
                            match source_map.span_to_snippet(interior_span) {
                                Ok(snippet) if !snippet.contains('\n') =>
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("`{0}`", snippet))
                                        }),
                                _ => "the value".to_string(),
                            };
                        span.push_span_label(yield_span,
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("{0} occurs here, with {1} maybe used later",
                                            await_or_yield, snippet))
                                }));
                        span.push_span_label(interior_span,
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("has type `{0}` which {1}",
                                            target_ty, trait_explanation))
                                }));
                        err.span_note(span,
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("{0} {1} as this value is used across {2}",
                                            future_or_coroutine, trait_explanation, an_await_or_yield))
                                }));
                    };
            match interior_or_upvar_span {
                CoroutineInteriorOrUpvar::Interior(interior_span,
                    interior_extra_info) => {
                    if let Some((yield_span, from_awaited_ty)) =
                            interior_extra_info {
                        if let Some(await_span) = from_awaited_ty {
                            let mut span = MultiSpan::from_span(await_span);
                            span.push_span_label(await_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("await occurs here on type `{0}`, which {1}",
                                                target_ty, trait_explanation))
                                    }));
                            err.span_note(span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("future {0} as it awaits another future which {0}",
                                                trait_explanation))
                                    }));
                        } else { explain_yield(interior_span, yield_span); }
                    }
                }
                CoroutineInteriorOrUpvar::Upvar(upvar_span) => {
                    let non_send =
                        match target_ty.kind() {
                            ty::Ref(_, ref_ty, mutability) =>
                                match self.evaluate_obligation(obligation) {
                                    Ok(eval) if !eval.may_apply() =>
                                        Some((ref_ty, mutability.is_mut())),
                                    _ => None,
                                },
                            _ => None,
                        };
                    let (span_label, span_note) =
                        match non_send {
                            Some((ref_ty, is_mut)) => {
                                let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
                                let ref_kind = if is_mut { "&mut" } else { "&" };
                                (::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("has type `{0}` which {1}, because `{2}` is not `{3}`",
                                                    target_ty, trait_explanation, ref_ty, ref_ty_trait))
                                        }),
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("captured value {0} because `{1}` references cannot be sent unless their referent is `{2}`",
                                                    trait_explanation, ref_kind, ref_ty_trait))
                                        }))
                            }
                            None =>
                                (::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("has type `{0}` which {1}",
                                                    target_ty, trait_explanation))
                                        }),
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("captured value {0}",
                                                    trait_explanation))
                                        })),
                        };
                    let mut span = MultiSpan::from_span(upvar_span);
                    span.push_span_label(upvar_span, span_label);
                    err.span_note(span, span_note);
                }
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3455",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3455u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["next_code"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&next_code)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            self.note_obligation_cause_code(obligation.cause.body_def_id, err,
                obligation.predicate, obligation.param_env,
                next_code.unwrap(), &mut Vec::new(), &mut Default::default());
        }
    }
}#[instrument(level = "debug", skip_all)]
3233    fn note_obligation_cause_for_async_await<G: EmissionGuarantee>(
3234        &self,
3235        err: &mut Diag<'_, G>,
3236        interior_or_upvar_span: CoroutineInteriorOrUpvar,
3237        is_async: bool,
3238        outer_coroutine: Option<DefId>,
3239        trait_pred: ty::TraitPredicate<'tcx>,
3240        target_ty: Ty<'tcx>,
3241        obligation: &PredicateObligation<'tcx>,
3242        next_code: Option<&ObligationCauseCode<'tcx>>,
3243    ) {
3244        let source_map = self.tcx.sess.source_map();
3245
3246        let (await_or_yield, an_await_or_yield) =
3247            if is_async { ("await", "an await") } else { ("yield", "a yield") };
3248        let future_or_coroutine = if is_async { "future" } else { "coroutine" };
3249
3250        // Special case the primary error message when send or sync is the trait that was
3251        // not implemented.
3252        let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
3253            self.tcx.get_diagnostic_name(trait_pred.def_id())
3254        {
3255            let (trait_name, trait_verb) =
3256                if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
3257
3258            err.code = None;
3259            err.primary_message(format!(
3260                "{future_or_coroutine} cannot be {trait_verb} between threads safely"
3261            ));
3262
3263            let original_span = err.span.primary_span().unwrap();
3264            let mut span = MultiSpan::from_span(original_span);
3265
3266            let message = outer_coroutine
3267                .and_then(|coroutine_did| {
3268                    Some(match self.tcx.coroutine_kind(coroutine_did).unwrap() {
3269                        CoroutineKind::Coroutine(_) => format!("coroutine is not {trait_name}"),
3270                        CoroutineKind::Desugared(
3271                            CoroutineDesugaring::Async,
3272                            CoroutineSource::Fn,
3273                        ) => self
3274                            .tcx
3275                            .parent(coroutine_did)
3276                            .as_local()
3277                            .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3278                            .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3279                            .map(|name| {
3280                                format!("future returned by `{name}` is not {trait_name}")
3281                            })?,
3282                        CoroutineKind::Desugared(
3283                            CoroutineDesugaring::Async,
3284                            CoroutineSource::Block,
3285                        ) => {
3286                            format!("future created by async block is not {trait_name}")
3287                        }
3288                        CoroutineKind::Desugared(
3289                            CoroutineDesugaring::Async,
3290                            CoroutineSource::Closure,
3291                        ) => {
3292                            format!("future created by async closure is not {trait_name}")
3293                        }
3294                        CoroutineKind::Desugared(
3295                            CoroutineDesugaring::AsyncGen,
3296                            CoroutineSource::Fn,
3297                        ) => self
3298                            .tcx
3299                            .parent(coroutine_did)
3300                            .as_local()
3301                            .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3302                            .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3303                            .map(|name| {
3304                                format!("async iterator returned by `{name}` is not {trait_name}")
3305                            })?,
3306                        CoroutineKind::Desugared(
3307                            CoroutineDesugaring::AsyncGen,
3308                            CoroutineSource::Block,
3309                        ) => {
3310                            format!("async iterator created by async gen block is not {trait_name}")
3311                        }
3312                        CoroutineKind::Desugared(
3313                            CoroutineDesugaring::AsyncGen,
3314                            CoroutineSource::Closure,
3315                        ) => {
3316                            format!(
3317                                "async iterator created by async gen closure is not {trait_name}"
3318                            )
3319                        }
3320                        CoroutineKind::Desugared(CoroutineDesugaring::Gen, CoroutineSource::Fn) => {
3321                            self.tcx
3322                                .parent(coroutine_did)
3323                                .as_local()
3324                                .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3325                                .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3326                                .map(|name| {
3327                                    format!("iterator returned by `{name}` is not {trait_name}")
3328                                })?
3329                        }
3330                        CoroutineKind::Desugared(
3331                            CoroutineDesugaring::Gen,
3332                            CoroutineSource::Block,
3333                        ) => {
3334                            format!("iterator created by gen block is not {trait_name}")
3335                        }
3336                        CoroutineKind::Desugared(
3337                            CoroutineDesugaring::Gen,
3338                            CoroutineSource::Closure,
3339                        ) => {
3340                            format!("iterator created by gen closure is not {trait_name}")
3341                        }
3342                    })
3343                })
3344                .unwrap_or_else(|| format!("{future_or_coroutine} is not {trait_name}"));
3345
3346            span.push_span_label(original_span, message);
3347            err.span(span);
3348
3349            format!("is not {trait_name}")
3350        } else {
3351            format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
3352        };
3353
3354        let mut explain_yield = |interior_span: Span, yield_span: Span| {
3355            let mut span = MultiSpan::from_span(yield_span);
3356            let snippet = match source_map.span_to_snippet(interior_span) {
3357                // #70935: If snippet contains newlines, display "the value" instead
3358                // so that we do not emit complex diagnostics.
3359                Ok(snippet) if !snippet.contains('\n') => format!("`{snippet}`"),
3360                _ => "the value".to_string(),
3361            };
3362            // note: future is not `Send` as this value is used across an await
3363            //   --> $DIR/issue-70935-complex-spans.rs:13:9
3364            //    |
3365            // LL |            baz(|| async {
3366            //    |  ______________-
3367            //    | |
3368            //    | |
3369            // LL | |              foo(tx.clone());
3370            // LL | |          }).await;
3371            //    | |          - ^^^^^^ await occurs here, with value maybe used later
3372            //    | |__________|
3373            //    |            has type `closure` which is not `Send`
3374            // note: value is later dropped here
3375            // LL | |          }).await;
3376            //    | |                  ^
3377            //
3378            span.push_span_label(
3379                yield_span,
3380                format!("{await_or_yield} occurs here, with {snippet} maybe used later"),
3381            );
3382            span.push_span_label(
3383                interior_span,
3384                format!("has type `{target_ty}` which {trait_explanation}"),
3385            );
3386            err.span_note(
3387                span,
3388                format!("{future_or_coroutine} {trait_explanation} as this value is used across {an_await_or_yield}"),
3389            );
3390        };
3391        match interior_or_upvar_span {
3392            CoroutineInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
3393                if let Some((yield_span, from_awaited_ty)) = interior_extra_info {
3394                    if let Some(await_span) = from_awaited_ty {
3395                        // The type causing this obligation is one being awaited at await_span.
3396                        let mut span = MultiSpan::from_span(await_span);
3397                        span.push_span_label(
3398                            await_span,
3399                            format!(
3400                                "await occurs here on type `{target_ty}`, which {trait_explanation}"
3401                            ),
3402                        );
3403                        err.span_note(
3404                            span,
3405                            format!(
3406                                "future {trait_explanation} as it awaits another future which {trait_explanation}"
3407                            ),
3408                        );
3409                    } else {
3410                        // Look at the last interior type to get a span for the `.await`.
3411                        explain_yield(interior_span, yield_span);
3412                    }
3413                }
3414            }
3415            CoroutineInteriorOrUpvar::Upvar(upvar_span) => {
3416                // `Some((ref_ty, is_mut))` if `target_ty` is `&T` or `&mut T` and fails to impl `Send`
3417                let non_send = match target_ty.kind() {
3418                    ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(obligation) {
3419                        Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
3420                        _ => None,
3421                    },
3422                    _ => None,
3423                };
3424
3425                let (span_label, span_note) = match non_send {
3426                    // if `target_ty` is `&T` or `&mut T` and fails to impl `Send`,
3427                    // include suggestions to make `T: Sync` so that `&T: Send`,
3428                    // or to make `T: Send` so that `&mut T: Send`
3429                    Some((ref_ty, is_mut)) => {
3430                        let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
3431                        let ref_kind = if is_mut { "&mut" } else { "&" };
3432                        (
3433                            format!(
3434                                "has type `{target_ty}` which {trait_explanation}, because `{ref_ty}` is not `{ref_ty_trait}`"
3435                            ),
3436                            format!(
3437                                "captured value {trait_explanation} because `{ref_kind}` references cannot be sent unless their referent is `{ref_ty_trait}`"
3438                            ),
3439                        )
3440                    }
3441                    None => (
3442                        format!("has type `{target_ty}` which {trait_explanation}"),
3443                        format!("captured value {trait_explanation}"),
3444                    ),
3445                };
3446
3447                let mut span = MultiSpan::from_span(upvar_span);
3448                span.push_span_label(upvar_span, span_label);
3449                err.span_note(span, span_note);
3450            }
3451        }
3452
3453        // Add a note for the item obligation that remains - normally a note pointing to the
3454        // bound that introduced the obligation (e.g. `T: Send`).
3455        debug!(?next_code);
3456        self.note_obligation_cause_code(
3457            obligation.cause.body_def_id,
3458            err,
3459            obligation.predicate,
3460            obligation.param_env,
3461            next_code.unwrap(),
3462            &mut Vec::new(),
3463            &mut Default::default(),
3464        );
3465    }
3466
3467    pub(super) fn note_obligation_cause_code<G: EmissionGuarantee, T>(
3468        &self,
3469        body_def_id: LocalDefId,
3470        err: &mut Diag<'_, G>,
3471        predicate: T,
3472        param_env: ty::ParamEnv<'tcx>,
3473        cause_code: &ObligationCauseCode<'tcx>,
3474        obligated_types: &mut Vec<Ty<'tcx>>,
3475        seen_requirements: &mut FxHashSet<DefId>,
3476    ) where
3477        T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
3478    {
3479        let tcx = self.tcx;
3480        let predicate = predicate.upcast(tcx);
3481        let suggest_remove_deref = |err: &mut Diag<'_, G>, expr: &hir::Expr<'_>| {
3482            if let Some(pred) = predicate.as_trait_clause()
3483                && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
3484                && let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind
3485            {
3486                err.span_suggestion_verbose(
3487                    expr.span.until(inner.span),
3488                    "references are always `Sized`, even if they point to unsized data; consider \
3489                     not dereferencing the expression",
3490                    String::new(),
3491                    Applicability::MaybeIncorrect,
3492                );
3493            }
3494        };
3495        match *cause_code {
3496            ObligationCauseCode::ExprAssignable
3497            | ObligationCauseCode::MatchExpressionArm { .. }
3498            | ObligationCauseCode::Pattern { .. }
3499            | ObligationCauseCode::IfExpression { .. }
3500            | ObligationCauseCode::IfExpressionWithNoElse
3501            | ObligationCauseCode::MainFunctionType
3502            | ObligationCauseCode::LangFunctionType(_)
3503            | ObligationCauseCode::IntrinsicType
3504            | ObligationCauseCode::MethodReceiver
3505            | ObligationCauseCode::ReturnNoExpression
3506            | ObligationCauseCode::Misc
3507            | ObligationCauseCode::WellFormed(..)
3508            | ObligationCauseCode::MatchImpl(..)
3509            | ObligationCauseCode::ReturnValue(_)
3510            | ObligationCauseCode::BlockTailExpression(..)
3511            | ObligationCauseCode::AwaitableExpr(_)
3512            | ObligationCauseCode::ForLoopIterator
3513            | ObligationCauseCode::QuestionMark
3514            | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
3515            | ObligationCauseCode::LetElse
3516            | ObligationCauseCode::UnOp { .. }
3517            | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
3518            | ObligationCauseCode::AlwaysApplicableImpl
3519            | ObligationCauseCode::ConstParam(_)
3520            | ObligationCauseCode::ReferenceOutlivesReferent(..)
3521            | ObligationCauseCode::ObjectTypeBound(..) => {}
3522            ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. } => {
3523                if let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
3524                    && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
3525                    && tcx.sess.source_map().lookup_char_pos(lhs.span.lo()).line
3526                        != tcx.sess.source_map().lookup_char_pos(rhs.span.hi()).line
3527                {
3528                    err.span_label(lhs.span, "");
3529                    err.span_label(rhs.span, "");
3530                }
3531            }
3532            ObligationCauseCode::RustCall => {
3533                if let Some(pred) = predicate.as_trait_clause()
3534                    && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
3535                {
3536                    err.note("argument required to be sized due to `extern \"rust-call\"` ABI");
3537                }
3538            }
3539            ObligationCauseCode::SliceOrArrayElem => {
3540                err.note("slice and array elements must have `Sized` type");
3541            }
3542            ObligationCauseCode::ArrayLen(array_ty) => {
3543                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the length of array `{0}` must be type `usize`",
                array_ty))
    })format!("the length of array `{array_ty}` must be type `usize`"));
3544            }
3545            ObligationCauseCode::TupleElem => {
3546                err.note("only the last element of a tuple may have a dynamically sized type");
3547            }
3548            ObligationCauseCode::DynCompatible(span) => {
3549                err.multipart_suggestion(
3550                    "you might have meant to use `Self` to refer to the implementing type",
3551                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span, "Self".into())]))vec![(span, "Self".into())],
3552                    Applicability::MachineApplicable,
3553                );
3554            }
3555            ObligationCauseCode::WhereClause(item_def_id, span)
3556            | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)
3557            | ObligationCauseCode::HostEffectInExpr(item_def_id, span, ..)
3558                if !span.is_dummy() =>
3559            {
3560                if let ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, pos) = &cause_code {
3561                    if let Node::Expr(expr) = tcx.parent_hir_node(*hir_id)
3562                        && let hir::ExprKind::Call(_, args) = expr.kind
3563                        && let Some(expr) = args.get(*pos)
3564                    {
3565                        suggest_remove_deref(err, &expr);
3566                    } else if let Node::Expr(expr) = self.tcx.hir_node(*hir_id)
3567                        && let hir::ExprKind::MethodCall(_, _, args, _) = expr.kind
3568                        && let Some(expr) = args.get(*pos)
3569                    {
3570                        suggest_remove_deref(err, &expr);
3571                    }
3572                }
3573                let item_name = tcx.def_path_str(item_def_id);
3574                let short_item_name = { let _guard = ForceTrimmedGuard::new(); tcx.def_path_str(item_def_id) }with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
3575                let mut multispan = MultiSpan::from(span);
3576                let sm = tcx.sess.source_map();
3577                if let Some(ident) = tcx.opt_item_ident(item_def_id) {
3578                    let same_line =
3579                        match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
3580                            (Ok(l), Ok(r)) => l.line == r.line,
3581                            _ => true,
3582                        };
3583                    if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
3584                        multispan.push_span_label(
3585                            ident.span,
3586                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required by a bound in this {0}",
                tcx.def_kind(item_def_id).descr(item_def_id)))
    })format!(
3587                                "required by a bound in this {}",
3588                                tcx.def_kind(item_def_id).descr(item_def_id)
3589                            ),
3590                        );
3591                    }
3592                }
3593                let mut a = "a";
3594                let mut this = "this bound";
3595                let mut note = None;
3596                let mut help = None;
3597                if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() {
3598                    match clause {
3599                        ty::ClauseKind::Trait(trait_pred) => {
3600                            let def_id = trait_pred.def_id();
3601                            let visible_item = if let Some(local) = def_id.as_local() {
3602                                let ty = trait_pred.self_ty();
3603                                // when `TraitA: TraitB` and `S` only impl TraitA,
3604                                // we check if `TraitB` can be reachable from `S`
3605                                // to determine whether to note `TraitA` is sealed trait.
3606                                if let ty::Adt(adt, _) = ty.kind() {
3607                                    let visibilities = &tcx.resolutions(()).effective_visibilities;
3608                                    visibilities.effective_vis(local).is_none_or(|v| {
3609                                        v.at_level(Level::Reexported)
3610                                            .is_accessible_from(adt.did(), tcx)
3611                                    })
3612                                } else {
3613                                    // FIXME(xizheyin): if the type is not ADT, we should not suggest it
3614                                    true
3615                                }
3616                            } else {
3617                                // Check for foreign traits being reachable.
3618                                tcx.visible_parent_map(()).get(&def_id).is_some()
3619                            };
3620                            if tcx.is_lang_item(def_id, LangItem::Sized) {
3621                                // Check if this is an implicit bound, even in foreign crates.
3622                                if tcx
3623                                    .generics_of(item_def_id)
3624                                    .own_params
3625                                    .iter()
3626                                    .any(|param| tcx.def_span(param.def_id) == span)
3627                                {
3628                                    a = "an implicit `Sized`";
3629                                    this =
3630                                        "the implicit `Sized` requirement on this type parameter";
3631                                }
3632                                if let Some(hir::Node::TraitItem(hir::TraitItem {
3633                                    generics,
3634                                    kind: hir::TraitItemKind::Type(bounds, None),
3635                                    ..
3636                                })) = tcx.hir_get_if_local(item_def_id)
3637                                    // Do not suggest relaxing if there is an explicit `Sized` obligation.
3638                                    && !bounds.iter()
3639                                        .filter_map(|bound| bound.trait_ref())
3640                                        .any(|tr| tr.trait_def_id().is_some_and(|def_id| tcx.is_lang_item(def_id, LangItem::Sized)))
3641                                {
3642                                    let (span, separator) = if let [.., last] = bounds {
3643                                        (last.span().shrink_to_hi(), " +")
3644                                    } else {
3645                                        (generics.span.shrink_to_hi(), ":")
3646                                    };
3647                                    err.span_suggestion_verbose(
3648                                        span,
3649                                        "consider relaxing the implicit `Sized` restriction",
3650                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ?Sized", separator))
    })format!("{separator} ?Sized"),
3651                                        Applicability::MachineApplicable,
3652                                    );
3653                                }
3654                            }
3655                            if let DefKind::Trait = tcx.def_kind(item_def_id)
3656                                && !visible_item
3657                            {
3658                                note = Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{1}` is a \"sealed trait\", because to implement it you also need to implement `{0}`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it",
                {
                    let _guard = NoTrimmedGuard::new();
                    tcx.def_path_str(def_id)
                }, short_item_name))
    })format!(
3659                                    "`{short_item_name}` is a \"sealed trait\", because to implement it \
3660                                    you also need to implement `{}`, which is not accessible; this is \
3661                                    usually done to force you to use one of the provided types that \
3662                                    already implement it",
3663                                    with_no_trimmed_paths!(tcx.def_path_str(def_id)),
3664                                ));
3665                                let mut types = tcx
3666                                    .all_impls(def_id)
3667                                    .map(|t| {
3668                                        {
    let _guard = NoTrimmedGuard::new();
    ::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("  {0}",
                    tcx.type_of(t).instantiate_identity().skip_norm_wip()))
        })
}with_no_trimmed_paths!(format!(
3669                                            "  {}",
3670                                            tcx.type_of(t).instantiate_identity().skip_norm_wip(),
3671                                        ))
3672                                    })
3673                                    .collect::<Vec<_>>();
3674                                if !types.is_empty() {
3675                                    let len = types.len();
3676                                    let post = if len > 9 {
3677                                        types.truncate(8);
3678                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\nand {0} others", len - 8))
    })format!("\nand {} others", len - 8)
3679                                    } else {
3680                                        String::new()
3681                                    };
3682                                    help = Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the following type{0} implement{1} the trait:\n{2}{3}",
                if len == 1 { "" } else { "s" },
                if len == 1 { "s" } else { "" }, types.join("\n"), post))
    })format!(
3683                                        "the following type{} implement{} the trait:\n{}{post}",
3684                                        pluralize!(len),
3685                                        if len == 1 { "s" } else { "" },
3686                                        types.join("\n"),
3687                                    ));
3688                                }
3689                            }
3690                        }
3691                        ty::ClauseKind::ConstArgHasType(..) => {
3692                            let descr =
3693                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required by a const generic parameter in `{0}`",
                item_name))
    })format!("required by a const generic parameter in `{item_name}`");
3694                            if span.is_visible(sm) {
3695                                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required by this const generic parameter in `{0}`",
                short_item_name))
    })format!(
3696                                    "required by this const generic parameter in `{short_item_name}`"
3697                                );
3698                                multispan.push_span_label(span, msg);
3699                                err.span_note(multispan, descr);
3700                            } else {
3701                                err.span_note(tcx.def_span(item_def_id), descr);
3702                            }
3703                            return;
3704                        }
3705                        _ => (),
3706                    }
3707                }
3708
3709                // If this is from a format string literal desugaring,
3710                // we've already said "required by this formatting parameter"
3711                let is_in_fmt_lit = if let Some(s) = err.span.primary_span() {
3712                    #[allow(non_exhaustive_omitted_patterns)] match s.desugaring_kind() {
    Some(DesugaringKind::FormatLiteral { .. }) => true,
    _ => false,
}matches!(s.desugaring_kind(), Some(DesugaringKind::FormatLiteral { .. }))
3713                } else {
3714                    false
3715                };
3716                if !is_in_fmt_lit {
3717                    let descr = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required by {0} bound in `{1}`", a,
                item_name))
    })format!("required by {a} bound in `{item_name}`");
3718                    if span.is_visible(sm) {
3719                        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required by {0} in `{1}`", this,
                short_item_name))
    })format!("required by {this} in `{short_item_name}`");
3720                        multispan.push_span_label(span, msg);
3721                        err.span_note(multispan, descr);
3722                    } else {
3723                        err.span_note(tcx.def_span(item_def_id), descr);
3724                    }
3725                }
3726                if let Some(note) = note {
3727                    err.note(note);
3728                }
3729                if let Some(help) = help {
3730                    err.help(help);
3731                }
3732            }
3733            ObligationCauseCode::WhereClause(..)
3734            | ObligationCauseCode::WhereClauseInExpr(..)
3735            | ObligationCauseCode::HostEffectInExpr(..) => {
3736                // We hold the `DefId` of the item introducing the obligation, but displaying it
3737                // doesn't add user usable information. It always point at an associated item.
3738            }
3739            ObligationCauseCode::OpaqueTypeBound(span, definition_def_id) => {
3740                err.span_note(span, "required by a bound in an opaque type");
3741                if let Some(definition_def_id) = definition_def_id
3742                    // If there are any stalled coroutine obligations, then this
3743                    // error may be due to that, and not because the body has more
3744                    // where-clauses.
3745                    && self.tcx.typeck(definition_def_id).coroutine_stalled_predicates.is_empty()
3746                {
3747                    // FIXME(compiler-errors): We could probably point to something
3748                    // specific here if we tried hard enough...
3749                    err.span_note(
3750                        tcx.def_span(definition_def_id),
3751                        "this definition site has more where clauses than the opaque type",
3752                    );
3753                }
3754            }
3755            ObligationCauseCode::Coercion { source, target } => {
3756                let source =
3757                    tcx.short_string(self.resolve_vars_if_possible(source), err.long_ty_path());
3758                let target =
3759                    tcx.short_string(self.resolve_vars_if_possible(target), err.long_ty_path());
3760                err.note({
    let _guard = ForceTrimmedGuard::new();
    ::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("required for the cast from `{0}` to `{1}`",
                    source, target))
        })
}with_forced_trimmed_paths!(format!(
3761                    "required for the cast from `{source}` to `{target}`",
3762                )));
3763            }
3764            ObligationCauseCode::RepeatElementCopy { is_constable, elt_span } => {
3765                err.note(
3766                    "the `Copy` trait is required because this value will be copied for each element of the array",
3767                );
3768                let sm = tcx.sess.source_map();
3769                if #[allow(non_exhaustive_omitted_patterns)] match is_constable {
    IsConstable::Fn | IsConstable::Ctor => true,
    _ => false,
}matches!(is_constable, IsConstable::Fn | IsConstable::Ctor)
3770                    && let Ok(_) = sm.span_to_snippet(elt_span)
3771                {
3772                    err.multipart_suggestion(
3773                        "create an inline `const` block",
3774                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(elt_span.shrink_to_lo(), "const { ".to_string()),
                (elt_span.shrink_to_hi(), " }".to_string())]))vec![
3775                            (elt_span.shrink_to_lo(), "const { ".to_string()),
3776                            (elt_span.shrink_to_hi(), " }".to_string()),
3777                        ],
3778                        Applicability::MachineApplicable,
3779                    );
3780                } else {
3781                    // FIXME: we may suggest array::repeat instead
3782                    err.help("consider using `core::array::from_fn` to initialize the array");
3783                    err.help("see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html for more information");
3784                }
3785            }
3786            ObligationCauseCode::VariableType(hir_id) => {
3787                if let Some(typeck_results) = &self.typeck_results
3788                    && let Some(ty) = typeck_results.node_type_opt(hir_id)
3789                    && let ty::Error(_) = ty.kind()
3790                {
3791                    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` isn\'t satisfied, but the type of this pattern is `{{type error}}`",
                predicate))
    })format!(
3792                        "`{predicate}` isn't satisfied, but the type of this pattern is \
3793                         `{{type error}}`",
3794                    ));
3795                    err.downgrade_to_delayed_bug();
3796                }
3797                let mut local = true;
3798                match tcx.parent_hir_node(hir_id) {
3799                    Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }) => {
3800                        err.span_suggestion_verbose(
3801                            ty.span.shrink_to_lo(),
3802                            "consider borrowing here",
3803                            "&",
3804                            Applicability::MachineApplicable,
3805                        );
3806                    }
3807                    Node::LetStmt(hir::LetStmt {
3808                        init: Some(hir::Expr { kind: hir::ExprKind::Index(..), span, .. }),
3809                        ..
3810                    }) => {
3811                        // When encountering an assignment of an unsized trait, like
3812                        // `let x = ""[..];`, provide a suggestion to borrow the initializer in
3813                        // order to use have a slice instead.
3814                        err.span_suggestion_verbose(
3815                            span.shrink_to_lo(),
3816                            "consider borrowing here",
3817                            "&",
3818                            Applicability::MachineApplicable,
3819                        );
3820                    }
3821                    Node::LetStmt(hir::LetStmt { init: Some(expr), .. }) => {
3822                        // When encountering an assignment of an unsized trait, like `let x = *"";`,
3823                        // we check if the RHS is a deref operation, to suggest removing it.
3824                        suggest_remove_deref(err, &expr);
3825                    }
3826                    Node::Param(param) => {
3827                        err.span_suggestion_verbose(
3828                            param.ty_span.shrink_to_lo(),
3829                            "function arguments must have a statically known size, borrowed types \
3830                            always have a known size",
3831                            "&",
3832                            Applicability::MachineApplicable,
3833                        );
3834                        local = false;
3835                    }
3836                    _ => {}
3837                }
3838                if local {
3839                    err.note("all local variables must have a statically known size");
3840                }
3841            }
3842            ObligationCauseCode::SizedArgumentType(hir_id) => {
3843                let mut ty = None;
3844                let borrowed_msg = "function arguments must have a statically known size, borrowed \
3845                                    types always have a known size";
3846                if let Some(hir_id) = hir_id
3847                    && let hir::Node::Param(param) = self.tcx.hir_node(hir_id)
3848                    && let Some(decl) = self.tcx.parent_hir_node(hir_id).fn_decl()
3849                    && let Some(t) = decl.inputs.iter().find(|t| param.ty_span.contains(t.span))
3850                {
3851                    // We use `contains` because the type might be surrounded by parentheses,
3852                    // which makes `ty_span` and `t.span` disagree with each other, but one
3853                    // fully contains the other: `foo: (dyn Foo + Bar)`
3854                    //                                 ^-------------^
3855                    //                                 ||
3856                    //                                 |t.span
3857                    //                                 param._ty_span
3858                    ty = Some(t);
3859                } else if let Some(hir_id) = hir_id
3860                    && let hir::Node::Ty(t) = self.tcx.hir_node(hir_id)
3861                {
3862                    ty = Some(t);
3863                }
3864                if let Some(ty) = ty {
3865                    match ty.kind {
3866                        hir::TyKind::TraitObject(traits, _) => {
3867                            let (span, kw) = match traits {
3868                                [first, ..] if first.span.lo() == ty.span.lo() => {
3869                                    // Missing `dyn` in front of trait object.
3870                                    (ty.span.shrink_to_lo(), "dyn ")
3871                                }
3872                                [first, ..] => (ty.span.until(first.span), ""),
3873                                [] => ::rustc_middle::util::bug::span_bug_fmt(ty.span,
    format_args!("trait object with no traits: {0:?}", ty))span_bug!(ty.span, "trait object with no traits: {ty:?}"),
3874                            };
3875                            let needs_parens = traits.len() != 1;
3876                            // Don't recommend impl Trait as a closure argument
3877                            if let Some(hir_id) = hir_id
3878                                && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.parent_hir_node(hir_id)
    {
    hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { .. }, .. }) => true,
    _ => false,
}matches!(
3879                                    self.tcx.parent_hir_node(hir_id),
3880                                    hir::Node::Item(hir::Item {
3881                                        kind: hir::ItemKind::Fn { .. },
3882                                        ..
3883                                    })
3884                                )
3885                            {
3886                                err.span_suggestion_verbose(
3887                                    span,
3888                                    "you can use `impl Trait` as the argument type",
3889                                    "impl ",
3890                                    Applicability::MaybeIncorrect,
3891                                );
3892                            }
3893                            let sugg = if !needs_parens {
3894                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("&{0}", kw))
                        }))]))vec![(span.shrink_to_lo(), format!("&{kw}"))]
3895                            } else {
3896                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("&({0}", kw))
                        })), (ty.span.shrink_to_hi(), ")".to_string())]))vec![
3897                                    (span.shrink_to_lo(), format!("&({kw}")),
3898                                    (ty.span.shrink_to_hi(), ")".to_string()),
3899                                ]
3900                            };
3901                            err.multipart_suggestion(
3902                                borrowed_msg,
3903                                sugg,
3904                                Applicability::MachineApplicable,
3905                            );
3906                        }
3907                        hir::TyKind::Slice(_ty) => {
3908                            err.span_suggestion_verbose(
3909                                ty.span.shrink_to_lo(),
3910                                "function arguments must have a statically known size, borrowed \
3911                                 slices always have a known size",
3912                                "&",
3913                                Applicability::MachineApplicable,
3914                            );
3915                        }
3916                        hir::TyKind::Path(_) => {
3917                            err.span_suggestion_verbose(
3918                                ty.span.shrink_to_lo(),
3919                                borrowed_msg,
3920                                "&",
3921                                Applicability::MachineApplicable,
3922                            );
3923                        }
3924                        _ => {}
3925                    }
3926                } else {
3927                    err.note("all function arguments must have a statically known size");
3928                }
3929                if tcx.sess.opts.unstable_features.is_nightly_build()
3930                    && !tcx.features().unsized_fn_params()
3931                {
3932                    err.help("unsized fn params are gated as an unstable feature");
3933                }
3934            }
3935            ObligationCauseCode::SizedReturnType | ObligationCauseCode::SizedCallReturnType => {
3936                err.note("the return type of a function must have a statically known size");
3937            }
3938            ObligationCauseCode::SizedYieldType => {
3939                err.note("the yield type of a coroutine must have a statically known size");
3940            }
3941            ObligationCauseCode::AssignmentLhsSized => {
3942                err.note("the left-hand-side of an assignment must have a statically known size");
3943            }
3944            ObligationCauseCode::TupleInitializerSized => {
3945                err.note("tuples must have a statically known size to be initialized");
3946            }
3947            ObligationCauseCode::StructInitializerSized => {
3948                err.note("structs must have a statically known size to be initialized");
3949            }
3950            ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
3951                match *item {
3952                    AdtKind::Struct => {
3953                        if last {
3954                            err.note(
3955                                "the last field of a packed struct may only have a \
3956                                dynamically sized type if it does not need drop to be run",
3957                            );
3958                        } else {
3959                            err.note(
3960                                "only the last field of a struct may have a dynamically sized type",
3961                            );
3962                        }
3963                    }
3964                    AdtKind::Union => {
3965                        err.note("no field of a union may have a dynamically sized type");
3966                    }
3967                    AdtKind::Enum => {
3968                        err.note("no field of an enum variant may have a dynamically sized type");
3969                    }
3970                }
3971                err.help("change the field's type to have a statically known size");
3972                err.span_suggestion_verbose(
3973                    span.shrink_to_lo(),
3974                    "borrowed types always have a statically known size",
3975                    "&",
3976                    Applicability::MachineApplicable,
3977                );
3978                err.multipart_suggestion(
3979                    "the `Box` type always has a statically known size and allocates its contents \
3980                     in the heap",
3981                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(), "Box<".to_string()),
                (span.shrink_to_hi(), ">".to_string())]))vec![
3982                        (span.shrink_to_lo(), "Box<".to_string()),
3983                        (span.shrink_to_hi(), ">".to_string()),
3984                    ],
3985                    Applicability::MachineApplicable,
3986                );
3987            }
3988            ObligationCauseCode::SizedConstOrStatic => {
3989                err.note("statics and constants must have a statically known size");
3990            }
3991            ObligationCauseCode::InlineAsmSized => {
3992                err.note("all inline asm arguments must have a statically known size");
3993            }
3994            ObligationCauseCode::SizedClosureCapture(closure_def_id) => {
3995                err.note(
3996                    "all values captured by value by a closure must have a statically known size",
3997                );
3998                let hir::ExprKind::Closure(closure) =
3999                    tcx.hir_node_by_def_id(closure_def_id).expect_expr().kind
4000                else {
4001                    ::rustc_middle::util::bug::bug_fmt(format_args!("expected closure in SizedClosureCapture obligation"));bug!("expected closure in SizedClosureCapture obligation");
4002                };
4003                if let hir::CaptureBy::Value { .. } = closure.capture_clause
4004                    && let Some(span) = closure.fn_arg_span
4005                {
4006                    err.span_label(span, "this closure captures all values by move");
4007                }
4008            }
4009            ObligationCauseCode::SizedCoroutineInterior(coroutine_def_id) => {
4010                let what = match tcx.coroutine_kind(coroutine_def_id) {
4011                    None
4012                    | Some(hir::CoroutineKind::Coroutine(_))
4013                    | Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)) => {
4014                        "yield"
4015                    }
4016                    Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
4017                        "await"
4018                    }
4019                    Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => {
4020                        "yield`/`await"
4021                    }
4022                };
4023                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("all values live across `{0}` must have a statically known size",
                what))
    })format!(
4024                    "all values live across `{what}` must have a statically known size"
4025                ));
4026            }
4027            ObligationCauseCode::SharedStatic => {
4028                err.note("shared static variables must have a type that implements `Sync`");
4029            }
4030            ObligationCauseCode::BuiltinDerived(ref data) => {
4031                let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
4032                let ty = parent_trait_ref.skip_binder().self_ty();
4033                if parent_trait_ref.references_error() {
4034                    // NOTE(eddyb) this was `.cancel()`, but `err`
4035                    // is borrowed, so we can't fully defuse it.
4036                    err.downgrade_to_delayed_bug();
4037                    return;
4038                }
4039
4040                // If the obligation for a tuple is set directly by a Coroutine or Closure,
4041                // then the tuple must be the one containing capture types.
4042                let is_upvar_tys_infer_tuple = if !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Tuple(..) => true,
    _ => false,
}matches!(ty.kind(), ty::Tuple(..)) {
4043                    false
4044                } else if let ObligationCauseCode::BuiltinDerived(data) = &*data.parent_code {
4045                    let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
4046                    let nested_ty = parent_trait_ref.skip_binder().self_ty();
4047                    #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
    ty::Coroutine(..) => true,
    _ => false,
}matches!(nested_ty.kind(), ty::Coroutine(..))
4048                        || #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
    ty::Closure(..) => true,
    _ => false,
}matches!(nested_ty.kind(), ty::Closure(..))
4049                } else {
4050                    false
4051                };
4052
4053                let is_builtin_async_fn_trait =
4054                    tcx.async_fn_trait_kind_from_def_id(data.parent_trait_pred.def_id()).is_some();
4055
4056                if !is_upvar_tys_infer_tuple && !is_builtin_async_fn_trait {
4057                    let mut msg = || {
4058                        let ty_str = tcx.short_string(ty, err.long_ty_path());
4059                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required because it appears within the type `{0}`",
                ty_str))
    })format!("required because it appears within the type `{ty_str}`")
4060                    };
4061                    match *ty.kind() {
4062                        ty::Adt(def, _) => {
4063                            let msg = msg();
4064                            match tcx.opt_item_ident(def.did()) {
4065                                Some(ident) => {
4066                                    err.span_note(ident.span, msg);
4067                                }
4068                                None => {
4069                                    err.note(msg);
4070                                }
4071                            }
4072                        }
4073                        ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) => {
4074                            // If the previous type is async fn, this is the future generated by the body of an async function.
4075                            // Avoid printing it twice (it was already printed in the `ty::Coroutine` arm below).
4076                            let is_future = tcx.ty_is_opaque_future(ty);
4077                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:4077",
                        "rustc_trait_selection::error_reporting::traits::suggestions",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                        ::tracing_core::__macro_support::Option::Some(4077u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "obligated_types", "is_future"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("note_obligation_cause_code: check for async fn")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&obligated_types)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&is_future)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(
4078                                ?obligated_types,
4079                                ?is_future,
4080                                "note_obligation_cause_code: check for async fn"
4081                            );
4082                            if is_future
4083                                && obligated_types.last().is_some_and(|ty| match ty.kind() {
4084                                    ty::Coroutine(last_def_id, ..) => {
4085                                        tcx.coroutine_is_async(*last_def_id)
4086                                    }
4087                                    _ => false,
4088                                })
4089                            {
4090                                // See comment above; skip printing twice.
4091                            } else {
4092                                let msg = msg();
4093                                err.span_note(tcx.def_span(def_id), msg);
4094                            }
4095                        }
4096                        ty::Coroutine(def_id, _) => {
4097                            let sp = tcx.def_span(def_id);
4098
4099                            // Special-case this to say "async block" instead of `[static coroutine]`.
4100                            let kind = tcx.coroutine_kind(def_id).unwrap();
4101                            err.span_note(
4102                                sp,
4103                                {
    let _guard = ForceTrimmedGuard::new();
    ::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("required because it\'s used within this {0:#}",
                    kind))
        })
}with_forced_trimmed_paths!(format!(
4104                                    "required because it's used within this {kind:#}",
4105                                )),
4106                            );
4107                        }
4108                        ty::CoroutineWitness(..) => {
4109                            // Skip printing coroutine-witnesses, since we'll drill into
4110                            // the bad field in another derived obligation cause.
4111                        }
4112                        ty::Closure(def_id, _) | ty::CoroutineClosure(def_id, _) => {
4113                            err.span_note(
4114                                tcx.def_span(def_id),
4115                                "required because it's used within this closure",
4116                            );
4117                        }
4118                        ty::Str => {
4119                            err.note("`str` is considered to contain a `[u8]` slice for auto trait purposes");
4120                        }
4121                        _ => {
4122                            let msg = msg();
4123                            err.note(msg);
4124                        }
4125                    };
4126                }
4127
4128                obligated_types.push(ty);
4129
4130                let parent_predicate = parent_trait_ref;
4131                if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
4132                    // #74711: avoid a stack overflow
4133                    ensure_sufficient_stack(|| {
4134                        self.note_obligation_cause_code(
4135                            body_def_id,
4136                            err,
4137                            parent_predicate,
4138                            param_env,
4139                            &data.parent_code,
4140                            obligated_types,
4141                            seen_requirements,
4142                        )
4143                    });
4144                } else {
4145                    ensure_sufficient_stack(|| {
4146                        self.note_obligation_cause_code(
4147                            body_def_id,
4148                            err,
4149                            parent_predicate,
4150                            param_env,
4151                            cause_code.peel_derives(),
4152                            obligated_types,
4153                            seen_requirements,
4154                        )
4155                    });
4156                }
4157            }
4158            ObligationCauseCode::ImplDerived(ref data) => {
4159                let mut parent_trait_pred =
4160                    self.resolve_vars_if_possible(data.derived.parent_trait_pred);
4161                let parent_def_id = parent_trait_pred.def_id();
4162                if tcx.is_diagnostic_item(sym::FromResidual, parent_def_id)
4163                    && !tcx.features().enabled(sym::try_trait_v2)
4164                {
4165                    // If `#![feature(try_trait_v2)]` is not enabled, then there's no point on
4166                    // talking about `FromResidual<Result<A, B>>`, as the end user has nothing they
4167                    // can do about it. As far as they are concerned, `?` is compiler magic.
4168                    return;
4169                }
4170                if tcx.is_diagnostic_item(sym::PinDerefMutHelper, parent_def_id) {
4171                    let parent_predicate =
4172                        self.resolve_vars_if_possible(data.derived.parent_trait_pred);
4173
4174                    // Skip PinDerefMutHelper in suggestions, but still show downstream suggestions.
4175                    ensure_sufficient_stack(|| {
4176                        self.note_obligation_cause_code(
4177                            body_def_id,
4178                            err,
4179                            parent_predicate,
4180                            param_env,
4181                            &data.derived.parent_code,
4182                            obligated_types,
4183                            seen_requirements,
4184                        )
4185                    });
4186                    return;
4187                }
4188                let self_ty_str =
4189                    tcx.short_string(parent_trait_pred.skip_binder().self_ty(), err.long_ty_path());
4190                let trait_name = tcx.short_string(
4191                    parent_trait_pred.print_modifiers_and_trait_path(),
4192                    err.long_ty_path(),
4193                );
4194                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required for `{0}` to implement `{1}`",
                self_ty_str, trait_name))
    })format!("required for `{self_ty_str}` to implement `{trait_name}`");
4195                let mut is_auto_trait = false;
4196                match tcx.hir_get_if_local(data.impl_or_alias_def_id) {
4197                    Some(Node::Item(hir::Item {
4198                        kind: hir::ItemKind::Trait { is_auto, ident, .. },
4199                        ..
4200                    })) => {
4201                        // FIXME: we should do something else so that it works even on crate foreign
4202                        // auto traits.
4203                        is_auto_trait = #[allow(non_exhaustive_omitted_patterns)] match is_auto {
    hir::IsAuto::Yes => true,
    _ => false,
}matches!(is_auto, hir::IsAuto::Yes);
4204                        err.span_note(ident.span, msg);
4205                    }
4206                    Some(Node::Item(hir::Item {
4207                        kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, generics, .. }),
4208                        ..
4209                    })) => {
4210                        let mut spans = Vec::with_capacity(2);
4211                        if let Some(of_trait) = of_trait
4212                            && !of_trait.trait_ref.path.span.in_derive_expansion()
4213                        {
4214                            spans.push(of_trait.trait_ref.path.span);
4215                        }
4216                        spans.push(self_ty.span);
4217                        let mut spans: MultiSpan = spans.into();
4218                        let mut derived = false;
4219                        if #[allow(non_exhaustive_omitted_patterns)] match self_ty.span.ctxt().outer_expn_data().kind
    {
    ExpnKind::Macro(MacroKind::Derive, _) => true,
    _ => false,
}matches!(
4220                            self_ty.span.ctxt().outer_expn_data().kind,
4221                            ExpnKind::Macro(MacroKind::Derive, _)
4222                        ) || #[allow(non_exhaustive_omitted_patterns)] match of_trait.map(|t|
            t.trait_ref.path.span.ctxt().outer_expn_data().kind) {
    Some(ExpnKind::Macro(MacroKind::Derive, _)) => true,
    _ => false,
}matches!(
4223                            of_trait.map(|t| t.trait_ref.path.span.ctxt().outer_expn_data().kind),
4224                            Some(ExpnKind::Macro(MacroKind::Derive, _))
4225                        ) {
4226                            derived = true;
4227                            spans.push_span_label(
4228                                data.span,
4229                                if data.span.in_derive_expansion() {
4230                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type parameter would need to implement `{0}`",
                trait_name))
    })format!("type parameter would need to implement `{trait_name}`")
4231                                } else {
4232                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unsatisfied trait bound"))
    })format!("unsatisfied trait bound")
4233                                },
4234                            );
4235                        } else if !data.span.is_dummy() && !data.span.overlaps(self_ty.span) {
4236                            // `Sized` may be an explicit or implicit trait bound. If it is
4237                            // implicit, mention it as such.
4238                            if let Some(pred) = predicate.as_trait_clause()
4239                                && self.tcx.is_lang_item(pred.def_id(), LangItem::Sized)
4240                                && self
4241                                    .tcx
4242                                    .generics_of(data.impl_or_alias_def_id)
4243                                    .own_params
4244                                    .iter()
4245                                    .any(|param| self.tcx.def_span(param.def_id) == data.span)
4246                            {
4247                                spans.push_span_label(
4248                                    data.span,
4249                                    "unsatisfied trait bound implicitly introduced here",
4250                                );
4251                            } else {
4252                                spans.push_span_label(
4253                                    data.span,
4254                                    "unsatisfied trait bound introduced here",
4255                                );
4256                            }
4257                        }
4258                        err.span_note(spans, msg);
4259                        if derived && trait_name != "Copy" {
4260                            err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider manually implementing `{0}` to avoid undesired bounds",
                trait_name))
    })format!(
4261                                "consider manually implementing `{trait_name}` to avoid undesired \
4262                                 bounds",
4263                            ));
4264                        }
4265                        point_at_assoc_type_restriction(
4266                            tcx,
4267                            err,
4268                            &self_ty_str,
4269                            &trait_name,
4270                            predicate,
4271                            &generics,
4272                            &data,
4273                        );
4274                    }
4275                    _ => {
4276                        err.note(msg);
4277                    }
4278                };
4279
4280                let mut parent_predicate = parent_trait_pred;
4281                let mut data = &data.derived;
4282                let mut count = 0;
4283                seen_requirements.insert(parent_def_id);
4284                if is_auto_trait {
4285                    // We don't want to point at the ADT saying "required because it appears within
4286                    // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
4287                    while let ObligationCauseCode::BuiltinDerived(derived) = &*data.parent_code {
4288                        let child_trait_ref =
4289                            self.resolve_vars_if_possible(derived.parent_trait_pred);
4290                        let child_def_id = child_trait_ref.def_id();
4291                        if seen_requirements.insert(child_def_id) {
4292                            break;
4293                        }
4294                        data = derived;
4295                        parent_predicate = child_trait_ref.upcast(tcx);
4296                        parent_trait_pred = child_trait_ref;
4297                    }
4298                }
4299                while let ObligationCauseCode::ImplDerived(child) = &*data.parent_code {
4300                    // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
4301                    let child_trait_pred =
4302                        self.resolve_vars_if_possible(child.derived.parent_trait_pred);
4303                    let child_def_id = child_trait_pred.def_id();
4304                    if seen_requirements.insert(child_def_id) {
4305                        break;
4306                    }
4307                    count += 1;
4308                    data = &child.derived;
4309                    parent_predicate = child_trait_pred.upcast(tcx);
4310                    parent_trait_pred = child_trait_pred;
4311                }
4312                if count > 0 {
4313                    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} redundant requirement{1} hidden",
                count, if count == 1 { "" } else { "s" }))
    })format!(
4314                        "{} redundant requirement{} hidden",
4315                        count,
4316                        pluralize!(count)
4317                    ));
4318                    let self_ty = tcx.short_string(
4319                        parent_trait_pred.skip_binder().self_ty(),
4320                        err.long_ty_path(),
4321                    );
4322                    let trait_path = tcx.short_string(
4323                        parent_trait_pred.print_modifiers_and_trait_path(),
4324                        err.long_ty_path(),
4325                    );
4326                    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required for `{0}` to implement `{1}`",
                self_ty, trait_path))
    })format!("required for `{self_ty}` to implement `{trait_path}`"));
4327                }
4328                // #74711: avoid a stack overflow
4329                ensure_sufficient_stack(|| {
4330                    self.note_obligation_cause_code(
4331                        body_def_id,
4332                        err,
4333                        parent_predicate,
4334                        param_env,
4335                        &data.parent_code,
4336                        obligated_types,
4337                        seen_requirements,
4338                    )
4339                });
4340            }
4341            ObligationCauseCode::ImplDerivedHost(ref data) => {
4342                let self_ty = tcx.short_string(
4343                    self.resolve_vars_if_possible(data.derived.parent_host_pred.self_ty()),
4344                    err.long_ty_path(),
4345                );
4346                let trait_path = tcx.short_string(
4347                    data.derived
4348                        .parent_host_pred
4349                        .map_bound(|pred| pred.trait_ref)
4350                        .print_only_trait_path(),
4351                    err.long_ty_path(),
4352                );
4353                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required for `{1}` to implement `{0} {2}`",
                data.derived.parent_host_pred.skip_binder().constness,
                self_ty, trait_path))
    })format!(
4354                    "required for `{self_ty}` to implement `{} {trait_path}`",
4355                    data.derived.parent_host_pred.skip_binder().constness,
4356                );
4357                match tcx.hir_get_if_local(data.impl_def_id) {
4358                    Some(Node::Item(hir::Item {
4359                        kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
4360                        ..
4361                    })) => {
4362                        let mut spans = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self_ty.span]))vec![self_ty.span];
4363                        spans.extend(of_trait.map(|t| t.trait_ref.path.span));
4364                        let mut spans: MultiSpan = spans.into();
4365                        spans.push_span_label(data.span, "unsatisfied trait bound introduced here");
4366                        err.span_note(spans, msg);
4367                    }
4368                    _ => {
4369                        err.note(msg);
4370                    }
4371                }
4372                ensure_sufficient_stack(|| {
4373                    self.note_obligation_cause_code(
4374                        body_def_id,
4375                        err,
4376                        data.derived.parent_host_pred,
4377                        param_env,
4378                        &data.derived.parent_code,
4379                        obligated_types,
4380                        seen_requirements,
4381                    )
4382                });
4383            }
4384            ObligationCauseCode::BuiltinDerivedHost(ref data) => {
4385                ensure_sufficient_stack(|| {
4386                    self.note_obligation_cause_code(
4387                        body_def_id,
4388                        err,
4389                        data.parent_host_pred,
4390                        param_env,
4391                        &data.parent_code,
4392                        obligated_types,
4393                        seen_requirements,
4394                    )
4395                });
4396            }
4397            ObligationCauseCode::WellFormedDerived(ref data) => {
4398                let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
4399                let parent_predicate = parent_trait_ref;
4400                // #74711: avoid a stack overflow
4401                ensure_sufficient_stack(|| {
4402                    self.note_obligation_cause_code(
4403                        body_def_id,
4404                        err,
4405                        parent_predicate,
4406                        param_env,
4407                        &data.parent_code,
4408                        obligated_types,
4409                        seen_requirements,
4410                    )
4411                });
4412            }
4413            ObligationCauseCode::TypeAlias(ref nested, span, def_id) => {
4414                // #74711: avoid a stack overflow
4415                ensure_sufficient_stack(|| {
4416                    self.note_obligation_cause_code(
4417                        body_def_id,
4418                        err,
4419                        predicate,
4420                        param_env,
4421                        nested,
4422                        obligated_types,
4423                        seen_requirements,
4424                    )
4425                });
4426                let mut multispan = MultiSpan::from(span);
4427                multispan.push_span_label(span, "required by this bound");
4428                err.span_note(
4429                    multispan,
4430                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required by a bound on the type alias `{0}`",
                tcx.item_name(def_id)))
    })format!("required by a bound on the type alias `{}`", tcx.item_name(def_id)),
4431                );
4432            }
4433            ObligationCauseCode::FunctionArg {
4434                arg_hir_id, call_hir_id, ref parent_code, ..
4435            } => {
4436                self.note_function_argument_obligation(
4437                    body_def_id,
4438                    err,
4439                    arg_hir_id,
4440                    parent_code,
4441                    param_env,
4442                    predicate,
4443                    call_hir_id,
4444                );
4445                ensure_sufficient_stack(|| {
4446                    self.note_obligation_cause_code(
4447                        body_def_id,
4448                        err,
4449                        predicate,
4450                        param_env,
4451                        parent_code,
4452                        obligated_types,
4453                        seen_requirements,
4454                    )
4455                });
4456            }
4457            // Suppress `compare_type_predicate_entailment` errors for RPITITs, since they
4458            // should be implied by the parent method.
4459            ObligationCauseCode::CompareImplItem { trait_item_def_id, .. }
4460                if tcx.is_impl_trait_in_trait(trait_item_def_id) => {}
4461            ObligationCauseCode::CompareImplItem { trait_item_def_id, kind, .. } => {
4462                let item_name = tcx.item_name(trait_item_def_id);
4463                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the requirement `{0}` appears on the `impl`\'s {1} `{2}` but not on the corresponding trait\'s {1}",
                predicate, kind, item_name))
    })format!(
4464                    "the requirement `{predicate}` appears on the `impl`'s {kind} \
4465                     `{item_name}` but not on the corresponding trait's {kind}",
4466                );
4467                let sp = tcx
4468                    .opt_item_ident(trait_item_def_id)
4469                    .map(|i| i.span)
4470                    .unwrap_or_else(|| tcx.def_span(trait_item_def_id));
4471                let mut assoc_span: MultiSpan = sp.into();
4472                assoc_span.push_span_label(
4473                    sp,
4474                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this trait\'s {0} doesn\'t have the requirement `{1}`",
                kind, predicate))
    })format!("this trait's {kind} doesn't have the requirement `{predicate}`"),
4475                );
4476                if let Some(ident) = tcx
4477                    .opt_associated_item(trait_item_def_id)
4478                    .and_then(|i| tcx.opt_item_ident(i.container_id(tcx)))
4479                {
4480                    assoc_span.push_span_label(ident.span, "in this trait");
4481                }
4482                err.span_note(assoc_span, msg);
4483            }
4484            ObligationCauseCode::TrivialBound => {
4485                tcx.disabled_nightly_features(err, [(String::new(), sym::trivial_bounds)]);
4486            }
4487            ObligationCauseCode::OpaqueReturnType(expr_info) => {
4488                let (expr_ty, expr) = if let Some((expr_ty, hir_id)) = expr_info {
4489                    let expr = tcx.hir_expect_expr(hir_id);
4490                    (expr_ty, expr)
4491                } else if let Some(body_id) = tcx.hir_node_by_def_id(body_def_id).body_id()
4492                    && let body = tcx.hir_body(body_id)
4493                    && let hir::ExprKind::Block(block, _) = body.value.kind
4494                    && let Some(expr) = block.expr
4495                    && let Some(expr_ty) = self
4496                        .typeck_results
4497                        .as_ref()
4498                        .and_then(|typeck| typeck.node_type_opt(expr.hir_id))
4499                    && let Some(pred) = predicate.as_clause()
4500                    && let ty::ClauseKind::Trait(pred) = pred.kind().skip_binder()
4501                    && self.can_eq(param_env, pred.self_ty(), expr_ty)
4502                {
4503                    (expr_ty, expr)
4504                } else {
4505                    return;
4506                };
4507                let expr_ty_string = tcx.short_string(expr_ty, err.long_ty_path());
4508                if expr_ty.is_never()
4509                    && let span = expr.span.source_callsite()
4510                    && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(span)
4511                    && span != expr.span
4512                {
4513                    err.span_suggestion(
4514                        span,
4515                        "`!` can be coerced to any type; consider casting it to a concrete type that implements the trait",
4516                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} as /* Type */", snippet))
    })format!("{snippet} as /* Type */"),
4517                        Applicability::HasPlaceholders,
4518                    );
4519                }
4520                err.span_label(
4521                    expr.span,
4522                    {
    let _guard = ForceTrimmedGuard::new();
    ::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("return type was inferred to be `{0}` here",
                    expr_ty_string))
        })
}with_forced_trimmed_paths!(format!(
4523                        "return type was inferred to be `{expr_ty_string}` here",
4524                    )),
4525                );
4526                suggest_remove_deref(err, &expr);
4527            }
4528            ObligationCauseCode::UnsizedNonPlaceExpr(span) => {
4529                err.span_note(
4530                    span,
4531                    "unsized values must be place expressions and cannot be put in temporaries",
4532                );
4533            }
4534            ObligationCauseCode::CompareEii { .. } => {
4535                {
    ::core::panicking::panic_fmt(format_args!("trait bounds on EII not yet supported "));
}panic!("trait bounds on EII not yet supported ")
4536            }
4537        }
4538    }
4539
4540    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("suggest_await_before_try",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(4540u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["obligation",
                                                    "trait_pred", "span", "trait_pred.self_ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_pred)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&trait_pred.self_ty())
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let future_trait =
                self.tcx.require_lang_item(LangItem::Future, span);
            let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
            let impls_future =
                self.type_implements_trait(future_trait,
                    [self.tcx.instantiate_bound_regions_with_erased(self_ty)],
                    obligation.param_env);
            if !impls_future.must_apply_modulo_regions() { return; }
            let item_def_id =
                self.tcx.associated_item_def_ids(future_trait)[0];
            let projection_ty =
                trait_pred.map_bound(|trait_pred|
                        {
                            Ty::new_projection(self.tcx, ty::IsRigid::No, item_def_id,
                                [trait_pred.self_ty()])
                        });
            let InferOk { value: projection_ty, .. } =
                self.at(&obligation.cause,
                        obligation.param_env).normalize(Unnormalized::new_wip(projection_ty));
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:4577",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(4577u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["normalized_projection_type"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&self.resolve_vars_if_possible(projection_ty))
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let try_obligation =
                self.mk_trait_obligation_with_new_self_ty(obligation.param_env,
                    trait_pred.map_bound(|trait_pred|
                            (trait_pred, projection_ty.skip_binder())));
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:4584",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(4584u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["try_trait_obligation"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&try_obligation)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            if self.predicate_may_hold(&try_obligation) &&
                        let Ok(snippet) =
                            self.tcx.sess.source_map().span_to_snippet(span) &&
                    snippet.ends_with('?') {
                match self.tcx.coroutine_kind(obligation.cause.body_def_id) {
                    Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
                        _)) => {
                        err.span_suggestion_verbose(span.with_hi(span.hi() -
                                        BytePos(1)).shrink_to_hi(),
                            "consider `await`ing on the `Future`", ".await",
                            Applicability::MaybeIncorrect);
                    }
                    _ => {
                        let mut span: MultiSpan =
                            span.with_lo(span.hi() - BytePos(1)).into();
                        span.push_span_label(self.tcx.def_span(obligation.cause.body_def_id),
                            "this is not `async`");
                        err.span_note(span,
                            "this implements `Future` and its output type supports \
                        `?`, but the future cannot be awaited in a synchronous function");
                    }
                }
            }
        }
    }
}#[instrument(
4541        level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
4542    )]
4543    pub(super) fn suggest_await_before_try(
4544        &self,
4545        err: &mut Diag<'_>,
4546        obligation: &PredicateObligation<'tcx>,
4547        trait_pred: ty::PolyTraitPredicate<'tcx>,
4548        span: Span,
4549    ) {
4550        let future_trait = self.tcx.require_lang_item(LangItem::Future, span);
4551
4552        let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
4553        let impls_future = self.type_implements_trait(
4554            future_trait,
4555            [self.tcx.instantiate_bound_regions_with_erased(self_ty)],
4556            obligation.param_env,
4557        );
4558        if !impls_future.must_apply_modulo_regions() {
4559            return;
4560        }
4561
4562        let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
4563        // `<T as Future>::Output`
4564        let projection_ty = trait_pred.map_bound(|trait_pred| {
4565            Ty::new_projection(
4566                self.tcx,
4567                ty::IsRigid::No,
4568                item_def_id,
4569                // Future::Output has no args
4570                [trait_pred.self_ty()],
4571            )
4572        });
4573        let InferOk { value: projection_ty, .. } = self
4574            .at(&obligation.cause, obligation.param_env)
4575            .normalize(Unnormalized::new_wip(projection_ty));
4576
4577        debug!(
4578            normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
4579        );
4580        let try_obligation = self.mk_trait_obligation_with_new_self_ty(
4581            obligation.param_env,
4582            trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
4583        );
4584        debug!(try_trait_obligation = ?try_obligation);
4585        if self.predicate_may_hold(&try_obligation)
4586            && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
4587            && snippet.ends_with('?')
4588        {
4589            match self.tcx.coroutine_kind(obligation.cause.body_def_id) {
4590                Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
4591                    err.span_suggestion_verbose(
4592                        span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
4593                        "consider `await`ing on the `Future`",
4594                        ".await",
4595                        Applicability::MaybeIncorrect,
4596                    );
4597                }
4598                _ => {
4599                    let mut span: MultiSpan = span.with_lo(span.hi() - BytePos(1)).into();
4600                    span.push_span_label(
4601                        self.tcx.def_span(obligation.cause.body_def_id),
4602                        "this is not `async`",
4603                    );
4604                    err.span_note(
4605                        span,
4606                        "this implements `Future` and its output type supports \
4607                        `?`, but the future cannot be awaited in a synchronous function",
4608                    );
4609                }
4610            }
4611        }
4612    }
4613
4614    pub(super) fn suggest_floating_point_literal(
4615        &self,
4616        obligation: &PredicateObligation<'tcx>,
4617        err: &mut Diag<'_>,
4618        trait_pred: ty::PolyTraitPredicate<'tcx>,
4619    ) {
4620        let rhs_span = match obligation.cause.code() {
4621            ObligationCauseCode::BinOp { rhs_span, rhs_is_lit, .. } if *rhs_is_lit => rhs_span,
4622            _ => return,
4623        };
4624        if let ty::Float(_) = trait_pred.skip_binder().self_ty().kind()
4625            && let ty::Infer(InferTy::IntVar(_)) =
4626                trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
4627        {
4628            err.span_suggestion_verbose(
4629                rhs_span.shrink_to_hi(),
4630                "consider using a floating-point literal by writing it with `.0`",
4631                ".0",
4632                Applicability::MaybeIncorrect,
4633            );
4634        }
4635    }
4636
4637    pub fn can_suggest_derive(
4638        &self,
4639        obligation: &PredicateObligation<'tcx>,
4640        trait_pred: ty::PolyTraitPredicate<'tcx>,
4641    ) -> bool {
4642        if trait_pred.polarity() == ty::PredicatePolarity::Negative {
4643            return false;
4644        }
4645        let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
4646            return false;
4647        };
4648        let (adt, args) = match trait_pred.skip_binder().self_ty().kind() {
4649            ty::Adt(adt, args) if adt.did().is_local() => (adt, args),
4650            _ => return false,
4651        };
4652        let is_derivable_trait = match diagnostic_name {
4653            sym::Copy | sym::Clone => true,
4654            _ if adt.is_union() => false,
4655            sym::PartialEq | sym::PartialOrd => {
4656                let rhs_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
4657                trait_pred.skip_binder().self_ty() == rhs_ty
4658            }
4659            sym::Eq | sym::Ord | sym::Hash | sym::Debug | sym::Default => true,
4660            _ => false,
4661        };
4662        is_derivable_trait &&
4663            // Ensure all fields impl the trait.
4664            adt.all_fields().all(|field| {
4665                let field_ty = ty::GenericArg::from(field.ty(self.tcx, args).skip_norm_wip());
4666                let trait_args = match diagnostic_name {
4667                    sym::PartialEq | sym::PartialOrd => {
4668                        Some(field_ty)
4669                    }
4670                    _ => None,
4671                };
4672                let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
4673                    trait_ref: ty::TraitRef::new(self.tcx,
4674                        trait_pred.def_id(),
4675                        [field_ty].into_iter().chain(trait_args),
4676                    ),
4677                    ..*tr
4678                });
4679                let field_obl = Obligation::new(
4680                    self.tcx,
4681                    obligation.cause.clone(),
4682                    obligation.param_env,
4683                    trait_pred,
4684                );
4685                self.predicate_must_hold_modulo_regions(&field_obl)
4686            })
4687    }
4688
4689    pub fn suggest_derive(
4690        &self,
4691        obligation: &PredicateObligation<'tcx>,
4692        err: &mut Diag<'_>,
4693        trait_pred: ty::PolyTraitPredicate<'tcx>,
4694    ) {
4695        let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
4696            return;
4697        };
4698        let adt = match trait_pred.skip_binder().self_ty().kind() {
4699            ty::Adt(adt, _) if adt.did().is_local() => adt,
4700            _ => return,
4701        };
4702        if self.can_suggest_derive(obligation, trait_pred) {
4703            err.span_suggestion_verbose(
4704                self.tcx.def_span(adt.did()).shrink_to_lo(),
4705                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider annotating `{0}` with `#[derive({1})]`",
                trait_pred.skip_binder().self_ty(), diagnostic_name))
    })format!(
4706                    "consider annotating `{}` with `#[derive({})]`",
4707                    trait_pred.skip_binder().self_ty(),
4708                    diagnostic_name,
4709                ),
4710                // FIXME(const_trait_impl) derive_const as suggestion?
4711                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#[derive({0})]\n",
                diagnostic_name))
    })format!("#[derive({diagnostic_name})]\n"),
4712                Applicability::MaybeIncorrect,
4713            );
4714        }
4715    }
4716
4717    pub(super) fn suggest_dereferencing_index(
4718        &self,
4719        obligation: &PredicateObligation<'tcx>,
4720        err: &mut Diag<'_>,
4721        trait_pred: ty::PolyTraitPredicate<'tcx>,
4722    ) {
4723        if let ObligationCauseCode::ImplDerived(_) = obligation.cause.code()
4724            && self
4725                .tcx
4726                .is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
4727            && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
4728            && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
4729            && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
4730        {
4731            err.span_suggestion_verbose(
4732                obligation.cause.span.shrink_to_lo(),
4733                "dereference this index",
4734                '*',
4735                Applicability::MachineApplicable,
4736            );
4737        }
4738    }
4739
4740    fn note_function_argument_obligation<G: EmissionGuarantee>(
4741        &self,
4742        body_def_id: LocalDefId,
4743        err: &mut Diag<'_, G>,
4744        arg_hir_id: HirId,
4745        parent_code: &ObligationCauseCode<'tcx>,
4746        param_env: ty::ParamEnv<'tcx>,
4747        failed_pred: ty::Predicate<'tcx>,
4748        call_hir_id: HirId,
4749    ) {
4750        let tcx = self.tcx;
4751        if let Node::Expr(expr) = tcx.hir_node(arg_hir_id)
4752            && let Some(typeck_results) = &self.typeck_results
4753        {
4754            if let hir::Expr { kind: hir::ExprKind::MethodCall(_, rcvr, _, _), .. } = expr
4755                && let Some(ty) = typeck_results.node_type_opt(rcvr.hir_id)
4756                && let Some(failed_pred) = failed_pred.as_trait_clause()
4757                && let pred = failed_pred.map_bound(|pred| pred.with_replaced_self_ty(tcx, ty))
4758                && self.predicate_must_hold_modulo_regions(&Obligation::misc(
4759                    tcx,
4760                    expr.span,
4761                    body_def_id,
4762                    param_env,
4763                    pred,
4764                ))
4765                && expr.span.hi() != rcvr.span.hi()
4766            {
4767                let should_sugg = match tcx.hir_node(call_hir_id) {
4768                    Node::Expr(hir::Expr {
4769                        kind: hir::ExprKind::MethodCall(_, call_receiver, _, _),
4770                        ..
4771                    }) if let Some((DefKind::AssocFn, did)) =
4772                        typeck_results.type_dependent_def(call_hir_id)
4773                        && call_receiver.hir_id == arg_hir_id =>
4774                    {
4775                        // Avoid suggesting removing a method call if the argument is the receiver of the parent call and
4776                        // removing the receiver would make the method inaccessible. i.e. `x.a().b()`, suggesting removing
4777                        // `.a()` could change the type and make `.b()` unavailable.
4778                        if tcx.inherent_impl_of_assoc(did).is_some() {
4779                            // if we're calling an inherent impl method, just try to make sure that the receiver type stays the same.
4780                            Some(ty) == typeck_results.node_type_opt(arg_hir_id)
4781                        } else {
4782                            // we're calling a trait method, so we just check removing the method call still satisfies the trait.
4783                            let trait_id = tcx
4784                                .trait_of_assoc(did)
4785                                .unwrap_or_else(|| tcx.impl_trait_id(tcx.parent(did)));
4786                            let args = typeck_results.node_args(call_hir_id);
4787                            let tr = ty::TraitRef::from_assoc(tcx, trait_id, args)
4788                                .with_replaced_self_ty(tcx, ty);
4789                            self.type_implements_trait(tr.def_id, tr.args, param_env)
4790                                .must_apply_modulo_regions()
4791                        }
4792                    }
4793                    _ => true,
4794                };
4795
4796                if should_sugg {
4797                    err.span_suggestion_verbose(
4798                        expr.span.with_lo(rcvr.span.hi()),
4799                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider removing this method call, as the receiver has type `{0}` and `{1}` trivially holds",
                ty, pred))
    })format!(
4800                            "consider removing this method call, as the receiver has type `{ty}` and \
4801                            `{pred}` trivially holds",
4802                        ),
4803                        "",
4804                        Applicability::MaybeIncorrect,
4805                    );
4806                }
4807            }
4808            if let hir::Expr { kind: hir::ExprKind::Block(block, _), .. } = expr {
4809                let inner_expr = expr.peel_blocks();
4810                let ty = typeck_results
4811                    .expr_ty_adjusted_opt(inner_expr)
4812                    .unwrap_or(Ty::new_misc_error(tcx));
4813                let span = inner_expr.span;
4814                if Some(span) != err.span.primary_span()
4815                    && !span.in_external_macro(tcx.sess.source_map())
4816                {
4817                    err.span_label(
4818                        span,
4819                        if ty.references_error() {
4820                            String::new()
4821                        } else {
4822                            let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
4823                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this tail expression is of type `{0}`",
                ty))
    })format!("this tail expression is of type `{ty}`")
4824                        },
4825                    );
4826                    if let ty::PredicateKind::Clause(clause) = failed_pred.kind().skip_binder()
4827                        && let ty::ClauseKind::Trait(pred) = clause
4828                        && tcx.fn_trait_kind_from_def_id(pred.def_id()).is_some()
4829                    {
4830                        if let [stmt, ..] = block.stmts
4831                            && let hir::StmtKind::Semi(value) = stmt.kind
4832                            && let hir::ExprKind::Closure(hir::Closure {
4833                                body, fn_decl_span, ..
4834                            }) = value.kind
4835                            && let body = tcx.hir_body(*body)
4836                            && !#[allow(non_exhaustive_omitted_patterns)] match body.value.kind {
    hir::ExprKind::Block(..) => true,
    _ => false,
}matches!(body.value.kind, hir::ExprKind::Block(..))
4837                        {
4838                            // Check if the failed predicate was an expectation of a closure type
4839                            // and if there might have been a `{ |args|` typo instead of `|args| {`.
4840                            err.multipart_suggestion(
4841                                "you might have meant to open the closure body instead of placing \
4842                                 a closure within a block",
4843                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.with_hi(value.span.lo()), String::new()),
                (fn_decl_span.shrink_to_hi(), " {".to_string())]))vec![
4844                                    (expr.span.with_hi(value.span.lo()), String::new()),
4845                                    (fn_decl_span.shrink_to_hi(), " {".to_string()),
4846                                ],
4847                                Applicability::MaybeIncorrect,
4848                            );
4849                        } else {
4850                            // Maybe the bare block was meant to be a closure.
4851                            err.span_suggestion_verbose(
4852                                expr.span.shrink_to_lo(),
4853                                "you might have meant to create the closure instead of a block",
4854                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("|{0}| ",
                (0..pred.trait_ref.args.len() -
                                        1).map(|_| "_").collect::<Vec<_>>().join(", ")))
    })format!(
4855                                    "|{}| ",
4856                                    (0..pred.trait_ref.args.len() - 1)
4857                                        .map(|_| "_")
4858                                        .collect::<Vec<_>>()
4859                                        .join(", ")
4860                                ),
4861                                Applicability::MaybeIncorrect,
4862                            );
4863                        }
4864                    }
4865                }
4866            }
4867
4868            // FIXME: visit the ty to see if there's any closure involved, and if there is,
4869            // check whether its evaluated return type is the same as the one corresponding
4870            // to an associated type (as seen from `trait_pred`) in the predicate. Like in
4871            // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
4872            let mut type_diffs = ::alloc::vec::Vec::new()vec![];
4873            if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = *parent_code
4874                && let Some(node_args) = typeck_results.node_args_opt(call_hir_id)
4875                && let where_clauses =
4876                    self.tcx.predicates_of(def_id).instantiate(self.tcx, node_args)
4877                && let Some(where_pred) = where_clauses.predicates.get(idx)
4878            {
4879                let where_pred = where_pred.as_ref().skip_norm_wip();
4880                if let Some(where_pred) = where_pred.as_trait_clause()
4881                    && let Some(failed_pred) = failed_pred.as_trait_clause()
4882                    && where_pred.def_id() == failed_pred.def_id()
4883                {
4884                    self.enter_forall(where_pred, |where_pred| {
4885                        let failed_pred = self.instantiate_binder_with_fresh_vars(
4886                            expr.span,
4887                            BoundRegionConversionTime::FnCall,
4888                            failed_pred,
4889                        );
4890
4891                        let zipped =
4892                            iter::zip(where_pred.trait_ref.args, failed_pred.trait_ref.args);
4893                        for (expected, actual) in zipped {
4894                            self.probe(|_| {
4895                                match self
4896                                    .at(&ObligationCause::misc(expr.span, body_def_id), param_env)
4897                                    // Doesn't actually matter if we define opaque types here, this is just used for
4898                                    // diagnostics, and the result is never kept around.
4899                                    .eq(DefineOpaqueTypes::Yes, expected, actual)
4900                                {
4901                                    Ok(_) => (), // We ignore nested obligations here for now.
4902                                    Err(err) => type_diffs.push(err),
4903                                }
4904                            })
4905                        }
4906                    })
4907                } else if let Some(where_pred) = where_pred.as_projection_clause()
4908                    && let Some(failed_pred) = failed_pred.as_projection_clause()
4909                    && let Some(found) =
4910                        failed_pred.map_bound(|pred| pred.term.as_type()).transpose().map(|term| {
4911                            self.instantiate_binder_with_fresh_vars(
4912                                expr.span,
4913                                BoundRegionConversionTime::FnCall,
4914                                term,
4915                            )
4916                        })
4917                {
4918                    type_diffs = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [TypeError::Sorts(ty::error::ExpectedFound {
                        expected: self.instantiate_binder_with_fresh_vars(expr.span,
                                    BoundRegionConversionTime::FnCall,
                                    where_pred.map_bound(|pred|
                                            pred.projection_term)).expect_ty().to_ty(self.tcx,
                            ty::IsRigid::No),
                        found,
                    })]))vec![TypeError::Sorts(ty::error::ExpectedFound {
4919                        expected: self
4920                            .instantiate_binder_with_fresh_vars(
4921                                expr.span,
4922                                BoundRegionConversionTime::FnCall,
4923                                where_pred.map_bound(|pred| pred.projection_term),
4924                            )
4925                            .expect_ty()
4926                            .to_ty(self.tcx, ty::IsRigid::No),
4927                        found,
4928                    })];
4929                }
4930            }
4931            if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
4932                && let hir::Path { res: Res::Local(hir_id), .. } = path
4933                && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
4934                && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(binding.hir_id)
4935                && let Some(binding_expr) = local.init
4936            {
4937                // If the expression we're calling on is a binding, we want to point at the
4938                // `let` when talking about the type. Otherwise we'll point at every part
4939                // of the method chain with the type.
4940                self.point_at_chain(binding_expr, typeck_results, type_diffs, param_env, err);
4941            } else {
4942                self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
4943            }
4944        }
4945        let call_node = tcx.hir_node(call_hir_id);
4946        if let Node::Expr(hir::Expr { kind: hir::ExprKind::MethodCall(path, rcvr, ..), .. }) =
4947            call_node
4948        {
4949            if Some(rcvr.span) == err.span.primary_span() {
4950                err.replace_span_with(path.ident.span, true);
4951            }
4952        }
4953
4954        if let Node::Expr(expr) = call_node {
4955            if let hir::ExprKind::Call(hir::Expr { span, .. }, _)
4956            | hir::ExprKind::MethodCall(
4957                hir::PathSegment { ident: Ident { span, .. }, .. },
4958                ..,
4959            ) = expr.kind
4960            {
4961                if Some(*span) != err.span.primary_span() {
4962                    let msg = if span.is_desugaring(DesugaringKind::FormatLiteral { source: true })
4963                    {
4964                        "required by this formatting parameter"
4965                    } else if span.is_desugaring(DesugaringKind::FormatLiteral { source: false }) {
4966                        "required by a formatting parameter in this expression"
4967                    } else {
4968                        "required by a bound introduced by this call"
4969                    };
4970                    err.span_label(*span, msg);
4971                }
4972            }
4973
4974            if let hir::ExprKind::MethodCall(_, expr, ..) = expr.kind {
4975                self.suggest_option_method_if_applicable(failed_pred, param_env, err, expr);
4976            }
4977        }
4978    }
4979
4980    fn suggest_option_method_if_applicable<G: EmissionGuarantee>(
4981        &self,
4982        failed_pred: ty::Predicate<'tcx>,
4983        param_env: ty::ParamEnv<'tcx>,
4984        err: &mut Diag<'_, G>,
4985        expr: &hir::Expr<'_>,
4986    ) {
4987        let tcx = self.tcx;
4988        let infcx = self.infcx;
4989        let Some(typeck_results) = self.typeck_results.as_ref() else { return };
4990
4991        // Make sure we're dealing with the `Option` type.
4992        let Some(option_ty_adt) = typeck_results.expr_ty_adjusted(expr).ty_adt_def() else {
4993            return;
4994        };
4995        if !tcx.is_diagnostic_item(sym::Option, option_ty_adt.did()) {
4996            return;
4997        }
4998
4999        // Given the predicate `fn(&T): FnOnce<(U,)>`, extract `fn(&T)` and `(U,)`,
5000        // then suggest `Option::as_deref(_mut)` if `U` can deref to `T`
5001        if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, .. }))
5002            = failed_pred.kind().skip_binder()
5003            && tcx.is_fn_trait(trait_ref.def_id)
5004            && let [self_ty, found_ty] = trait_ref.args.as_slice()
5005            && let Some(fn_ty) = self_ty.as_type().filter(|ty| ty.is_fn())
5006            && let fn_sig @ ty::FnSig {
5007                ..
5008            } = fn_ty.fn_sig(tcx).skip_binder()
5009            // FIXME(splat): this might need to change if the Fn* traits start using/supporting splat
5010            && fn_sig.abi() == ExternAbi::Rust
5011            && !fn_sig.c_variadic()
5012            && fn_sig.safety() == hir::Safety::Safe
5013
5014            // Extract first param of fn sig with peeled refs, e.g. `fn(&T)` -> `T`
5015            && let Some(&ty::Ref(_, target_ty, needs_mut)) = fn_sig.inputs().first().map(|t| t.kind())
5016            && !target_ty.has_escaping_bound_vars()
5017
5018            // Extract first tuple element out of fn trait, e.g. `FnOnce<(U,)>` -> `U`
5019            && let Some(ty::Tuple(tys)) = found_ty.as_type().map(Ty::kind)
5020            && let &[found_ty] = tys.as_slice()
5021            && !found_ty.has_escaping_bound_vars()
5022
5023            // Extract `<U as Deref>::Target` assoc type and check that it is `T`
5024            && let Some(deref_target_did) = tcx.lang_items().deref_target()
5025            && let projection = Ty::new_projection_from_args(tcx,ty::IsRigid::No, deref_target_did, tcx.mk_args(&[ty::GenericArg::from(found_ty)]))
5026            && let InferOk { value: deref_target, obligations } = infcx.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(projection))
5027            && obligations.iter().all(|obligation| infcx.predicate_must_hold_modulo_regions(obligation))
5028            && infcx.can_eq(param_env, deref_target, target_ty)
5029        {
5030            let help = if let hir::Mutability::Mut = needs_mut
5031                && let Some(deref_mut_did) = tcx.lang_items().deref_mut_trait()
5032                && infcx
5033                    .type_implements_trait(deref_mut_did, iter::once(found_ty), param_env)
5034                    .must_apply_modulo_regions()
5035            {
5036                Some(("call `Option::as_deref_mut()` first", ".as_deref_mut()"))
5037            } else if let hir::Mutability::Not = needs_mut {
5038                Some(("call `Option::as_deref()` first", ".as_deref()"))
5039            } else {
5040                None
5041            };
5042
5043            if let Some((msg, sugg)) = help {
5044                err.span_suggestion_with_style(
5045                    expr.span.shrink_to_hi(),
5046                    msg,
5047                    sugg,
5048                    Applicability::MaybeIncorrect,
5049                    SuggestionStyle::ShowAlways,
5050                );
5051            }
5052        }
5053    }
5054
5055    fn look_for_iterator_item_mistakes<G: EmissionGuarantee>(
5056        &self,
5057        assocs_in_this_method: &[Option<(Span, (DefId, Ty<'tcx>))>],
5058        typeck_results: &TypeckResults<'tcx>,
5059        type_diffs: &[TypeError<'tcx>],
5060        param_env: ty::ParamEnv<'tcx>,
5061        path_segment: &hir::PathSegment<'_>,
5062        args: &[hir::Expr<'_>],
5063        prev_ty: Ty<'_>,
5064        err: &mut Diag<'_, G>,
5065    ) {
5066        let tcx = self.tcx;
5067        // Special case for iterator chains, we look at potential failures of `Iterator::Item`
5068        // not being `: Clone` and `Iterator::map` calls with spurious trailing `;`.
5069        for entry in assocs_in_this_method {
5070            let Some((_span, (def_id, ty))) = entry else {
5071                continue;
5072            };
5073            for diff in type_diffs {
5074                let TypeError::Sorts(expected_found) = diff else {
5075                    continue;
5076                };
5077                if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
5078                    && path_segment.ident.name == sym::iter
5079                    && self.can_eq(
5080                        param_env,
5081                        Ty::new_ref(
5082                            tcx,
5083                            tcx.lifetimes.re_erased,
5084                            expected_found.found,
5085                            ty::Mutability::Not,
5086                        ),
5087                        *ty,
5088                    )
5089                    && let [] = args
5090                {
5091                    // Used `.iter()` when `.into_iter()` was likely meant.
5092                    err.span_suggestion_verbose(
5093                        path_segment.ident.span,
5094                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider consuming the `{0}` to construct the `Iterator`",
                prev_ty))
    })format!("consider consuming the `{prev_ty}` to construct the `Iterator`"),
5095                        "into_iter".to_string(),
5096                        Applicability::MachineApplicable,
5097                    );
5098                }
5099                if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
5100                    && path_segment.ident.name == sym::into_iter
5101                    && self.can_eq(
5102                        param_env,
5103                        expected_found.found,
5104                        Ty::new_ref(tcx, tcx.lifetimes.re_erased, *ty, ty::Mutability::Not),
5105                    )
5106                    && let [] = args
5107                {
5108                    // Used `.into_iter()` when `.iter()` was likely meant.
5109                    err.span_suggestion_verbose(
5110                        path_segment.ident.span,
5111                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider not consuming the `{0}` to construct the `Iterator`",
                prev_ty))
    })format!(
5112                            "consider not consuming the `{prev_ty}` to construct the `Iterator`"
5113                        ),
5114                        "iter".to_string(),
5115                        Applicability::MachineApplicable,
5116                    );
5117                }
5118                if tcx.is_diagnostic_item(sym::IteratorItem, *def_id)
5119                    && path_segment.ident.name == sym::map
5120                    && self.can_eq(param_env, expected_found.found, *ty)
5121                    && let [arg] = args
5122                    && let hir::ExprKind::Closure(closure) = arg.kind
5123                {
5124                    let body = tcx.hir_body(closure.body);
5125                    if let hir::ExprKind::Block(block, None) = body.value.kind
5126                        && let None = block.expr
5127                        && let [.., stmt] = block.stmts
5128                        && let hir::StmtKind::Semi(expr) = stmt.kind
5129                        // FIXME: actually check the expected vs found types, but right now
5130                        // the expected is a projection that we need to resolve.
5131                        // && let Some(tail_ty) = typeck_results.expr_ty_opt(expr)
5132                        && expected_found.found.is_unit()
5133                        // FIXME: this happens with macro calls. Need to figure out why the stmt
5134                        // `println!();` doesn't include the `;` in its `Span`. (#133845)
5135                        // We filter these out to avoid ICEs with debug assertions on caused by
5136                        // empty suggestions.
5137                        && expr.span.hi() != stmt.span.hi()
5138                    {
5139                        err.span_suggestion_verbose(
5140                            expr.span.shrink_to_hi().with_hi(stmt.span.hi()),
5141                            "consider removing this semicolon",
5142                            String::new(),
5143                            Applicability::MachineApplicable,
5144                        );
5145                    }
5146                    let expr = if let hir::ExprKind::Block(block, None) = body.value.kind
5147                        && let Some(expr) = block.expr
5148                    {
5149                        expr
5150                    } else {
5151                        body.value
5152                    };
5153                    if let hir::ExprKind::MethodCall(path_segment, rcvr, [], span) = expr.kind
5154                        && path_segment.ident.name == sym::clone
5155                        && let Some(expr_ty) = typeck_results.expr_ty_opt(expr)
5156                        && let Some(rcvr_ty) = typeck_results.expr_ty_opt(rcvr)
5157                        && self.can_eq(param_env, expr_ty, rcvr_ty)
5158                        && let ty::Ref(_, ty, _) = expr_ty.kind()
5159                    {
5160                        err.span_label(
5161                            span,
5162                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this method call is cloning the reference `{0}`, not `{1}` which doesn\'t implement `Clone`",
                expr_ty, ty))
    })format!(
5163                                "this method call is cloning the reference `{expr_ty}`, not \
5164                                 `{ty}` which doesn't implement `Clone`",
5165                            ),
5166                        );
5167                        let ty::Param(..) = ty.kind() else {
5168                            continue;
5169                        };
5170                        let node =
5171                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(expr.hir_id).def_id);
5172
5173                        let pred = ty::Binder::dummy(ty::TraitPredicate {
5174                            trait_ref: ty::TraitRef::new(
5175                                tcx,
5176                                tcx.require_lang_item(LangItem::Clone, span),
5177                                [*ty],
5178                            ),
5179                            polarity: ty::PredicatePolarity::Positive,
5180                        });
5181                        let Some(generics) = node.generics() else {
5182                            continue;
5183                        };
5184                        let Some(body_id) = node.body_id() else {
5185                            continue;
5186                        };
5187                        suggest_restriction(
5188                            tcx,
5189                            tcx.hir_body_owner_def_id(body_id),
5190                            generics,
5191                            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type parameter `{0}`", ty))
    })format!("type parameter `{ty}`"),
5192                            err,
5193                            node.fn_sig(),
5194                            None,
5195                            pred,
5196                            None,
5197                        );
5198                    }
5199                }
5200            }
5201        }
5202    }
5203
5204    fn point_at_chain<G: EmissionGuarantee>(
5205        &self,
5206        expr: &hir::Expr<'_>,
5207        typeck_results: &TypeckResults<'tcx>,
5208        type_diffs: Vec<TypeError<'tcx>>,
5209        param_env: ty::ParamEnv<'tcx>,
5210        err: &mut Diag<'_, G>,
5211    ) {
5212        let mut primary_spans = ::alloc::vec::Vec::new()vec![];
5213        let mut span_labels = ::alloc::vec::Vec::new()vec![];
5214
5215        let tcx = self.tcx;
5216
5217        let mut print_root_expr = true;
5218        let mut assocs = ::alloc::vec::Vec::new()vec![];
5219        let mut expr = expr;
5220        let mut prev_ty = self.resolve_vars_if_possible(
5221            typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5222        );
5223        while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
5224            // Point at every method call in the chain with the resulting type.
5225            // vec![1, 2, 3].iter().map(mapper).sum<i32>()
5226            //               ^^^^^^ ^^^^^^^^^^^
5227            expr = rcvr_expr;
5228            let assocs_in_this_method =
5229                self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
5230            prev_ty = self.resolve_vars_if_possible(
5231                typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5232            );
5233            self.look_for_iterator_item_mistakes(
5234                &assocs_in_this_method,
5235                typeck_results,
5236                &type_diffs,
5237                param_env,
5238                path_segment,
5239                args,
5240                prev_ty,
5241                err,
5242            );
5243            assocs.push(assocs_in_this_method);
5244
5245            if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
5246                && let hir::Path { res: Res::Local(hir_id), .. } = path
5247                && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
5248            {
5249                let parent = self.tcx.parent_hir_node(binding.hir_id);
5250                // We've reached the root of the method call chain...
5251                if let hir::Node::LetStmt(local) = parent
5252                    && let Some(binding_expr) = local.init
5253                {
5254                    // ...and it is a binding. Get the binding creation and continue the chain.
5255                    expr = binding_expr;
5256                }
5257                if let hir::Node::Param(param) = parent {
5258                    // ...and it is an fn argument.
5259                    let prev_ty = self.resolve_vars_if_possible(
5260                        typeck_results
5261                            .node_type_opt(param.hir_id)
5262                            .unwrap_or(Ty::new_misc_error(tcx)),
5263                    );
5264                    let assocs_in_this_method = self.probe_assoc_types_at_expr(
5265                        &type_diffs,
5266                        param.ty_span,
5267                        prev_ty,
5268                        param.hir_id,
5269                        param_env,
5270                    );
5271                    if assocs_in_this_method.iter().any(|a| a.is_some()) {
5272                        assocs.push(assocs_in_this_method);
5273                        print_root_expr = false;
5274                    }
5275                    break;
5276                }
5277            }
5278        }
5279        // We want the type before deref coercions, otherwise we talk about `&[_]`
5280        // instead of `Vec<_>`.
5281        if let Some(ty) = typeck_results.expr_ty_opt(expr)
5282            && print_root_expr
5283        {
5284            let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5285            // Point at the root expression
5286            // vec![1, 2, 3].iter().map(mapper).sum<i32>()
5287            // ^^^^^^^^^^^^^
5288            span_labels.push((expr.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this expression has type `{0}`",
                ty))
    })format!("this expression has type `{ty}`")));
5289        };
5290        // Only show this if it is not a "trivial" expression (not a method
5291        // chain) and there are associated types to talk about.
5292        let mut assocs = assocs.into_iter().peekable();
5293        while let Some(assocs_in_method) = assocs.next() {
5294            let Some(prev_assoc_in_method) = assocs.peek() else {
5295                for entry in assocs_in_method {
5296                    let Some((span, (assoc, ty))) = entry else {
5297                        continue;
5298                    };
5299                    if primary_spans.is_empty()
5300                        || type_diffs.iter().any(|diff| {
5301                            let TypeError::Sorts(expected_found) = diff else {
5302                                return false;
5303                            };
5304                            self.can_eq(param_env, expected_found.found, ty)
5305                        })
5306                    {
5307                        // FIXME: this doesn't quite work for `Iterator::collect`
5308                        // because we have `Vec<i32>` and `()`, but we'd want `i32`
5309                        // to point at the `.into_iter()` call, but as long as we
5310                        // still point at the other method calls that might have
5311                        // introduced the issue, this is fine for now.
5312                        primary_spans.push(span);
5313                    }
5314                    span_labels.push((
5315                        span,
5316                        {
    let _guard = ForceTrimmedGuard::new();
    ::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("`{0}` is `{1}` here",
                    self.tcx.def_path_str(assoc), ty))
        })
}with_forced_trimmed_paths!(format!(
5317                            "`{}` is `{ty}` here",
5318                            self.tcx.def_path_str(assoc),
5319                        )),
5320                    ));
5321                }
5322                break;
5323            };
5324            for (entry, prev_entry) in
5325                assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
5326            {
5327                match (entry, prev_entry) {
5328                    (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
5329                        let ty_str = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5330
5331                        let assoc = { let _guard = ForceTrimmedGuard::new(); self.tcx.def_path_str(assoc) }with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
5332                        if !self.can_eq(param_env, ty, *prev_ty) {
5333                            if type_diffs.iter().any(|diff| {
5334                                let TypeError::Sorts(expected_found) = diff else {
5335                                    return false;
5336                                };
5337                                self.can_eq(param_env, expected_found.found, ty)
5338                            }) {
5339                                primary_spans.push(span);
5340                            }
5341                            span_labels
5342                                .push((span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` changed to `{1}` here",
                assoc, ty_str))
    })format!("`{assoc}` changed to `{ty_str}` here")));
5343                        } else {
5344                            span_labels.push((span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` remains `{1}` here", assoc,
                ty_str))
    })format!("`{assoc}` remains `{ty_str}` here")));
5345                        }
5346                    }
5347                    (Some((span, (assoc, ty))), None) => {
5348                        span_labels.push((
5349                            span,
5350                            {
    let _guard = ForceTrimmedGuard::new();
    ::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("`{0}` is `{1}` here",
                    self.tcx.def_path_str(assoc), self.ty_to_string(ty)))
        })
}with_forced_trimmed_paths!(format!(
5351                                "`{}` is `{}` here",
5352                                self.tcx.def_path_str(assoc),
5353                                self.ty_to_string(ty),
5354                            )),
5355                        ));
5356                    }
5357                    (None, Some(_)) | (None, None) => {}
5358                }
5359            }
5360        }
5361        if !primary_spans.is_empty() {
5362            let mut multi_span: MultiSpan = primary_spans.into();
5363            for (span, label) in span_labels {
5364                multi_span.push_span_label(span, label);
5365            }
5366            err.span_note(
5367                multi_span,
5368                "the method call chain might not have had the expected associated types",
5369            );
5370        }
5371    }
5372
5373    fn probe_assoc_types_at_expr(
5374        &self,
5375        type_diffs: &[TypeError<'tcx>],
5376        span: Span,
5377        prev_ty: Ty<'tcx>,
5378        body_id: HirId,
5379        param_env: ty::ParamEnv<'tcx>,
5380    ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
5381        let ocx = ObligationCtxt::new(self.infcx);
5382        let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
5383        for diff in type_diffs {
5384            let TypeError::Sorts(expected_found) = diff else {
5385                continue;
5386            };
5387            let &ty::Alias(_, ty::AliasTy { kind: kind @ ty::Projection { def_id }, .. }) =
5388                expected_found.expected.kind()
5389            else {
5390                continue;
5391            };
5392
5393            // Make `Self` be equivalent to the type of the call chain
5394            // expression we're looking at now, so that we can tell what
5395            // for example `Iterator::Item` is at this point in the chain.
5396            let args = GenericArgs::for_item(self.tcx, def_id, |param, _| {
5397                if param.index == 0 {
5398                    if true {
    {
        match param.kind {
            ty::GenericParamDefKind::Type { .. } => {}
            ref left_val => {
                ::core::panicking::assert_matches_failed(left_val,
                    "ty::GenericParamDefKind::Type { .. }",
                    ::core::option::Option::None);
            }
        }
    };
};debug_assert_matches!(param.kind, ty::GenericParamDefKind::Type { .. });
5399                    return prev_ty.into();
5400                }
5401                self.var_for_def(span, param)
5402            });
5403            // This will hold the resolved type of the associated type, if the
5404            // current expression implements the trait that associated type is
5405            // in. For example, this would be what `Iterator::Item` is here.
5406            let ty = self.infcx.next_ty_var(span);
5407            // This corresponds to `<ExprTy as Iterator>::Item = _`.
5408            let projection = ty::Binder::dummy(ty::PredicateKind::Clause(
5409                ty::ClauseKind::Projection(ty::ProjectionPredicate {
5410                    projection_term: ty::AliasTerm::new_from_args(self.tcx, kind.into(), args),
5411                    term: ty.into(),
5412                }),
5413            ));
5414            let body_def_id = self.tcx.hir_enclosing_body_owner(body_id);
5415            // Add `<ExprTy as Iterator>::Item = _` obligation.
5416            ocx.register_obligation(Obligation::misc(
5417                self.tcx,
5418                span,
5419                body_def_id,
5420                param_env,
5421                projection,
5422            ));
5423            if ocx.try_evaluate_obligations().is_empty()
5424                && let ty = self.resolve_vars_if_possible(ty)
5425                && !ty.is_ty_var()
5426            {
5427                assocs_in_this_method.push(Some((span, (def_id, ty))));
5428            } else {
5429                // `<ExprTy as Iterator>` didn't select, so likely we've
5430                // reached the end of the iterator chain, like the originating
5431                // `Vec<_>` or the `ty` couldn't be determined.
5432                // Keep the space consistent for later zipping.
5433                assocs_in_this_method.push(None);
5434            }
5435        }
5436        assocs_in_this_method
5437    }
5438
5439    /// If the type that failed selection is an array or a reference to an array,
5440    /// but the trait is implemented for slices, suggest that the user converts
5441    /// the array into a slice.
5442    pub(super) fn suggest_convert_to_slice(
5443        &self,
5444        err: &mut Diag<'_>,
5445        obligation: &PredicateObligation<'tcx>,
5446        trait_pred: ty::PolyTraitPredicate<'tcx>,
5447        candidate_impls: &[ImplCandidate<'tcx>],
5448        span: Span,
5449    ) {
5450        if span.in_external_macro(self.tcx.sess.source_map()) {
5451            return;
5452        }
5453        // We can only suggest the slice coercion for function and binary operation arguments,
5454        // since the suggestion would make no sense in turbofish or call
5455        let (ObligationCauseCode::BinOp { .. } | ObligationCauseCode::FunctionArg { .. }) =
5456            obligation.cause.code()
5457        else {
5458            return;
5459        };
5460
5461        // Three cases where we can make a suggestion:
5462        // 1. `[T; _]` (array of T)
5463        // 2. `&[T; _]` (reference to array of T)
5464        // 3. `&mut [T; _]` (mutable reference to array of T)
5465        let (element_ty, mut mutability) = match *trait_pred.skip_binder().self_ty().kind() {
5466            ty::Array(element_ty, _) => (element_ty, None),
5467
5468            ty::Ref(_, pointee_ty, mutability) => match *pointee_ty.kind() {
5469                ty::Array(element_ty, _) => (element_ty, Some(mutability)),
5470                _ => return,
5471            },
5472
5473            _ => return,
5474        };
5475
5476        // Go through all the candidate impls to see if any of them is for
5477        // slices of `element_ty` with `mutability`.
5478        let mut is_slice = |candidate: Ty<'tcx>| match *candidate.kind() {
5479            ty::RawPtr(t, m) | ty::Ref(_, t, m) => {
5480                if let ty::Slice(e) = *t.kind()
5481                    && e == element_ty
5482                    && m == mutability.unwrap_or(m)
5483                {
5484                    // Use the candidate's mutability going forward.
5485                    mutability = Some(m);
5486                    true
5487                } else {
5488                    false
5489                }
5490            }
5491            _ => false,
5492        };
5493
5494        // Grab the first candidate that matches, if any, and make a suggestion.
5495        if let Some(slice_ty) = candidate_impls
5496            .iter()
5497            .map(|trait_ref| trait_ref.trait_ref.self_ty())
5498            .find(|t| is_slice(*t))
5499        {
5500            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("convert the array to a `{0}` slice instead",
                slice_ty))
    })format!("convert the array to a `{slice_ty}` slice instead");
5501
5502            if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
5503                let mut suggestions = ::alloc::vec::Vec::new()vec![];
5504                if snippet.starts_with('&') {
5505                } else if let Some(hir::Mutability::Mut) = mutability {
5506                    suggestions.push((span.shrink_to_lo(), "&mut ".into()));
5507                } else {
5508                    suggestions.push((span.shrink_to_lo(), "&".into()));
5509                }
5510                suggestions.push((span.shrink_to_hi(), "[..]".into()));
5511                err.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
5512            } else {
5513                err.span_help(span, msg);
5514            }
5515        }
5516    }
5517
5518    /// If the type failed selection but the trait is implemented for `(T,)`, suggest that the user
5519    /// creates a unary tuple
5520    ///
5521    /// This is a common gotcha when using libraries that emulate variadic functions with traits for tuples.
5522    pub(super) fn suggest_tuple_wrapping(
5523        &self,
5524        err: &mut Diag<'_>,
5525        root_obligation: &PredicateObligation<'tcx>,
5526        obligation: &PredicateObligation<'tcx>,
5527    ) {
5528        let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code() else {
5529            return;
5530        };
5531
5532        let Some(root_pred) = root_obligation.predicate.as_trait_clause() else { return };
5533
5534        let trait_ref = root_pred.map_bound(|root_pred| {
5535            root_pred.trait_ref.with_replaced_self_ty(
5536                self.tcx,
5537                Ty::new_tup(self.tcx, &[root_pred.trait_ref.self_ty()]),
5538            )
5539        });
5540
5541        let obligation =
5542            Obligation::new(self.tcx, obligation.cause.clone(), obligation.param_env, trait_ref);
5543
5544        if self.predicate_must_hold_modulo_regions(&obligation) {
5545            let arg_span = self.tcx.hir_span(*arg_hir_id);
5546            err.multipart_suggestion(
5547                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use a unary tuple instead"))
    })format!("use a unary tuple instead"),
5548                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(arg_span.shrink_to_lo(), "(".into()),
                (arg_span.shrink_to_hi(), ",)".into())]))vec![(arg_span.shrink_to_lo(), "(".into()), (arg_span.shrink_to_hi(), ",)".into())],
5549                Applicability::MaybeIncorrect,
5550            );
5551        }
5552    }
5553
5554    pub(super) fn suggest_shadowed_inherent_method(
5555        &self,
5556        err: &mut Diag<'_>,
5557        obligation: &PredicateObligation<'tcx>,
5558        trait_predicate: ty::PolyTraitPredicate<'tcx>,
5559    ) {
5560        let ObligationCauseCode::FunctionArg { call_hir_id, .. } = obligation.cause.code() else {
5561            return;
5562        };
5563        let Node::Expr(call) = self.tcx.hir_node(*call_hir_id) else { return };
5564        let hir::ExprKind::MethodCall(segment, rcvr, args, ..) = call.kind else { return };
5565        let Some(typeck) = &self.typeck_results else { return };
5566        let Some(rcvr_ty) = typeck.expr_ty_adjusted_opt(rcvr) else { return };
5567        let rcvr_ty = self.resolve_vars_if_possible(rcvr_ty);
5568        let autoderef = (self.autoderef_steps)(rcvr_ty);
5569        for (ty, def_id) in autoderef.iter().filter_map(|(ty, obligations)| {
5570            if let ty::Adt(def, _) = ty.kind()
5571                && *ty != rcvr_ty.peel_refs()
5572                && obligations.iter().all(|obligation| self.predicate_may_hold(obligation))
5573            {
5574                Some((ty, def.did()))
5575            } else {
5576                None
5577            }
5578        }) {
5579            for impl_def_id in self.tcx.inherent_impls(def_id) {
5580                if *impl_def_id == trait_predicate.def_id() {
5581                    continue;
5582                }
5583                for m in self
5584                    .tcx
5585                    .provided_trait_methods(*impl_def_id)
5586                    .filter(|m| m.name() == segment.ident.name)
5587                {
5588                    let fn_sig = self.tcx.fn_sig(m.def_id);
5589                    if fn_sig.skip_binder().inputs().skip_binder().len() != args.len() + 1 {
5590                        continue;
5591                    }
5592                    let rcvr_ty = fn_sig.skip_binder().input(0).skip_binder();
5593                    let (mutability, _ty) = match rcvr_ty.kind() {
5594                        ty::Ref(_, ty, hir::Mutability::Mut) => ("&mut ", ty),
5595                        ty::Ref(_, ty, _) => ("&", ty),
5596                        _ => ("", &rcvr_ty),
5597                    };
5598                    let path = self.tcx.def_path_str(def_id);
5599                    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("there\'s an inherent method on `{0}` of the same name, which can be auto-dereferenced from `{1}`",
                ty, rcvr_ty))
    })format!(
5600                        "there's an inherent method on `{ty}` of the same name, which can be \
5601                         auto-dereferenced from `{rcvr_ty}`"
5602                    ));
5603                    err.multipart_suggestion(
5604                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("to access the inherent method on `{0}`, use the fully-qualified path",
                ty))
    })format!(
5605                            "to access the inherent method on `{ty}`, use the fully-qualified path",
5606                        ),
5607                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(call.span.until(rcvr.span),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{2}::{0}({1}", m.name(),
                                    mutability, path))
                        })),
                match &args {
                    [] =>
                        (rcvr.span.shrink_to_hi().with_hi(call.span.hi()),
                            ")".to_string()),
                    [first, ..] =>
                        (rcvr.span.between(first.span), ", ".to_string()),
                }]))vec![
5608                            (
5609                                call.span.until(rcvr.span),
5610                                format!("{path}::{}({}", m.name(), mutability),
5611                            ),
5612                            match &args {
5613                                [] => (
5614                                    rcvr.span.shrink_to_hi().with_hi(call.span.hi()),
5615                                    ")".to_string(),
5616                                ),
5617                                [first, ..] => (rcvr.span.between(first.span), ", ".to_string()),
5618                            },
5619                        ],
5620                        Applicability::MaybeIncorrect,
5621                    );
5622                }
5623            }
5624        }
5625    }
5626
5627    pub(super) fn explain_hrtb_projection(
5628        &self,
5629        diag: &mut Diag<'_>,
5630        pred: ty::PolyTraitPredicate<'tcx>,
5631        param_env: ty::ParamEnv<'tcx>,
5632        cause: &ObligationCause<'tcx>,
5633    ) {
5634        if pred.skip_binder().has_escaping_bound_vars() && pred.skip_binder().has_non_region_infer()
5635        {
5636            self.probe(|_| {
5637                let ocx = ObligationCtxt::new(self);
5638                self.enter_forall(pred, |pred| {
5639                    let pred = ocx.normalize(
5640                        &ObligationCause::dummy(),
5641                        param_env,
5642                        Unnormalized::new_wip(pred),
5643                    );
5644                    ocx.register_obligation(Obligation::new(
5645                        self.tcx,
5646                        ObligationCause::dummy(),
5647                        param_env,
5648                        pred,
5649                    ));
5650                });
5651                if !ocx.try_evaluate_obligations().is_empty() {
5652                    // encountered errors.
5653                    return;
5654                }
5655
5656                if let ObligationCauseCode::FunctionArg {
5657                    call_hir_id,
5658                    arg_hir_id,
5659                    parent_code: _,
5660                } = cause.code()
5661                {
5662                    let arg_span = self.tcx.hir_span(*arg_hir_id);
5663                    let mut sp: MultiSpan = arg_span.into();
5664
5665                    sp.push_span_label(
5666                        arg_span,
5667                        "the trait solver is unable to infer the \
5668                        generic types that should be inferred from this argument",
5669                    );
5670                    sp.push_span_label(
5671                        self.tcx.hir_span(*call_hir_id),
5672                        "add turbofish arguments to this call to \
5673                        specify the types manually, even if it's redundant",
5674                    );
5675                    diag.span_note(
5676                        sp,
5677                        "this is a known limitation of the trait solver that \
5678                        will be lifted in the future",
5679                    );
5680                } else {
5681                    let mut sp: MultiSpan = cause.span.into();
5682                    sp.push_span_label(
5683                        cause.span,
5684                        "try adding turbofish arguments to this expression to \
5685                        specify the types manually, even if it's redundant",
5686                    );
5687                    diag.span_note(
5688                        sp,
5689                        "this is a known limitation of the trait solver that \
5690                        will be lifted in the future",
5691                    );
5692                }
5693            });
5694        }
5695    }
5696
5697    pub(super) fn suggest_desugaring_async_fn_in_trait(
5698        &self,
5699        err: &mut Diag<'_>,
5700        trait_pred: ty::PolyTraitPredicate<'tcx>,
5701    ) {
5702        // Don't suggest if RTN is active -- we should prefer a where-clause bound instead.
5703        if self.tcx.features().return_type_notation() {
5704            return;
5705        }
5706
5707        let trait_def_id = trait_pred.def_id();
5708
5709        // Only suggest specifying auto traits
5710        if !self.tcx.trait_is_auto(trait_def_id) {
5711            return;
5712        }
5713
5714        // Look for an RPITIT
5715        let ty::Alias(_, alias_ty @ ty::AliasTy { kind: ty::Projection { def_id }, .. }) =
5716            trait_pred.self_ty().skip_binder().kind()
5717        else {
5718            return;
5719        };
5720        let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, opaque_def_id }) =
5721            self.tcx.opt_rpitit_info(*def_id)
5722        else {
5723            return;
5724        };
5725
5726        let auto_trait = self.tcx.def_path_str(trait_def_id);
5727        // ... which is a local function
5728        let Some(fn_def_id) = fn_def_id.as_local() else {
5729            // If it's not local, we can at least mention that the method is async, if it is.
5730            if self.tcx.asyncness(fn_def_id).is_async() {
5731                err.span_note(
5732                    self.tcx.def_span(fn_def_id),
5733                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}::{1}` is an `async fn` in trait, which does not automatically imply that its future is `{2}`",
                alias_ty.trait_ref(self.tcx), self.tcx.item_name(fn_def_id),
                auto_trait))
    })format!(
5734                        "`{}::{}` is an `async fn` in trait, which does not \
5735                    automatically imply that its future is `{auto_trait}`",
5736                        alias_ty.trait_ref(self.tcx),
5737                        self.tcx.item_name(fn_def_id)
5738                    ),
5739                );
5740            }
5741            return;
5742        };
5743        let hir::Node::TraitItem(item) = self.tcx.hir_node_by_def_id(fn_def_id) else {
5744            return;
5745        };
5746
5747        // ... whose signature is `async` (i.e. this is an AFIT)
5748        let (sig, body) = item.expect_fn();
5749        let hir::FnRetTy::Return(hir::Ty { kind: hir::TyKind::OpaqueDef(opaq_def, ..), .. }) =
5750            sig.decl.output
5751        else {
5752            // This should never happen, but let's not ICE.
5753            return;
5754        };
5755
5756        // Check that this is *not* a nested `impl Future` RPIT in an async fn
5757        // (i.e. `async fn foo() -> impl Future`)
5758        if opaq_def.def_id.to_def_id() != opaque_def_id {
5759            return;
5760        }
5761
5762        let Some(sugg) = suggest_desugaring_async_fn_to_impl_future_in_trait(
5763            self.tcx,
5764            *sig,
5765            *body,
5766            opaque_def_id.expect_local(),
5767            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" + {0}", auto_trait))
    })format!(" + {auto_trait}"),
5768        ) else {
5769            return;
5770        };
5771
5772        let function_name = self.tcx.def_path_str(fn_def_id);
5773        err.multipart_suggestion(
5774            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` can be made part of the associated future\'s guarantees for all implementations of `{1}`",
                auto_trait, function_name))
    })format!(
5775                "`{auto_trait}` can be made part of the associated future's \
5776                guarantees for all implementations of `{function_name}`"
5777            ),
5778            sugg,
5779            Applicability::MachineApplicable,
5780        );
5781    }
5782
5783    pub fn ty_kind_suggestion(
5784        &self,
5785        param_env: ty::ParamEnv<'tcx>,
5786        ty: Ty<'tcx>,
5787    ) -> Option<String> {
5788        let tcx = self.infcx.tcx;
5789        let implements_default = |ty| {
5790            let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
5791                return false;
5792            };
5793            self.type_implements_trait(default_trait, [ty], param_env).must_apply_modulo_regions()
5794        };
5795
5796        Some(match *ty.kind() {
5797            ty::Never | ty::Error(_) => return None,
5798            ty::Bool => "false".to_string(),
5799            ty::Char => "\'x\'".to_string(),
5800            ty::Int(_) | ty::Uint(_) => "42".into(),
5801            ty::Float(_) => "3.14159".into(),
5802            ty::Slice(_) => "[]".to_string(),
5803            ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => {
5804                "vec![]".to_string()
5805            }
5806            ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::String) => {
5807                "String::new()".to_string()
5808            }
5809            ty::Adt(def, args) if def.is_box() => {
5810                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Box::new({0})",
                self.ty_kind_suggestion(param_env, args[0].expect_ty())?))
    })format!("Box::new({})", self.ty_kind_suggestion(param_env, args[0].expect_ty())?)
5811            }
5812            ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Option) => {
5813                "None".to_string()
5814            }
5815            ty::Adt(def, args) if Some(def.did()) == tcx.get_diagnostic_item(sym::Result) => {
5816                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Ok({0})",
                self.ty_kind_suggestion(param_env, args[0].expect_ty())?))
    })format!("Ok({})", self.ty_kind_suggestion(param_env, args[0].expect_ty())?)
5817            }
5818            ty::Adt(_, _) if implements_default(ty) => "Default::default()".to_string(),
5819            ty::Ref(_, ty, mutability) => {
5820                if let (ty::Str, hir::Mutability::Not) = (ty.kind(), mutability) {
5821                    "\"\"".to_string()
5822                } else {
5823                    let ty = self.ty_kind_suggestion(param_env, ty)?;
5824                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}{1}", mutability.prefix_str(),
                ty))
    })format!("&{}{ty}", mutability.prefix_str())
5825                }
5826            }
5827            ty::Array(ty, len) if let Some(len) = len.try_to_target_usize(tcx) => {
5828                if len == 0 {
5829                    "[]".to_string()
5830                } else if self.type_is_copy_modulo_regions(param_env, ty) || len == 1 {
5831                    // Can only suggest `[ty; 0]` if sz == 1 or copy
5832                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("[{0}; {1}]",
                self.ty_kind_suggestion(param_env, ty)?, len))
    })format!("[{}; {}]", self.ty_kind_suggestion(param_env, ty)?, len)
5833                } else {
5834                    "/* value */".to_string()
5835                }
5836            }
5837            ty::Tuple(tys) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0}{1})",
                tys.iter().map(|ty|
                                    self.ty_kind_suggestion(param_env,
                                        ty)).collect::<Option<Vec<String>>>()?.join(", "),
                if tys.len() == 1 { "," } else { "" }))
    })format!(
5838                "({}{})",
5839                tys.iter()
5840                    .map(|ty| self.ty_kind_suggestion(param_env, ty))
5841                    .collect::<Option<Vec<String>>>()?
5842                    .join(", "),
5843                if tys.len() == 1 { "," } else { "" }
5844            ),
5845            _ => "/* value */".to_string(),
5846        })
5847    }
5848
5849    // For E0277 when use `?` operator, suggest adding
5850    // a suitable return type in `FnSig`, and a default
5851    // return value at the end of the function's body.
5852    pub(super) fn suggest_add_result_as_return_type(
5853        &self,
5854        obligation: &PredicateObligation<'tcx>,
5855        err: &mut Diag<'_>,
5856        trait_pred: ty::PolyTraitPredicate<'tcx>,
5857    ) {
5858        if ObligationCauseCode::QuestionMark != *obligation.cause.code().peel_derives() {
5859            return;
5860        }
5861
5862        // Only suggest for local function and associated method,
5863        // because this suggest adding both return type in
5864        // the `FnSig` and a default return value in the body, so it
5865        // is not suitable for foreign function without a local body,
5866        // and neither for trait method which may be also implemented
5867        // in other place, so shouldn't change it's FnSig.
5868        fn choose_suggest_items<'tcx, 'hir>(
5869            tcx: TyCtxt<'tcx>,
5870            node: hir::Node<'hir>,
5871        ) -> Option<(&'hir hir::FnDecl<'hir>, hir::BodyId)> {
5872            match node {
5873                hir::Node::Item(item)
5874                    if let hir::ItemKind::Fn { sig, body: body_id, .. } = item.kind =>
5875                {
5876                    Some((sig.decl, body_id))
5877                }
5878                hir::Node::ImplItem(item)
5879                    if let hir::ImplItemKind::Fn(sig, body_id) = item.kind =>
5880                {
5881                    let parent = tcx.parent_hir_node(item.hir_id());
5882                    if let hir::Node::Item(item) = parent
5883                        && let hir::ItemKind::Impl(imp) = item.kind
5884                        && imp.of_trait.is_none()
5885                    {
5886                        return Some((sig.decl, body_id));
5887                    }
5888                    None
5889                }
5890                _ => None,
5891            }
5892        }
5893
5894        let node = self.tcx.hir_node_by_def_id(obligation.cause.body_def_id);
5895        if let Some((fn_decl, body_id)) = choose_suggest_items(self.tcx, node)
5896            && let hir::FnRetTy::DefaultReturn(ret_span) = fn_decl.output
5897            && self.tcx.is_diagnostic_item(sym::FromResidual, trait_pred.def_id())
5898            && trait_pred.skip_binder().trait_ref.args.type_at(0).is_unit()
5899            && let ty::Adt(def, _) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
5900            && self.tcx.is_diagnostic_item(sym::Result, def.did())
5901        {
5902            let mut sugg_spans =
5903                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(ret_span,
                    " -> Result<(), Box<dyn std::error::Error>>".to_string())]))vec![(ret_span, " -> Result<(), Box<dyn std::error::Error>>".to_string())];
5904            let body = self.tcx.hir_body(body_id);
5905            if let hir::ExprKind::Block(b, _) = body.value.kind
5906                && b.expr.is_none()
5907            {
5908                // The span of '}' in the end of block.
5909                let span = self.tcx.sess.source_map().end_point(b.span);
5910                sugg_spans.push((
5911                    span.shrink_to_lo(),
5912                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", "    Ok(())\n",
                self.tcx.sess.source_map().indentation_before(span).unwrap_or_default()))
    })format!(
5913                        "{}{}",
5914                        "    Ok(())\n",
5915                        self.tcx.sess.source_map().indentation_before(span).unwrap_or_default(),
5916                    ),
5917                ));
5918            }
5919            err.multipart_suggestion(
5920                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider adding return type"))
    })format!("consider adding return type"),
5921                sugg_spans,
5922                Applicability::MaybeIncorrect,
5923            );
5924        }
5925    }
5926
5927    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("suggest_unsized_bound_if_applicable",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(5927u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
                obligation.predicate.kind().skip_binder() else { return; };
            let (ObligationCauseCode::WhereClause(item_def_id, span) |
                    ObligationCauseCode::WhereClauseInExpr(item_def_id, span,
                    ..)) =
                *obligation.cause.code().peel_derives() else { return; };
            if span.is_dummy() { return; }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5947",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(5947u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["pred",
                                                    "item_def_id", "span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&pred) as
                                                        &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&item_def_id)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&span) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            let (Some(node), true) =
                (self.tcx.hir_get_if_local(item_def_id),
                    self.tcx.is_lang_item(pred.def_id(),
                        LangItem::Sized)) else { return; };
            let Some(generics) = node.generics() else { return; };
            let sized_trait = self.tcx.lang_items().sized_trait();
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5960",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(5960u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["generics.params"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&generics.params)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5961",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(5961u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["generics.predicates"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&generics.predicates)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let Some(param) =
                generics.params.iter().find(|param|
                        param.span == span) else { return; };
            let explicitly_sized =
                generics.bounds_for_param(param.def_id).flat_map(|bp|
                            bp.bounds).any(|bound|
                        bound.trait_ref().and_then(|tr| tr.trait_def_id()) ==
                            sized_trait);
            if explicitly_sized { return; }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5974",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(5974u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["param"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&param) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            match node {
                hir::Node::Item(item @ hir::Item {
                    kind: hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) |
                        hir::ItemKind::Union(..), .. }) => {
                    if self.suggest_indirection_for_unsized(err, item, param) {
                        return;
                    }
                }
                _ => {}
            };
            let (span, separator, open_paren_sp) =
                if let Some((s, open_paren_sp)) =
                        generics.bounds_span_for_suggestions(param.def_id) {
                    (s, " +", open_paren_sp)
                } else {
                    (param.name.ident().span.shrink_to_hi(), ":", None)
                };
            let mut suggs = ::alloc::vec::Vec::new();
            let suggestion =
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("{0} ?Sized", separator))
                    });
            if let Some(open_paren_sp) = open_paren_sp {
                suggs.push((open_paren_sp, "(".to_string()));
                suggs.push((span,
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("){0}", suggestion))
                            })));
            } else { suggs.push((span, suggestion)); }
            err.multipart_suggestion("consider relaxing the implicit `Sized` restriction",
                suggs, Applicability::MachineApplicable);
        }
    }
}#[instrument(level = "debug", skip_all)]
5928    pub(super) fn suggest_unsized_bound_if_applicable(
5929        &self,
5930        err: &mut Diag<'_>,
5931        obligation: &PredicateObligation<'tcx>,
5932    ) {
5933        let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
5934            obligation.predicate.kind().skip_binder()
5935        else {
5936            return;
5937        };
5938        let (ObligationCauseCode::WhereClause(item_def_id, span)
5939        | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)) =
5940            *obligation.cause.code().peel_derives()
5941        else {
5942            return;
5943        };
5944        if span.is_dummy() {
5945            return;
5946        }
5947        debug!(?pred, ?item_def_id, ?span);
5948
5949        let (Some(node), true) = (
5950            self.tcx.hir_get_if_local(item_def_id),
5951            self.tcx.is_lang_item(pred.def_id(), LangItem::Sized),
5952        ) else {
5953            return;
5954        };
5955
5956        let Some(generics) = node.generics() else {
5957            return;
5958        };
5959        let sized_trait = self.tcx.lang_items().sized_trait();
5960        debug!(?generics.params);
5961        debug!(?generics.predicates);
5962        let Some(param) = generics.params.iter().find(|param| param.span == span) else {
5963            return;
5964        };
5965        // Check that none of the explicit trait bounds is `Sized`. Assume that an explicit
5966        // `Sized` bound is there intentionally and we don't need to suggest relaxing it.
5967        let explicitly_sized = generics
5968            .bounds_for_param(param.def_id)
5969            .flat_map(|bp| bp.bounds)
5970            .any(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) == sized_trait);
5971        if explicitly_sized {
5972            return;
5973        }
5974        debug!(?param);
5975        match node {
5976            hir::Node::Item(
5977                item @ hir::Item {
5978                    // Only suggest indirection for uses of type parameters in ADTs.
5979                    kind:
5980                        hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..),
5981                    ..
5982                },
5983            ) => {
5984                if self.suggest_indirection_for_unsized(err, item, param) {
5985                    return;
5986                }
5987            }
5988            _ => {}
5989        };
5990
5991        // Didn't add an indirection suggestion, so add a general suggestion to relax `Sized`.
5992        let (span, separator, open_paren_sp) =
5993            if let Some((s, open_paren_sp)) = generics.bounds_span_for_suggestions(param.def_id) {
5994                (s, " +", open_paren_sp)
5995            } else {
5996                (param.name.ident().span.shrink_to_hi(), ":", None)
5997            };
5998
5999        let mut suggs = vec![];
6000        let suggestion = format!("{separator} ?Sized");
6001
6002        if let Some(open_paren_sp) = open_paren_sp {
6003            suggs.push((open_paren_sp, "(".to_string()));
6004            suggs.push((span, format!("){suggestion}")));
6005        } else {
6006            suggs.push((span, suggestion));
6007        }
6008
6009        err.multipart_suggestion(
6010            "consider relaxing the implicit `Sized` restriction",
6011            suggs,
6012            Applicability::MachineApplicable,
6013        );
6014    }
6015
6016    fn suggest_indirection_for_unsized(
6017        &self,
6018        err: &mut Diag<'_>,
6019        item: &hir::Item<'tcx>,
6020        param: &hir::GenericParam<'tcx>,
6021    ) -> bool {
6022        // Suggesting `T: ?Sized` is only valid in an ADT if `T` is only used in a
6023        // borrow. `struct S<'a, T: ?Sized>(&'a T);` is valid, `struct S<T: ?Sized>(T);`
6024        // is not. Look for invalid "bare" parameter uses, and suggest using indirection.
6025        let mut visitor = FindTypeParam { param: param.name.ident().name, .. };
6026        visitor.visit_item(item);
6027        if visitor.invalid_spans.is_empty() {
6028            return false;
6029        }
6030        let mut multispan: MultiSpan = param.span.into();
6031        multispan.push_span_label(
6032            param.span,
6033            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this could be changed to `{0}: ?Sized`...",
                param.name.ident()))
    })format!("this could be changed to `{}: ?Sized`...", param.name.ident()),
6034        );
6035        for sp in visitor.invalid_spans {
6036            multispan.push_span_label(
6037                sp,
6038                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("...if indirection were used here: `Box<{0}>`",
                param.name.ident()))
    })format!("...if indirection were used here: `Box<{}>`", param.name.ident()),
6039            );
6040        }
6041        err.span_help(
6042            multispan,
6043            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you could relax the implicit `Sized` bound on `{0}` if it were used through indirection like `&{0}` or `Box<{0}>`",
                param.name.ident()))
    })format!(
6044                "you could relax the implicit `Sized` bound on `{T}` if it were \
6045                used through indirection like `&{T}` or `Box<{T}>`",
6046                T = param.name.ident(),
6047            ),
6048        );
6049        true
6050    }
6051    pub(crate) fn suggest_swapping_lhs_and_rhs<T>(
6052        &self,
6053        err: &mut Diag<'_>,
6054        predicate: T,
6055        param_env: ty::ParamEnv<'tcx>,
6056        cause_code: &ObligationCauseCode<'tcx>,
6057    ) where
6058        T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
6059    {
6060        let tcx = self.tcx;
6061        let predicate = predicate.upcast(tcx);
6062        match *cause_code {
6063            ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, rhs_span, .. }
6064                if let Some(typeck_results) = &self.typeck_results
6065                    && let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
6066                    && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
6067                    && let Some(lhs_ty) = typeck_results.expr_ty_opt(lhs)
6068                    && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs) =>
6069            {
6070                if let Some(pred) = predicate.as_trait_clause()
6071                    && tcx.is_lang_item(pred.def_id(), LangItem::PartialEq)
6072                    && self
6073                        .infcx
6074                        .type_implements_trait(pred.def_id(), [rhs_ty, lhs_ty], param_env)
6075                        .must_apply_modulo_regions()
6076                {
6077                    let lhs_span = tcx.hir_span(lhs_hir_id);
6078                    let sm = tcx.sess.source_map();
6079                    if let Ok(rhs_snippet) = sm.span_to_snippet(rhs_span)
6080                        && let Ok(lhs_snippet) = sm.span_to_snippet(lhs_span)
6081                    {
6082                        err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` implements `PartialEq<{1}>`",
                rhs_ty, lhs_ty))
    })format!("`{rhs_ty}` implements `PartialEq<{lhs_ty}>`"));
6083                        err.multipart_suggestion(
6084                            "consider swapping the equality",
6085                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(lhs_span, rhs_snippet), (rhs_span, lhs_snippet)]))vec![(lhs_span, rhs_snippet), (rhs_span, lhs_snippet)],
6086                            Applicability::MaybeIncorrect,
6087                        );
6088                    }
6089                }
6090            }
6091            _ => {}
6092        }
6093    }
6094}
6095
6096/// Add a hint to add a missing borrow or remove an unnecessary one.
6097fn hint_missing_borrow<'tcx>(
6098    infcx: &InferCtxt<'tcx>,
6099    param_env: ty::ParamEnv<'tcx>,
6100    span: Span,
6101    found: Ty<'tcx>,
6102    expected: Ty<'tcx>,
6103    found_node: Node<'_>,
6104    err: &mut Diag<'_>,
6105) {
6106    if #[allow(non_exhaustive_omitted_patterns)] match found_node {
    Node::TraitItem(..) => true,
    _ => false,
}matches!(found_node, Node::TraitItem(..)) {
6107        return;
6108    }
6109
6110    let found_args = match found.kind() {
6111        ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
6112        kind => {
6113            ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("found was converted to a FnPtr above but is now {0:?}",
        kind))span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
6114        }
6115    };
6116    let expected_args = match expected.kind() {
6117        ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
6118        kind => {
6119            ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("expected was converted to a FnPtr above but is now {0:?}",
        kind))span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
6120        }
6121    };
6122
6123    // This could be a variant constructor, for example.
6124    let Some(fn_decl) = found_node.fn_decl() else {
6125        return;
6126    };
6127
6128    let args = fn_decl.inputs.iter();
6129
6130    let mut to_borrow = Vec::new();
6131    let mut remove_borrow = Vec::new();
6132
6133    for ((found_arg, expected_arg), arg) in found_args.zip(expected_args).zip(args) {
6134        let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
6135        let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
6136
6137        if infcx.can_eq(param_env, found_ty, expected_ty) {
6138            // FIXME: This could handle more exotic cases like mutability mismatches too!
6139            if found_refs.len() < expected_refs.len()
6140                && found_refs[..] == expected_refs[expected_refs.len() - found_refs.len()..]
6141            {
6142                to_borrow.push((
6143                    arg.span.shrink_to_lo(),
6144                    expected_refs[..expected_refs.len() - found_refs.len()]
6145                        .iter()
6146                        .map(|mutbl| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
    })format!("&{}", mutbl.prefix_str()))
6147                        .collect::<Vec<_>>()
6148                        .join(""),
6149                ));
6150            } else if found_refs.len() > expected_refs.len() {
6151                let mut span = arg.span.shrink_to_lo();
6152                let mut left = found_refs.len() - expected_refs.len();
6153                let mut ty = arg;
6154                while let hir::TyKind::Ref(_, mut_ty) = &ty.kind
6155                    && left > 0
6156                {
6157                    span = span.with_hi(mut_ty.ty.span.lo());
6158                    ty = mut_ty.ty;
6159                    left -= 1;
6160                }
6161                if left == 0 {
6162                    remove_borrow.push((span, String::new()));
6163                }
6164            }
6165        }
6166    }
6167
6168    if !to_borrow.is_empty() {
6169        err.subdiagnostic(diagnostics::AdjustSignatureBorrow::Borrow { to_borrow });
6170    }
6171
6172    if !remove_borrow.is_empty() {
6173        err.subdiagnostic(diagnostics::AdjustSignatureBorrow::RemoveBorrow { remove_borrow });
6174    }
6175}
6176
6177/// Collect all the paths that reference `Self`.
6178/// Used to suggest replacing associated types with an explicit type in `where` clauses.
6179#[derive(#[automatically_derived]
impl<'v> ::core::fmt::Debug for SelfVisitor<'v> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "SelfVisitor",
            "paths", &self.paths, "name", &&self.name)
    }
}Debug)]
6180pub struct SelfVisitor<'v> {
6181    pub paths: Vec<&'v hir::Ty<'v>> = Vec::new(),
6182    pub name: Option<Symbol>,
6183}
6184
6185impl<'v> Visitor<'v> for SelfVisitor<'v> {
6186    fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
6187        if let hir::TyKind::Path(path) = ty.kind
6188            && let hir::QPath::TypeRelative(inner_ty, segment) = path
6189            && (Some(segment.ident.name) == self.name || self.name.is_none())
6190            && let hir::TyKind::Path(inner_path) = inner_ty.kind
6191            && let hir::QPath::Resolved(None, inner_path) = inner_path
6192            && let Res::SelfTyAlias { .. } = inner_path.res
6193        {
6194            self.paths.push(ty.as_unambig_ty());
6195        }
6196        hir::intravisit::walk_ty(self, ty);
6197    }
6198}
6199
6200/// Collect all the returned expressions within the input expression.
6201/// Used to point at the return spans when we want to suggest some change to them.
6202#[derive(#[automatically_derived]
impl<'v> ::core::default::Default for ReturnsVisitor<'v> {
    #[inline]
    fn default() -> ReturnsVisitor<'v> {
        ReturnsVisitor {
            returns: ::core::default::Default::default(),
            in_block_tail: ::core::default::Default::default(),
        }
    }
}Default)]
6203pub struct ReturnsVisitor<'v> {
6204    pub returns: Vec<&'v hir::Expr<'v>>,
6205    in_block_tail: bool,
6206}
6207
6208impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
6209    fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
6210        // Visit every expression to detect `return` paths, either through the function's tail
6211        // expression or `return` statements. We walk all nodes to find `return` statements, but
6212        // we only care about tail expressions when `in_block_tail` is `true`, which means that
6213        // they're in the return path of the function body.
6214        match ex.kind {
6215            hir::ExprKind::Ret(Some(ex)) => {
6216                self.returns.push(ex);
6217            }
6218            hir::ExprKind::Block(block, _) if self.in_block_tail => {
6219                self.in_block_tail = false;
6220                for stmt in block.stmts {
6221                    hir::intravisit::walk_stmt(self, stmt);
6222                }
6223                self.in_block_tail = true;
6224                if let Some(expr) = block.expr {
6225                    self.visit_expr(expr);
6226                }
6227            }
6228            hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
6229                self.visit_expr(then);
6230                if let Some(el) = else_opt {
6231                    self.visit_expr(el);
6232                }
6233            }
6234            hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
6235                for arm in arms {
6236                    self.visit_expr(arm.body);
6237                }
6238            }
6239            // We need to walk to find `return`s in the entire body.
6240            _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
6241            _ => self.returns.push(ex),
6242        }
6243    }
6244
6245    fn visit_body(&mut self, body: &hir::Body<'v>) {
6246        if !!self.in_block_tail {
    ::core::panicking::panic("assertion failed: !self.in_block_tail")
};assert!(!self.in_block_tail);
6247        self.in_block_tail = true;
6248        hir::intravisit::walk_body(self, body);
6249    }
6250}
6251
6252/// Collect all the awaited expressions within the input expression.
6253#[derive(#[automatically_derived]
impl ::core::default::Default for AwaitsVisitor {
    #[inline]
    fn default() -> AwaitsVisitor {
        AwaitsVisitor { awaits: ::core::default::Default::default() }
    }
}Default)]
6254struct AwaitsVisitor {
6255    awaits: Vec<HirId>,
6256}
6257
6258impl<'v> Visitor<'v> for AwaitsVisitor {
6259    fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
6260        if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
6261            self.awaits.push(id)
6262        }
6263        hir::intravisit::walk_expr(self, ex)
6264    }
6265}
6266
6267/// Suggest a new type parameter name for diagnostic purposes.
6268///
6269/// `name` is the preferred name you'd like to suggest if it's not in use already.
6270pub trait NextTypeParamName {
6271    fn next_type_param_name(&self, name: Option<&str>) -> String;
6272}
6273
6274impl NextTypeParamName for &[hir::GenericParam<'_>] {
6275    fn next_type_param_name(&self, name: Option<&str>) -> String {
6276        // Type names are usually single letters in uppercase. So convert the first letter of input string to uppercase.
6277        let name = name.and_then(|n| n.chars().next()).map(|c| c.to_uppercase().to_string());
6278        let name = name.as_deref();
6279
6280        // This is the list of possible parameter names that we might suggest.
6281        let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
6282
6283        // Filter out used names based on `filter_fn`.
6284        let used_names: Vec<Symbol> = self
6285            .iter()
6286            .filter_map(|param| match param.name {
6287                hir::ParamName::Plain(ident) => Some(ident.name),
6288                _ => None,
6289            })
6290            .collect();
6291
6292        // Find a name from `possible_names` that is not in `used_names`.
6293        possible_names
6294            .iter()
6295            .find(|n| !used_names.contains(&Symbol::intern(n)))
6296            .unwrap_or(&"ParamName")
6297            .to_string()
6298    }
6299}
6300
6301/// Collect the spans that we see the generic param `param_did`
6302struct ReplaceImplTraitVisitor<'a> {
6303    ty_spans: &'a mut Vec<Span>,
6304    param_did: DefId,
6305}
6306
6307impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
6308    fn visit_ty(&mut self, t: &'hir hir::Ty<'hir, AmbigArg>) {
6309        if let hir::TyKind::Path(hir::QPath::Resolved(
6310            None,
6311            hir::Path { res: Res::Def(_, segment_did), .. },
6312        )) = t.kind
6313        {
6314            if self.param_did == *segment_did {
6315                // `fn foo(t: impl Trait)`
6316                //            ^^^^^^^^^^ get this to suggest `T` instead
6317
6318                // There might be more than one `impl Trait`.
6319                self.ty_spans.push(t.span);
6320                return;
6321            }
6322        }
6323
6324        hir::intravisit::walk_ty(self, t);
6325    }
6326}
6327
6328pub(super) fn get_explanation_based_on_obligation<'tcx>(
6329    tcx: TyCtxt<'tcx>,
6330    obligation: &PredicateObligation<'tcx>,
6331    trait_predicate: ty::PolyTraitPredicate<'tcx>,
6332    pre_message: String,
6333    long_ty_path: &mut Option<PathBuf>,
6334) -> String {
6335    if let ObligationCauseCode::MainFunctionType = obligation.cause.code() {
6336        "consider using `()`, or a `Result`".to_owned()
6337    } else {
6338        let ty_desc = match trait_predicate.self_ty().skip_binder().kind() {
6339            ty::FnDef(_, _) => Some("fn item"),
6340            ty::Closure(_, _) => Some("closure"),
6341            _ => None,
6342        };
6343
6344        let desc = match ty_desc {
6345            Some(desc) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {0}", desc))
    })format!(" {desc}"),
6346            None => String::new(),
6347        };
6348        if let ty::PredicatePolarity::Positive = trait_predicate.polarity() {
6349            // If the trait in question is unstable, mention that fact in the diagnostic.
6350            // But if we're building with `-Zforce-unstable-if-unmarked` then _any_ trait
6351            // not explicitly marked stable is considered unstable, so the extra text is
6352            // unhelpful noise. See <https://github.com/rust-lang/rust/issues/152692>.
6353            let mention_unstable = !tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
6354                && try { tcx.lookup_stability(trait_predicate.def_id())?.level.is_stable() }
6355                    == Some(false);
6356            let unstable = if mention_unstable { "nightly-only, unstable " } else { "" };
6357
6358            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{2}the {3}trait `{0}` is not implemented for{4} `{1}`",
                trait_predicate.print_modifiers_and_trait_path(),
                tcx.short_string(trait_predicate.self_ty().skip_binder(),
                    long_ty_path), pre_message, unstable, desc))
    })format!(
6359                "{pre_message}the {unstable}trait `{}` is not implemented for{desc} `{}`",
6360                trait_predicate.print_modifiers_and_trait_path(),
6361                tcx.short_string(trait_predicate.self_ty().skip_binder(), long_ty_path),
6362            )
6363        } else {
6364            // "the trait bound `T: !Send` is not satisfied" reads better than "`!Send` is
6365            // not implemented for `T`".
6366            // FIXME: add note explaining explicit negative trait bounds.
6367            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}the trait bound `{1}` is not satisfied",
                pre_message, trait_predicate))
    })format!("{pre_message}the trait bound `{trait_predicate}` is not satisfied")
6368        }
6369    }
6370}
6371
6372// Replace `param` with `replace_ty`
6373struct ReplaceImplTraitFolder<'tcx> {
6374    tcx: TyCtxt<'tcx>,
6375    param: &'tcx ty::GenericParamDef,
6376    replace_ty: Ty<'tcx>,
6377}
6378
6379impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceImplTraitFolder<'tcx> {
6380    fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
6381        if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
6382            if self.param.index == *index {
6383                return self.replace_ty;
6384            }
6385        }
6386        t.super_fold_with(self)
6387    }
6388
6389    fn cx(&self) -> TyCtxt<'tcx> {
6390        self.tcx
6391    }
6392}
6393
6394pub fn suggest_desugaring_async_fn_to_impl_future_in_trait<'tcx>(
6395    tcx: TyCtxt<'tcx>,
6396    sig: hir::FnSig<'tcx>,
6397    body: hir::TraitFn<'tcx>,
6398    opaque_def_id: LocalDefId,
6399    add_bounds: &str,
6400) -> Option<Vec<(Span, String)>> {
6401    let hir::IsAsync::Async(async_span) = sig.header.asyncness else {
6402        return None;
6403    };
6404    let async_span = tcx.sess.source_map().span_extend_while_whitespace(async_span);
6405
6406    let future = tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
6407    let [hir::GenericBound::Trait(trait_ref)] = future.bounds else {
6408        // `async fn` should always lower to a single bound... but don't ICE.
6409        return None;
6410    };
6411    let Some(hir::PathSegment { args: Some(args), .. }) = trait_ref.trait_ref.path.segments.last()
6412    else {
6413        // desugaring to a single path segment for `Future<...>`.
6414        return None;
6415    };
6416    let Some(future_output_ty) = args.constraints.first().and_then(|constraint| constraint.ty())
6417    else {
6418        // Also should never happen.
6419        return None;
6420    };
6421
6422    let mut sugg = if future_output_ty.span.is_empty() {
6423        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(async_span, String::new()),
                (future_output_ty.span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(" -> impl std::future::Future<Output = ()>{0}",
                                    add_bounds))
                        }))]))vec![
6424            (async_span, String::new()),
6425            (
6426                future_output_ty.span,
6427                format!(" -> impl std::future::Future<Output = ()>{add_bounds}"),
6428            ),
6429        ]
6430    } else {
6431        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(future_output_ty.span.shrink_to_lo(),
                    "impl std::future::Future<Output = ".to_owned()),
                (future_output_ty.span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(">{0}", add_bounds))
                        })), (async_span, String::new())]))vec![
6432            (future_output_ty.span.shrink_to_lo(), "impl std::future::Future<Output = ".to_owned()),
6433            (future_output_ty.span.shrink_to_hi(), format!(">{add_bounds}")),
6434            (async_span, String::new()),
6435        ]
6436    };
6437
6438    // If there's a body, we also need to wrap it in `async {}`
6439    if let hir::TraitFn::Provided(body) = body {
6440        let body = tcx.hir_body(body);
6441        let body_span = body.value.span;
6442        let body_span_without_braces =
6443            body_span.with_lo(body_span.lo() + BytePos(1)).with_hi(body_span.hi() - BytePos(1));
6444        if body_span_without_braces.is_empty() {
6445            sugg.push((body_span_without_braces, " async {} ".to_owned()));
6446        } else {
6447            sugg.extend([
6448                (body_span_without_braces.shrink_to_lo(), "async {".to_owned()),
6449                (body_span_without_braces.shrink_to_hi(), "} ".to_owned()),
6450            ]);
6451        }
6452    }
6453
6454    Some(sugg)
6455}
6456
6457/// On `impl` evaluation cycles, look for `Self::AssocTy` restrictions in `where` clauses, explain
6458/// they are not allowed and if possible suggest alternatives.
6459fn point_at_assoc_type_restriction<G: EmissionGuarantee>(
6460    tcx: TyCtxt<'_>,
6461    err: &mut Diag<'_, G>,
6462    self_ty_str: &str,
6463    trait_name: &str,
6464    predicate: ty::Predicate<'_>,
6465    generics: &hir::Generics<'_>,
6466    data: &ImplDerivedCause<'_>,
6467) {
6468    let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() else {
6469        return;
6470    };
6471    let ty::ClauseKind::Projection(proj) = clause else {
6472        return;
6473    };
6474    let Some(name) = tcx
6475        .opt_rpitit_info(proj.def_id())
6476        .and_then(|data| match data {
6477            ty::ImplTraitInTraitData::Trait { fn_def_id, .. } => Some(tcx.item_name(fn_def_id)),
6478            ty::ImplTraitInTraitData::Impl { .. } => None,
6479        })
6480        .or_else(|| tcx.opt_item_name(proj.def_id()))
6481    else {
6482        return;
6483    };
6484    let mut predicates = generics.predicates.iter().peekable();
6485    let mut prev: Option<(&hir::WhereBoundPredicate<'_>, Span)> = None;
6486    while let Some(pred) = predicates.next() {
6487        let curr_span = pred.span;
6488        let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind else {
6489            continue;
6490        };
6491        let mut bounds = pred.bounds.iter();
6492        while let Some(bound) = bounds.next() {
6493            let Some(trait_ref) = bound.trait_ref() else {
6494                continue;
6495            };
6496            if bound.span() != data.span {
6497                continue;
6498            }
6499            if let hir::TyKind::Path(path) = pred.bounded_ty.kind
6500                && let hir::QPath::TypeRelative(ty, segment) = path
6501                && segment.ident.name == name
6502                && let hir::TyKind::Path(inner_path) = ty.kind
6503                && let hir::QPath::Resolved(None, inner_path) = inner_path
6504                && let Res::SelfTyAlias { .. } = inner_path.res
6505            {
6506                // The following block is to determine the right span to delete for this bound
6507                // that will leave valid code after the suggestion is applied.
6508                let span = if pred.origin == hir::PredicateOrigin::WhereClause
6509                    && generics
6510                        .predicates
6511                        .iter()
6512                        .filter(|p| {
6513                            #[allow(non_exhaustive_omitted_patterns)] match p.kind {
    hir::WherePredicateKind::BoundPredicate(p) if
        hir::PredicateOrigin::WhereClause == p.origin => true,
    _ => false,
}matches!(
6514                                p.kind,
6515                                hir::WherePredicateKind::BoundPredicate(p)
6516                                if hir::PredicateOrigin::WhereClause == p.origin
6517                            )
6518                        })
6519                        .count()
6520                        == 1
6521                {
6522                    // There's only one `where` bound, that needs to be removed. Remove the whole
6523                    // `where` clause.
6524                    generics.where_clause_span
6525                } else if let Some(next_pred) = predicates.peek()
6526                    && let hir::WherePredicateKind::BoundPredicate(next) = next_pred.kind
6527                    && pred.origin == next.origin
6528                {
6529                    // There's another bound, include the comma for the current one.
6530                    curr_span.until(next_pred.span)
6531                } else if let Some((prev, prev_span)) = prev
6532                    && pred.origin == prev.origin
6533                {
6534                    // Last bound, try to remove the previous comma.
6535                    prev_span.shrink_to_hi().to(curr_span)
6536                } else if pred.origin == hir::PredicateOrigin::WhereClause {
6537                    curr_span.with_hi(generics.where_clause_span.hi())
6538                } else {
6539                    curr_span
6540                };
6541
6542                err.span_suggestion_verbose(
6543                    span,
6544                    "associated type for the current `impl` cannot be restricted in `where` \
6545                     clauses, remove this bound",
6546                    "",
6547                    Applicability::MaybeIncorrect,
6548                );
6549            }
6550            if let Some(new) =
6551                tcx.associated_items(data.impl_or_alias_def_id).find_by_ident_and_kind(
6552                    tcx,
6553                    Ident::with_dummy_span(name),
6554                    ty::AssocTag::Type,
6555                    data.impl_or_alias_def_id,
6556                )
6557            {
6558                // The associated type is specified in the `impl` we're
6559                // looking at. Point at it.
6560                let span = tcx.def_span(new.def_id);
6561                err.span_label(
6562                    span,
6563                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("associated type `<{0} as {1}>::{2}` is specified here",
                self_ty_str, trait_name, name))
    })format!(
6564                        "associated type `<{self_ty_str} as {trait_name}>::{name}` is specified \
6565                         here",
6566                    ),
6567                );
6568                // Search for the associated type `Self::{name}`, get
6569                // its type and suggest replacing the bound with it.
6570                let mut visitor = SelfVisitor { name: Some(name), .. };
6571                visitor.visit_trait_ref(trait_ref);
6572                for path in visitor.paths {
6573                    err.span_suggestion_verbose(
6574                        path.span,
6575                        "replace the associated type with the type specified in this `impl`",
6576                        tcx.type_of(new.def_id).skip_binder(),
6577                        Applicability::MachineApplicable,
6578                    );
6579                }
6580            } else {
6581                let mut visitor = SelfVisitor { name: None, .. };
6582                visitor.visit_trait_ref(trait_ref);
6583                let span: MultiSpan =
6584                    visitor.paths.iter().map(|p| p.span).collect::<Vec<Span>>().into();
6585                err.span_note(
6586                    span,
6587                    "associated types for the current `impl` cannot be restricted in `where` \
6588                     clauses",
6589                );
6590            }
6591        }
6592        prev = Some((pred, curr_span));
6593    }
6594}
6595
6596fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec<hir::Mutability>) {
6597    let mut refs = ::alloc::vec::Vec::new()vec![];
6598
6599    while let ty::Ref(_, new_ty, mutbl) = ty.kind() {
6600        ty = *new_ty;
6601        refs.push(*mutbl);
6602    }
6603
6604    (ty, refs)
6605}
6606
6607/// Look for type `param` in an ADT being used only through a reference to confirm that suggesting
6608/// `param: ?Sized` would be a valid constraint.
6609struct FindTypeParam {
6610    param: rustc_span::Symbol,
6611    invalid_spans: Vec<Span> = Vec::new(),
6612    nested: bool = false,
6613}
6614
6615impl<'v> Visitor<'v> for FindTypeParam {
6616    fn visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>) {
6617        // Skip where-clauses, to avoid suggesting indirection for type parameters found there.
6618    }
6619
6620    fn visit_ty(&mut self, ty: &hir::Ty<'_, AmbigArg>) {
6621        // We collect the spans of all uses of the "bare" type param, like in `field: T` or
6622        // `field: (T, T)` where we could make `T: ?Sized` while skipping cases that are known to be
6623        // valid like `field: &'a T` or `field: *mut T` and cases that *might* have further `Sized`
6624        // obligations like `Box<T>` and `Vec<T>`, but we perform no extra analysis for those cases
6625        // and suggest `T: ?Sized` regardless of their obligations. This is fine because the errors
6626        // in that case should make what happened clear enough.
6627        match ty.kind {
6628            hir::TyKind::Ptr(_) | hir::TyKind::Ref(..) | hir::TyKind::TraitObject(..) => {}
6629            hir::TyKind::Path(hir::QPath::Resolved(None, path))
6630                if let [segment] = path.segments
6631                    && segment.ident.name == self.param =>
6632            {
6633                if !self.nested {
6634                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6634",
                        "rustc_trait_selection::error_reporting::traits::suggestions",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                        ::tracing_core::__macro_support::Option::Some(6634u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                        ::tracing_core::field::FieldSet::new(&["message", "ty"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("FindTypeParam::visit_ty")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&ty) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?ty, "FindTypeParam::visit_ty");
6635                    self.invalid_spans.push(ty.span);
6636                }
6637            }
6638            hir::TyKind::Path(_) => {
6639                let prev = self.nested;
6640                self.nested = true;
6641                hir::intravisit::walk_ty(self, ty);
6642                self.nested = prev;
6643            }
6644            _ => {
6645                hir::intravisit::walk_ty(self, ty);
6646            }
6647        }
6648    }
6649}
6650
6651/// Look for type parameters in predicates. We use this to identify whether a bound is suitable in
6652/// on a given item.
6653struct ParamFinder {
6654    params: Vec<Symbol> = Vec::new(),
6655}
6656
6657impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ParamFinder {
6658    fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
6659        match t.kind() {
6660            ty::Param(p) => self.params.push(p.name),
6661            _ => {}
6662        }
6663        t.super_visit_with(self)
6664    }
6665}
6666
6667impl ParamFinder {
6668    /// Whether the `hir::Generics` of the current item can suggest the evaluated bound because its
6669    /// references to type parameters are present in the generics.
6670    fn can_suggest_bound(&self, generics: &hir::Generics<'_>) -> bool {
6671        if self.params.is_empty() {
6672            // There are no references to type parameters at all, so suggesting the bound
6673            // would be reasonable.
6674            return true;
6675        }
6676        generics.params.iter().any(|p| match p.name {
6677            hir::ParamName::Plain(p_name) => {
6678                // All of the parameters in the bound can be referenced in the current item.
6679                self.params.iter().any(|p| *p == p_name.name || *p == kw::SelfUpper)
6680            }
6681            _ => true,
6682        })
6683    }
6684}