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