Skip to main content

rustc_trait_selection/error_reporting/traits/
suggestions.rs

1// ignore-tidy-file-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 a `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 gen_clauses = self.tcx.clauses_of(def_id).instantiate_identity(self.tcx)
2883            && let Some(clause) = gen_clauses.clauses.get(idx).map(|c| c.as_ref().skip_norm_wip())
2884            && let ty::ClauseKind::Trait(trait_pred) = clause.kind().skip_binder()
2885            && self.tcx.is_fn_trait(trait_pred.def_id())
2886        {
2887            let expected_self =
2888                self.tcx.anonymize_bound_vars(clause.kind().rebind(trait_pred.self_ty()));
2889            let expected_args =
2890                self.tcx.anonymize_bound_vars(clause.kind().rebind(trait_pred.trait_ref.args));
2891
2892            // Find another clause whose self-type is equal to the expected self type,
2893            // but whose args don't match.
2894            let other_clause =
2895                gen_clauses.into_iter().enumerate().find(|&(other_idx, (clause, _))| {
2896                    let clause = clause.skip_norm_wip();
2897                    match clause.kind().skip_binder() {
2898                        ty::ClauseKind::Trait(trait_pred)
2899                            if self.tcx.is_fn_trait(trait_pred.def_id())
2900                            && other_idx != idx
2901                            // Make sure that the self type matches
2902                            // (i.e. constraining this closure)
2903                            && expected_self
2904                                == self.tcx.anonymize_bound_vars(
2905                                    clause.kind().rebind(trait_pred.self_ty()),
2906                                )
2907                            // But the args don't match (i.e. incompatible args)
2908                            && expected_args
2909                                != self.tcx.anonymize_bound_vars(
2910                                    clause.kind().rebind(trait_pred.trait_ref.args),
2911                                ) =>
2912                        {
2913                            true
2914                        }
2915                        _ => false,
2916                    }
2917                });
2918            // If we found one, then it's very likely the cause of the error.
2919            if let Some((_, (_, other_clause_span))) = other_clause {
2920                err.span_note(
2921                    other_clause_span,
2922                    "closure inferred to have a different signature due to this bound",
2923                );
2924            }
2925        }
2926    }
2927
2928    pub(super) fn suggest_fully_qualified_path(
2929        &self,
2930        err: &mut Diag<'_>,
2931        item_def_id: DefId,
2932        span: Span,
2933        trait_ref: DefId,
2934    ) {
2935        if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id)
2936            && let ty::AssocKind::Const { .. } | ty::AssocKind::Type { .. } = assoc_item.kind
2937        {
2938            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!(
2939                "{}s cannot be accessed directly on a `trait`, they can only be \
2940                        accessed through a specific `impl`",
2941                self.tcx.def_kind_descr(assoc_item.as_def_kind(), item_def_id)
2942            ));
2943
2944            if !assoc_item.is_impl_trait_in_trait() {
2945                err.span_suggestion_verbose(
2946                    span,
2947                    "use the fully qualified path to an implementation",
2948                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<Type as {0}>::{1}",
                self.tcx.def_path_str(trait_ref), assoc_item.name()))
    })format!(
2949                        "<Type as {}>::{}",
2950                        self.tcx.def_path_str(trait_ref),
2951                        assoc_item.name()
2952                    ),
2953                    Applicability::HasPlaceholders,
2954                );
2955            }
2956        }
2957    }
2958
2959    /// Adds an async-await specific note to the diagnostic when the future does not implement
2960    /// an auto trait because of a captured type.
2961    ///
2962    /// ```text
2963    /// note: future does not implement `Qux` as this value is used across an await
2964    ///   --> $DIR/issue-64130-3-other.rs:17:5
2965    ///    |
2966    /// LL |     let x = Foo;
2967    ///    |         - has type `Foo`
2968    /// LL |     baz().await;
2969    ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2970    /// LL | }
2971    ///    | - `x` is later dropped here
2972    /// ```
2973    ///
2974    /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
2975    /// is "replaced" with a different message and a more specific error.
2976    ///
2977    /// ```text
2978    /// error: future cannot be sent between threads safely
2979    ///   --> $DIR/issue-64130-2-send.rs:21:5
2980    ///    |
2981    /// LL | fn is_send<T: Send>(t: T) { }
2982    ///    |               ---- required by this bound in `is_send`
2983    /// ...
2984    /// LL |     is_send(bar());
2985    ///    |     ^^^^^^^ future returned by `bar` is not send
2986    ///    |
2987    ///    = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
2988    ///            implemented for `Foo`
2989    /// note: future is not send as this value is used across an await
2990    ///   --> $DIR/issue-64130-2-send.rs:15:5
2991    ///    |
2992    /// LL |     let x = Foo;
2993    ///    |         - has type `Foo`
2994    /// LL |     baz().await;
2995    ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2996    /// LL | }
2997    ///    | - `x` is later dropped here
2998    /// ```
2999    ///
3000    /// Returns `true` if an async-await specific note was added to the diagnostic.
3001    #[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(3001u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("obligation.predicate")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("obligation.predicate");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("obligation.cause.span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("obligation.cause.span");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation.predicate)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation.cause.span)
                                                            as &dyn ::tracing::field::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:3040",
                                        "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(3040u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                        ::tracing_core::field::FieldSet::new(&[{
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("code")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("code");
                                                            NAME.as_str()
                                                        }], ::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};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&code)
                                                            as &dyn ::tracing::field::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:3047",
                                                "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(3047u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&["message",
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("parent_trait_ref")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("parent_trait_ref");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("self_ty.kind")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("self_ty.kind");
                                                                    NAME.as_str()
                                                                }], ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("ImplDerived")
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause.derived.parent_trait_pred)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty.kind())
                                                                    as &dyn ::tracing::field::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:3077",
                                                "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(3077u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("parent_trait_ref")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("parent_trait_ref");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("self_ty.kind")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("self_ty.kind");
                                                                    NAME.as_str()
                                                                }], ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&derived_obligation.parent_trait_pred)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty.kind())
                                                                    as &dyn ::tracing::field::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:3108",
                                    "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(3108u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("coroutine")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("coroutine");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_ref");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("target_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("target_ty");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coroutine)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ref)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target_ty)
                                                        as &dyn ::tracing::field::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:3118",
                                    "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(3118u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("coroutine_did")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("coroutine_did");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("coroutine_did_root")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("coroutine_did_root");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("typeck_results.hir_owner")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("typeck_results.hir_owner");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coroutine_did)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coroutine_did_root)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.typeck_results.as_ref().map(|t|
                                                                            t.hir_owner)) as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                        as &dyn ::tracing::field::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:3131",
                                    "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(3131u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("awaits")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("awaits");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&visitor.awaits)
                                                        as &dyn ::tracing::field::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:3152",
                                                "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(3152u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("ty_erased")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("ty_erased");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("target_ty_erased")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("target_ty_erased");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("eq")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("eq");
                                                                    NAME.as_str()
                                                                }], ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty_erased)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target_ty_erased)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&eq)
                                                                    as &dyn ::tracing::field::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:3176",
                                    "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(3176u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("from_awaited_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("from_awaited_ty");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&from_awaited_ty)
                                                        as &dyn ::tracing::field::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:3184",
                                        "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(3184u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                        ::tracing_core::field::FieldSet::new(&[{
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("coroutine_info")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("coroutine_info");
                                                            NAME.as_str()
                                                        }], ::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};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coroutine_info)
                                                            as &dyn ::tracing::field::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:3188",
                                            "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(3188u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                            ::tracing_core::field::FieldSet::new(&[{
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("variant")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("variant");
                                                                NAME.as_str()
                                                            }], ::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};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&variant)
                                                                as &dyn ::tracing::field::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:3191",
                                                "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(3191u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("decl")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("decl");
                                                                    NAME.as_str()
                                                                }], ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&decl)
                                                                    as &dyn ::tracing::field::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:3212",
                                    "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(3212u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("interior_or_upvar_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("interior_or_upvar_span");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&interior_or_upvar_span)
                                                        as &dyn ::tracing::field::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))]
3002    pub fn maybe_note_obligation_cause_for_async_await<G: EmissionGuarantee>(
3003        &self,
3004        err: &mut Diag<'_, G>,
3005        obligation: &PredicateObligation<'tcx>,
3006    ) -> bool {
3007        // Attempt to detect an async-await error by looking at the obligation causes, looking
3008        // for a coroutine to be present.
3009        //
3010        // When a future does not implement a trait because of a captured type in one of the
3011        // coroutines somewhere in the call stack, then the result is a chain of obligations.
3012        //
3013        // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
3014        // future is passed as an argument to a function C which requires a `Send` type, then the
3015        // chain looks something like this:
3016        //
3017        // - `BuiltinDerivedObligation` with a coroutine witness (B)
3018        // - `BuiltinDerivedObligation` with a coroutine (B)
3019        // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
3020        // - `BuiltinDerivedObligation` with a coroutine witness (A)
3021        // - `BuiltinDerivedObligation` with a coroutine (A)
3022        // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
3023        // - `BindingObligation` with `impl_send` (Send requirement)
3024        //
3025        // The first obligation in the chain is the most useful and has the coroutine that captured
3026        // the type. The last coroutine (`outer_coroutine` below) has information about where the
3027        // bound was introduced. At least one coroutine should be present for this diagnostic to be
3028        // modified.
3029        let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
3030            ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) => (Some(p), Some(p.self_ty())),
3031            _ => (None, None),
3032        };
3033        let mut coroutine = None;
3034        let mut outer_coroutine = None;
3035        let mut next_code = Some(obligation.cause.code());
3036
3037        let mut seen_upvar_tys_infer_tuple = false;
3038
3039        while let Some(code) = next_code {
3040            debug!(?code);
3041            match code {
3042                ObligationCauseCode::FunctionArg { parent_code, .. } => {
3043                    next_code = Some(parent_code);
3044                }
3045                ObligationCauseCode::ImplDerived(cause) => {
3046                    let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
3047                    debug!(
3048                        parent_trait_ref = ?cause.derived.parent_trait_pred,
3049                        self_ty.kind = ?ty.kind(),
3050                        "ImplDerived",
3051                    );
3052
3053                    match *ty.kind() {
3054                        ty::Coroutine(did, ..) | ty::CoroutineWitness(did, _) => {
3055                            coroutine = coroutine.or(Some(did));
3056                            outer_coroutine = Some(did);
3057                        }
3058                        ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
3059                            // By introducing a tuple of upvar types into the chain of obligations
3060                            // of a coroutine, the first non-coroutine item is now the tuple itself,
3061                            // we shall ignore this.
3062
3063                            seen_upvar_tys_infer_tuple = true;
3064                        }
3065                        _ if coroutine.is_none() => {
3066                            trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
3067                            target_ty = Some(ty);
3068                        }
3069                        _ => {}
3070                    }
3071
3072                    next_code = Some(&cause.derived.parent_code);
3073                }
3074                ObligationCauseCode::WellFormedDerived(derived_obligation)
3075                | ObligationCauseCode::BuiltinDerived(derived_obligation) => {
3076                    let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
3077                    debug!(
3078                        parent_trait_ref = ?derived_obligation.parent_trait_pred,
3079                        self_ty.kind = ?ty.kind(),
3080                    );
3081
3082                    match *ty.kind() {
3083                        ty::Coroutine(did, ..) | ty::CoroutineWitness(did, ..) => {
3084                            coroutine = coroutine.or(Some(did));
3085                            outer_coroutine = Some(did);
3086                        }
3087                        ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
3088                            // By introducing a tuple of upvar types into the chain of obligations
3089                            // of a coroutine, the first non-coroutine item is now the tuple itself,
3090                            // we shall ignore this.
3091
3092                            seen_upvar_tys_infer_tuple = true;
3093                        }
3094                        _ if coroutine.is_none() => {
3095                            trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
3096                            target_ty = Some(ty);
3097                        }
3098                        _ => {}
3099                    }
3100
3101                    next_code = Some(&derived_obligation.parent_code);
3102                }
3103                _ => break,
3104            }
3105        }
3106
3107        // Only continue if a coroutine was found.
3108        debug!(?coroutine, ?trait_ref, ?target_ty);
3109        let (Some(coroutine_did), Some(trait_ref), Some(target_ty)) =
3110            (coroutine, trait_ref, target_ty)
3111        else {
3112            return false;
3113        };
3114
3115        let span = self.tcx.def_span(coroutine_did);
3116
3117        let coroutine_did_root = self.tcx.typeck_root_def_id(coroutine_did);
3118        debug!(
3119            ?coroutine_did,
3120            ?coroutine_did_root,
3121            typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
3122            ?span,
3123        );
3124
3125        let coroutine_body =
3126            coroutine_did.as_local().and_then(|def_id| self.tcx.hir_maybe_body_owned_by(def_id));
3127        let mut visitor = AwaitsVisitor::default();
3128        if let Some(body) = coroutine_body {
3129            visitor.visit_body(&body);
3130        }
3131        debug!(awaits = ?visitor.awaits);
3132
3133        // Look for a type inside the coroutine interior that matches the target type to get
3134        // a span.
3135        let target_ty_erased = self.tcx.erase_and_anonymize_regions(target_ty);
3136        let ty_matches = |ty| -> bool {
3137            // Careful: the regions for types that appear in the
3138            // coroutine interior are not generally known, so we
3139            // want to erase them when comparing (and anyway,
3140            // `Send` and other bounds are generally unaffected by
3141            // the choice of region). When erasing regions, we
3142            // also have to erase late-bound regions. This is
3143            // because the types that appear in the coroutine
3144            // interior generally contain "bound regions" to
3145            // represent regions that are part of the suspended
3146            // coroutine frame. Bound regions are preserved by
3147            // `erase_and_anonymize_regions` and so we must also call
3148            // `instantiate_bound_regions_with_erased`.
3149            let ty_erased = self.tcx.instantiate_bound_regions_with_erased(ty);
3150            let ty_erased = self.tcx.erase_and_anonymize_regions(ty_erased);
3151            let eq = ty_erased == target_ty_erased;
3152            debug!(?ty_erased, ?target_ty_erased, ?eq);
3153            eq
3154        };
3155
3156        // Get the typeck results from the infcx if the coroutine is the function we are currently
3157        // type-checking; otherwise, get them by performing a query. This is needed to avoid
3158        // cycles. If we can't use resolved types because the coroutine comes from another crate,
3159        // we still provide a targeted error but without all the relevant spans.
3160        let coroutine_data = match &self.typeck_results {
3161            Some(t) if t.hir_owner.to_def_id() == coroutine_did_root => CoroutineData(t),
3162            _ if coroutine_did.is_local() => {
3163                CoroutineData(self.tcx.typeck(coroutine_did.expect_local()))
3164            }
3165            _ => return false,
3166        };
3167
3168        let coroutine_within_in_progress_typeck = match &self.typeck_results {
3169            Some(t) => t.hir_owner.to_def_id() == coroutine_did_root,
3170            _ => false,
3171        };
3172
3173        let mut interior_or_upvar_span = None;
3174
3175        let from_awaited_ty = coroutine_data.get_from_await_ty(visitor, self.tcx, ty_matches);
3176        debug!(?from_awaited_ty);
3177
3178        // Avoid disclosing internal information to downstream crates.
3179        if coroutine_did.is_local()
3180            // Try to avoid cycles.
3181            && !coroutine_within_in_progress_typeck
3182            && let Some(coroutine_info) = self.tcx.mir_coroutine_witnesses(coroutine_did)
3183        {
3184            debug!(?coroutine_info);
3185            'find_source: for (variant, source_info) in
3186                coroutine_info.variant_fields.iter().zip(&coroutine_info.variant_source_info)
3187            {
3188                debug!(?variant);
3189                for &local in variant {
3190                    let decl = &coroutine_info.field_tys[local];
3191                    debug!(?decl);
3192                    if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.ignore_for_traits {
3193                        interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(
3194                            decl.source_info.span,
3195                            Some((source_info.span, from_awaited_ty)),
3196                        ));
3197                        break 'find_source;
3198                    }
3199                }
3200            }
3201        }
3202
3203        if interior_or_upvar_span.is_none() {
3204            interior_or_upvar_span =
3205                coroutine_data.try_get_upvar_span(self, coroutine_did, ty_matches);
3206        }
3207
3208        if interior_or_upvar_span.is_none() && !coroutine_did.is_local() {
3209            interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(span, None));
3210        }
3211
3212        debug!(?interior_or_upvar_span);
3213        if let Some(interior_or_upvar_span) = interior_or_upvar_span {
3214            let is_async = self.tcx.coroutine_is_async(coroutine_did);
3215            self.note_obligation_cause_for_async_await(
3216                err,
3217                interior_or_upvar_span,
3218                is_async,
3219                outer_coroutine,
3220                trait_ref,
3221                target_ty,
3222                obligation,
3223                next_code,
3224            );
3225            true
3226        } else {
3227            false
3228        }
3229    }
3230
3231    /// Unconditionally adds the diagnostic note described in
3232    /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
3233    #[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(3233u32),
                                    ::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_all(&[]) })
                } 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:3456",
                                    "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(3456u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("next_code")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("next_code");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&next_code)
                                                        as &dyn ::tracing::field::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)]
3234    fn note_obligation_cause_for_async_await<G: EmissionGuarantee>(
3235        &self,
3236        err: &mut Diag<'_, G>,
3237        interior_or_upvar_span: CoroutineInteriorOrUpvar,
3238        is_async: bool,
3239        outer_coroutine: Option<DefId>,
3240        trait_pred: ty::TraitPredicate<'tcx>,
3241        target_ty: Ty<'tcx>,
3242        obligation: &PredicateObligation<'tcx>,
3243        next_code: Option<&ObligationCauseCode<'tcx>>,
3244    ) {
3245        let source_map = self.tcx.sess.source_map();
3246
3247        let (await_or_yield, an_await_or_yield) =
3248            if is_async { ("await", "an await") } else { ("yield", "a yield") };
3249        let future_or_coroutine = if is_async { "future" } else { "coroutine" };
3250
3251        // Special case the primary error message when send or sync is the trait that was
3252        // not implemented.
3253        let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
3254            self.tcx.get_diagnostic_name(trait_pred.def_id())
3255        {
3256            let (trait_name, trait_verb) =
3257                if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
3258
3259            err.code = None;
3260            err.primary_message(format!(
3261                "{future_or_coroutine} cannot be {trait_verb} between threads safely"
3262            ));
3263
3264            let original_span = err.span.primary_span().unwrap();
3265            let mut span = MultiSpan::from_span(original_span);
3266
3267            let message = outer_coroutine
3268                .and_then(|coroutine_did| {
3269                    Some(match self.tcx.coroutine_kind(coroutine_did).unwrap() {
3270                        CoroutineKind::Coroutine(_) => format!("coroutine is not {trait_name}"),
3271                        CoroutineKind::Desugared(
3272                            CoroutineDesugaring::Async,
3273                            CoroutineSource::Fn,
3274                        ) => self
3275                            .tcx
3276                            .parent(coroutine_did)
3277                            .as_local()
3278                            .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3279                            .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3280                            .map(|name| {
3281                                format!("future returned by `{name}` is not {trait_name}")
3282                            })?,
3283                        CoroutineKind::Desugared(
3284                            CoroutineDesugaring::Async,
3285                            CoroutineSource::Block,
3286                        ) => {
3287                            format!("future created by async block is not {trait_name}")
3288                        }
3289                        CoroutineKind::Desugared(
3290                            CoroutineDesugaring::Async,
3291                            CoroutineSource::Closure,
3292                        ) => {
3293                            format!("future created by async closure is not {trait_name}")
3294                        }
3295                        CoroutineKind::Desugared(
3296                            CoroutineDesugaring::AsyncGen,
3297                            CoroutineSource::Fn,
3298                        ) => self
3299                            .tcx
3300                            .parent(coroutine_did)
3301                            .as_local()
3302                            .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3303                            .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3304                            .map(|name| {
3305                                format!("async iterator returned by `{name}` is not {trait_name}")
3306                            })?,
3307                        CoroutineKind::Desugared(
3308                            CoroutineDesugaring::AsyncGen,
3309                            CoroutineSource::Block,
3310                        ) => {
3311                            format!("async iterator created by async gen block is not {trait_name}")
3312                        }
3313                        CoroutineKind::Desugared(
3314                            CoroutineDesugaring::AsyncGen,
3315                            CoroutineSource::Closure,
3316                        ) => {
3317                            format!(
3318                                "async iterator created by async gen closure is not {trait_name}"
3319                            )
3320                        }
3321                        CoroutineKind::Desugared(CoroutineDesugaring::Gen, CoroutineSource::Fn) => {
3322                            self.tcx
3323                                .parent(coroutine_did)
3324                                .as_local()
3325                                .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3326                                .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3327                                .map(|name| {
3328                                    format!("iterator returned by `{name}` is not {trait_name}")
3329                                })?
3330                        }
3331                        CoroutineKind::Desugared(
3332                            CoroutineDesugaring::Gen,
3333                            CoroutineSource::Block,
3334                        ) => {
3335                            format!("iterator created by gen block is not {trait_name}")
3336                        }
3337                        CoroutineKind::Desugared(
3338                            CoroutineDesugaring::Gen,
3339                            CoroutineSource::Closure,
3340                        ) => {
3341                            format!("iterator created by gen closure is not {trait_name}")
3342                        }
3343                    })
3344                })
3345                .unwrap_or_else(|| format!("{future_or_coroutine} is not {trait_name}"));
3346
3347            span.push_span_label(original_span, message);
3348            err.span(span);
3349
3350            format!("is not {trait_name}")
3351        } else {
3352            format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
3353        };
3354
3355        let mut explain_yield = |interior_span: Span, yield_span: Span| {
3356            let mut span = MultiSpan::from_span(yield_span);
3357            let snippet = match source_map.span_to_snippet(interior_span) {
3358                // #70935: If snippet contains newlines, display "the value" instead
3359                // so that we do not emit complex diagnostics.
3360                Ok(snippet) if !snippet.contains('\n') => format!("`{snippet}`"),
3361                _ => "the value".to_string(),
3362            };
3363            // note: future is not `Send` as this value is used across an await
3364            //   --> $DIR/issue-70935-complex-spans.rs:13:9
3365            //    |
3366            // LL |            baz(|| async {
3367            //    |  ______________-
3368            //    | |
3369            //    | |
3370            // LL | |              foo(tx.clone());
3371            // LL | |          }).await;
3372            //    | |          - ^^^^^^ await occurs here, with value maybe used later
3373            //    | |__________|
3374            //    |            has type `closure` which is not `Send`
3375            // note: value is later dropped here
3376            // LL | |          }).await;
3377            //    | |                  ^
3378            //
3379            span.push_span_label(
3380                yield_span,
3381                format!("{await_or_yield} occurs here, with {snippet} maybe used later"),
3382            );
3383            span.push_span_label(
3384                interior_span,
3385                format!("has type `{target_ty}` which {trait_explanation}"),
3386            );
3387            err.span_note(
3388                span,
3389                format!("{future_or_coroutine} {trait_explanation} as this value is used across {an_await_or_yield}"),
3390            );
3391        };
3392        match interior_or_upvar_span {
3393            CoroutineInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
3394                if let Some((yield_span, from_awaited_ty)) = interior_extra_info {
3395                    if let Some(await_span) = from_awaited_ty {
3396                        // The type causing this obligation is one being awaited at await_span.
3397                        let mut span = MultiSpan::from_span(await_span);
3398                        span.push_span_label(
3399                            await_span,
3400                            format!(
3401                                "await occurs here on type `{target_ty}`, which {trait_explanation}"
3402                            ),
3403                        );
3404                        err.span_note(
3405                            span,
3406                            format!(
3407                                "future {trait_explanation} as it awaits another future which {trait_explanation}"
3408                            ),
3409                        );
3410                    } else {
3411                        // Look at the last interior type to get a span for the `.await`.
3412                        explain_yield(interior_span, yield_span);
3413                    }
3414                }
3415            }
3416            CoroutineInteriorOrUpvar::Upvar(upvar_span) => {
3417                // `Some((ref_ty, is_mut))` if `target_ty` is `&T` or `&mut T` and fails to impl `Send`
3418                let non_send = match target_ty.kind() {
3419                    ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(obligation) {
3420                        Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
3421                        _ => None,
3422                    },
3423                    _ => None,
3424                };
3425
3426                let (span_label, span_note) = match non_send {
3427                    // if `target_ty` is `&T` or `&mut T` and fails to impl `Send`,
3428                    // include suggestions to make `T: Sync` so that `&T: Send`,
3429                    // or to make `T: Send` so that `&mut T: Send`
3430                    Some((ref_ty, is_mut)) => {
3431                        let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
3432                        let ref_kind = if is_mut { "&mut" } else { "&" };
3433                        (
3434                            format!(
3435                                "has type `{target_ty}` which {trait_explanation}, because `{ref_ty}` is not `{ref_ty_trait}`"
3436                            ),
3437                            format!(
3438                                "captured value {trait_explanation} because `{ref_kind}` references cannot be sent unless their referent is `{ref_ty_trait}`"
3439                            ),
3440                        )
3441                    }
3442                    None => (
3443                        format!("has type `{target_ty}` which {trait_explanation}"),
3444                        format!("captured value {trait_explanation}"),
3445                    ),
3446                };
3447
3448                let mut span = MultiSpan::from_span(upvar_span);
3449                span.push_span_label(upvar_span, span_label);
3450                err.span_note(span, span_note);
3451            }
3452        }
3453
3454        // Add a note for the item obligation that remains - normally a note pointing to the
3455        // bound that introduced the obligation (e.g. `T: Send`).
3456        debug!(?next_code);
3457        self.note_obligation_cause_code(
3458            obligation.cause.body_def_id,
3459            err,
3460            obligation.predicate,
3461            obligation.param_env,
3462            next_code.unwrap(),
3463            &mut Vec::new(),
3464            &mut Default::default(),
3465        );
3466    }
3467
3468    pub(super) fn note_obligation_cause_code<G: EmissionGuarantee, T>(
3469        &self,
3470        body_def_id: LocalDefId,
3471        err: &mut Diag<'_, G>,
3472        predicate: T,
3473        param_env: ty::ParamEnv<'tcx>,
3474        cause_code: &ObligationCauseCode<'tcx>,
3475        obligated_types: &mut Vec<Ty<'tcx>>,
3476        seen_requirements: &mut FxHashSet<DefId>,
3477    ) where
3478        T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
3479    {
3480        let tcx = self.tcx;
3481        let predicate = predicate.upcast(tcx);
3482        let suggest_remove_deref = |err: &mut Diag<'_, G>, expr: &hir::Expr<'_>| {
3483            if let Some(pred) = predicate.as_trait_clause()
3484                && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
3485                && let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind
3486            {
3487                err.span_suggestion_verbose(
3488                    expr.span.until(inner.span),
3489                    "references are always `Sized`, even if they point to unsized data; consider \
3490                     not dereferencing the expression",
3491                    String::new(),
3492                    Applicability::MaybeIncorrect,
3493                );
3494            }
3495        };
3496        match *cause_code {
3497            ObligationCauseCode::ExprAssignable
3498            | ObligationCauseCode::MatchExpressionArm { .. }
3499            | ObligationCauseCode::Pattern { .. }
3500            | ObligationCauseCode::IfExpression { .. }
3501            | ObligationCauseCode::IfExpressionWithNoElse
3502            | ObligationCauseCode::MainFunctionType
3503            | ObligationCauseCode::LangFunctionType(_)
3504            | ObligationCauseCode::IntrinsicType
3505            | ObligationCauseCode::MethodReceiver
3506            | ObligationCauseCode::ReturnNoExpression
3507            | ObligationCauseCode::Misc
3508            | ObligationCauseCode::WellFormed(..)
3509            | ObligationCauseCode::MatchImpl(..)
3510            | ObligationCauseCode::ReturnValue(_)
3511            | ObligationCauseCode::BlockTailExpression(..)
3512            | ObligationCauseCode::AwaitableExpr(_)
3513            | ObligationCauseCode::ForLoopIterator
3514            | ObligationCauseCode::QuestionMark
3515            | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
3516            | ObligationCauseCode::LetElse
3517            | ObligationCauseCode::UnOp { .. }
3518            | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
3519            | ObligationCauseCode::AlwaysApplicableImpl
3520            | ObligationCauseCode::ConstParam(_)
3521            | ObligationCauseCode::ReferenceOutlivesReferent(..)
3522            | ObligationCauseCode::ObjectTypeBound(..) => {}
3523            ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. } => {
3524                if let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
3525                    && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
3526                    && tcx.sess.source_map().lookup_char_pos(lhs.span.lo()).line
3527                        != tcx.sess.source_map().lookup_char_pos(rhs.span.hi()).line
3528                {
3529                    err.span_label(lhs.span, "");
3530                    err.span_label(rhs.span, "");
3531                }
3532            }
3533            ObligationCauseCode::RustCall => {
3534                if let Some(pred) = predicate.as_trait_clause()
3535                    && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
3536                {
3537                    err.note("argument required to be sized due to `extern \"rust-call\"` ABI");
3538                }
3539            }
3540            ObligationCauseCode::SliceOrArrayElem => {
3541                err.note("slice and array elements must have `Sized` type");
3542            }
3543            ObligationCauseCode::ArrayLen(array_ty) => {
3544                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`"));
3545            }
3546            ObligationCauseCode::TupleElem => {
3547                err.note("only the last element of a tuple may have a dynamically sized type");
3548            }
3549            ObligationCauseCode::DynCompatible(span) => {
3550                err.multipart_suggestion(
3551                    "you might have meant to use `Self` to refer to the implementing type",
3552                    ::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())],
3553                    Applicability::MachineApplicable,
3554                );
3555            }
3556            ObligationCauseCode::WhereClause(item_def_id, span)
3557            | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)
3558            | ObligationCauseCode::HostEffectInExpr(item_def_id, span, ..)
3559                if !span.is_dummy() =>
3560            {
3561                if let ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, pos) = &cause_code {
3562                    if let Node::Expr(expr) = tcx.parent_hir_node(*hir_id)
3563                        && let hir::ExprKind::Call(_, args) = expr.kind
3564                        && let Some(expr) = args.get(*pos)
3565                    {
3566                        suggest_remove_deref(err, &expr);
3567                    } else if let Node::Expr(expr) = self.tcx.hir_node(*hir_id)
3568                        && let hir::ExprKind::MethodCall(_, _, args, _) = expr.kind
3569                        && let Some(expr) = args.get(*pos)
3570                    {
3571                        suggest_remove_deref(err, &expr);
3572                    }
3573                }
3574                let item_name = tcx.def_path_str(item_def_id);
3575                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));
3576                let mut multispan = MultiSpan::from(span);
3577                let sm = tcx.sess.source_map();
3578                if let Some(ident) = tcx.opt_item_ident(item_def_id) {
3579                    let same_line =
3580                        match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
3581                            (Ok(l), Ok(r)) => l.line == r.line,
3582                            _ => true,
3583                        };
3584                    if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
3585                        multispan.push_span_label(
3586                            ident.span,
3587                            ::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!(
3588                                "required by a bound in this {}",
3589                                tcx.def_kind(item_def_id).descr(item_def_id)
3590                            ),
3591                        );
3592                    }
3593                }
3594                let mut a = "a";
3595                let mut this = "this bound";
3596                let mut note = None;
3597                let mut help = None;
3598                if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() {
3599                    match clause {
3600                        ty::ClauseKind::Trait(trait_pred) => {
3601                            let def_id = trait_pred.def_id();
3602                            let visible_item = if let Some(local) = def_id.as_local() {
3603                                let ty = trait_pred.self_ty();
3604                                // when `TraitA: TraitB` and `S` only impl TraitA,
3605                                // we check if `TraitB` can be reachable from `S`
3606                                // to determine whether to note `TraitA` is sealed trait.
3607                                if let ty::Adt(adt, _) = ty.kind() {
3608                                    let visibilities = &tcx.resolutions(()).effective_visibilities;
3609                                    visibilities.effective_vis(local).is_none_or(|v| {
3610                                        v.at_level(Level::Reexported)
3611                                            .is_accessible_from(adt.did(), tcx)
3612                                    })
3613                                } else {
3614                                    // FIXME(xizheyin): if the type is not ADT, we should not suggest it
3615                                    true
3616                                }
3617                            } else {
3618                                // Check for foreign traits being reachable.
3619                                tcx.visible_parent_map(()).get(&def_id).is_some()
3620                            };
3621                            if tcx.is_lang_item(def_id, LangItem::Sized) {
3622                                // Check if this is an implicit bound, even in foreign crates.
3623                                if tcx
3624                                    .generics_of(item_def_id)
3625                                    .own_params
3626                                    .iter()
3627                                    .any(|param| tcx.def_span(param.def_id) == span)
3628                                {
3629                                    a = "an implicit `Sized`";
3630                                    this =
3631                                        "the implicit `Sized` requirement on this type parameter";
3632                                }
3633                                if let Some(hir::Node::TraitItem(hir::TraitItem {
3634                                    generics,
3635                                    kind: hir::TraitItemKind::Type(bounds, None),
3636                                    ..
3637                                })) = tcx.hir_get_if_local(item_def_id)
3638                                    // Do not suggest relaxing if there is an explicit `Sized` obligation.
3639                                    && !bounds.iter()
3640                                        .filter_map(|bound| bound.trait_ref())
3641                                        .any(|tr| tr.trait_def_id().is_some_and(|def_id| tcx.is_lang_item(def_id, LangItem::Sized)))
3642                                {
3643                                    let (span, separator) = if let [.., last] = bounds {
3644                                        (last.span().shrink_to_hi(), " +")
3645                                    } else {
3646                                        (generics.span.shrink_to_hi(), ":")
3647                                    };
3648                                    err.span_suggestion_verbose(
3649                                        span,
3650                                        "consider relaxing the implicit `Sized` restriction",
3651                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ?Sized", separator))
    })format!("{separator} ?Sized"),
3652                                        Applicability::MachineApplicable,
3653                                    );
3654                                }
3655                            }
3656                            if let DefKind::Trait = tcx.def_kind(item_def_id)
3657                                && !visible_item
3658                            {
3659                                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!(
3660                                    "`{short_item_name}` is a \"sealed trait\", because to implement it \
3661                                    you also need to implement `{}`, which is not accessible; this is \
3662                                    usually done to force you to use one of the provided types that \
3663                                    already implement it",
3664                                    with_no_trimmed_paths!(tcx.def_path_str(def_id)),
3665                                ));
3666                                let mut types = tcx
3667                                    .all_impls(def_id)
3668                                    .map(|t| {
3669                                        {
    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!(
3670                                            "  {}",
3671                                            tcx.type_of(t).instantiate_identity().skip_norm_wip(),
3672                                        ))
3673                                    })
3674                                    .collect::<Vec<_>>();
3675                                if !types.is_empty() {
3676                                    let len = types.len();
3677                                    let post = if len > 9 {
3678                                        types.truncate(8);
3679                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\nand {0} others", len - 8))
    })format!("\nand {} others", len - 8)
3680                                    } else {
3681                                        String::new()
3682                                    };
3683                                    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!(
3684                                        "the following type{} implement{} the trait:\n{}{post}",
3685                                        pluralize!(len),
3686                                        if len == 1 { "s" } else { "" },
3687                                        types.join("\n"),
3688                                    ));
3689                                }
3690                            }
3691                        }
3692                        ty::ClauseKind::ConstArgHasType(..) => {
3693                            let descr =
3694                                ::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}`");
3695                            if span.is_visible(sm) {
3696                                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required by this const generic parameter in `{0}`",
                short_item_name))
    })format!(
3697                                    "required by this const generic parameter in `{short_item_name}`"
3698                                );
3699                                multispan.push_span_label(span, msg);
3700                                err.span_note(multispan, descr);
3701                            } else {
3702                                err.span_note(tcx.def_span(item_def_id), descr);
3703                            }
3704                            return;
3705                        }
3706                        _ => (),
3707                    }
3708                }
3709
3710                // If this is from a format string literal desugaring,
3711                // we've already said "required by this formatting parameter"
3712                let is_in_fmt_lit = if let Some(s) = err.span.primary_span() {
3713                    #[allow(non_exhaustive_omitted_patterns)] match s.desugaring_kind() {
    Some(DesugaringKind::FormatLiteral { .. }) => true,
    _ => false,
}matches!(s.desugaring_kind(), Some(DesugaringKind::FormatLiteral { .. }))
3714                } else {
3715                    false
3716                };
3717                if !is_in_fmt_lit {
3718                    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}`");
3719                    if span.is_visible(sm) {
3720                        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}`");
3721                        multispan.push_span_label(span, msg);
3722                        err.span_note(multispan, descr);
3723                    } else {
3724                        err.span_note(tcx.def_span(item_def_id), descr);
3725                    }
3726                }
3727                if let Some(note) = note {
3728                    err.note(note);
3729                }
3730                if let Some(help) = help {
3731                    err.help(help);
3732                }
3733            }
3734            ObligationCauseCode::WhereClause(..)
3735            | ObligationCauseCode::WhereClauseInExpr(..)
3736            | ObligationCauseCode::HostEffectInExpr(..) => {
3737                // We hold the `DefId` of the item introducing the obligation, but displaying it
3738                // doesn't add user usable information. It always point at an associated item.
3739            }
3740            ObligationCauseCode::OpaqueTypeBound(span, definition_def_id) => {
3741                err.span_note(span, "required by a bound in an opaque type");
3742                if let Some(definition_def_id) = definition_def_id
3743                    // If there are any stalled coroutine obligations, then this
3744                    // error may be due to that, and not because the body has more
3745                    // where-clauses.
3746                    && self.tcx.typeck(definition_def_id).coroutine_stalled_predicates.is_empty()
3747                {
3748                    // FIXME(compiler-errors): We could probably point to something
3749                    // specific here if we tried hard enough...
3750                    err.span_note(
3751                        tcx.def_span(definition_def_id),
3752                        "this definition site has more where clauses than the opaque type",
3753                    );
3754                }
3755            }
3756            ObligationCauseCode::Coercion { source, target } => {
3757                let source =
3758                    tcx.short_string(self.resolve_vars_if_possible(source), err.long_ty_path());
3759                let target =
3760                    tcx.short_string(self.resolve_vars_if_possible(target), err.long_ty_path());
3761                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!(
3762                    "required for the cast from `{source}` to `{target}`",
3763                )));
3764            }
3765            ObligationCauseCode::RepeatElementCopy { is_constable, elt_span } => {
3766                err.note(
3767                    "the `Copy` trait is required because this value will be copied for each element of the array",
3768                );
3769                let sm = tcx.sess.source_map();
3770                if #[allow(non_exhaustive_omitted_patterns)] match is_constable {
    IsConstable::Fn | IsConstable::Ctor => true,
    _ => false,
}matches!(is_constable, IsConstable::Fn | IsConstable::Ctor)
3771                    && let Ok(_) = sm.span_to_snippet(elt_span)
3772                {
3773                    err.multipart_suggestion(
3774                        "create an inline `const` block",
3775                        ::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![
3776                            (elt_span.shrink_to_lo(), "const { ".to_string()),
3777                            (elt_span.shrink_to_hi(), " }".to_string()),
3778                        ],
3779                        Applicability::MachineApplicable,
3780                    );
3781                } else {
3782                    // FIXME: we may suggest array::repeat instead
3783                    err.help("consider using `core::array::from_fn` to initialize the array");
3784                    err.help("see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html for more information");
3785                }
3786            }
3787            ObligationCauseCode::VariableType(hir_id) => {
3788                if let Some(typeck_results) = &self.typeck_results
3789                    && let Some(ty) = typeck_results.node_type_opt(hir_id)
3790                    && let ty::Error(_) = ty.kind()
3791                {
3792                    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!(
3793                        "`{predicate}` isn't satisfied, but the type of this pattern is \
3794                         `{{type error}}`",
3795                    ));
3796                    err.downgrade_to_delayed_bug();
3797                }
3798                let mut local = true;
3799                match tcx.parent_hir_node(hir_id) {
3800                    Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }) => {
3801                        err.span_suggestion_verbose(
3802                            ty.span.shrink_to_lo(),
3803                            "consider borrowing here",
3804                            "&",
3805                            Applicability::MachineApplicable,
3806                        );
3807                    }
3808                    Node::LetStmt(hir::LetStmt {
3809                        init: Some(hir::Expr { kind: hir::ExprKind::Index(..), span, .. }),
3810                        ..
3811                    }) => {
3812                        // When encountering an assignment of an unsized trait, like
3813                        // `let x = ""[..];`, provide a suggestion to borrow the initializer in
3814                        // order to use have a slice instead.
3815                        err.span_suggestion_verbose(
3816                            span.shrink_to_lo(),
3817                            "consider borrowing here",
3818                            "&",
3819                            Applicability::MachineApplicable,
3820                        );
3821                    }
3822                    Node::LetStmt(hir::LetStmt { init: Some(expr), .. }) => {
3823                        // When encountering an assignment of an unsized trait, like `let x = *"";`,
3824                        // we check if the RHS is a deref operation, to suggest removing it.
3825                        suggest_remove_deref(err, &expr);
3826                    }
3827                    Node::Param(param) => {
3828                        err.span_suggestion_verbose(
3829                            param.ty_span.shrink_to_lo(),
3830                            "function arguments must have a statically known size, borrowed types \
3831                            always have a known size",
3832                            "&",
3833                            Applicability::MachineApplicable,
3834                        );
3835                        local = false;
3836                    }
3837                    _ => {}
3838                }
3839                if local {
3840                    err.note("all local variables must have a statically known size");
3841                }
3842            }
3843            ObligationCauseCode::SizedArgumentType(hir_id) => {
3844                let mut ty = None;
3845                let borrowed_msg = "function arguments must have a statically known size, borrowed \
3846                                    types always have a known size";
3847                if let Some(hir_id) = hir_id
3848                    && let hir::Node::Param(param) = self.tcx.hir_node(hir_id)
3849                    && let Some(decl) = self.tcx.parent_hir_node(hir_id).fn_decl()
3850                    && let Some(t) = decl.inputs.iter().find(|t| param.ty_span.contains(t.span))
3851                {
3852                    // We use `contains` because the type might be surrounded by parentheses,
3853                    // which makes `ty_span` and `t.span` disagree with each other, but one
3854                    // fully contains the other: `foo: (dyn Foo + Bar)`
3855                    //                                 ^-------------^
3856                    //                                 ||
3857                    //                                 |t.span
3858                    //                                 param._ty_span
3859                    ty = Some(t);
3860                } else if let Some(hir_id) = hir_id
3861                    && let hir::Node::Ty(t) = self.tcx.hir_node(hir_id)
3862                {
3863                    ty = Some(t);
3864                }
3865                if let Some(ty) = ty {
3866                    match ty.kind {
3867                        hir::TyKind::TraitObject(traits, _) => {
3868                            let (span, kw) = match traits {
3869                                [first, ..] if first.span.lo() == ty.span.lo() => {
3870                                    // Missing `dyn` in front of trait object.
3871                                    (ty.span.shrink_to_lo(), "dyn ")
3872                                }
3873                                [first, ..] => (ty.span.until(first.span), ""),
3874                                [] => ::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:?}"),
3875                            };
3876                            let needs_parens = traits.len() != 1;
3877                            // Don't recommend impl Trait as a closure argument
3878                            if let Some(hir_id) = hir_id
3879                                && #[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!(
3880                                    self.tcx.parent_hir_node(hir_id),
3881                                    hir::Node::Item(hir::Item {
3882                                        kind: hir::ItemKind::Fn { .. },
3883                                        ..
3884                                    })
3885                                )
3886                            {
3887                                err.span_suggestion_verbose(
3888                                    span,
3889                                    "you can use `impl Trait` as the argument type",
3890                                    "impl ",
3891                                    Applicability::MaybeIncorrect,
3892                                );
3893                            }
3894                            let sugg = if !needs_parens {
3895                                ::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}"))]
3896                            } else {
3897                                ::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![
3898                                    (span.shrink_to_lo(), format!("&({kw}")),
3899                                    (ty.span.shrink_to_hi(), ")".to_string()),
3900                                ]
3901                            };
3902                            err.multipart_suggestion(
3903                                borrowed_msg,
3904                                sugg,
3905                                Applicability::MachineApplicable,
3906                            );
3907                        }
3908                        hir::TyKind::Slice(_ty) => {
3909                            err.span_suggestion_verbose(
3910                                ty.span.shrink_to_lo(),
3911                                "function arguments must have a statically known size, borrowed \
3912                                 slices always have a known size",
3913                                "&",
3914                                Applicability::MachineApplicable,
3915                            );
3916                        }
3917                        hir::TyKind::Path(_) => {
3918                            err.span_suggestion_verbose(
3919                                ty.span.shrink_to_lo(),
3920                                borrowed_msg,
3921                                "&",
3922                                Applicability::MachineApplicable,
3923                            );
3924                        }
3925                        _ => {}
3926                    }
3927                } else {
3928                    err.note("all function arguments must have a statically known size");
3929                }
3930                if tcx.sess.opts.unstable_features.is_nightly_build()
3931                    && !tcx.features().unsized_fn_params()
3932                {
3933                    err.help("unsized fn params are gated as an unstable feature");
3934                }
3935            }
3936            ObligationCauseCode::SizedReturnType | ObligationCauseCode::SizedCallReturnType => {
3937                err.note("the return type of a function must have a statically known size");
3938            }
3939            ObligationCauseCode::SizedYieldType => {
3940                err.note("the yield type of a coroutine must have a statically known size");
3941            }
3942            ObligationCauseCode::AssignmentLhsSized => {
3943                err.note("the left-hand-side of an assignment must have a statically known size");
3944            }
3945            ObligationCauseCode::TupleInitializerSized => {
3946                err.note("tuples must have a statically known size to be initialized");
3947            }
3948            ObligationCauseCode::StructInitializerSized => {
3949                err.note("structs must have a statically known size to be initialized");
3950            }
3951            ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
3952                match *item {
3953                    AdtKind::Struct => {
3954                        if last {
3955                            err.note(
3956                                "the last field of a packed struct may only have a \
3957                                dynamically sized type if it does not need drop to be run",
3958                            );
3959                        } else {
3960                            err.note(
3961                                "only the last field of a struct may have a dynamically sized type",
3962                            );
3963                        }
3964                    }
3965                    AdtKind::Union => {
3966                        err.note("no field of a union may have a dynamically sized type");
3967                    }
3968                    AdtKind::Enum => {
3969                        err.note("no field of an enum variant may have a dynamically sized type");
3970                    }
3971                }
3972                err.help("change the field's type to have a statically known size");
3973                err.span_suggestion_verbose(
3974                    span.shrink_to_lo(),
3975                    "borrowed types always have a statically known size",
3976                    "&",
3977                    Applicability::MachineApplicable,
3978                );
3979                err.multipart_suggestion(
3980                    "the `Box` type always has a statically known size and allocates its contents \
3981                     in the heap",
3982                    ::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![
3983                        (span.shrink_to_lo(), "Box<".to_string()),
3984                        (span.shrink_to_hi(), ">".to_string()),
3985                    ],
3986                    Applicability::MachineApplicable,
3987                );
3988            }
3989            ObligationCauseCode::SizedConstOrStatic => {
3990                err.note("statics and constants must have a statically known size");
3991            }
3992            ObligationCauseCode::InlineAsmSized => {
3993                err.note("all inline asm arguments must have a statically known size");
3994            }
3995            ObligationCauseCode::SizedClosureCapture(closure_def_id) => {
3996                err.note(
3997                    "all values captured by value by a closure must have a statically known size",
3998                );
3999                let hir::ExprKind::Closure(closure) =
4000                    tcx.hir_node_by_def_id(closure_def_id).expect_expr().kind
4001                else {
4002                    ::rustc_middle::util::bug::bug_fmt(format_args!("expected closure in SizedClosureCapture obligation"));bug!("expected closure in SizedClosureCapture obligation");
4003                };
4004                if let hir::CaptureBy::Value { .. } = closure.capture_clause
4005                    && let Some(span) = closure.fn_arg_span
4006                {
4007                    err.span_label(span, "this closure captures all values by move");
4008                }
4009            }
4010            ObligationCauseCode::SizedCoroutineInterior(coroutine_def_id) => {
4011                let what = match tcx.coroutine_kind(coroutine_def_id) {
4012                    None
4013                    | Some(hir::CoroutineKind::Coroutine(_))
4014                    | Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)) => {
4015                        "yield"
4016                    }
4017                    Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
4018                        "await"
4019                    }
4020                    Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => {
4021                        "yield`/`await"
4022                    }
4023                };
4024                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("all values live across `{0}` must have a statically known size",
                what))
    })format!(
4025                    "all values live across `{what}` must have a statically known size"
4026                ));
4027            }
4028            ObligationCauseCode::SharedStatic => {
4029                err.note("shared static variables must have a type that implements `Sync`");
4030            }
4031            ObligationCauseCode::BuiltinDerived(ref data) => {
4032                let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
4033                let ty = parent_trait_ref.skip_binder().self_ty();
4034                if parent_trait_ref.references_error() {
4035                    // NOTE(eddyb) this was `.cancel()`, but `err`
4036                    // is borrowed, so we can't fully defuse it.
4037                    err.downgrade_to_delayed_bug();
4038                    return;
4039                }
4040
4041                // If the obligation for a tuple is set directly by a Coroutine or Closure,
4042                // then the tuple must be the one containing capture types.
4043                let is_upvar_tys_infer_tuple = if !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Tuple(..) => true,
    _ => false,
}matches!(ty.kind(), ty::Tuple(..)) {
4044                    false
4045                } else if let ObligationCauseCode::BuiltinDerived(data) = &*data.parent_code {
4046                    let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
4047                    let nested_ty = parent_trait_ref.skip_binder().self_ty();
4048                    #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
    ty::Coroutine(..) => true,
    _ => false,
}matches!(nested_ty.kind(), ty::Coroutine(..))
4049                        || #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
    ty::Closure(..) => true,
    _ => false,
}matches!(nested_ty.kind(), ty::Closure(..))
4050                } else {
4051                    false
4052                };
4053
4054                let is_builtin_async_fn_trait =
4055                    tcx.async_fn_trait_kind_from_def_id(data.parent_trait_pred.def_id()).is_some();
4056
4057                if !is_upvar_tys_infer_tuple && !is_builtin_async_fn_trait {
4058                    let mut msg = || {
4059                        let ty_str = tcx.short_string(ty, err.long_ty_path());
4060                        ::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}`")
4061                    };
4062                    match *ty.kind() {
4063                        ty::Adt(def, _) => {
4064                            let msg = msg();
4065                            match tcx.opt_item_ident(def.did()) {
4066                                Some(ident) => {
4067                                    err.span_note(ident.span, msg);
4068                                }
4069                                None => {
4070                                    err.note(msg);
4071                                }
4072                            }
4073                        }
4074                        ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) => {
4075                            // If the previous type is async fn, this is the future generated by the body of an async function.
4076                            // Avoid printing it twice (it was already printed in the `ty::Coroutine` arm below).
4077                            let is_future = tcx.ty_is_opaque_future(ty);
4078                            {
    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:4078",
                        "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(4078u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("obligated_types")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("obligated_types");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("is_future")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("is_future");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("note_obligation_cause_code: check for async fn")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligated_types)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&is_future)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
4079                                ?obligated_types,
4080                                ?is_future,
4081                                "note_obligation_cause_code: check for async fn"
4082                            );
4083                            if is_future
4084                                && obligated_types.last().is_some_and(|ty| match ty.kind() {
4085                                    ty::Coroutine(last_def_id, ..) => {
4086                                        tcx.coroutine_is_async(*last_def_id)
4087                                    }
4088                                    _ => false,
4089                                })
4090                            {
4091                                // See comment above; skip printing twice.
4092                            } else {
4093                                let msg = msg();
4094                                err.span_note(tcx.def_span(def_id), msg);
4095                            }
4096                        }
4097                        ty::Coroutine(def_id, _) => {
4098                            let sp = tcx.def_span(def_id);
4099
4100                            // Special-case this to say "async block" instead of `[static coroutine]`.
4101                            let kind = tcx.coroutine_kind(def_id).unwrap();
4102                            err.span_note(
4103                                sp,
4104                                {
    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!(
4105                                    "required because it's used within this {kind:#}",
4106                                )),
4107                            );
4108                        }
4109                        ty::CoroutineWitness(..) => {
4110                            // Skip printing coroutine-witnesses, since we'll drill into
4111                            // the bad field in another derived obligation cause.
4112                        }
4113                        ty::Closure(def_id, _) | ty::CoroutineClosure(def_id, _) => {
4114                            err.span_note(
4115                                tcx.def_span(def_id),
4116                                "required because it's used within this closure",
4117                            );
4118                        }
4119                        ty::Str => {
4120                            err.note("`str` is considered to contain a `[u8]` slice for auto trait purposes");
4121                        }
4122                        _ => {
4123                            let msg = msg();
4124                            err.note(msg);
4125                        }
4126                    };
4127                }
4128
4129                obligated_types.push(ty);
4130
4131                let parent_predicate = parent_trait_ref;
4132                if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
4133                    // #74711: avoid a stack overflow
4134                    ensure_sufficient_stack(|| {
4135                        self.note_obligation_cause_code(
4136                            body_def_id,
4137                            err,
4138                            parent_predicate,
4139                            param_env,
4140                            &data.parent_code,
4141                            obligated_types,
4142                            seen_requirements,
4143                        )
4144                    });
4145                } else {
4146                    ensure_sufficient_stack(|| {
4147                        self.note_obligation_cause_code(
4148                            body_def_id,
4149                            err,
4150                            parent_predicate,
4151                            param_env,
4152                            cause_code.peel_derives(),
4153                            obligated_types,
4154                            seen_requirements,
4155                        )
4156                    });
4157                }
4158            }
4159            ObligationCauseCode::ImplDerived(ref data) => {
4160                let mut parent_trait_pred =
4161                    self.resolve_vars_if_possible(data.derived.parent_trait_pred);
4162                let parent_def_id = parent_trait_pred.def_id();
4163                if tcx.is_diagnostic_item(sym::FromResidual, parent_def_id)
4164                    && !tcx.features().enabled(sym::try_trait_v2)
4165                {
4166                    // If `#![feature(try_trait_v2)]` is not enabled, then there's no point on
4167                    // talking about `FromResidual<Result<A, B>>`, as the end user has nothing they
4168                    // can do about it. As far as they are concerned, `?` is compiler magic.
4169                    return;
4170                }
4171                if tcx.is_diagnostic_item(sym::PinDerefMutHelper, parent_def_id) {
4172                    let parent_predicate =
4173                        self.resolve_vars_if_possible(data.derived.parent_trait_pred);
4174
4175                    // Skip PinDerefMutHelper in suggestions, but still show downstream suggestions.
4176                    ensure_sufficient_stack(|| {
4177                        self.note_obligation_cause_code(
4178                            body_def_id,
4179                            err,
4180                            parent_predicate,
4181                            param_env,
4182                            &data.derived.parent_code,
4183                            obligated_types,
4184                            seen_requirements,
4185                        )
4186                    });
4187                    return;
4188                }
4189                let self_ty_str =
4190                    tcx.short_string(parent_trait_pred.skip_binder().self_ty(), err.long_ty_path());
4191                let trait_name = tcx.short_string(
4192                    parent_trait_pred.print_modifiers_and_trait_path(),
4193                    err.long_ty_path(),
4194                );
4195                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}`");
4196                let mut is_auto_trait = false;
4197                match tcx.hir_get_if_local(data.impl_or_alias_def_id) {
4198                    Some(Node::Item(hir::Item {
4199                        kind: hir::ItemKind::Trait { is_auto, ident, .. },
4200                        ..
4201                    })) => {
4202                        // FIXME: we should do something else so that it works even on crate foreign
4203                        // auto traits.
4204                        is_auto_trait = #[allow(non_exhaustive_omitted_patterns)] match is_auto {
    hir::IsAuto::Yes => true,
    _ => false,
}matches!(is_auto, hir::IsAuto::Yes);
4205                        err.span_note(ident.span, msg);
4206                    }
4207                    Some(Node::Item(hir::Item {
4208                        kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, generics, .. }),
4209                        ..
4210                    })) => {
4211                        let mut spans = Vec::with_capacity(2);
4212                        if let Some(of_trait) = of_trait
4213                            && !of_trait.trait_ref.path.span.in_derive_expansion()
4214                        {
4215                            spans.push(of_trait.trait_ref.path.span);
4216                        }
4217                        spans.push(self_ty.span);
4218                        let mut spans: MultiSpan = spans.into();
4219                        let mut derived = false;
4220                        if #[allow(non_exhaustive_omitted_patterns)] match self_ty.span.ctxt().outer_expn_data().kind
    {
    ExpnKind::Macro(MacroKind::Derive, _) => true,
    _ => false,
}matches!(
4221                            self_ty.span.ctxt().outer_expn_data().kind,
4222                            ExpnKind::Macro(MacroKind::Derive, _)
4223                        ) || #[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!(
4224                            of_trait.map(|t| t.trait_ref.path.span.ctxt().outer_expn_data().kind),
4225                            Some(ExpnKind::Macro(MacroKind::Derive, _))
4226                        ) {
4227                            derived = true;
4228                            spans.push_span_label(
4229                                data.span,
4230                                if data.span.in_derive_expansion() {
4231                                    ::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}`")
4232                                } else {
4233                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unsatisfied trait bound"))
    })format!("unsatisfied trait bound")
4234                                },
4235                            );
4236                        } else if !data.span.is_dummy() && !data.span.overlaps(self_ty.span) {
4237                            // `Sized` may be an explicit or implicit trait bound. If it is
4238                            // implicit, mention it as such.
4239                            if let Some(pred) = predicate.as_trait_clause()
4240                                && self.tcx.is_lang_item(pred.def_id(), LangItem::Sized)
4241                                && self
4242                                    .tcx
4243                                    .generics_of(data.impl_or_alias_def_id)
4244                                    .own_params
4245                                    .iter()
4246                                    .any(|param| self.tcx.def_span(param.def_id) == data.span)
4247                            {
4248                                spans.push_span_label(
4249                                    data.span,
4250                                    "unsatisfied trait bound implicitly introduced here",
4251                                );
4252                            } else {
4253                                spans.push_span_label(
4254                                    data.span,
4255                                    "unsatisfied trait bound introduced here",
4256                                );
4257                            }
4258                        }
4259                        err.span_note(spans, msg);
4260                        if derived && trait_name != "Copy" {
4261                            err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider manually implementing `{0}` to avoid undesired bounds caused by \"imperfect derives\"",
                trait_name))
    })format!(
4262                                "consider manually implementing `{trait_name}` to avoid undesired bounds caused by \"imperfect derives\"",
4263                            ));
4264                            err.note(
4265                                "to learn more, visit <https://github.com/rust-lang/rust/issues/26925>",
4266                            );
4267                        }
4268                        point_at_assoc_type_restriction(
4269                            tcx,
4270                            err,
4271                            &self_ty_str,
4272                            &trait_name,
4273                            predicate,
4274                            &generics,
4275                            &data,
4276                        );
4277                    }
4278                    _ => {
4279                        err.note(msg);
4280                    }
4281                };
4282
4283                let mut parent_predicate = parent_trait_pred;
4284                let mut data = &data.derived;
4285                let mut count = 0;
4286                seen_requirements.insert(parent_def_id);
4287                if is_auto_trait {
4288                    // We don't want to point at the ADT saying "required because it appears within
4289                    // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
4290                    while let ObligationCauseCode::BuiltinDerived(derived) = &*data.parent_code {
4291                        let child_trait_ref =
4292                            self.resolve_vars_if_possible(derived.parent_trait_pred);
4293                        let child_def_id = child_trait_ref.def_id();
4294                        if seen_requirements.insert(child_def_id) {
4295                            break;
4296                        }
4297                        data = derived;
4298                        parent_predicate = child_trait_ref.upcast(tcx);
4299                        parent_trait_pred = child_trait_ref;
4300                    }
4301                }
4302                while let ObligationCauseCode::ImplDerived(child) = &*data.parent_code {
4303                    // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
4304                    let child_trait_pred =
4305                        self.resolve_vars_if_possible(child.derived.parent_trait_pred);
4306                    let child_def_id = child_trait_pred.def_id();
4307                    if seen_requirements.insert(child_def_id) {
4308                        break;
4309                    }
4310                    count += 1;
4311                    data = &child.derived;
4312                    parent_predicate = child_trait_pred.upcast(tcx);
4313                    parent_trait_pred = child_trait_pred;
4314                }
4315                if count > 0 {
4316                    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} redundant requirement{1} hidden",
                count, if count == 1 { "" } else { "s" }))
    })format!(
4317                        "{} redundant requirement{} hidden",
4318                        count,
4319                        pluralize!(count)
4320                    ));
4321                    let self_ty = tcx.short_string(
4322                        parent_trait_pred.skip_binder().self_ty(),
4323                        err.long_ty_path(),
4324                    );
4325                    let trait_path = tcx.short_string(
4326                        parent_trait_pred.print_modifiers_and_trait_path(),
4327                        err.long_ty_path(),
4328                    );
4329                    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}`"));
4330                }
4331                // #74711: avoid a stack overflow
4332                ensure_sufficient_stack(|| {
4333                    self.note_obligation_cause_code(
4334                        body_def_id,
4335                        err,
4336                        parent_predicate,
4337                        param_env,
4338                        &data.parent_code,
4339                        obligated_types,
4340                        seen_requirements,
4341                    )
4342                });
4343            }
4344            ObligationCauseCode::ImplDerivedHost(ref data) => {
4345                let self_ty = tcx.short_string(
4346                    self.resolve_vars_if_possible(data.derived.parent_host_pred.self_ty()),
4347                    err.long_ty_path(),
4348                );
4349                let trait_path = tcx.short_string(
4350                    data.derived
4351                        .parent_host_pred
4352                        .map_bound(|pred| pred.trait_ref)
4353                        .print_only_trait_path(),
4354                    err.long_ty_path(),
4355                );
4356                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!(
4357                    "required for `{self_ty}` to implement `{} {trait_path}`",
4358                    data.derived.parent_host_pred.skip_binder().constness,
4359                );
4360                match tcx.hir_get_if_local(data.impl_def_id) {
4361                    Some(Node::Item(hir::Item {
4362                        kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
4363                        ..
4364                    })) => {
4365                        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];
4366                        spans.extend(of_trait.map(|t| t.trait_ref.path.span));
4367                        let mut spans: MultiSpan = spans.into();
4368                        spans.push_span_label(data.span, "unsatisfied trait bound introduced here");
4369                        err.span_note(spans, msg);
4370                    }
4371                    _ => {
4372                        err.note(msg);
4373                    }
4374                }
4375                ensure_sufficient_stack(|| {
4376                    self.note_obligation_cause_code(
4377                        body_def_id,
4378                        err,
4379                        data.derived.parent_host_pred,
4380                        param_env,
4381                        &data.derived.parent_code,
4382                        obligated_types,
4383                        seen_requirements,
4384                    )
4385                });
4386            }
4387            ObligationCauseCode::BuiltinDerivedHost(ref data) => {
4388                ensure_sufficient_stack(|| {
4389                    self.note_obligation_cause_code(
4390                        body_def_id,
4391                        err,
4392                        data.parent_host_pred,
4393                        param_env,
4394                        &data.parent_code,
4395                        obligated_types,
4396                        seen_requirements,
4397                    )
4398                });
4399            }
4400            ObligationCauseCode::WellFormedDerived(ref data) => {
4401                let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
4402                let parent_predicate = parent_trait_ref;
4403                // #74711: avoid a stack overflow
4404                ensure_sufficient_stack(|| {
4405                    self.note_obligation_cause_code(
4406                        body_def_id,
4407                        err,
4408                        parent_predicate,
4409                        param_env,
4410                        &data.parent_code,
4411                        obligated_types,
4412                        seen_requirements,
4413                    )
4414                });
4415            }
4416            ObligationCauseCode::TypeAlias(ref nested, span, def_id) => {
4417                // #74711: avoid a stack overflow
4418                ensure_sufficient_stack(|| {
4419                    self.note_obligation_cause_code(
4420                        body_def_id,
4421                        err,
4422                        predicate,
4423                        param_env,
4424                        nested,
4425                        obligated_types,
4426                        seen_requirements,
4427                    )
4428                });
4429                let mut multispan = MultiSpan::from(span);
4430                multispan.push_span_label(span, "required by this bound");
4431                err.span_note(
4432                    multispan,
4433                    ::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)),
4434                );
4435            }
4436            ObligationCauseCode::FunctionArg {
4437                arg_hir_id, call_hir_id, ref parent_code, ..
4438            } => {
4439                self.note_function_argument_obligation(
4440                    body_def_id,
4441                    err,
4442                    arg_hir_id,
4443                    parent_code,
4444                    param_env,
4445                    predicate,
4446                    call_hir_id,
4447                );
4448                ensure_sufficient_stack(|| {
4449                    self.note_obligation_cause_code(
4450                        body_def_id,
4451                        err,
4452                        predicate,
4453                        param_env,
4454                        parent_code,
4455                        obligated_types,
4456                        seen_requirements,
4457                    )
4458                });
4459            }
4460            // Suppress `compare_type_predicate_entailment` errors for RPITITs, since they
4461            // should be implied by the parent method.
4462            ObligationCauseCode::CompareImplItem { trait_item_def_id, .. }
4463                if tcx.is_impl_trait_in_trait(trait_item_def_id) => {}
4464            ObligationCauseCode::CompareImplItem { trait_item_def_id, kind, .. } => {
4465                let item_name = tcx.item_name(trait_item_def_id);
4466                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!(
4467                    "the requirement `{predicate}` appears on the `impl`'s {kind} \
4468                     `{item_name}` but not on the corresponding trait's {kind}",
4469                );
4470                let sp = tcx
4471                    .opt_item_ident(trait_item_def_id)
4472                    .map(|i| i.span)
4473                    .unwrap_or_else(|| tcx.def_span(trait_item_def_id));
4474                let mut assoc_span: MultiSpan = sp.into();
4475                assoc_span.push_span_label(
4476                    sp,
4477                    ::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}`"),
4478                );
4479                if let Some(ident) = tcx
4480                    .opt_associated_item(trait_item_def_id)
4481                    .and_then(|i| tcx.opt_item_ident(i.container_id(tcx)))
4482                {
4483                    assoc_span.push_span_label(ident.span, "in this trait");
4484                }
4485                err.span_note(assoc_span, msg);
4486            }
4487            ObligationCauseCode::TrivialBound => {
4488                tcx.disabled_nightly_features(err, [(String::new(), sym::trivial_bounds)]);
4489            }
4490            ObligationCauseCode::OpaqueReturnType(expr_info) => {
4491                // Point at the method call in the returned expression's chain where an
4492                // associated type diverged from what the signature's opaque type expects,
4493                // regardless of how the failed predicate was derived from that expectation.
4494                if let Some(typeck_results) = self.typeck_results.as_deref() {
4495                    let chain_expr = match expr_info {
4496                        Some((_, hir_id)) => Some(tcx.hir_expect_expr(hir_id)),
4497                        None => tcx.hir_node_by_def_id(body_def_id).body_id().and_then(|body_id| {
4498                            match tcx.hir_body(body_id).value.kind {
4499                                hir::ExprKind::Block(block, _) => block.expr,
4500                                _ => None,
4501                            }
4502                        }),
4503                    };
4504                    if let Some(chain_expr) = chain_expr {
4505                        self.point_at_chain_in_return_position(
4506                            body_def_id,
4507                            chain_expr,
4508                            typeck_results,
4509                            param_env,
4510                            err,
4511                        );
4512                    }
4513                }
4514                let (expr_ty, expr) = if let Some((expr_ty, hir_id)) = expr_info {
4515                    let expr = tcx.hir_expect_expr(hir_id);
4516                    (expr_ty, expr)
4517                } else if let Some(body_id) = tcx.hir_node_by_def_id(body_def_id).body_id()
4518                    && let body = tcx.hir_body(body_id)
4519                    && let hir::ExprKind::Block(block, _) = body.value.kind
4520                    && let Some(expr) = block.expr
4521                    && let Some(expr_ty) = self
4522                        .typeck_results
4523                        .as_ref()
4524                        .and_then(|typeck| typeck.node_type_opt(expr.hir_id))
4525                    && let Some(pred) = predicate.as_clause()
4526                    && let ty::ClauseKind::Trait(pred) = pred.kind().skip_binder()
4527                    && self.can_eq(param_env, pred.self_ty(), expr_ty)
4528                {
4529                    (expr_ty, expr)
4530                } else {
4531                    return;
4532                };
4533                let expr_ty_string = tcx.short_string(expr_ty, err.long_ty_path());
4534                if expr_ty.is_never()
4535                    && let span = expr.span.source_callsite()
4536                    && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(span)
4537                    && span != expr.span
4538                {
4539                    err.span_suggestion(
4540                        span,
4541                        "`!` can be coerced to any type; consider casting it to a concrete type that implements the trait",
4542                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} as /* Type */", snippet))
    })format!("{snippet} as /* Type */"),
4543                        Applicability::HasPlaceholders,
4544                    );
4545                }
4546                err.span_label(
4547                    expr.span,
4548                    {
    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!(
4549                        "return type was inferred to be `{expr_ty_string}` here",
4550                    )),
4551                );
4552                suggest_remove_deref(err, &expr);
4553            }
4554            ObligationCauseCode::UnsizedNonPlaceExpr(span) => {
4555                err.span_note(
4556                    span,
4557                    "unsized values must be place expressions and cannot be put in temporaries",
4558                );
4559            }
4560            ObligationCauseCode::CompareEii { .. } => {
4561                {
    ::core::panicking::panic_fmt(format_args!("trait bounds on EII not yet supported "));
}panic!("trait bounds on EII not yet supported ")
4562            }
4563        }
4564    }
4565
4566    #[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(4566u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("obligation")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("obligation");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_pred")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_pred");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_pred.self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_pred.self_ty");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_pred)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_pred.self_ty())
                                                            as &dyn ::tracing::field::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:4603",
                                    "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(4603u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("normalized_projection_type")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("normalized_projection_type");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.resolve_vars_if_possible(projection_ty))
                                                        as &dyn ::tracing::field::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:4610",
                                    "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(4610u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("try_trait_obligation")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("try_trait_obligation");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&try_obligation)
                                                        as &dyn ::tracing::field::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(
4567        level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
4568    )]
4569    pub(super) fn suggest_await_before_try(
4570        &self,
4571        err: &mut Diag<'_>,
4572        obligation: &PredicateObligation<'tcx>,
4573        trait_pred: ty::PolyTraitPredicate<'tcx>,
4574        span: Span,
4575    ) {
4576        let future_trait = self.tcx.require_lang_item(LangItem::Future, span);
4577
4578        let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
4579        let impls_future = self.type_implements_trait(
4580            future_trait,
4581            [self.tcx.instantiate_bound_regions_with_erased(self_ty)],
4582            obligation.param_env,
4583        );
4584        if !impls_future.must_apply_modulo_regions() {
4585            return;
4586        }
4587
4588        let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
4589        // `<T as Future>::Output`
4590        let projection_ty = trait_pred.map_bound(|trait_pred| {
4591            Ty::new_projection(
4592                self.tcx,
4593                ty::IsRigid::No,
4594                item_def_id,
4595                // Future::Output has no args
4596                [trait_pred.self_ty()],
4597            )
4598        });
4599        let InferOk { value: projection_ty, .. } = self
4600            .at(&obligation.cause, obligation.param_env)
4601            .normalize(Unnormalized::new_wip(projection_ty));
4602
4603        debug!(
4604            normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
4605        );
4606        let try_obligation = self.mk_trait_obligation_with_new_self_ty(
4607            obligation.param_env,
4608            trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
4609        );
4610        debug!(try_trait_obligation = ?try_obligation);
4611        if self.predicate_may_hold(&try_obligation)
4612            && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
4613            && snippet.ends_with('?')
4614        {
4615            match self.tcx.coroutine_kind(obligation.cause.body_def_id) {
4616                Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
4617                    err.span_suggestion_verbose(
4618                        span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
4619                        "consider `await`ing on the `Future`",
4620                        ".await",
4621                        Applicability::MaybeIncorrect,
4622                    );
4623                }
4624                _ => {
4625                    let mut span: MultiSpan = span.with_lo(span.hi() - BytePos(1)).into();
4626                    span.push_span_label(
4627                        self.tcx.def_span(obligation.cause.body_def_id),
4628                        "this is not `async`",
4629                    );
4630                    err.span_note(
4631                        span,
4632                        "this implements `Future` and its output type supports \
4633                        `?`, but the future cannot be awaited in a synchronous function",
4634                    );
4635                }
4636            }
4637        }
4638    }
4639
4640    pub(super) fn suggest_floating_point_literal(
4641        &self,
4642        obligation: &PredicateObligation<'tcx>,
4643        err: &mut Diag<'_>,
4644        trait_pred: ty::PolyTraitPredicate<'tcx>,
4645    ) {
4646        let rhs_span = match obligation.cause.code() {
4647            ObligationCauseCode::BinOp { rhs_span, rhs_is_lit, .. } if *rhs_is_lit => rhs_span,
4648            _ => return,
4649        };
4650        if let ty::Float(_) = trait_pred.skip_binder().self_ty().kind()
4651            && let ty::Infer(InferTy::IntVar(_)) =
4652                trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
4653        {
4654            err.span_suggestion_verbose(
4655                rhs_span.shrink_to_hi(),
4656                "consider using a floating-point literal by writing it with `.0`",
4657                ".0",
4658                Applicability::MaybeIncorrect,
4659            );
4660        }
4661    }
4662
4663    pub fn can_suggest_derive(
4664        &self,
4665        obligation: &PredicateObligation<'tcx>,
4666        trait_pred: ty::PolyTraitPredicate<'tcx>,
4667    ) -> bool {
4668        if trait_pred.polarity() == ty::PredicatePolarity::Negative {
4669            return false;
4670        }
4671        let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
4672            return false;
4673        };
4674        let (adt, args) = match trait_pred.skip_binder().self_ty().kind() {
4675            ty::Adt(adt, args) if adt.did().is_local() => (adt, args),
4676            _ => return false,
4677        };
4678        let is_derivable_trait = match diagnostic_name {
4679            sym::Copy | sym::Clone => true,
4680            _ if adt.is_union() => false,
4681            sym::PartialEq | sym::PartialOrd => {
4682                let rhs_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
4683                trait_pred.skip_binder().self_ty() == rhs_ty
4684            }
4685            sym::Eq | sym::Ord | sym::Hash | sym::Debug | sym::Default => true,
4686            _ => false,
4687        };
4688        is_derivable_trait &&
4689            // Ensure all fields impl the trait.
4690            adt.all_fields().all(|field| {
4691                let field_ty = ty::GenericArg::from(field.ty(self.tcx, args).skip_norm_wip());
4692                let trait_args = match diagnostic_name {
4693                    sym::PartialEq | sym::PartialOrd => {
4694                        Some(field_ty)
4695                    }
4696                    _ => None,
4697                };
4698                let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
4699                    trait_ref: ty::TraitRef::new(self.tcx,
4700                        trait_pred.def_id(),
4701                        [field_ty].into_iter().chain(trait_args),
4702                    ),
4703                    ..*tr
4704                });
4705                let field_obl = Obligation::new(
4706                    self.tcx,
4707                    obligation.cause.clone(),
4708                    obligation.param_env,
4709                    trait_pred,
4710                );
4711                self.predicate_must_hold_modulo_regions(&field_obl)
4712            })
4713    }
4714
4715    pub fn suggest_derive(
4716        &self,
4717        obligation: &PredicateObligation<'tcx>,
4718        err: &mut Diag<'_>,
4719        trait_pred: ty::PolyTraitPredicate<'tcx>,
4720    ) {
4721        let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
4722            return;
4723        };
4724        let adt = match trait_pred.skip_binder().self_ty().kind() {
4725            ty::Adt(adt, _) if adt.did().is_local() => adt,
4726            _ => return,
4727        };
4728        if self.can_suggest_derive(obligation, trait_pred) {
4729            err.span_suggestion_verbose(
4730                self.tcx.def_span(adt.did()).shrink_to_lo(),
4731                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider annotating `{0}` with `#[derive({1})]`",
                trait_pred.skip_binder().self_ty(), diagnostic_name))
    })format!(
4732                    "consider annotating `{}` with `#[derive({})]`",
4733                    trait_pred.skip_binder().self_ty(),
4734                    diagnostic_name,
4735                ),
4736                // FIXME(const_trait_impl) derive_const as suggestion?
4737                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#[derive({0})]\n",
                diagnostic_name))
    })format!("#[derive({diagnostic_name})]\n"),
4738                Applicability::MaybeIncorrect,
4739            );
4740        }
4741    }
4742
4743    pub(super) fn suggest_dereferencing_index(
4744        &self,
4745        obligation: &PredicateObligation<'tcx>,
4746        err: &mut Diag<'_>,
4747        trait_pred: ty::PolyTraitPredicate<'tcx>,
4748    ) {
4749        if let ObligationCauseCode::ImplDerived(_) = obligation.cause.code()
4750            && self
4751                .tcx
4752                .is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
4753            && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
4754            && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
4755            && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
4756        {
4757            err.span_suggestion_verbose(
4758                obligation.cause.span.shrink_to_lo(),
4759                "dereference this index",
4760                '*',
4761                Applicability::MachineApplicable,
4762            );
4763        }
4764    }
4765
4766    fn note_function_argument_obligation<G: EmissionGuarantee>(
4767        &self,
4768        body_def_id: LocalDefId,
4769        err: &mut Diag<'_, G>,
4770        arg_hir_id: HirId,
4771        parent_code: &ObligationCauseCode<'tcx>,
4772        param_env: ty::ParamEnv<'tcx>,
4773        failed_pred: ty::Predicate<'tcx>,
4774        call_hir_id: HirId,
4775    ) {
4776        let tcx = self.tcx;
4777        if let Node::Expr(expr) = tcx.hir_node(arg_hir_id)
4778            && let Some(typeck_results) = &self.typeck_results
4779        {
4780            if let hir::Expr { kind: hir::ExprKind::MethodCall(_, rcvr, _, _), .. } = expr
4781                && let Some(ty) = typeck_results.node_type_opt(rcvr.hir_id)
4782                && let Some(failed_pred) = failed_pred.as_trait_clause()
4783                && let pred = failed_pred.map_bound(|pred| pred.with_replaced_self_ty(tcx, ty))
4784                && self.predicate_must_hold_modulo_regions(&Obligation::misc(
4785                    tcx,
4786                    expr.span,
4787                    body_def_id,
4788                    param_env,
4789                    pred,
4790                ))
4791                && expr.span.hi() != rcvr.span.hi()
4792            {
4793                let should_sugg = match tcx.hir_node(call_hir_id) {
4794                    Node::Expr(hir::Expr {
4795                        kind: hir::ExprKind::MethodCall(_, call_receiver, _, _),
4796                        ..
4797                    }) if let Some((DefKind::AssocFn, did)) =
4798                        typeck_results.type_dependent_def(call_hir_id)
4799                        && call_receiver.hir_id == arg_hir_id =>
4800                    {
4801                        // Avoid suggesting removing a method call if the argument is the receiver of the parent call and
4802                        // removing the receiver would make the method inaccessible. i.e. `x.a().b()`, suggesting removing
4803                        // `.a()` could change the type and make `.b()` unavailable.
4804                        if tcx.inherent_impl_of_assoc(did).is_some() {
4805                            // if we're calling an inherent impl method, just try to make sure that the receiver type stays the same.
4806                            Some(ty) == typeck_results.node_type_opt(arg_hir_id)
4807                        } else {
4808                            // we're calling a trait method, so we just check removing the method call still satisfies the trait.
4809                            let trait_id = tcx
4810                                .trait_of_assoc(did)
4811                                .unwrap_or_else(|| tcx.impl_trait_id(tcx.parent(did)));
4812                            let args = typeck_results.node_args(call_hir_id);
4813                            let tr = ty::TraitRef::from_assoc(tcx, trait_id, args)
4814                                .with_replaced_self_ty(tcx, ty);
4815                            self.type_implements_trait(tr.def_id, tr.args, param_env)
4816                                .must_apply_modulo_regions()
4817                        }
4818                    }
4819                    _ => true,
4820                };
4821
4822                if should_sugg {
4823                    err.span_suggestion_verbose(
4824                        expr.span.with_lo(rcvr.span.hi()),
4825                        ::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!(
4826                            "consider removing this method call, as the receiver has type `{ty}` and \
4827                            `{pred}` trivially holds",
4828                        ),
4829                        "",
4830                        Applicability::MaybeIncorrect,
4831                    );
4832                }
4833            }
4834            if let hir::Expr { kind: hir::ExprKind::Block(block, _), .. } = expr {
4835                let inner_expr = expr.peel_blocks();
4836                let ty = typeck_results
4837                    .expr_ty_adjusted_opt(inner_expr)
4838                    .unwrap_or(Ty::new_misc_error(tcx));
4839                let span = inner_expr.span;
4840                if Some(span) != err.span.primary_span()
4841                    && !span.in_external_macro(tcx.sess.source_map())
4842                {
4843                    err.span_label(
4844                        span,
4845                        if ty.references_error() {
4846                            String::new()
4847                        } else {
4848                            let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
4849                            ::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}`")
4850                        },
4851                    );
4852                    if let ty::PredicateKind::Clause(clause) = failed_pred.kind().skip_binder()
4853                        && let ty::ClauseKind::Trait(pred) = clause
4854                        && tcx.fn_trait_kind_from_def_id(pred.def_id()).is_some()
4855                    {
4856                        if let [stmt, ..] = block.stmts
4857                            && let hir::StmtKind::Semi(value) = stmt.kind
4858                            && let hir::ExprKind::Closure(hir::Closure {
4859                                body, fn_decl_span, ..
4860                            }) = value.kind
4861                            && let body = tcx.hir_body(*body)
4862                            && !#[allow(non_exhaustive_omitted_patterns)] match body.value.kind {
    hir::ExprKind::Block(..) => true,
    _ => false,
}matches!(body.value.kind, hir::ExprKind::Block(..))
4863                        {
4864                            // Check if the failed predicate was an expectation of a closure type
4865                            // and if there might have been a `{ |args|` typo instead of `|args| {`.
4866                            err.multipart_suggestion(
4867                                "you might have meant to open the closure body instead of placing \
4868                                 a closure within a block",
4869                                ::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![
4870                                    (expr.span.with_hi(value.span.lo()), String::new()),
4871                                    (fn_decl_span.shrink_to_hi(), " {".to_string()),
4872                                ],
4873                                Applicability::MaybeIncorrect,
4874                            );
4875                        } else {
4876                            // Maybe the bare block was meant to be a closure.
4877                            err.span_suggestion_verbose(
4878                                expr.span.shrink_to_lo(),
4879                                "you might have meant to create the closure instead of a block",
4880                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("|{0}| ",
                (0..pred.trait_ref.args.len() -
                                        1).map(|_| "_").collect::<Vec<_>>().join(", ")))
    })format!(
4881                                    "|{}| ",
4882                                    (0..pred.trait_ref.args.len() - 1)
4883                                        .map(|_| "_")
4884                                        .collect::<Vec<_>>()
4885                                        .join(", ")
4886                                ),
4887                                Applicability::MaybeIncorrect,
4888                            );
4889                        }
4890                    }
4891                }
4892            }
4893
4894            // FIXME: visit the ty to see if there's any closure involved, and if there is,
4895            // check whether its evaluated return type is the same as the one corresponding
4896            // to an associated type (as seen from `trait_pred`) in the predicate. Like in
4897            // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
4898            let mut type_diffs = ::alloc::vec::Vec::new()vec![];
4899            if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = *parent_code
4900                && let Some(node_args) = typeck_results.node_args_opt(call_hir_id)
4901                && let where_clauses = self.tcx.clauses_of(def_id).instantiate(self.tcx, node_args)
4902                && let Some(where_pred) = where_clauses.clauses.get(idx)
4903            {
4904                let where_pred = where_pred.as_ref().skip_norm_wip();
4905                if let Some(where_pred) = where_pred.as_trait_clause()
4906                    && let Some(failed_pred) = failed_pred.as_trait_clause()
4907                    && where_pred.def_id() == failed_pred.def_id()
4908                {
4909                    self.enter_forall(where_pred, |where_pred| {
4910                        let failed_pred = self.instantiate_binder_with_fresh_vars(
4911                            expr.span,
4912                            BoundRegionConversionTime::FnCall,
4913                            failed_pred,
4914                        );
4915
4916                        let zipped =
4917                            iter::zip(where_pred.trait_ref.args, failed_pred.trait_ref.args);
4918                        for (expected, actual) in zipped {
4919                            self.probe(|_| {
4920                                match self
4921                                    .at(&ObligationCause::misc(expr.span, body_def_id), param_env)
4922                                    // Doesn't actually matter if we define opaque types here, this is just used for
4923                                    // diagnostics, and the result is never kept around.
4924                                    .eq(DefineOpaqueTypes::Yes, expected, actual)
4925                                {
4926                                    Ok(_) => (), // We ignore nested obligations here for now.
4927                                    Err(err) => type_diffs.push(err),
4928                                }
4929                            })
4930                        }
4931                    })
4932                } else if let Some(where_pred) = where_pred.as_projection_clause()
4933                    && let Some(failed_pred) = failed_pred.as_projection_clause()
4934                    && let Some(found) =
4935                        failed_pred.map_bound(|pred| pred.term.as_type()).transpose().map(|term| {
4936                            self.instantiate_binder_with_fresh_vars(
4937                                expr.span,
4938                                BoundRegionConversionTime::FnCall,
4939                                term,
4940                            )
4941                        })
4942                {
4943                    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 {
4944                        expected: self
4945                            .instantiate_binder_with_fresh_vars(
4946                                expr.span,
4947                                BoundRegionConversionTime::FnCall,
4948                                where_pred.map_bound(|pred| pred.projection_term),
4949                            )
4950                            .expect_ty()
4951                            .to_ty(self.tcx, ty::IsRigid::No),
4952                        found,
4953                    })];
4954                }
4955            }
4956            if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
4957                && let hir::Path { res: Res::Local(hir_id), .. } = path
4958                && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
4959                && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(binding.hir_id)
4960                && let Some(binding_expr) = local.init
4961            {
4962                // If the expression we're calling on is a binding, we want to point at the
4963                // `let` when talking about the type. Otherwise we'll point at every part
4964                // of the method chain with the type.
4965                self.point_at_chain(binding_expr, typeck_results, type_diffs, param_env, err);
4966            } else {
4967                self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
4968            }
4969        }
4970        let call_node = tcx.hir_node(call_hir_id);
4971        if let Node::Expr(hir::Expr { kind: hir::ExprKind::MethodCall(path, rcvr, ..), .. }) =
4972            call_node
4973        {
4974            if Some(rcvr.span) == err.span.primary_span() {
4975                err.replace_span_with(path.ident.span, true);
4976            }
4977        }
4978
4979        if let Node::Expr(expr) = call_node {
4980            if let hir::ExprKind::Call(hir::Expr { span, .. }, _)
4981            | hir::ExprKind::MethodCall(
4982                hir::PathSegment { ident: Ident { span, .. }, .. },
4983                ..,
4984            ) = expr.kind
4985            {
4986                if Some(*span) != err.span.primary_span() {
4987                    let msg = if span.is_desugaring(DesugaringKind::FormatLiteral { source: true })
4988                    {
4989                        "required by this formatting parameter"
4990                    } else if span.is_desugaring(DesugaringKind::FormatLiteral { source: false }) {
4991                        "required by a formatting parameter in this expression"
4992                    } else {
4993                        "required by a bound introduced by this call"
4994                    };
4995                    err.span_label(*span, msg);
4996                }
4997            }
4998
4999            if let hir::ExprKind::MethodCall(_, expr, ..) = expr.kind {
5000                self.suggest_option_method_if_applicable(failed_pred, param_env, err, expr);
5001            }
5002        }
5003    }
5004
5005    fn suggest_option_method_if_applicable<G: EmissionGuarantee>(
5006        &self,
5007        failed_pred: ty::Predicate<'tcx>,
5008        param_env: ty::ParamEnv<'tcx>,
5009        err: &mut Diag<'_, G>,
5010        expr: &hir::Expr<'_>,
5011    ) {
5012        let tcx = self.tcx;
5013        let infcx = self.infcx;
5014        let Some(typeck_results) = self.typeck_results.as_ref() else { return };
5015
5016        // Make sure we're dealing with the `Option` type.
5017        let Some(option_ty_adt) = typeck_results.expr_ty_adjusted(expr).ty_adt_def() else {
5018            return;
5019        };
5020        if !tcx.is_diagnostic_item(sym::Option, option_ty_adt.did()) {
5021            return;
5022        }
5023
5024        // Given the predicate `fn(&T): FnOnce<(U,)>`, extract `fn(&T)` and `(U,)`,
5025        // then suggest `Option::as_deref(_mut)` if `U` can deref to `T`
5026        if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, .. }))
5027            = failed_pred.kind().skip_binder()
5028            && tcx.is_fn_trait(trait_ref.def_id)
5029            && let [self_ty, found_ty] = trait_ref.args.as_slice()
5030            && let Some(fn_ty) = self_ty.as_type().filter(|ty| ty.is_fn())
5031            && let fn_sig @ ty::FnSig {
5032                ..
5033            } = fn_ty.fn_sig(tcx).skip_binder()
5034            // FIXME(splat): this might need to change if the Fn* traits start using/supporting splat
5035            && fn_sig.abi() == ExternAbi::Rust
5036            && !fn_sig.c_variadic()
5037            && fn_sig.safety() == hir::Safety::Safe
5038
5039            // Extract first param of fn sig with peeled refs, e.g. `fn(&T)` -> `T`
5040            && let Some(&ty::Ref(_, target_ty, needs_mut)) = fn_sig.inputs().first().map(|t| t.kind())
5041            && !target_ty.has_escaping_bound_vars()
5042
5043            // Extract first tuple element out of fn trait, e.g. `FnOnce<(U,)>` -> `U`
5044            && let Some(ty::Tuple(tys)) = found_ty.as_type().map(Ty::kind)
5045            && let &[found_ty] = tys.as_slice()
5046            && !found_ty.has_escaping_bound_vars()
5047
5048            // Extract `<U as Deref>::Target` assoc type and check that it is `T`
5049            && let Some(deref_target_did) = tcx.lang_items().deref_target()
5050            && let projection = Ty::new_projection_from_args(tcx,ty::IsRigid::No, deref_target_did, tcx.mk_args(&[ty::GenericArg::from(found_ty)]))
5051            && let InferOk { value: deref_target, obligations } = infcx.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(projection))
5052            && obligations.iter().all(|obligation| infcx.predicate_must_hold_modulo_regions(obligation))
5053            && infcx.can_eq(param_env, deref_target, target_ty)
5054        {
5055            let help = if let hir::Mutability::Mut = needs_mut
5056                && let Some(deref_mut_did) = tcx.lang_items().deref_mut_trait()
5057                && infcx
5058                    .type_implements_trait(deref_mut_did, iter::once(found_ty), param_env)
5059                    .must_apply_modulo_regions()
5060            {
5061                Some(("call `Option::as_deref_mut()` first", ".as_deref_mut()"))
5062            } else if let hir::Mutability::Not = needs_mut {
5063                Some(("call `Option::as_deref()` first", ".as_deref()"))
5064            } else {
5065                None
5066            };
5067
5068            if let Some((msg, sugg)) = help {
5069                err.span_suggestion_with_style(
5070                    expr.span.shrink_to_hi(),
5071                    msg,
5072                    sugg,
5073                    Applicability::MaybeIncorrect,
5074                    SuggestionStyle::ShowAlways,
5075                );
5076            }
5077        }
5078    }
5079
5080    fn look_for_iterator_item_mistakes<G: EmissionGuarantee>(
5081        &self,
5082        assocs_in_this_method: &[Option<(Span, (DefId, Ty<'tcx>))>],
5083        typeck_results: &TypeckResults<'tcx>,
5084        type_diffs: &[TypeError<'tcx>],
5085        param_env: ty::ParamEnv<'tcx>,
5086        path_segment: &hir::PathSegment<'_>,
5087        args: &[hir::Expr<'_>],
5088        prev_ty: Ty<'_>,
5089        err: &mut Diag<'_, G>,
5090    ) {
5091        let tcx = self.tcx;
5092        // Special case for iterator chains, we look at potential failures of `Iterator::Item`
5093        // not being `: Clone` and `Iterator::map` calls with spurious trailing `;`.
5094        for entry in assocs_in_this_method {
5095            let Some((_span, (def_id, ty))) = entry else {
5096                continue;
5097            };
5098            for diff in type_diffs {
5099                let TypeError::Sorts(expected_found) = diff else {
5100                    continue;
5101                };
5102                if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
5103                    && path_segment.ident.name == sym::iter
5104                    && self.can_eq(
5105                        param_env,
5106                        Ty::new_ref(
5107                            tcx,
5108                            tcx.lifetimes.re_erased,
5109                            expected_found.found,
5110                            ty::Mutability::Not,
5111                        ),
5112                        *ty,
5113                    )
5114                    && let [] = args
5115                {
5116                    // Used `.iter()` when `.into_iter()` was likely meant.
5117                    err.span_suggestion_verbose(
5118                        path_segment.ident.span,
5119                        ::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`"),
5120                        "into_iter".to_string(),
5121                        Applicability::MachineApplicable,
5122                    );
5123                }
5124                if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
5125                    && path_segment.ident.name == sym::into_iter
5126                    && self.can_eq(
5127                        param_env,
5128                        expected_found.found,
5129                        Ty::new_ref(tcx, tcx.lifetimes.re_erased, *ty, ty::Mutability::Not),
5130                    )
5131                    && let [] = args
5132                {
5133                    // Used `.into_iter()` when `.iter()` was likely meant.
5134                    err.span_suggestion_verbose(
5135                        path_segment.ident.span,
5136                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider not consuming the `{0}` to construct the `Iterator`",
                prev_ty))
    })format!(
5137                            "consider not consuming the `{prev_ty}` to construct the `Iterator`"
5138                        ),
5139                        "iter".to_string(),
5140                        Applicability::MachineApplicable,
5141                    );
5142                }
5143                if tcx.is_diagnostic_item(sym::IteratorItem, *def_id)
5144                    && path_segment.ident.name == sym::map
5145                    && self.can_eq(param_env, expected_found.found, *ty)
5146                    && let [arg] = args
5147                    && let hir::ExprKind::Closure(closure) = arg.kind
5148                {
5149                    let body = tcx.hir_body(closure.body);
5150                    if let hir::ExprKind::Block(block, None) = body.value.kind
5151                        && let None = block.expr
5152                        && let [.., stmt] = block.stmts
5153                        && let hir::StmtKind::Semi(expr) = stmt.kind
5154                        // FIXME: actually check the expected vs found types, but right now
5155                        // the expected is a projection that we need to resolve.
5156                        // && let Some(tail_ty) = typeck_results.expr_ty_opt(expr)
5157                        && expected_found.found.is_unit()
5158                        // FIXME: this happens with macro calls. Need to figure out why the stmt
5159                        // `println!();` doesn't include the `;` in its `Span`. (#133845)
5160                        // We filter these out to avoid ICEs with debug assertions on caused by
5161                        // empty suggestions.
5162                        && expr.span.hi() != stmt.span.hi()
5163                    {
5164                        err.span_suggestion_verbose(
5165                            expr.span.shrink_to_hi().with_hi(stmt.span.hi()),
5166                            "consider removing this semicolon",
5167                            String::new(),
5168                            Applicability::MachineApplicable,
5169                        );
5170                    }
5171                    let expr = if let hir::ExprKind::Block(block, None) = body.value.kind
5172                        && let Some(expr) = block.expr
5173                    {
5174                        expr
5175                    } else {
5176                        body.value
5177                    };
5178                    if let hir::ExprKind::MethodCall(path_segment, rcvr, [], span) = expr.kind
5179                        && path_segment.ident.name == sym::clone
5180                        && let Some(expr_ty) = typeck_results.expr_ty_opt(expr)
5181                        && let Some(rcvr_ty) = typeck_results.expr_ty_opt(rcvr)
5182                        && self.can_eq(param_env, expr_ty, rcvr_ty)
5183                        && let ty::Ref(_, ty, _) = expr_ty.kind()
5184                    {
5185                        err.span_label(
5186                            span,
5187                            ::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!(
5188                                "this method call is cloning the reference `{expr_ty}`, not \
5189                                 `{ty}` which doesn't implement `Clone`",
5190                            ),
5191                        );
5192                        let ty::Param(..) = ty.kind() else {
5193                            continue;
5194                        };
5195                        let node =
5196                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(expr.hir_id).def_id);
5197
5198                        let pred = ty::Binder::dummy(ty::TraitPredicate {
5199                            trait_ref: ty::TraitRef::new(
5200                                tcx,
5201                                tcx.require_lang_item(LangItem::Clone, span),
5202                                [*ty],
5203                            ),
5204                            polarity: ty::PredicatePolarity::Positive,
5205                        });
5206                        let Some(generics) = node.generics() else {
5207                            continue;
5208                        };
5209                        let Some(body_id) = node.body_id() else {
5210                            continue;
5211                        };
5212                        suggest_restriction(
5213                            tcx,
5214                            tcx.hir_body_owner_def_id(body_id),
5215                            generics,
5216                            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type parameter `{0}`", ty))
    })format!("type parameter `{ty}`"),
5217                            err,
5218                            node.fn_sig(),
5219                            None,
5220                            pred,
5221                            None,
5222                        );
5223                    }
5224                }
5225            }
5226        }
5227    }
5228
5229    fn point_at_chain<G: EmissionGuarantee>(
5230        &self,
5231        expr: &hir::Expr<'_>,
5232        typeck_results: &TypeckResults<'tcx>,
5233        type_diffs: Vec<TypeError<'tcx>>,
5234        param_env: ty::ParamEnv<'tcx>,
5235        err: &mut Diag<'_, G>,
5236    ) {
5237        let mut primary_spans = ::alloc::vec::Vec::new()vec![];
5238        let mut span_labels = ::alloc::vec::Vec::new()vec![];
5239
5240        let tcx = self.tcx;
5241
5242        let mut print_root_expr = true;
5243        let mut assocs = ::alloc::vec::Vec::new()vec![];
5244        let mut expr = expr;
5245        let mut prev_ty = self.resolve_vars_if_possible(
5246            typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5247        );
5248        while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
5249            // Point at every method call in the chain with the resulting type.
5250            // vec![1, 2, 3].iter().map(mapper).sum<i32>()
5251            //               ^^^^^^ ^^^^^^^^^^^
5252            expr = rcvr_expr;
5253            let assocs_in_this_method =
5254                self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
5255            prev_ty = self.resolve_vars_if_possible(
5256                typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5257            );
5258            self.look_for_iterator_item_mistakes(
5259                &assocs_in_this_method,
5260                typeck_results,
5261                &type_diffs,
5262                param_env,
5263                path_segment,
5264                args,
5265                prev_ty,
5266                err,
5267            );
5268            assocs.push(assocs_in_this_method);
5269
5270            if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
5271                && let hir::Path { res: Res::Local(hir_id), .. } = path
5272                && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
5273            {
5274                let parent = self.tcx.parent_hir_node(binding.hir_id);
5275                // We've reached the root of the method call chain...
5276                if let hir::Node::LetStmt(local) = parent
5277                    && let Some(binding_expr) = local.init
5278                {
5279                    // ...and it is a binding. Get the binding creation and continue the chain.
5280                    expr = binding_expr;
5281                }
5282                if let hir::Node::Param(param) = parent {
5283                    // ...and it is an fn argument.
5284                    let prev_ty = self.resolve_vars_if_possible(
5285                        typeck_results
5286                            .node_type_opt(param.hir_id)
5287                            .unwrap_or(Ty::new_misc_error(tcx)),
5288                    );
5289                    let assocs_in_this_method = self.probe_assoc_types_at_expr(
5290                        &type_diffs,
5291                        param.ty_span,
5292                        prev_ty,
5293                        param.hir_id,
5294                        param_env,
5295                    );
5296                    if assocs_in_this_method.iter().any(|a| a.is_some()) {
5297                        assocs.push(assocs_in_this_method);
5298                        print_root_expr = false;
5299                    }
5300                    break;
5301                }
5302            }
5303        }
5304        // We want the type before deref coercions, otherwise we talk about `&[_]`
5305        // instead of `Vec<_>`.
5306        if let Some(ty) = typeck_results.expr_ty_opt(expr)
5307            && print_root_expr
5308        {
5309            let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5310            // Point at the root expression
5311            // vec![1, 2, 3].iter().map(mapper).sum<i32>()
5312            // ^^^^^^^^^^^^^
5313            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}`")));
5314        };
5315        // Only show this if it is not a "trivial" expression (not a method
5316        // chain) and there are associated types to talk about.
5317        let mut assocs = assocs.into_iter().peekable();
5318        while let Some(assocs_in_method) = assocs.next() {
5319            let Some(prev_assoc_in_method) = assocs.peek() else {
5320                for entry in assocs_in_method {
5321                    let Some((span, (assoc, ty))) = entry else {
5322                        continue;
5323                    };
5324                    if primary_spans.is_empty()
5325                        || type_diffs.iter().any(|diff| {
5326                            let TypeError::Sorts(expected_found) = diff else {
5327                                return false;
5328                            };
5329                            self.can_eq(param_env, expected_found.found, ty)
5330                        })
5331                    {
5332                        // FIXME: this doesn't quite work for `Iterator::collect`
5333                        // because we have `Vec<i32>` and `()`, but we'd want `i32`
5334                        // to point at the `.into_iter()` call, but as long as we
5335                        // still point at the other method calls that might have
5336                        // introduced the issue, this is fine for now.
5337                        primary_spans.push(span);
5338                    }
5339                    span_labels.push((
5340                        span,
5341                        {
    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!(
5342                            "`{}` is `{ty}` here",
5343                            self.tcx.def_path_str(assoc),
5344                        )),
5345                    ));
5346                }
5347                break;
5348            };
5349            for (entry, prev_entry) in
5350                assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
5351            {
5352                match (entry, prev_entry) {
5353                    (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
5354                        let ty_str = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5355
5356                        let assoc = { let _guard = ForceTrimmedGuard::new(); self.tcx.def_path_str(assoc) }with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
5357                        if !self.can_eq(param_env, ty, *prev_ty) {
5358                            if type_diffs.iter().any(|diff| {
5359                                let TypeError::Sorts(expected_found) = diff else {
5360                                    return false;
5361                                };
5362                                self.can_eq(param_env, expected_found.found, ty)
5363                            }) {
5364                                primary_spans.push(span);
5365                            }
5366                            span_labels
5367                                .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")));
5368                        } else {
5369                            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")));
5370                        }
5371                    }
5372                    (Some((span, (assoc, ty))), None) => {
5373                        span_labels.push((
5374                            span,
5375                            {
    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!(
5376                                "`{}` is `{}` here",
5377                                self.tcx.def_path_str(assoc),
5378                                self.ty_to_string(ty),
5379                            )),
5380                        ));
5381                    }
5382                    (None, Some(_)) | (None, None) => {}
5383                }
5384            }
5385        }
5386        if !primary_spans.is_empty() {
5387            let mut multi_span: MultiSpan = primary_spans.into();
5388            for (span, label) in span_labels {
5389                multi_span.push_span_label(span, label);
5390            }
5391            err.span_note(
5392                multi_span,
5393                "the method call chain might not have had the expected associated types",
5394            );
5395        }
5396    }
5397
5398    fn probe_assoc_types_at_expr(
5399        &self,
5400        type_diffs: &[TypeError<'tcx>],
5401        span: Span,
5402        prev_ty: Ty<'tcx>,
5403        body_id: HirId,
5404        param_env: ty::ParamEnv<'tcx>,
5405    ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
5406        let ocx = ObligationCtxt::new(self.infcx);
5407        let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
5408        for diff in type_diffs {
5409            let TypeError::Sorts(expected_found) = diff else {
5410                continue;
5411            };
5412            let &ty::Alias(_, ty::AliasTy { kind: kind @ ty::Projection { def_id }, .. }) =
5413                expected_found.expected.kind()
5414            else {
5415                continue;
5416            };
5417
5418            // Make `Self` be equivalent to the type of the call chain
5419            // expression we're looking at now, so that we can tell what
5420            // for example `Iterator::Item` is at this point in the chain.
5421            let args = GenericArgs::for_item(self.tcx, def_id, |param, _| {
5422                if param.index == 0 {
5423                    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 { .. });
5424                    return prev_ty.into();
5425                }
5426                self.var_for_def(span, param)
5427            });
5428            // This will hold the resolved type of the associated type, if the
5429            // current expression implements the trait that associated type is
5430            // in. For example, this would be what `Iterator::Item` is here.
5431            let ty = self.infcx.next_ty_var(span);
5432            // This corresponds to `<ExprTy as Iterator>::Item = _`.
5433            let projection = ty::Binder::dummy(ty::PredicateKind::Clause(
5434                ty::ClauseKind::Projection(ty::ProjectionPredicate {
5435                    projection_term: ty::AliasTerm::new_from_args(self.tcx, kind.into(), args),
5436                    term: ty.into(),
5437                }),
5438            ));
5439            let body_def_id = self.tcx.hir_enclosing_body_owner(body_id);
5440            // Add `<ExprTy as Iterator>::Item = _` obligation.
5441            ocx.register_obligation(Obligation::misc(
5442                self.tcx,
5443                span,
5444                body_def_id,
5445                param_env,
5446                projection,
5447            ));
5448            if ocx.try_evaluate_obligations().is_empty()
5449                && let ty = self.resolve_vars_if_possible(ty)
5450                && !ty.is_ty_var()
5451            {
5452                assocs_in_this_method.push(Some((span, (def_id, ty))));
5453            } else {
5454                // `<ExprTy as Iterator>` didn't select, so likely we've
5455                // reached the end of the iterator chain, like the originating
5456                // `Vec<_>` or the `ty` couldn't be determined.
5457                // Keep the space consistent for later zipping.
5458                assocs_in_this_method.push(None);
5459            }
5460        }
5461        assocs_in_this_method
5462    }
5463
5464    /// When a `-> impl Trait<Assoc = Ty>` return type obligation fails, walk the method call
5465    /// chain in the returned expression to point at where the associated type diverged from
5466    /// what the signature expects.
5467    ///
5468    /// ```text
5469    /// note: the method call chain might not have had the expected associated types
5470    ///   --> $DIR/invalid-iterator-chain-in-return-position.rs:16:18
5471    ///    |
5472    /// LL |     x.iter_mut().map(foo)
5473    ///    |     - ---------- ^^^^^^^^ `Iterator::Item` changed to `()` here
5474    ///    |     | |
5475    ///    |     | `Iterator::Item` is `&mut Vec<u8>` here
5476    ///    |     this expression has type `Vec<Vec<u8>>`
5477    /// ```
5478    fn point_at_chain_in_return_position<G: EmissionGuarantee>(
5479        &self,
5480        body_def_id: LocalDefId,
5481        expr: &hir::Expr<'_>,
5482        typeck_results: &TypeckResults<'tcx>,
5483        param_env: ty::ParamEnv<'tcx>,
5484        err: &mut Diag<'_, G>,
5485    ) {
5486        let tcx = self.tcx;
5487        if !#[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(body_def_id) {
    DefKind::Fn | DefKind::AssocFn => true,
    _ => false,
}matches!(tcx.def_kind(body_def_id), DefKind::Fn | DefKind::AssocFn) {
5488            return;
5489        }
5490
5491        let binder = tcx.fn_sig(body_def_id).instantiate_identity().skip_norm_wip().output();
5492        self.enter_forall(binder, |output| {
5493            let &ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id: opaque_def_id }, args, .. }) =
5494                output.kind()
5495            else {
5496                return;
5497            };
5498
5499            // The predicate that reaches here has been rewritten through the impls it was
5500            // derived from (e.g. `Iterator for Map<I, F>` turns `Iterator::Item` requirements
5501            // into requirements on `F`'s return type), so the associated types the user wrote
5502            // in the signature are recovered from the opaque's bounds instead.
5503            let mut probe_diffs = ::alloc::vec::Vec::new()vec![];
5504            for clause in tcx.item_bounds(opaque_def_id).instantiate(tcx, args).skip_norm_wip() {
5505                let Some(proj) = clause.as_projection_clause() else { continue };
5506                let proj = self.instantiate_binder_with_fresh_vars(
5507                    expr.span,
5508                    BoundRegionConversionTime::FnCall,
5509                    proj,
5510                );
5511                let Some(expected_term) = proj.term.as_type() else { continue };
5512                // Only the projection (for its `DefId`) is used when probing the chain; the
5513                // bound's own term is carried in `found` for the divergence check below and
5514                // is replaced with the probed type afterwards.
5515                probe_diffs.push(TypeError::Sorts(ty::error::ExpectedFound {
5516                    expected: proj.projection_term.expect_ty().to_ty(tcx, ty::IsRigid::No),
5517                    found: expected_term,
5518                }));
5519            }
5520            if probe_diffs.is_empty() {
5521                return;
5522            }
5523
5524            // If the returned expression is a binding, walk the chain that created it instead.
5525            let expr = if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
5526                && let hir::Path { res: Res::Local(hir_id), .. } = path
5527                && let hir::Node::Pat(binding) = tcx.hir_node(*hir_id)
5528                && let hir::Node::LetStmt(local) = tcx.parent_hir_node(binding.hir_id)
5529                && let Some(binding_expr) = local.init
5530            {
5531                binding_expr
5532            } else {
5533                expr
5534            };
5535
5536            // Resolve what each bound associated type actually is for the returned expression,
5537            // and keep only the ones that diverged from the signature.
5538            let expr_ty = self.resolve_vars_if_possible(
5539                typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5540            );
5541            let assocs = self.probe_assoc_types_at_expr(
5542                &probe_diffs,
5543                expr.span,
5544                expr_ty,
5545                expr.hir_id,
5546                param_env,
5547            );
5548            let mut type_diffs = ::alloc::vec::Vec::new()vec![];
5549            for (probe_diff, assoc) in iter::zip(probe_diffs, assocs) {
5550                let TypeError::Sorts(ty::error::ExpectedFound { expected, found: expected_term }) =
5551                    probe_diff
5552                else {
5553                    continue;
5554                };
5555                let Some((_, (_, actual_ty))) = assoc else { continue };
5556                if !self.can_eq(param_env, expected_term, actual_ty) {
5557                    type_diffs.push(TypeError::Sorts(ty::error::ExpectedFound {
5558                        expected,
5559                        found: actual_ty,
5560                    }));
5561                }
5562            }
5563            if !type_diffs.is_empty() {
5564                self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
5565            }
5566        });
5567    }
5568
5569    /// If the type that failed selection is an array or a reference to an array,
5570    /// but the trait is implemented for slices, suggest that the user converts
5571    /// the array into a slice.
5572    pub(super) fn suggest_convert_to_slice(
5573        &self,
5574        err: &mut Diag<'_>,
5575        obligation: &PredicateObligation<'tcx>,
5576        trait_pred: ty::PolyTraitPredicate<'tcx>,
5577        candidate_impls: &[ImplCandidate<'tcx>],
5578        span: Span,
5579    ) {
5580        if span.in_external_macro(self.tcx.sess.source_map()) {
5581            return;
5582        }
5583        // We can only suggest the slice coercion for function and binary operation arguments,
5584        // since the suggestion would make no sense in turbofish or call
5585        let (ObligationCauseCode::BinOp { .. } | ObligationCauseCode::FunctionArg { .. }) =
5586            obligation.cause.code()
5587        else {
5588            return;
5589        };
5590
5591        // Three cases where we can make a suggestion:
5592        // 1. `[T; _]` (array of T)
5593        // 2. `&[T; _]` (reference to array of T)
5594        // 3. `&mut [T; _]` (mutable reference to array of T)
5595        let (element_ty, mut mutability) = match *trait_pred.skip_binder().self_ty().kind() {
5596            ty::Array(element_ty, _) => (element_ty, None),
5597
5598            ty::Ref(_, pointee_ty, mutability) => match *pointee_ty.kind() {
5599                ty::Array(element_ty, _) => (element_ty, Some(mutability)),
5600                _ => return,
5601            },
5602
5603            _ => return,
5604        };
5605
5606        // Go through all the candidate impls to see if any of them is for
5607        // slices of `element_ty` with `mutability`.
5608        let mut is_slice = |candidate: Ty<'tcx>| match *candidate.kind() {
5609            ty::RawPtr(t, m) | ty::Ref(_, t, m) => {
5610                if let ty::Slice(e) = *t.kind()
5611                    && e == element_ty
5612                    && m == mutability.unwrap_or(m)
5613                {
5614                    // Use the candidate's mutability going forward.
5615                    mutability = Some(m);
5616                    true
5617                } else {
5618                    false
5619                }
5620            }
5621            _ => false,
5622        };
5623
5624        // Grab the first candidate that matches, if any, and make a suggestion.
5625        if let Some(slice_ty) = candidate_impls
5626            .iter()
5627            .map(|trait_ref| trait_ref.trait_ref.self_ty())
5628            .find(|t| is_slice(*t))
5629        {
5630            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");
5631
5632            if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
5633                let mut suggestions = ::alloc::vec::Vec::new()vec![];
5634                if snippet.starts_with('&') {
5635                } else if let Some(hir::Mutability::Mut) = mutability {
5636                    suggestions.push((span.shrink_to_lo(), "&mut ".into()));
5637                } else {
5638                    suggestions.push((span.shrink_to_lo(), "&".into()));
5639                }
5640                suggestions.push((span.shrink_to_hi(), "[..]".into()));
5641                err.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
5642            } else {
5643                err.span_help(span, msg);
5644            }
5645        }
5646    }
5647
5648    /// If the type failed selection but the trait is implemented for `(T,)`, suggest that the user
5649    /// creates a unary tuple
5650    ///
5651    /// This is a common gotcha when using libraries that emulate variadic functions with traits for tuples.
5652    pub(super) fn suggest_tuple_wrapping(
5653        &self,
5654        err: &mut Diag<'_>,
5655        root_obligation: &PredicateObligation<'tcx>,
5656        obligation: &PredicateObligation<'tcx>,
5657    ) {
5658        let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code() else {
5659            return;
5660        };
5661
5662        let Some(root_pred) = root_obligation.predicate.as_trait_clause() else { return };
5663
5664        let trait_ref = root_pred.map_bound(|root_pred| {
5665            root_pred.trait_ref.with_replaced_self_ty(
5666                self.tcx,
5667                Ty::new_tup(self.tcx, &[root_pred.trait_ref.self_ty()]),
5668            )
5669        });
5670
5671        let obligation =
5672            Obligation::new(self.tcx, obligation.cause.clone(), obligation.param_env, trait_ref);
5673
5674        if self.predicate_must_hold_modulo_regions(&obligation) {
5675            let arg_span = self.tcx.hir_span(*arg_hir_id);
5676            err.multipart_suggestion(
5677                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use a unary tuple instead"))
    })format!("use a unary tuple instead"),
5678                ::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())],
5679                Applicability::MaybeIncorrect,
5680            );
5681        }
5682    }
5683
5684    pub(super) fn suggest_shadowed_inherent_method(
5685        &self,
5686        err: &mut Diag<'_>,
5687        obligation: &PredicateObligation<'tcx>,
5688        trait_predicate: ty::PolyTraitPredicate<'tcx>,
5689    ) {
5690        let ObligationCauseCode::FunctionArg { call_hir_id, .. } = obligation.cause.code() else {
5691            return;
5692        };
5693        let Node::Expr(call) = self.tcx.hir_node(*call_hir_id) else { return };
5694        let hir::ExprKind::MethodCall(segment, rcvr, args, ..) = call.kind else { return };
5695        let Some(typeck) = &self.typeck_results else { return };
5696        let Some(rcvr_ty) = typeck.expr_ty_adjusted_opt(rcvr) else { return };
5697        let rcvr_ty = self.resolve_vars_if_possible(rcvr_ty);
5698        let autoderef = (self.autoderef_steps)(rcvr_ty);
5699        for (ty, def_id) in autoderef.iter().filter_map(|(ty, obligations)| {
5700            if let ty::Adt(def, _) = ty.kind()
5701                && *ty != rcvr_ty.peel_refs()
5702                && obligations.iter().all(|obligation| self.predicate_may_hold(obligation))
5703            {
5704                Some((ty, def.did()))
5705            } else {
5706                None
5707            }
5708        }) {
5709            for impl_def_id in self.tcx.inherent_impls(def_id) {
5710                if *impl_def_id == trait_predicate.def_id() {
5711                    continue;
5712                }
5713                for m in self
5714                    .tcx
5715                    .provided_trait_methods(*impl_def_id)
5716                    .filter(|m| m.name() == segment.ident.name)
5717                {
5718                    let fn_sig = self.tcx.fn_sig(m.def_id);
5719                    if fn_sig.skip_binder().inputs().skip_binder().len() != args.len() + 1 {
5720                        continue;
5721                    }
5722                    let rcvr_ty = fn_sig.skip_binder().input(0).skip_binder();
5723                    let (mutability, _ty) = match rcvr_ty.kind() {
5724                        ty::Ref(_, ty, hir::Mutability::Mut) => ("&mut ", ty),
5725                        ty::Ref(_, ty, _) => ("&", ty),
5726                        _ => ("", &rcvr_ty),
5727                    };
5728                    let path = self.tcx.def_path_str(def_id);
5729                    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!(
5730                        "there's an inherent method on `{ty}` of the same name, which can be \
5731                         auto-dereferenced from `{rcvr_ty}`"
5732                    ));
5733                    err.multipart_suggestion(
5734                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("to access the inherent method on `{0}`, use the fully-qualified path",
                ty))
    })format!(
5735                            "to access the inherent method on `{ty}`, use the fully-qualified path",
5736                        ),
5737                        ::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![
5738                            (
5739                                call.span.until(rcvr.span),
5740                                format!("{path}::{}({}", m.name(), mutability),
5741                            ),
5742                            match &args {
5743                                [] => (
5744                                    rcvr.span.shrink_to_hi().with_hi(call.span.hi()),
5745                                    ")".to_string(),
5746                                ),
5747                                [first, ..] => (rcvr.span.between(first.span), ", ".to_string()),
5748                            },
5749                        ],
5750                        Applicability::MaybeIncorrect,
5751                    );
5752                }
5753            }
5754        }
5755    }
5756
5757    pub(super) fn explain_hrtb_projection(
5758        &self,
5759        diag: &mut Diag<'_>,
5760        pred: ty::PolyTraitPredicate<'tcx>,
5761        param_env: ty::ParamEnv<'tcx>,
5762        cause: &ObligationCause<'tcx>,
5763    ) {
5764        if pred.skip_binder().has_escaping_bound_vars() && pred.skip_binder().has_non_region_infer()
5765        {
5766            self.probe(|_| {
5767                let ocx = ObligationCtxt::new(self);
5768                self.enter_forall(pred, |pred| {
5769                    let pred = ocx.normalize(
5770                        &ObligationCause::dummy(),
5771                        param_env,
5772                        Unnormalized::new_wip(pred),
5773                    );
5774                    ocx.register_obligation(Obligation::new(
5775                        self.tcx,
5776                        ObligationCause::dummy(),
5777                        param_env,
5778                        pred,
5779                    ));
5780                });
5781                if !ocx.try_evaluate_obligations().is_empty() {
5782                    // encountered errors.
5783                    return;
5784                }
5785
5786                if let ObligationCauseCode::FunctionArg {
5787                    call_hir_id,
5788                    arg_hir_id,
5789                    parent_code: _,
5790                } = cause.code()
5791                {
5792                    let arg_span = self.tcx.hir_span(*arg_hir_id);
5793                    let mut sp: MultiSpan = arg_span.into();
5794
5795                    sp.push_span_label(
5796                        arg_span,
5797                        "the trait solver is unable to infer the \
5798                        generic types that should be inferred from this argument",
5799                    );
5800                    sp.push_span_label(
5801                        self.tcx.hir_span(*call_hir_id),
5802                        "add turbofish arguments to this call to \
5803                        specify the types manually, even if it's redundant",
5804                    );
5805                    diag.span_note(
5806                        sp,
5807                        "this is a known limitation of the trait solver that \
5808                        will be lifted in the future",
5809                    );
5810                } else {
5811                    let mut sp: MultiSpan = cause.span.into();
5812                    sp.push_span_label(
5813                        cause.span,
5814                        "try adding turbofish arguments to this expression to \
5815                        specify the types manually, even if it's redundant",
5816                    );
5817                    diag.span_note(
5818                        sp,
5819                        "this is a known limitation of the trait solver that \
5820                        will be lifted in the future",
5821                    );
5822                }
5823            });
5824        }
5825    }
5826
5827    pub(super) fn suggest_desugaring_async_fn_in_trait(
5828        &self,
5829        err: &mut Diag<'_>,
5830        trait_pred: ty::PolyTraitPredicate<'tcx>,
5831    ) {
5832        // Don't suggest if RTN is active -- we should prefer a where-clause bound instead.
5833        if self.tcx.features().return_type_notation() {
5834            return;
5835        }
5836
5837        let trait_def_id = trait_pred.def_id();
5838
5839        // Only suggest specifying auto traits
5840        if !self.tcx.trait_is_auto(trait_def_id) {
5841            return;
5842        }
5843
5844        // Look for an RPITIT
5845        let ty::Alias(_, alias_ty @ ty::AliasTy { kind: ty::Projection { def_id }, .. }) =
5846            trait_pred.self_ty().skip_binder().kind()
5847        else {
5848            return;
5849        };
5850        let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, opaque_def_id }) =
5851            self.tcx.opt_rpitit_info(*def_id)
5852        else {
5853            return;
5854        };
5855
5856        let auto_trait = self.tcx.def_path_str(trait_def_id);
5857        // ... which is a local function
5858        let Some(fn_def_id) = fn_def_id.as_local() else {
5859            // If it's not local, we can at least mention that the method is async, if it is.
5860            if self.tcx.asyncness(fn_def_id).is_async() {
5861                err.span_note(
5862                    self.tcx.def_span(fn_def_id),
5863                    ::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!(
5864                        "`{}::{}` is an `async fn` in trait, which does not \
5865                    automatically imply that its future is `{auto_trait}`",
5866                        alias_ty.trait_ref(self.tcx),
5867                        self.tcx.item_name(fn_def_id)
5868                    ),
5869                );
5870            }
5871            return;
5872        };
5873        let hir::Node::TraitItem(item) = self.tcx.hir_node_by_def_id(fn_def_id) else {
5874            return;
5875        };
5876
5877        // ... whose signature is `async` (i.e. this is an AFIT)
5878        let (sig, body) = item.expect_fn();
5879        let hir::FnRetTy::Return(hir::Ty { kind: hir::TyKind::OpaqueDef(opaq_def, ..), .. }) =
5880            sig.decl.output
5881        else {
5882            // This should never happen, but let's not ICE.
5883            return;
5884        };
5885
5886        // Check that this is *not* a nested `impl Future` RPIT in an async fn
5887        // (i.e. `async fn foo() -> impl Future`)
5888        if opaq_def.def_id.to_def_id() != opaque_def_id {
5889            return;
5890        }
5891
5892        let Some(sugg) = suggest_desugaring_async_fn_to_impl_future_in_trait(
5893            self.tcx,
5894            *sig,
5895            *body,
5896            opaque_def_id.expect_local(),
5897            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" + {0}", auto_trait))
    })format!(" + {auto_trait}"),
5898        ) else {
5899            return;
5900        };
5901
5902        let function_name = self.tcx.def_path_str(fn_def_id);
5903        err.multipart_suggestion(
5904            ::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!(
5905                "`{auto_trait}` can be made part of the associated future's \
5906                guarantees for all implementations of `{function_name}`"
5907            ),
5908            sugg,
5909            Applicability::MachineApplicable,
5910        );
5911    }
5912
5913    pub fn ty_kind_suggestion(
5914        &self,
5915        param_env: ty::ParamEnv<'tcx>,
5916        ty: Ty<'tcx>,
5917    ) -> Option<String> {
5918        let tcx = self.infcx.tcx;
5919        let implements_default = |ty| {
5920            let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
5921                return false;
5922            };
5923            self.type_implements_trait(default_trait, [ty], param_env).must_apply_modulo_regions()
5924        };
5925
5926        Some(match *ty.kind() {
5927            ty::Never | ty::Error(_) => return None,
5928            ty::Bool => "false".to_string(),
5929            ty::Char => "\'x\'".to_string(),
5930            ty::Int(_) | ty::Uint(_) => "42".into(),
5931            ty::Float(_) => "3.14159".into(),
5932            ty::Slice(_) => "[]".to_string(),
5933            ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => {
5934                "vec![]".to_string()
5935            }
5936            ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::String) => {
5937                "String::new()".to_string()
5938            }
5939            ty::Adt(def, args) if def.is_box() => {
5940                ::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())?)
5941            }
5942            ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Option) => {
5943                "None".to_string()
5944            }
5945            ty::Adt(def, args) if Some(def.did()) == tcx.get_diagnostic_item(sym::Result) => {
5946                ::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())?)
5947            }
5948            ty::Adt(_, _) if implements_default(ty) => "Default::default()".to_string(),
5949            ty::Ref(_, ty, mutability) => {
5950                if let (ty::Str, hir::Mutability::Not) = (ty.kind(), mutability) {
5951                    "\"\"".to_string()
5952                } else {
5953                    let ty = self.ty_kind_suggestion(param_env, ty)?;
5954                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}{1}", mutability.prefix_str(),
                ty))
    })format!("&{}{ty}", mutability.prefix_str())
5955                }
5956            }
5957            ty::Array(ty, len) if let Some(len) = len.try_to_target_usize(tcx) => {
5958                if len == 0 {
5959                    "[]".to_string()
5960                } else if self.type_is_copy_modulo_regions(param_env, ty) || len == 1 {
5961                    // Can only suggest `[ty; 0]` if sz == 1 or copy
5962                    ::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)
5963                } else {
5964                    "/* value */".to_string()
5965                }
5966            }
5967            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!(
5968                "({}{})",
5969                tys.iter()
5970                    .map(|ty| self.ty_kind_suggestion(param_env, ty))
5971                    .collect::<Option<Vec<String>>>()?
5972                    .join(", "),
5973                if tys.len() == 1 { "," } else { "" }
5974            ),
5975            _ => "/* value */".to_string(),
5976        })
5977    }
5978
5979    // For E0277 when use `?` operator, suggest adding
5980    // a suitable return type in `FnSig`, and a default
5981    // return value at the end of the function's body.
5982    pub(super) fn suggest_add_result_as_return_type(
5983        &self,
5984        obligation: &PredicateObligation<'tcx>,
5985        err: &mut Diag<'_>,
5986        trait_pred: ty::PolyTraitPredicate<'tcx>,
5987    ) {
5988        if ObligationCauseCode::QuestionMark != *obligation.cause.code().peel_derives() {
5989            return;
5990        }
5991
5992        // Only suggest for local function and associated method,
5993        // because this suggest adding both return type in
5994        // the `FnSig` and a default return value in the body, so it
5995        // is not suitable for foreign function without a local body,
5996        // and neither for trait method which may be also implemented
5997        // in other place, so shouldn't change it's FnSig.
5998        fn choose_suggest_items<'tcx, 'hir>(
5999            tcx: TyCtxt<'tcx>,
6000            node: hir::Node<'hir>,
6001        ) -> Option<(&'hir hir::FnDecl<'hir>, hir::BodyId)> {
6002            match node {
6003                hir::Node::Item(item)
6004                    if let hir::ItemKind::Fn { sig, body: body_id, .. } = item.kind =>
6005                {
6006                    Some((sig.decl, body_id))
6007                }
6008                hir::Node::ImplItem(item)
6009                    if let hir::ImplItemKind::Fn(sig, body_id) = item.kind =>
6010                {
6011                    let parent = tcx.parent_hir_node(item.hir_id());
6012                    if let hir::Node::Item(item) = parent
6013                        && let hir::ItemKind::Impl(imp) = item.kind
6014                        && imp.of_trait.is_none()
6015                    {
6016                        return Some((sig.decl, body_id));
6017                    }
6018                    None
6019                }
6020                _ => None,
6021            }
6022        }
6023
6024        let node = self.tcx.hir_node_by_def_id(obligation.cause.body_def_id);
6025        if let Some((fn_decl, body_id)) = choose_suggest_items(self.tcx, node)
6026            && let hir::FnRetTy::DefaultReturn(ret_span) = fn_decl.output
6027            && self.tcx.is_diagnostic_item(sym::FromResidual, trait_pred.def_id())
6028            && trait_pred.skip_binder().trait_ref.args.type_at(0).is_unit()
6029            && let ty::Adt(def, _) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
6030            && self.tcx.is_diagnostic_item(sym::Result, def.did())
6031        {
6032            let mut sugg_spans =
6033                ::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())];
6034            let body = self.tcx.hir_body(body_id);
6035            if let hir::ExprKind::Block(b, _) = body.value.kind
6036                && b.expr.is_none()
6037            {
6038                // The span of '}' in the end of block.
6039                let span = self.tcx.sess.source_map().end_point(b.span);
6040                sugg_spans.push((
6041                    span.shrink_to_lo(),
6042                    ::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!(
6043                        "{}{}",
6044                        "    Ok(())\n",
6045                        self.tcx.sess.source_map().indentation_before(span).unwrap_or_default(),
6046                    ),
6047                ));
6048            }
6049            err.multipart_suggestion(
6050                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider adding return type"))
    })format!("consider adding return type"),
6051                sugg_spans,
6052                Applicability::MaybeIncorrect,
6053            );
6054        }
6055    }
6056
6057    #[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(6057u32),
                                    ::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_all(&[]) })
                } 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:6077",
                                    "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(6077u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("pred")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("pred");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pred)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_def_id)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                        as &dyn ::tracing::field::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:6090",
                                    "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(6090u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("generics.params")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("generics.params");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generics.params)
                                                        as &dyn ::tracing::field::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:6091",
                                    "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(6091u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("generics.predicates")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("generics.predicates");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generics.predicates)
                                                        as &dyn ::tracing::field::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:6104",
                                    "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(6104u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("param")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("param");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param)
                                                        as &dyn ::tracing::field::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)]
6058    pub(super) fn suggest_unsized_bound_if_applicable(
6059        &self,
6060        err: &mut Diag<'_>,
6061        obligation: &PredicateObligation<'tcx>,
6062    ) {
6063        let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
6064            obligation.predicate.kind().skip_binder()
6065        else {
6066            return;
6067        };
6068        let (ObligationCauseCode::WhereClause(item_def_id, span)
6069        | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)) =
6070            *obligation.cause.code().peel_derives()
6071        else {
6072            return;
6073        };
6074        if span.is_dummy() {
6075            return;
6076        }
6077        debug!(?pred, ?item_def_id, ?span);
6078
6079        let (Some(node), true) = (
6080            self.tcx.hir_get_if_local(item_def_id),
6081            self.tcx.is_lang_item(pred.def_id(), LangItem::Sized),
6082        ) else {
6083            return;
6084        };
6085
6086        let Some(generics) = node.generics() else {
6087            return;
6088        };
6089        let sized_trait = self.tcx.lang_items().sized_trait();
6090        debug!(?generics.params);
6091        debug!(?generics.predicates);
6092        let Some(param) = generics.params.iter().find(|param| param.span == span) else {
6093            return;
6094        };
6095        // Check that none of the explicit trait bounds is `Sized`. Assume that an explicit
6096        // `Sized` bound is there intentionally and we don't need to suggest relaxing it.
6097        let explicitly_sized = generics
6098            .bounds_for_param(param.def_id)
6099            .flat_map(|bp| bp.bounds)
6100            .any(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) == sized_trait);
6101        if explicitly_sized {
6102            return;
6103        }
6104        debug!(?param);
6105        match node {
6106            hir::Node::Item(
6107                item @ hir::Item {
6108                    // Only suggest indirection for uses of type parameters in ADTs.
6109                    kind:
6110                        hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..),
6111                    ..
6112                },
6113            ) => {
6114                if self.suggest_indirection_for_unsized(err, item, param) {
6115                    return;
6116                }
6117            }
6118            _ => {}
6119        };
6120
6121        // Didn't add an indirection suggestion, so add a general suggestion to relax `Sized`.
6122        let (span, separator, open_paren_sp) =
6123            if let Some((s, open_paren_sp)) = generics.bounds_span_for_suggestions(param.def_id) {
6124                (s, " +", open_paren_sp)
6125            } else {
6126                (param.name.ident().span.shrink_to_hi(), ":", None)
6127            };
6128
6129        let mut suggs = vec![];
6130        let suggestion = format!("{separator} ?Sized");
6131
6132        if let Some(open_paren_sp) = open_paren_sp {
6133            suggs.push((open_paren_sp, "(".to_string()));
6134            suggs.push((span, format!("){suggestion}")));
6135        } else {
6136            suggs.push((span, suggestion));
6137        }
6138
6139        err.multipart_suggestion(
6140            "consider relaxing the implicit `Sized` restriction",
6141            suggs,
6142            Applicability::MachineApplicable,
6143        );
6144    }
6145
6146    fn suggest_indirection_for_unsized(
6147        &self,
6148        err: &mut Diag<'_>,
6149        item: &hir::Item<'tcx>,
6150        param: &hir::GenericParam<'tcx>,
6151    ) -> bool {
6152        // Suggesting `T: ?Sized` is only valid in an ADT if `T` is only used in a
6153        // borrow. `struct S<'a, T: ?Sized>(&'a T);` is valid, `struct S<T: ?Sized>(T);`
6154        // is not. Look for invalid "bare" parameter uses, and suggest using indirection.
6155        let mut visitor = FindTypeParam { param: param.name.ident().name, .. };
6156        visitor.visit_item(item);
6157        if visitor.invalid_spans.is_empty() {
6158            return false;
6159        }
6160        let mut multispan: MultiSpan = param.span.into();
6161        multispan.push_span_label(
6162            param.span,
6163            ::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()),
6164        );
6165        for sp in visitor.invalid_spans {
6166            multispan.push_span_label(
6167                sp,
6168                ::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()),
6169            );
6170        }
6171        err.span_help(
6172            multispan,
6173            ::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!(
6174                "you could relax the implicit `Sized` bound on `{T}` if it were \
6175                used through indirection like `&{T}` or `Box<{T}>`",
6176                T = param.name.ident(),
6177            ),
6178        );
6179        true
6180    }
6181    pub(crate) fn suggest_swapping_lhs_and_rhs<T>(
6182        &self,
6183        err: &mut Diag<'_>,
6184        predicate: T,
6185        param_env: ty::ParamEnv<'tcx>,
6186        cause_code: &ObligationCauseCode<'tcx>,
6187    ) where
6188        T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
6189    {
6190        let tcx = self.tcx;
6191        let predicate = predicate.upcast(tcx);
6192        match *cause_code {
6193            ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, rhs_span, .. }
6194                if let Some(typeck_results) = &self.typeck_results
6195                    && let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
6196                    && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
6197                    && let Some(lhs_ty) = typeck_results.expr_ty_opt(lhs)
6198                    && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs) =>
6199            {
6200                if let Some(pred) = predicate.as_trait_clause()
6201                    && tcx.is_lang_item(pred.def_id(), LangItem::PartialEq)
6202                    && self
6203                        .infcx
6204                        .type_implements_trait(pred.def_id(), [rhs_ty, lhs_ty], param_env)
6205                        .must_apply_modulo_regions()
6206                {
6207                    let lhs_span = tcx.hir_span(lhs_hir_id);
6208                    let sm = tcx.sess.source_map();
6209                    if let Ok(rhs_snippet) = sm.span_to_snippet(rhs_span)
6210                        && let Ok(lhs_snippet) = sm.span_to_snippet(lhs_span)
6211                    {
6212                        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}>`"));
6213                        err.multipart_suggestion(
6214                            "consider swapping the equality",
6215                            ::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)],
6216                            Applicability::MaybeIncorrect,
6217                        );
6218                    }
6219                }
6220            }
6221            _ => {}
6222        }
6223    }
6224}
6225
6226/// Add a hint to add a missing borrow or remove an unnecessary one.
6227fn hint_missing_borrow<'tcx>(
6228    infcx: &InferCtxt<'tcx>,
6229    param_env: ty::ParamEnv<'tcx>,
6230    span: Span,
6231    found: Ty<'tcx>,
6232    expected: Ty<'tcx>,
6233    found_node: Node<'_>,
6234    err: &mut Diag<'_>,
6235) {
6236    if #[allow(non_exhaustive_omitted_patterns)] match found_node {
    Node::TraitItem(..) => true,
    _ => false,
}matches!(found_node, Node::TraitItem(..)) {
6237        return;
6238    }
6239
6240    let found_args = match found.kind() {
6241        ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
6242        kind => {
6243            ::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)
6244        }
6245    };
6246    let expected_args = match expected.kind() {
6247        ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
6248        kind => {
6249            ::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)
6250        }
6251    };
6252
6253    // This could be a variant constructor, for example.
6254    let Some(fn_decl) = found_node.fn_decl() else {
6255        return;
6256    };
6257
6258    let args = fn_decl.inputs.iter();
6259
6260    let mut to_borrow = Vec::new();
6261    let mut remove_borrow = Vec::new();
6262
6263    for ((found_arg, expected_arg), arg) in found_args.zip(expected_args).zip(args) {
6264        let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
6265        let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
6266
6267        if infcx.can_eq(param_env, found_ty, expected_ty) {
6268            // FIXME: This could handle more exotic cases like mutability mismatches too!
6269            if found_refs.len() < expected_refs.len()
6270                && found_refs[..] == expected_refs[expected_refs.len() - found_refs.len()..]
6271            {
6272                to_borrow.push((
6273                    arg.span.shrink_to_lo(),
6274                    expected_refs[..expected_refs.len() - found_refs.len()]
6275                        .iter()
6276                        .map(|mutbl| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
    })format!("&{}", mutbl.prefix_str()))
6277                        .collect::<Vec<_>>()
6278                        .join(""),
6279                ));
6280            } else if found_refs.len() > expected_refs.len() {
6281                let mut span = arg.span.shrink_to_lo();
6282                let mut left = found_refs.len() - expected_refs.len();
6283                let mut ty = arg;
6284                while let hir::TyKind::Ref(_, mut_ty) = &ty.kind
6285                    && left > 0
6286                {
6287                    span = span.with_hi(mut_ty.ty.span.lo());
6288                    ty = mut_ty.ty;
6289                    left -= 1;
6290                }
6291                if left == 0 {
6292                    remove_borrow.push((span, String::new()));
6293                }
6294            }
6295        }
6296    }
6297
6298    if !to_borrow.is_empty() {
6299        err.subdiagnostic(diagnostics::AdjustSignatureBorrow::Borrow { to_borrow });
6300    }
6301
6302    if !remove_borrow.is_empty() {
6303        err.subdiagnostic(diagnostics::AdjustSignatureBorrow::RemoveBorrow { remove_borrow });
6304    }
6305}
6306
6307/// Collect all the paths that reference `Self`.
6308/// Used to suggest replacing associated types with an explicit type in `where` clauses.
6309#[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)]
6310pub struct SelfVisitor<'v> {
6311    pub paths: Vec<&'v hir::Ty<'v>> = Vec::new(),
6312    pub name: Option<Symbol>,
6313}
6314
6315impl<'v> Visitor<'v> for SelfVisitor<'v> {
6316    fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
6317        if let hir::TyKind::Path(path) = ty.kind
6318            && let hir::QPath::TypeRelative(inner_ty, segment) = path
6319            && (Some(segment.ident.name) == self.name || self.name.is_none())
6320            && let hir::TyKind::Path(inner_path) = inner_ty.kind
6321            && let hir::QPath::Resolved(None, inner_path) = inner_path
6322            && let Res::SelfTyAlias { .. } = inner_path.res
6323        {
6324            self.paths.push(ty.as_unambig_ty());
6325        }
6326        hir::intravisit::walk_ty(self, ty);
6327    }
6328}
6329
6330/// Collect all the returned expressions within the input expression.
6331/// Used to point at the return spans when we want to suggest some change to them.
6332#[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)]
6333pub struct ReturnsVisitor<'v> {
6334    pub returns: Vec<&'v hir::Expr<'v>>,
6335    in_block_tail: bool,
6336}
6337
6338impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
6339    fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
6340        // Visit every expression to detect `return` paths, either through the function's tail
6341        // expression or `return` statements. We walk all nodes to find `return` statements, but
6342        // we only care about tail expressions when `in_block_tail` is `true`, which means that
6343        // they're in the return path of the function body.
6344        match ex.kind {
6345            hir::ExprKind::Ret(Some(ex)) => {
6346                self.returns.push(ex);
6347            }
6348            hir::ExprKind::Block(block, _) if self.in_block_tail => {
6349                self.in_block_tail = false;
6350                for stmt in block.stmts {
6351                    hir::intravisit::walk_stmt(self, stmt);
6352                }
6353                self.in_block_tail = true;
6354                if let Some(expr) = block.expr {
6355                    self.visit_expr(expr);
6356                }
6357            }
6358            hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
6359                self.visit_expr(then);
6360                if let Some(el) = else_opt {
6361                    self.visit_expr(el);
6362                }
6363            }
6364            hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
6365                for arm in arms {
6366                    self.visit_expr(arm.body);
6367                }
6368            }
6369            // We need to walk to find `return`s in the entire body.
6370            _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
6371            _ => self.returns.push(ex),
6372        }
6373    }
6374
6375    fn visit_body(&mut self, body: &hir::Body<'v>) {
6376        if !!self.in_block_tail {
    ::core::panicking::panic("assertion failed: !self.in_block_tail")
};assert!(!self.in_block_tail);
6377        self.in_block_tail = true;
6378        hir::intravisit::walk_body(self, body);
6379    }
6380}
6381
6382/// Collect all the awaited expressions within the input expression.
6383#[derive(#[automatically_derived]
impl ::core::default::Default for AwaitsVisitor {
    #[inline]
    fn default() -> AwaitsVisitor {
        AwaitsVisitor { awaits: ::core::default::Default::default() }
    }
}Default)]
6384struct AwaitsVisitor {
6385    awaits: Vec<HirId>,
6386}
6387
6388impl<'v> Visitor<'v> for AwaitsVisitor {
6389    fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
6390        if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
6391            self.awaits.push(id)
6392        }
6393        hir::intravisit::walk_expr(self, ex)
6394    }
6395}
6396
6397/// Suggest a new type parameter name for diagnostic purposes.
6398///
6399/// `name` is the preferred name you'd like to suggest if it's not in use already.
6400pub trait NextTypeParamName {
6401    fn next_type_param_name(&self, name: Option<&str>) -> String;
6402}
6403
6404impl NextTypeParamName for &[hir::GenericParam<'_>] {
6405    fn next_type_param_name(&self, name: Option<&str>) -> String {
6406        // Type names are usually single letters in uppercase. So convert the first letter of input string to uppercase.
6407        let name = name.and_then(|n| n.chars().next()).map(|c| c.to_uppercase().to_string());
6408        let name = name.as_deref();
6409
6410        // This is the list of possible parameter names that we might suggest.
6411        let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
6412
6413        // Filter out used names based on `filter_fn`.
6414        let used_names: Vec<Symbol> = self
6415            .iter()
6416            .filter_map(|param| match param.name {
6417                hir::ParamName::Plain(ident) => Some(ident.name),
6418                _ => None,
6419            })
6420            .collect();
6421
6422        // Find a name from `possible_names` that is not in `used_names`.
6423        possible_names
6424            .iter()
6425            .find(|n| !used_names.contains(&Symbol::intern(n)))
6426            .unwrap_or(&"ParamName")
6427            .to_string()
6428    }
6429}
6430
6431/// Collect the spans that we see the generic param `param_did`
6432struct ReplaceImplTraitVisitor<'a> {
6433    ty_spans: &'a mut Vec<Span>,
6434    param_did: DefId,
6435}
6436
6437impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
6438    fn visit_ty(&mut self, t: &'hir hir::Ty<'hir, AmbigArg>) {
6439        if let hir::TyKind::Path(hir::QPath::Resolved(
6440            None,
6441            hir::Path { res: Res::Def(_, segment_did), .. },
6442        )) = t.kind
6443        {
6444            if self.param_did == *segment_did {
6445                // `fn foo(t: impl Trait)`
6446                //            ^^^^^^^^^^ get this to suggest `T` instead
6447
6448                // There might be more than one `impl Trait`.
6449                self.ty_spans.push(t.span);
6450                return;
6451            }
6452        }
6453
6454        hir::intravisit::walk_ty(self, t);
6455    }
6456}
6457
6458pub(super) fn get_explanation_based_on_obligation<'tcx>(
6459    tcx: TyCtxt<'tcx>,
6460    obligation: &PredicateObligation<'tcx>,
6461    trait_predicate: ty::PolyTraitPredicate<'tcx>,
6462    pre_message: String,
6463    long_ty_path: &mut Option<PathBuf>,
6464) -> String {
6465    if let ObligationCauseCode::MainFunctionType = obligation.cause.code() {
6466        "consider using `()`, or a `Result`".to_owned()
6467    } else {
6468        let ty_desc = match trait_predicate.self_ty().skip_binder().kind() {
6469            ty::FnDef(_, _) => Some("fn item"),
6470            ty::Closure(_, _) => Some("closure"),
6471            _ => None,
6472        };
6473
6474        let desc = match ty_desc {
6475            Some(desc) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {0}", desc))
    })format!(" {desc}"),
6476            None => String::new(),
6477        };
6478        if let ty::PredicatePolarity::Positive = trait_predicate.polarity() {
6479            // If the trait in question is unstable, mention that fact in the diagnostic.
6480            // But if we're building with `-Zforce-unstable-if-unmarked` then _any_ trait
6481            // not explicitly marked stable is considered unstable, so the extra text is
6482            // unhelpful noise. See <https://github.com/rust-lang/rust/issues/152692>.
6483            let mention_unstable = !tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
6484                && try { tcx.lookup_stability(trait_predicate.def_id())?.level.is_stable() }
6485                    == Some(false);
6486            let unstable = if mention_unstable { "nightly-only, unstable " } else { "" };
6487
6488            ::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!(
6489                "{pre_message}the {unstable}trait `{}` is not implemented for{desc} `{}`",
6490                trait_predicate.print_modifiers_and_trait_path(),
6491                tcx.short_string(trait_predicate.self_ty().skip_binder(), long_ty_path),
6492            )
6493        } else {
6494            // "the trait bound `T: !Send` is not satisfied" reads better than "`!Send` is
6495            // not implemented for `T`".
6496            // FIXME: add note explaining explicit negative trait bounds.
6497            ::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")
6498        }
6499    }
6500}
6501
6502// Replace `param` with `replace_ty`
6503struct ReplaceImplTraitFolder<'tcx> {
6504    tcx: TyCtxt<'tcx>,
6505    param: &'tcx ty::GenericParamDef,
6506    replace_ty: Ty<'tcx>,
6507}
6508
6509impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceImplTraitFolder<'tcx> {
6510    fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
6511        if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
6512            if self.param.index == *index {
6513                return self.replace_ty;
6514            }
6515        }
6516        t.super_fold_with(self)
6517    }
6518
6519    fn cx(&self) -> TyCtxt<'tcx> {
6520        self.tcx
6521    }
6522}
6523
6524pub fn suggest_desugaring_async_fn_to_impl_future_in_trait<'tcx>(
6525    tcx: TyCtxt<'tcx>,
6526    sig: hir::FnSig<'tcx>,
6527    body: hir::TraitFn<'tcx>,
6528    opaque_def_id: LocalDefId,
6529    add_bounds: &str,
6530) -> Option<Vec<(Span, String)>> {
6531    let hir::IsAsync::Async(async_span) = sig.header.asyncness else {
6532        return None;
6533    };
6534    let async_span = tcx.sess.source_map().span_extend_while_whitespace(async_span);
6535
6536    let future = tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
6537    let [hir::GenericBound::Trait(trait_ref)] = future.bounds else {
6538        // `async fn` should always lower to a single bound... but don't ICE.
6539        return None;
6540    };
6541    let Some(hir::PathSegment { args: Some(args), .. }) = trait_ref.trait_ref.path.segments.last()
6542    else {
6543        // desugaring to a single path segment for `Future<...>`.
6544        return None;
6545    };
6546    let Some(future_output_ty) = args.constraints.first().and_then(|constraint| constraint.ty())
6547    else {
6548        // Also should never happen.
6549        return None;
6550    };
6551
6552    let mut sugg = if future_output_ty.span.is_empty() {
6553        ::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![
6554            (async_span, String::new()),
6555            (
6556                future_output_ty.span,
6557                format!(" -> impl std::future::Future<Output = ()>{add_bounds}"),
6558            ),
6559        ]
6560    } else {
6561        ::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![
6562            (future_output_ty.span.shrink_to_lo(), "impl std::future::Future<Output = ".to_owned()),
6563            (future_output_ty.span.shrink_to_hi(), format!(">{add_bounds}")),
6564            (async_span, String::new()),
6565        ]
6566    };
6567
6568    // If there's a body, we also need to wrap it in `async {}`
6569    if let hir::TraitFn::Provided(body) = body {
6570        let body = tcx.hir_body(body);
6571        let body_span = body.value.span;
6572        let body_span_without_braces =
6573            body_span.with_lo(body_span.lo() + BytePos(1)).with_hi(body_span.hi() - BytePos(1));
6574        if body_span_without_braces.is_empty() {
6575            sugg.push((body_span_without_braces, " async {} ".to_owned()));
6576        } else {
6577            sugg.extend([
6578                (body_span_without_braces.shrink_to_lo(), "async {".to_owned()),
6579                (body_span_without_braces.shrink_to_hi(), "} ".to_owned()),
6580            ]);
6581        }
6582    }
6583
6584    Some(sugg)
6585}
6586
6587/// On `impl` evaluation cycles, look for `Self::AssocTy` restrictions in `where` clauses, explain
6588/// they are not allowed and if possible suggest alternatives.
6589fn point_at_assoc_type_restriction<G: EmissionGuarantee>(
6590    tcx: TyCtxt<'_>,
6591    err: &mut Diag<'_, G>,
6592    self_ty_str: &str,
6593    trait_name: &str,
6594    predicate: ty::Predicate<'_>,
6595    generics: &hir::Generics<'_>,
6596    data: &ImplDerivedCause<'_>,
6597) {
6598    let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() else {
6599        return;
6600    };
6601    let ty::ClauseKind::Projection(proj) = clause else {
6602        return;
6603    };
6604    let Some(name) = tcx
6605        .opt_rpitit_info(proj.def_id())
6606        .and_then(|data| match data {
6607            ty::ImplTraitInTraitData::Trait { fn_def_id, .. } => Some(tcx.item_name(fn_def_id)),
6608            ty::ImplTraitInTraitData::Impl { .. } => None,
6609        })
6610        .or_else(|| tcx.opt_item_name(proj.def_id()))
6611    else {
6612        return;
6613    };
6614    let mut predicates = generics.predicates.iter().peekable();
6615    let mut prev: Option<(&hir::WhereBoundPredicate<'_>, Span)> = None;
6616    while let Some(pred) = predicates.next() {
6617        let curr_span = pred.span;
6618        let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind else {
6619            continue;
6620        };
6621        let mut bounds = pred.bounds.iter();
6622        while let Some(bound) = bounds.next() {
6623            let Some(trait_ref) = bound.trait_ref() else {
6624                continue;
6625            };
6626            if bound.span() != data.span {
6627                continue;
6628            }
6629            if let hir::TyKind::Path(path) = pred.bounded_ty.kind
6630                && let hir::QPath::TypeRelative(ty, segment) = path
6631                && segment.ident.name == name
6632                && let hir::TyKind::Path(inner_path) = ty.kind
6633                && let hir::QPath::Resolved(None, inner_path) = inner_path
6634                && let Res::SelfTyAlias { .. } = inner_path.res
6635            {
6636                // The following block is to determine the right span to delete for this bound
6637                // that will leave valid code after the suggestion is applied.
6638                let span = if pred.origin == hir::PredicateOrigin::WhereClause
6639                    && generics
6640                        .predicates
6641                        .iter()
6642                        .filter(|p| {
6643                            #[allow(non_exhaustive_omitted_patterns)] match p.kind {
    hir::WherePredicateKind::BoundPredicate(p) if
        hir::PredicateOrigin::WhereClause == p.origin => true,
    _ => false,
}matches!(
6644                                p.kind,
6645                                hir::WherePredicateKind::BoundPredicate(p)
6646                                if hir::PredicateOrigin::WhereClause == p.origin
6647                            )
6648                        })
6649                        .count()
6650                        == 1
6651                {
6652                    // There's only one `where` bound, that needs to be removed. Remove the whole
6653                    // `where` clause.
6654                    generics.where_clause_span
6655                } else if let Some(next_pred) = predicates.peek()
6656                    && let hir::WherePredicateKind::BoundPredicate(next) = next_pred.kind
6657                    && pred.origin == next.origin
6658                {
6659                    // There's another bound, include the comma for the current one.
6660                    curr_span.until(next_pred.span)
6661                } else if let Some((prev, prev_span)) = prev
6662                    && pred.origin == prev.origin
6663                {
6664                    // Last bound, try to remove the previous comma.
6665                    prev_span.shrink_to_hi().to(curr_span)
6666                } else if pred.origin == hir::PredicateOrigin::WhereClause {
6667                    curr_span.with_hi(generics.where_clause_span.hi())
6668                } else {
6669                    curr_span
6670                };
6671
6672                err.span_suggestion_verbose(
6673                    span,
6674                    "associated type for the current `impl` cannot be restricted in `where` \
6675                     clauses, remove this bound",
6676                    "",
6677                    Applicability::MaybeIncorrect,
6678                );
6679            }
6680            if let Some(new) =
6681                tcx.associated_items(data.impl_or_alias_def_id).find_by_ident_and_kind(
6682                    tcx,
6683                    Ident::with_dummy_span(name),
6684                    ty::AssocTag::Type,
6685                    data.impl_or_alias_def_id,
6686                )
6687            {
6688                // The associated type is specified in the `impl` we're
6689                // looking at. Point at it.
6690                let span = tcx.def_span(new.def_id);
6691                err.span_label(
6692                    span,
6693                    ::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!(
6694                        "associated type `<{self_ty_str} as {trait_name}>::{name}` is specified \
6695                         here",
6696                    ),
6697                );
6698                // Search for the associated type `Self::{name}`, get
6699                // its type and suggest replacing the bound with it.
6700                let mut visitor = SelfVisitor { name: Some(name), .. };
6701                visitor.visit_trait_ref(trait_ref);
6702                for path in visitor.paths {
6703                    err.span_suggestion_verbose(
6704                        path.span,
6705                        "replace the associated type with the type specified in this `impl`",
6706                        tcx.type_of(new.def_id).skip_binder(),
6707                        Applicability::MachineApplicable,
6708                    );
6709                }
6710            } else {
6711                let mut visitor = SelfVisitor { name: None, .. };
6712                visitor.visit_trait_ref(trait_ref);
6713                let span: MultiSpan =
6714                    visitor.paths.iter().map(|p| p.span).collect::<Vec<Span>>().into();
6715                err.span_note(
6716                    span,
6717                    "associated types for the current `impl` cannot be restricted in `where` \
6718                     clauses",
6719                );
6720            }
6721        }
6722        prev = Some((pred, curr_span));
6723    }
6724}
6725
6726fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec<hir::Mutability>) {
6727    let mut refs = ::alloc::vec::Vec::new()vec![];
6728
6729    while let ty::Ref(_, new_ty, mutbl) = ty.kind() {
6730        ty = *new_ty;
6731        refs.push(*mutbl);
6732    }
6733
6734    (ty, refs)
6735}
6736
6737/// Look for type `param` in an ADT being used only through a reference to confirm that suggesting
6738/// `param: ?Sized` would be a valid constraint.
6739struct FindTypeParam {
6740    param: rustc_span::Symbol,
6741    invalid_spans: Vec<Span> = Vec::new(),
6742    nested: bool = false,
6743}
6744
6745impl<'v> Visitor<'v> for FindTypeParam {
6746    fn visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>) {
6747        // Skip where-clauses, to avoid suggesting indirection for type parameters found there.
6748    }
6749
6750    fn visit_ty(&mut self, ty: &hir::Ty<'_, AmbigArg>) {
6751        // We collect the spans of all uses of the "bare" type param, like in `field: T` or
6752        // `field: (T, T)` where we could make `T: ?Sized` while skipping cases that are known to be
6753        // valid like `field: &'a T` or `field: *mut T` and cases that *might* have further `Sized`
6754        // obligations like `Box<T>` and `Vec<T>`, but we perform no extra analysis for those cases
6755        // and suggest `T: ?Sized` regardless of their obligations. This is fine because the errors
6756        // in that case should make what happened clear enough.
6757        match ty.kind {
6758            hir::TyKind::Ptr(_) | hir::TyKind::Ref(..) | hir::TyKind::TraitObject(..) => {}
6759            hir::TyKind::Path(hir::QPath::Resolved(None, path))
6760                if let [segment] = path.segments
6761                    && segment.ident.name == self.param =>
6762            {
6763                if !self.nested {
6764                    {
    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:6764",
                        "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(6764u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("ty")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("ty");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("FindTypeParam::visit_ty")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?ty, "FindTypeParam::visit_ty");
6765                    self.invalid_spans.push(ty.span);
6766                }
6767            }
6768            hir::TyKind::Path(_) => {
6769                let prev = self.nested;
6770                self.nested = true;
6771                hir::intravisit::walk_ty(self, ty);
6772                self.nested = prev;
6773            }
6774            _ => {
6775                hir::intravisit::walk_ty(self, ty);
6776            }
6777        }
6778    }
6779}
6780
6781/// Look for type parameters in predicates. We use this to identify whether a bound is suitable in
6782/// on a given item.
6783struct ParamFinder {
6784    params: Vec<Symbol> = Vec::new(),
6785}
6786
6787impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ParamFinder {
6788    fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
6789        match t.kind() {
6790            ty::Param(p) => self.params.push(p.name),
6791            _ => {}
6792        }
6793        t.super_visit_with(self)
6794    }
6795}
6796
6797impl ParamFinder {
6798    /// Whether the `hir::Generics` of the current item can suggest the evaluated bound because its
6799    /// references to type parameters are present in the generics.
6800    fn can_suggest_bound(&self, generics: &hir::Generics<'_>) -> bool {
6801        if self.params.is_empty() {
6802            // There are no references to type parameters at all, so suggesting the bound
6803            // would be reasonable.
6804            return true;
6805        }
6806        generics.params.iter().any(|p| match p.name {
6807            hir::ParamName::Plain(p_name) => {
6808                // All of the parameters in the bound can be referenced in the current item.
6809                self.params.iter().any(|p| *p == p_name.name || *p == kw::SelfUpper)
6810            }
6811            _ => true,
6812        })
6813    }
6814}