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_attr_ir::lang_items::{self, LangItem};
10use rustc_data_structures::fx::FxHashSet;
11use rustc_errors::codes::*;
12use rustc_errors::{
13    Applicability, Diag, MultiSpan, Style, SuggestionStyle, pluralize, struct_span_code_err,
14};
15use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
16use rustc_hir::def_id::DefId;
17use rustc_hir::intravisit::Visitor;
18use rustc_hir::{
19    self as hir, AmbigArg, CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, HirId, Node,
20    expr_needs_parens,
21};
22use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferCtxt, InferOk};
23use rustc_infer::traits::ImplSource;
24use rustc_middle::middle::privacy::Level;
25use rustc_middle::traits::IsConstable;
26use rustc_middle::ty::adjustment::{Adjust, DerefAdjustKind};
27use rustc_middle::ty::error::TypeError;
28use rustc_middle::ty::print::{
29    PrintPolyTraitClauseExt as _, PrintPolyTraitRefExt, PrintTraitClauseExt as _,
30    PrintTraitRefExt as _, with_forced_trimmed_paths, with_no_trimmed_paths,
31    with_types_for_suggestion,
32};
33use rustc_middle::ty::{
34    self, AdtKind, GenericArgs, InferTy, IsSuggestable, Ty, TyCtxt, TypeFoldable, TypeFolder,
35    TypeSuperFoldable, TypeSuperVisitable, TypeVisitableExt, TypeVisitor, TypeckResults,
36    Unnormalized, Upcast, suggest_arbitrary_trait_bound, suggest_constraining_type_param,
37};
38use rustc_span::def_id::LocalDefId;
39use rustc_span::{
40    BytePos, DUMMY_SP, DesugaringKind, ExpnKind, Ident, MacroKind, Span, Symbol, bug, kw, span_bug,
41    sym,
42};
43use tracing::{debug, instrument};
44
45use super::{
46    DefIdOrName, FindExprBySpan, ImplCandidate, Obligation, ObligationCause, ObligationCauseCode,
47    PredicateObligation,
48};
49use crate::diagnostics;
50use crate::error_reporting::TypeErrCtxt;
51use crate::infer::InferCtxtExt as _;
52use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
53use crate::traits::{ImplDerivedCause, NormalizeExt, ObligationCtxt, SelectionContext};
54
55#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CoroutineInteriorOrUpvar {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Interior(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "Interior", __self_0, &__self_1),
            Self::Upvar(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Upvar",
                    &__self_0),
        }
    }
}Debug)]
56pub enum CoroutineInteriorOrUpvar {
57    // span of interior type
58    Interior(Span, Option<(Span, Option<Span>)>),
59    // span of upvar
60    Upvar(Span),
61}
62
63// This type provides a uniform interface to retrieve data on coroutines, whether it originated from
64// the local crate being compiled or from a foreign crate.
65#[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)]
66struct CoroutineData<'a, 'tcx>(&'a TypeckResults<'tcx>);
67
68impl<'a, 'tcx> CoroutineData<'a, 'tcx> {
69    /// Try to get information about variables captured by the coroutine that matches a type we are
70    /// looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
71    /// meet an obligation
72    fn try_get_upvar_span<F>(
73        &self,
74        infer_context: &InferCtxt<'tcx>,
75        coroutine_did: DefId,
76        ty_matches: F,
77    ) -> Option<CoroutineInteriorOrUpvar>
78    where
79        F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
80    {
81        infer_context.tcx.upvars_mentioned(coroutine_did).and_then(|upvars| {
82            upvars.iter().find_map(|(upvar_id, upvar)| {
83                let upvar_ty = self.0.node_type(*upvar_id);
84                let upvar_ty = infer_context.deeply_resolve_ignoring_regions(upvar_ty);
85                ty_matches(ty::Binder::dummy(upvar_ty))
86                    .then(|| CoroutineInteriorOrUpvar::Upvar(upvar.span))
87            })
88        })
89    }
90
91    /// Try to get the span of a type being awaited on that matches the type we are looking with the
92    /// `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
93    /// obligation
94    fn get_from_await_ty<F>(
95        &self,
96        visitor: AwaitsVisitor,
97        tcx: TyCtxt<'tcx>,
98        ty_matches: F,
99    ) -> Option<Span>
100    where
101        F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
102    {
103        visitor
104            .awaits
105            .into_iter()
106            .map(|id| tcx.hir_expect_expr(id))
107            .find(|await_expr| ty_matches(ty::Binder::dummy(self.0.expr_ty_adjusted(await_expr))))
108            .map(|expr| expr.span)
109    }
110}
111
112fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
113    (
114        generics.tail_span_for_predicate_suggestion(),
115        {
    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)),
116    )
117}
118
119/// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
120/// it can also be an `impl Trait` param that needs to be decomposed to a type
121/// param for cleaner code.
122pub fn suggest_restriction<'tcx>(
123    tcx: TyCtxt<'tcx>,
124    item_id: LocalDefId,
125    hir_generics: &hir::Generics<'tcx>,
126    msg: &str,
127    err: &mut Diag<'_>,
128    fn_sig: Option<&hir::FnSig<'_>>,
129    projection: Option<ty::ProjectionAliasTy<'_>>,
130    trait_pred: ty::PolyTraitClause<'tcx>,
131    // When we are dealing with a trait, `super_traits` will be `Some`:
132    // Given `trait T: A + B + C {}`
133    //              -  ^^^^^^^^^ GenericBounds
134    //              |
135    //              &Ident
136    super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
137) {
138    if hir_generics.where_clause_span.from_expansion()
139        || hir_generics.where_clause_span.desugaring_kind().is_some()
140        || projection.is_some_and(|projection| {
141            (tcx.is_impl_trait_in_trait(projection.kind) && !tcx.features().return_type_notation())
142                || tcx.lookup_stability(projection.kind).is_some_and(|stab| stab.is_unstable())
143        })
144    {
145        return;
146    }
147    let generics = tcx.generics_of(item_id);
148    // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
149    if let Some((param, bound_str, fn_sig)) =
150        fn_sig.zip(projection).and_then(|(sig, p)| match *p.projection_self_ty().kind() {
151            // Shenanigans to get the `Trait` from the `impl Trait`.
152            ty::Param(param) => {
153                let param_def = generics.type_param(param, tcx);
154                if param_def.kind.is_synthetic() {
155                    let bound_str =
156                        param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
157                    return Some((param_def, bound_str, sig));
158                }
159                None
160            }
161            _ => None,
162        })
163    {
164        let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
165        let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
166            tcx,
167            param,
168            replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
169                .to_ty(tcx),
170        });
171        if !trait_pred.is_suggestable(tcx, false) {
172            return;
173        }
174        // We know we have an `impl Trait` that doesn't satisfy a required projection.
175
176        // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
177        // types. There should be at least one, but there might be *more* than one. In that
178        // case we could just ignore it and try to identify which one needs the restriction,
179        // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
180        // where `T: Trait`.
181        let mut ty_spans = ::alloc::vec::Vec::new()vec![];
182        for input in fn_sig.decl.inputs {
183            ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
184                .visit_ty_unambig(input);
185        }
186        // The type param `T: Trait` we will suggest to introduce.
187        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}");
188
189        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![
190            if let Some(span) = hir_generics.span_for_param_suggestion() {
191                (span, format!(", {type_param}"))
192            } else {
193                (hir_generics.span, format!("<{type_param}>"))
194            },
195            // `fn foo(t: impl Trait)`
196            //                       ^ suggest `where <T as Trait>::A: Bound`
197            predicate_constraint(hir_generics, trait_pred.upcast(tcx)),
198        ];
199        sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
200
201        // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
202        // FIXME: we should suggest `fn foo(t: impl Trait<A: Bound>)` instead.
203        err.multipart_suggestion(
204            "introduce a type parameter with a trait bound instead of using `impl Trait`",
205            sugg,
206            Applicability::MaybeIncorrect,
207        );
208    } else {
209        if !trait_pred.is_suggestable(tcx, false) {
210            return;
211        }
212        // Trivial case: `T` needs an extra bound: `T: Bound`.
213        let (sp, suggestion) = match (
214            hir_generics
215                .params
216                .iter()
217                .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, .. })),
218            super_traits,
219        ) {
220            (_, None) => predicate_constraint(hir_generics, trait_pred.upcast(tcx)),
221            (None, Some((ident, []))) => (
222                ident.span.shrink_to_hi(),
223                ::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()),
224            ),
225            (_, Some((_, [.., bounds]))) => (
226                bounds.span().shrink_to_hi(),
227                ::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()),
228            ),
229            (Some(_), Some((_, []))) => (
230                hir_generics.span.shrink_to_hi(),
231                ::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()),
232            ),
233        };
234
235        err.span_suggestion_verbose(
236            sp,
237            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider further restricting {0}",
                msg))
    })format!("consider further restricting {msg}"),
238            suggestion,
239            Applicability::MachineApplicable,
240        );
241    }
242}
243
244/// A single layer of `&` peeled from an expression, used by
245/// [`TypeErrCtxt::peel_expr_refs`].
246struct PeeledRef<'tcx> {
247    /// The span covering the `&` (and any whitespace/mutability keyword) to remove.
248    span: Span,
249    /// The type after peeling this layer (and all prior layers).
250    peeled_ty: Ty<'tcx>,
251}
252
253impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
254    pub fn note_field_shadowed_by_private_candidate_in_cause(
255        &self,
256        err: &mut Diag<'_>,
257        cause: &ObligationCause<'tcx>,
258        param_env: ty::ParamEnv<'tcx>,
259    ) {
260        let mut hir_ids = FxHashSet::default();
261        // Walk the parent chain so we can recover
262        // the source expression from whichever layer carries them.
263        let mut next_code = Some(cause.code());
264        while let Some(cause_code) = next_code {
265            match cause_code {
266                ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. } => {
267                    hir_ids.insert(*lhs_hir_id);
268                    hir_ids.insert(*rhs_hir_id);
269                }
270                ObligationCauseCode::FunctionArg { arg_hir_id, .. }
271                | ObligationCauseCode::ReturnValue(arg_hir_id)
272                | ObligationCauseCode::AwaitableExpr(arg_hir_id)
273                | ObligationCauseCode::BlockTailExpression(arg_hir_id, _)
274                | ObligationCauseCode::UnOp { hir_id: arg_hir_id } => {
275                    hir_ids.insert(*arg_hir_id);
276                }
277                ObligationCauseCode::OpaqueReturnType(Some((_, hir_id))) => {
278                    hir_ids.insert(*hir_id);
279                }
280                _ => {}
281            }
282            next_code = cause_code.parent();
283        }
284
285        if !cause.span.is_dummy()
286            && let Some(body) = self.tcx.hir_maybe_body_owned_by(cause.body_def_id)
287        {
288            let mut expr_finder = FindExprBySpan::new(cause.span, self.tcx);
289            expr_finder.visit_body(body);
290            if let Some(expr) = expr_finder.result {
291                hir_ids.insert(expr.hir_id);
292            }
293        }
294
295        // we will sort immediately by source order before emitting any diagnostics
296        #[allow(rustc::potential_query_instability)]
297        let mut hir_ids: Vec<_> = hir_ids.into_iter().collect();
298        let source_map = self.tcx.sess.source_map();
299        hir_ids.sort_by_cached_key(|hir_id| {
300            let span = self.tcx.hir_span(*hir_id);
301            let lo = source_map.lookup_byte_offset(span.lo());
302            let hi = source_map.lookup_byte_offset(span.hi());
303            (lo.sf.name.prefer_remapped_unconditionally().to_string(), lo.pos.0, hi.pos.0)
304        });
305
306        for hir_id in hir_ids {
307            self.note_field_shadowed_by_private_candidate(err, hir_id, param_env);
308        }
309    }
310
311    pub fn note_field_shadowed_by_private_candidate(
312        &self,
313        err: &mut Diag<'_>,
314        hir_id: hir::HirId,
315        param_env: ty::ParamEnv<'tcx>,
316    ) {
317        let Some(typeck_results) = &self.typeck_results else {
318            return;
319        };
320        let Node::Expr(expr) = self.tcx.hir_node(hir_id) else {
321            return;
322        };
323        let hir::ExprKind::Field(base_expr, field_ident) = expr.kind else {
324            return;
325        };
326
327        let Some(base_ty) = typeck_results.expr_ty_opt(base_expr) else {
328            return;
329        };
330        let base_ty = self.deeply_resolve_ignoring_regions(base_ty);
331        if base_ty.references_error() {
332            return;
333        }
334
335        let mut private_candidate: Option<(Ty<'tcx>, Ty<'tcx>, Span)> = None;
336
337        for (deref_base_ty, _) in (self.autoderef_steps)(base_ty) {
338            let ty::Adt(base_def, args) = deref_base_ty.kind() else {
339                continue;
340            };
341
342            if base_def.is_enum() {
343                continue;
344            }
345
346            let (adjusted_ident, def_scope) = self.tcx.adjust_ident_and_get_scope(
347                field_ident,
348                base_def.did(),
349                self.tcx.parent_module_from_def_id(typeck_results.hir_owner.def_id),
350            );
351
352            let Some((_, field_def)) =
353                base_def.non_enum_variant().fields.iter_enumerated().find(|(_, field)| {
354                    field.ident(self.tcx).normalize_to_macros_2_0() == adjusted_ident
355                })
356            else {
357                continue;
358            };
359            let field_span = self
360                .tcx
361                .def_ident_span(field_def.did)
362                .unwrap_or_else(|| self.tcx.def_span(field_def.did));
363
364            if field_def.vis.is_accessible_from(def_scope, self.tcx) {
365                let accessible_field_ty = field_def.ty(self.tcx, args).skip_norm_wip();
366                if let Some((private_base_ty, private_field_ty, private_field_span)) =
367                    private_candidate
368                    && !self.can_eq(param_env, private_field_ty, accessible_field_ty)
369                {
370                    let private_struct_span = match private_base_ty.kind() {
371                        ty::Adt(private_base_def, _) => self
372                            .tcx
373                            .def_ident_span(private_base_def.did())
374                            .unwrap_or_else(|| self.tcx.def_span(private_base_def.did())),
375                        _ => DUMMY_SP,
376                    };
377                    let accessible_struct_span = self
378                        .tcx
379                        .def_ident_span(base_def.did())
380                        .unwrap_or_else(|| self.tcx.def_span(base_def.did()));
381                    let deref_impl_span = (typeck_results
382                        .expr_adjustments(base_expr)
383                        .iter()
384                        .filter(|adj| {
385                            #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
    Adjust::Deref(DerefAdjustKind::Overloaded(_)) => true,
    _ => false,
}matches!(adj.kind, Adjust::Deref(DerefAdjustKind::Overloaded(_)))
386                        })
387                        .count()
388                        == 1)
389                        .then(|| {
390                            self.probe(|_| {
391                                let deref_trait_did =
392                                    self.tcx.require_lang_item(LangItem::Deref, DUMMY_SP);
393                                let trait_ref =
394                                    ty::TraitRef::new(self.tcx, deref_trait_did, [private_base_ty]);
395                                let obligation: Obligation<'tcx, ty::Predicate<'tcx>> =
396                                    Obligation::new(
397                                        self.tcx,
398                                        ObligationCause::dummy(),
399                                        param_env,
400                                        trait_ref,
401                                    );
402                                let Ok(Some(ImplSource::UserDefined(impl_data))) =
403                                    SelectionContext::new(self)
404                                        .select(&obligation.with(self.tcx, trait_ref))
405                                else {
406                                    return None;
407                                };
408                                Some(self.tcx.def_span(impl_data.impl_def_id))
409                            })
410                        })
411                        .flatten();
412
413                    let mut note_spans: MultiSpan = private_struct_span.into();
414                    if private_struct_span != DUMMY_SP {
415                        note_spans.push_span_label(private_struct_span, "in this struct");
416                    }
417                    if private_field_span != DUMMY_SP {
418                        note_spans.push_span_label(
419                            private_field_span,
420                            "if this field wasn't private, it would be accessible",
421                        );
422                    }
423                    if accessible_struct_span != DUMMY_SP {
424                        note_spans.push_span_label(
425                            accessible_struct_span,
426                            "this struct is accessible through auto-deref",
427                        );
428                    }
429                    if field_span != DUMMY_SP {
430                        note_spans
431                            .push_span_label(field_span, "this is the field that was accessed");
432                    }
433                    if let Some(deref_impl_span) = deref_impl_span
434                        && deref_impl_span != DUMMY_SP
435                    {
436                        note_spans.push_span_label(
437                            deref_impl_span,
438                            "the field was accessed through this `Deref`",
439                        );
440                    }
441
442                    err.span_note(
443                        note_spans,
444                        ::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!(
445                            "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"
446                        ),
447                    );
448                }
449
450                // we finally get to the accessible field,
451                // so we can return early without checking the rest of the autoderef candidates
452                return;
453            }
454
455            private_candidate.get_or_insert((
456                deref_base_ty,
457                field_def.ty(self.tcx, args).skip_norm_wip(),
458                field_span,
459            ));
460        }
461    }
462
463    pub fn suggest_restricting_param_bound(
464        &self,
465        err: &mut Diag<'_>,
466        trait_pred: ty::PolyTraitClause<'tcx>,
467        associated_ty: Option<(&'static str, Ty<'tcx>)>,
468        mut body_def_id: LocalDefId,
469    ) {
470        if trait_pred.skip_binder().polarity != ty::ClausePolarity::Positive {
471            return;
472        }
473
474        let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
475
476        let self_ty = trait_pred.skip_binder().self_ty();
477        let (param_ty, projection) = match *self_ty.kind() {
478            ty::Param(_) => (true, None),
479            ty::Alias(_, alias) => {
480                if let Some(projection) = alias.try_to_projection() {
481                    (false, Some(projection))
482                } else {
483                    (false, None)
484                }
485            }
486            _ => (false, None),
487        };
488
489        let mut finder = ParamFinder { .. };
490        finder.visit_binder(&trait_pred);
491
492        // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
493        //        don't suggest `T: Sized + ?Sized`.
494        loop {
495            let node = self.tcx.hir_node_by_def_id(body_def_id);
496            match node {
497                hir::Node::Item(hir::Item {
498                    kind: hir::ItemKind::Trait { ident, generics, bounds, .. },
499                    ..
500                }) if self_ty == self.tcx.types.self_param => {
501                    if !param_ty { ::core::panicking::panic("assertion failed: param_ty") };assert!(param_ty);
502                    // Restricting `Self` for a single method.
503                    suggest_restriction(
504                        self.tcx,
505                        body_def_id,
506                        generics,
507                        "`Self`",
508                        err,
509                        None,
510                        projection,
511                        trait_pred,
512                        Some((&ident, bounds)),
513                    );
514                    return;
515                }
516
517                hir::Node::TraitItem(hir::TraitItem {
518                    generics,
519                    kind: hir::TraitItemKind::Fn(..),
520                    ..
521                }) if self_ty == self.tcx.types.self_param => {
522                    if !param_ty { ::core::panicking::panic("assertion failed: param_ty") };assert!(param_ty);
523                    // Restricting `Self` for a single method.
524                    suggest_restriction(
525                        self.tcx,
526                        body_def_id,
527                        generics,
528                        "`Self`",
529                        err,
530                        None,
531                        projection,
532                        trait_pred,
533                        None,
534                    );
535                    return;
536                }
537
538                hir::Node::TraitItem(hir::TraitItem {
539                    generics,
540                    kind: hir::TraitItemKind::Fn(fn_sig, ..),
541                    ..
542                })
543                | hir::Node::ImplItem(hir::ImplItem {
544                    generics,
545                    kind: hir::ImplItemKind::Fn(fn_sig, ..),
546                    ..
547                })
548                | hir::Node::Item(hir::Item {
549                    kind: hir::ItemKind::Fn { sig: fn_sig, generics, .. },
550                    ..
551                }) if projection.is_some() => {
552                    // Missing restriction on associated type of type parameter (unmet projection).
553                    suggest_restriction(
554                        self.tcx,
555                        body_def_id,
556                        generics,
557                        "the associated type",
558                        err,
559                        Some(fn_sig),
560                        projection,
561                        trait_pred,
562                        None,
563                    );
564                    return;
565                }
566                hir::Node::Item(hir::Item {
567                    kind:
568                        hir::ItemKind::Trait { generics, .. }
569                        | hir::ItemKind::Impl(hir::Impl { generics, .. }),
570                    ..
571                }) if projection.is_some() => {
572                    // Missing restriction on associated type of type parameter (unmet projection).
573                    suggest_restriction(
574                        self.tcx,
575                        body_def_id,
576                        generics,
577                        "the associated type",
578                        err,
579                        None,
580                        projection,
581                        trait_pred,
582                        None,
583                    );
584                    return;
585                }
586
587                hir::Node::Item(hir::Item {
588                    kind:
589                        hir::ItemKind::Struct(_, generics, _)
590                        | hir::ItemKind::Enum(_, generics, _)
591                        | hir::ItemKind::Union(_, generics, _)
592                        | hir::ItemKind::Trait { generics, .. }
593                        | hir::ItemKind::Impl(hir::Impl { generics, .. })
594                        | hir::ItemKind::Fn { generics, .. }
595                        | hir::ItemKind::TyAlias(_, generics, _)
596                        | hir::ItemKind::Const(_, generics, _, _)
597                        | hir::ItemKind::TraitAlias(_, _, generics, _),
598                    ..
599                })
600                | hir::Node::TraitItem(hir::TraitItem { generics, .. })
601                | hir::Node::ImplItem(hir::ImplItem { generics, .. })
602                    if param_ty =>
603                {
604                    // We skip the 0'th arg (self) because we do not want
605                    // to consider the predicate as not suggestible if the
606                    // self type is an arg position `impl Trait` -- instead,
607                    // we handle that by adding ` + Bound` below.
608                    // FIXME(compiler-errors): It would be nice to do the same
609                    // this that we do in `suggest_restriction` and pull the
610                    // `impl Trait` into a new generic if it shows up somewhere
611                    // else in the predicate.
612                    if !trait_pred.skip_binder().trait_ref.args[1..]
613                        .iter()
614                        .all(|g| g.is_suggestable(self.tcx, false))
615                    {
616                        return;
617                    }
618                    // Missing generic type parameter bound.
619                    let param_name = self_ty.to_string();
620                    let mut constraint = {
    let _guard = NoTrimmedGuard::new();
    trait_pred.print_modifiers_and_trait_path().to_string()
}with_no_trimmed_paths!(
621                        trait_pred.print_modifiers_and_trait_path().to_string()
622                    );
623
624                    if let Some((name, term)) = associated_ty {
625                        // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
626                        // That should be extracted into a helper function.
627                        if let Some(stripped) = constraint.strip_suffix('>') {
628                            constraint = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, {1} = {2}>", stripped, name,
                term))
    })format!("{stripped}, {name} = {term}>");
629                        } else {
630                            constraint.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0} = {1}>", name, term))
    })format!("<{name} = {term}>"));
631                        }
632                    }
633
634                    if suggest_constraining_type_param(
635                        self.tcx,
636                        generics,
637                        err,
638                        &param_name,
639                        &constraint,
640                        Some(trait_pred.def_id()),
641                        None,
642                    ) {
643                        return;
644                    }
645                }
646
647                hir::Node::TraitItem(hir::TraitItem {
648                    generics,
649                    kind: hir::TraitItemKind::Fn(..),
650                    ..
651                })
652                | hir::Node::ImplItem(hir::ImplItem {
653                    generics,
654                    impl_kind: hir::ImplItemImplKind::Inherent { .. },
655                    kind: hir::ImplItemKind::Fn(..),
656                    ..
657                }) if finder.can_suggest_bound(generics) => {
658                    // Missing generic type parameter bound.
659                    suggest_arbitrary_trait_bound(
660                        self.tcx,
661                        generics,
662                        err,
663                        trait_pred,
664                        associated_ty,
665                    );
666                }
667                hir::Node::Item(hir::Item {
668                    kind:
669                        hir::ItemKind::Struct(_, generics, _)
670                        | hir::ItemKind::Enum(_, generics, _)
671                        | hir::ItemKind::Union(_, generics, _)
672                        | hir::ItemKind::Trait { generics, .. }
673                        | hir::ItemKind::Impl(hir::Impl { generics, .. })
674                        | hir::ItemKind::Fn { generics, .. }
675                        | hir::ItemKind::TyAlias(_, generics, _)
676                        | hir::ItemKind::Const(_, generics, _, _)
677                        | hir::ItemKind::TraitAlias(_, _, generics, _),
678                    ..
679                }) if finder.can_suggest_bound(generics) => {
680                    // Missing generic type parameter bound.
681                    if suggest_arbitrary_trait_bound(
682                        self.tcx,
683                        generics,
684                        err,
685                        trait_pred,
686                        associated_ty,
687                    ) {
688                        return;
689                    }
690                }
691                hir::Node::Crate(..) => return,
692
693                _ => {}
694            }
695            body_def_id = self.tcx.local_parent(body_def_id);
696        }
697    }
698
699    /// Provide a suggestion to dereference arguments to functions and binary operators, if that
700    /// would satisfy trait bounds.
701    pub(super) fn suggest_dereferences(
702        &self,
703        obligation: &PredicateObligation<'tcx>,
704        err: &mut Diag<'_>,
705        trait_pred: ty::PolyTraitClause<'tcx>,
706    ) -> bool {
707        let mut code = obligation.cause.code();
708        if let ObligationCauseCode::FunctionArg { arg_hir_id, call_hir_id, .. } = code
709            && let Some(typeck_results) = &self.typeck_results
710            && let hir::Node::Expr(expr) = self.tcx.hir_node(*arg_hir_id)
711            && let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
712        {
713            // Suggest dereferencing the argument to a function/method call if possible
714
715            // Get the root obligation, since the leaf obligation we have may be unhelpful (#87437)
716            let mut real_trait_pred = trait_pred;
717            while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
718                code = parent_code;
719                if let Some(parent_trait_pred) = parent_trait_pred {
720                    real_trait_pred = parent_trait_pred;
721                }
722            }
723
724            // We `instantiate_bound_regions_with_erased` here because `make_subregion` does not handle
725            // `ReBound`, and we don't particularly care about the regions.
726            let real_ty = self.tcx.instantiate_bound_regions_with_erased(real_trait_pred.self_ty());
727            if !self.can_eq(obligation.param_env, real_ty, arg_ty) {
728                return false;
729            }
730
731            // Potentially, we'll want to place our dereferences under a `&`. We don't try this for
732            // `&mut`, since we can't be sure users will get the side-effects they want from it.
733            // If this doesn't work, we'll try removing the `&` in `suggest_remove_reference`.
734            // FIXME(dianne): this misses the case where users need both to deref and remove `&`s.
735            // This method could be combined with `TypeErrCtxt::suggest_remove_reference` to handle
736            // that, similar to what `FnCtxt::suggest_deref_or_ref` does.
737            let (is_under_ref, base_ty, span) = match expr.kind {
738                hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, subexpr)
739                    if let &ty::Ref(region, base_ty, hir::Mutability::Not) = real_ty.kind() =>
740                {
741                    (Some(region), base_ty, subexpr.span)
742                }
743                // Don't suggest `*&mut`, etc.
744                hir::ExprKind::AddrOf(..) => return false,
745                _ => (None, real_ty, obligation.cause.span),
746            };
747
748            let autoderef = (self.autoderef_steps)(base_ty);
749            let mut is_boxed = base_ty.is_box();
750            if let Some(steps) = autoderef.into_iter().position(|(mut ty, obligations)| {
751                // Ensure one of the following for dereferencing to be valid: we're passing by
752                // reference, `ty` is `Copy`, or we're moving out of a (potentially nested) `Box`.
753                let can_deref = is_under_ref.is_some()
754                    || self.type_is_copy_modulo_regions(obligation.param_env, ty)
755                    || ty.is_numeric() // for inference vars (presumably but not provably `Copy`)
756                    || is_boxed && self.type_is_sized_modulo_regions(obligation.param_env, ty);
757                is_boxed &= ty.is_box();
758
759                // Re-add the `&` if necessary
760                if let Some(region) = is_under_ref {
761                    ty = Ty::new_ref(self.tcx, region, ty, hir::Mutability::Not);
762                }
763
764                // Remapping bound vars here
765                let real_trait_pred_and_ty =
766                    real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
767                let obligation = self.mk_trait_obligation_with_new_self_ty(
768                    obligation.param_env,
769                    real_trait_pred_and_ty,
770                );
771
772                can_deref
773                    && obligations
774                        .iter()
775                        .chain([&obligation])
776                        .all(|obligation| self.predicate_may_hold(obligation))
777            }) && steps > 0
778            {
779                if span.in_external_macro(self.tcx.sess.source_map()) {
780                    return false;
781                }
782
783                // For a shared reference, prefer removing the outer `&` over suggesting
784                // `&*reference`. Keep the reborrow for `&mut T` and smart pointers.
785                if is_under_ref.is_some()
786                    && steps == 1
787                    && #[allow(non_exhaustive_omitted_patterns)] match base_ty.kind() {
    ty::Ref(_, _, hir::Mutability::Not) => true,
    _ => false,
}matches!(base_ty.kind(), ty::Ref(_, _, hir::Mutability::Not))
788                    && !expr.span.from_expansion()
789                    && self.suggest_remove_reference(obligation, err, real_trait_pred)
790                {
791                    return true;
792                }
793                let derefs = "*".repeat(steps);
794                let msg = "consider dereferencing here";
795
796                let call_node = self.tcx.hir_node(*call_hir_id);
797                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!(
798                    call_node,
799                    Node::Expr(hir::Expr {
800                        kind: hir::ExprKind::MethodCall(_, receiver_expr, ..),
801                        ..
802                    })
803                    if receiver_expr.hir_id == *arg_hir_id
804                );
805                if is_receiver {
806                    err.multipart_suggestion(
807                        msg,
808                        ::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![
809                            (span.shrink_to_lo(), format!("({derefs}")),
810                            (span.shrink_to_hi(), ")".to_string()),
811                        ],
812                        Applicability::MachineApplicable,
813                    )
814                } else {
815                    err.span_suggestion_verbose(
816                        span.shrink_to_lo(),
817                        msg,
818                        derefs,
819                        Applicability::MachineApplicable,
820                    )
821                };
822                return true;
823            }
824        } else if let (
825            ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. },
826            predicate,
827        ) = code.peel_derives_with_predicate()
828            && let Some(typeck_results) = &self.typeck_results
829            && let hir::Node::Expr(lhs) = self.tcx.hir_node(*lhs_hir_id)
830            && let hir::Node::Expr(rhs) = self.tcx.hir_node(*rhs_hir_id)
831            && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs)
832            && let trait_pred = predicate.unwrap_or(trait_pred)
833            // Only run this code on binary operators
834            && lang_items::BINARY_OPERATORS
835                .iter()
836                .filter_map(|&op| self.tcx.lang_items().get(op))
837                .any(|op| {
838                    op == trait_pred.skip_binder().trait_ref.def_id
839                })
840        {
841            // Suggest dereferencing the LHS, RHS, or both terms of a binop if possible
842            let trait_pred = predicate.unwrap_or(trait_pred);
843            let lhs_ty = self.tcx.instantiate_bound_regions_with_erased(trait_pred.self_ty());
844            let lhs_autoderef = (self.autoderef_steps)(lhs_ty);
845            let rhs_autoderef = (self.autoderef_steps)(rhs_ty);
846            let first_lhs = lhs_autoderef.first().unwrap().clone();
847            let first_rhs = rhs_autoderef.first().unwrap().clone();
848            let mut autoderefs = lhs_autoderef
849                .into_iter()
850                .enumerate()
851                .rev()
852                .zip_longest(rhs_autoderef.into_iter().enumerate().rev())
853                .map(|t| match t {
854                    EitherOrBoth::Both(a, b) => (a, b),
855                    EitherOrBoth::Left(a) => (a, (0, first_rhs.clone())),
856                    EitherOrBoth::Right(b) => ((0, first_lhs.clone()), b),
857                })
858                .rev();
859            if let Some((lsteps, rsteps)) =
860                autoderefs.find_map(|((lsteps, (l_ty, _)), (rsteps, (r_ty, _)))| {
861                    // Create a new predicate with the dereferenced LHS and RHS
862                    // We simultaneously dereference both sides rather than doing them
863                    // one at a time to account for cases such as &Box<T> == &&T
864                    let trait_pred_and_ty = trait_pred.map_bound(|inner| {
865                        (
866                            ty::TraitClause {
867                                trait_ref: ty::TraitRef::new_from_args(
868                                    self.tcx,
869                                    inner.trait_ref.def_id,
870                                    self.tcx.mk_args(
871                                        &[&[l_ty.into(), r_ty.into()], &inner.trait_ref.args[2..]]
872                                            .concat(),
873                                    ),
874                                ),
875                                ..inner
876                            },
877                            l_ty,
878                        )
879                    });
880                    let obligation = self.mk_trait_obligation_with_new_self_ty(
881                        obligation.param_env,
882                        trait_pred_and_ty,
883                    );
884                    self.predicate_may_hold(&obligation).then_some(match (lsteps, rsteps) {
885                        (_, 0) => (Some(lsteps), None),
886                        (0, _) => (None, Some(rsteps)),
887                        _ => (Some(lsteps), Some(rsteps)),
888                    })
889                })
890            {
891                let make_sugg = |mut expr: &Expr<'_>, mut steps| {
892                    if expr.span.in_external_macro(self.tcx.sess.source_map()) {
893                        return None;
894                    }
895                    let mut prefix_span = expr.span.shrink_to_lo();
896                    let mut msg = "consider dereferencing here";
897                    if let hir::ExprKind::AddrOf(_, _, inner) = expr.kind {
898                        msg = "consider removing the borrow and dereferencing instead";
899                        if let hir::ExprKind::AddrOf(..) = inner.kind {
900                            msg = "consider removing the borrows and dereferencing instead";
901                        }
902                    }
903                    while let hir::ExprKind::AddrOf(_, _, inner) = expr.kind
904                        && steps > 0
905                    {
906                        prefix_span = prefix_span.with_hi(inner.span.lo());
907                        expr = inner;
908                        steps -= 1;
909                    }
910                    // Empty suggestions with empty spans ICE with debug assertions
911                    if steps == 0 {
912                        return Some((
913                            msg.trim_end_matches(" and dereferencing instead"),
914                            ::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())],
915                        ));
916                    }
917                    let derefs = "*".repeat(steps);
918                    let needs_parens = steps > 0 && expr_needs_parens(expr);
919                    let mut suggestion = if needs_parens {
920                        ::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![
921                            (
922                                expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
923                                format!("{derefs}("),
924                            ),
925                            (expr.span.shrink_to_hi(), ")".to_string()),
926                        ]
927                    } else {
928                        ::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![(
929                            expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
930                            format!("{derefs}"),
931                        )]
932                    };
933                    // Empty suggestions with empty spans ICE with debug assertions
934                    if !prefix_span.is_empty() {
935                        suggestion.push((prefix_span, String::new()));
936                    }
937                    Some((msg, suggestion))
938                };
939
940                if let Some(lsteps) = lsteps
941                    && let Some(rsteps) = rsteps
942                    && lsteps > 0
943                    && rsteps > 0
944                {
945                    let Some((_, mut suggestion)) = make_sugg(lhs, lsteps) else {
946                        return false;
947                    };
948                    let Some((_, mut rhs_suggestion)) = make_sugg(rhs, rsteps) else {
949                        return false;
950                    };
951                    suggestion.append(&mut rhs_suggestion);
952                    err.multipart_suggestion(
953                        "consider dereferencing both sides of the expression",
954                        suggestion,
955                        Applicability::MachineApplicable,
956                    );
957                    return true;
958                } else if let Some(lsteps) = lsteps
959                    && lsteps > 0
960                {
961                    let Some((msg, suggestion)) = make_sugg(lhs, lsteps) else {
962                        return false;
963                    };
964                    err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
965                    return true;
966                } else if let Some(rsteps) = rsteps
967                    && rsteps > 0
968                {
969                    let Some((msg, suggestion)) = make_sugg(rhs, rsteps) else {
970                        return false;
971                    };
972                    err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
973                    return true;
974                }
975            }
976        }
977        false
978    }
979
980    /// Given a closure's `DefId`, return the given name of the closure.
981    ///
982    /// This doesn't account for reassignments, but it's only used for suggestions.
983    fn get_closure_name(
984        &self,
985        def_id: DefId,
986        err: &mut Diag<'_>,
987        msg: Cow<'static, str>,
988    ) -> Option<Symbol> {
989        let get_name = |err: &mut Diag<'_>, kind: &hir::PatKind<'_>| -> Option<Symbol> {
990            // Get the local name of this closure. This can be inaccurate because
991            // of the possibility of reassignment, but this should be good enough.
992            match &kind {
993                hir::PatKind::Binding(hir::BindingMode::NONE, _, ident, None) => Some(ident.name),
994                _ => {
995                    err.note(msg);
996                    None
997                }
998            }
999        };
1000
1001        let hir_id = self.tcx.local_def_id_to_hir_id(def_id.as_local()?);
1002        match self.tcx.parent_hir_node(hir_id) {
1003            hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Let(local), .. }) => {
1004                get_name(err, &local.pat.kind)
1005            }
1006            // Different to previous arm because one is `&hir::Local` and the other
1007            // is `Box<hir::Local>`.
1008            hir::Node::LetStmt(local) => get_name(err, &local.pat.kind),
1009            _ => None,
1010        }
1011    }
1012
1013    /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
1014    /// evaluate to a type that *would* satisfy the trait bound. If it would, suggest calling
1015    /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
1016    pub(super) fn suggest_fn_call(
1017        &self,
1018        obligation: &PredicateObligation<'tcx>,
1019        err: &mut Diag<'_>,
1020        trait_pred: ty::PolyTraitClause<'tcx>,
1021    ) -> bool {
1022        // It doesn't make sense to make this suggestion outside of typeck...
1023        // (also autoderef will ICE...)
1024        if self.typeck_results.is_none() {
1025            return false;
1026        }
1027
1028        if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) =
1029            obligation.predicate.kind().skip_binder()
1030            && self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Sized)
1031        {
1032            // Don't suggest calling to turn an unsized type into a sized type
1033            return false;
1034        }
1035
1036        let self_ty = self.instantiate_binder_with_fresh_vars(
1037            DUMMY_SP,
1038            BoundRegionConversionTime::FnCall,
1039            trait_pred.self_ty(),
1040        );
1041
1042        let Some((def_id_or_name, output, inputs)) =
1043            self.extract_callable_info(obligation.cause.body_def_id, obligation.param_env, self_ty)
1044        else {
1045            return false;
1046        };
1047
1048        // Remapping bound vars here
1049        let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
1050
1051        let new_obligation =
1052            self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
1053        if !self.predicate_must_hold_modulo_regions(&new_obligation) {
1054            return false;
1055        }
1056
1057        // If this is a zero-argument async closure directly passed as an argument
1058        // and the expected type is `Future`, suggest using `async {}` block instead
1059        // of `async || {}`
1060        if let ty::CoroutineClosure(def_id, args) = *self_ty.kind()
1061            && let sig = args.as_coroutine_closure().coroutine_closure_sig().skip_binder()
1062            && let ty::Tuple(inputs) = *sig.tupled_inputs_ty.kind()
1063            && inputs.is_empty()
1064            && self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Future)
1065            && let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1066            && let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) =
1067                self.tcx.hir_node(*arg_hir_id)
1068            && let Some(hir::Node::Expr(hir::Expr {
1069                kind: hir::ExprKind::Closure(closure), ..
1070            })) = self.tcx.hir_get_if_local(def_id)
1071            && let hir::ClosureKind::CoroutineClosure(CoroutineDesugaring::Async) = closure.kind
1072            && let Some(arg_span) = closure.fn_arg_span
1073            && obligation.cause.span.contains(arg_span)
1074        {
1075            let mut body = self.tcx.hir_body(closure.body).value;
1076            let peeled = body.peel_blocks().peel_drop_temps();
1077            if let hir::ExprKind::Closure(inner) = peeled.kind {
1078                body = self.tcx.hir_body(inner.body).value;
1079            }
1080            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(..)) {
1081                return false;
1082            }
1083
1084            let sm = self.tcx.sess.source_map();
1085            let removal_span = if let Ok(snippet) =
1086                sm.span_to_snippet(arg_span.with_hi(arg_span.hi() + rustc_span::BytePos(1)))
1087                && snippet.ends_with(' ')
1088            {
1089                // There's a space after `||`, include it in the removal
1090                arg_span.with_hi(arg_span.hi() + rustc_span::BytePos(1))
1091            } else {
1092                arg_span
1093            };
1094            err.span_suggestion_verbose(
1095                removal_span,
1096                "use `async {}` instead of `async || {}` to introduce an async block",
1097                "",
1098                Applicability::MachineApplicable,
1099            );
1100            return true;
1101        }
1102
1103        // Get the name of the callable and the arguments to be used in the suggestion.
1104        let msg = match def_id_or_name {
1105            DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
1106                DefKind::Ctor(CtorOf::Struct, _) => {
1107                    Cow::from("use parentheses to construct this tuple struct")
1108                }
1109                DefKind::Ctor(CtorOf::Variant, _) => {
1110                    Cow::from("use parentheses to construct this tuple variant")
1111                }
1112                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!(
1113                    "use parentheses to call this {}",
1114                    self.tcx.def_kind_descr(kind, def_id)
1115                )),
1116            },
1117            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}")),
1118        };
1119
1120        let args = inputs
1121            .into_iter()
1122            .map(|ty| {
1123                if ty.is_suggestable(self.tcx, false) {
1124                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("/* {0} */", ty))
    })format!("/* {ty} */")
1125                } else {
1126                    "/* value */".to_string()
1127                }
1128            })
1129            .collect::<Vec<_>>()
1130            .join(", ");
1131
1132        let callee_hir_id = match obligation.cause.code() {
1133            ObligationCauseCode::FunctionArg { arg_hir_id, .. }
1134                if obligation.cause.span.can_be_used_for_suggestions() =>
1135            {
1136                Some(*arg_hir_id)
1137            }
1138            // The iterator of a `for` loop is passed to `IntoIterator::into_iter`, so the failing
1139            // `Iterator` goal is a derived obligation and `cause.span` carries the loop's
1140            // desugaring context. The expression is still the user's, which its own span attests.
1141            code => match code.peel_derives() {
1142                ObligationCauseCode::ForLoopIterator(iter_hir_id)
1143                    if self.tcx.hir_span(*iter_hir_id).can_be_used_for_suggestions() =>
1144                {
1145                    Some(*iter_hir_id)
1146                }
1147                _ => None,
1148            },
1149        };
1150
1151        if let Some(callee_hir_id) = callee_hir_id {
1152            let span = obligation.cause.span;
1153
1154            let arg_expr = match self.tcx.hir_node(callee_hir_id) {
1155                hir::Node::Expr(expr) => Some(expr),
1156                _ => None,
1157            };
1158
1159            let is_closure_expr =
1160                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(..)));
1161
1162            // If the user wrote `|| {}()`, suggesting to call the closure would produce `(|| {}())()`,
1163            // which doesn't help and is often outright wrong.
1164            if args.is_empty()
1165                && let Some(expr) = arg_expr
1166                && let hir::ExprKind::Closure(closure) = expr.kind
1167            {
1168                let mut body = self.tcx.hir_body(closure.body).value;
1169
1170                // Async closures desugar to a closure returning a coroutine
1171                if let hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) =
1172                    closure.kind
1173                {
1174                    let peeled = body.peel_blocks().peel_drop_temps();
1175                    if let hir::ExprKind::Closure(inner) = peeled.kind {
1176                        body = self.tcx.hir_body(inner.body).value;
1177                    }
1178                }
1179
1180                let peeled_body = body.peel_blocks().peel_drop_temps();
1181                if let hir::ExprKind::Call(callee, call_args) = peeled_body.kind
1182                    && call_args.is_empty()
1183                    && let hir::ExprKind::Block(..) = callee.peel_blocks().peel_drop_temps().kind
1184                {
1185                    return false;
1186                }
1187            }
1188
1189            if is_closure_expr {
1190                err.multipart_suggestions(
1191                    msg,
1192                    ::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![
1193                        (span.shrink_to_lo(), "(".to_string()),
1194                        (span.shrink_to_hi(), format!(")({args})")),
1195                    ]],
1196                    Applicability::HasPlaceholders,
1197                );
1198            } else {
1199                err.span_suggestion_verbose(
1200                    span.shrink_to_hi(),
1201                    msg,
1202                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0})", args))
    })format!("({args})"),
1203                    Applicability::HasPlaceholders,
1204                );
1205            }
1206        } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
1207            let name = match self.tcx.hir_get_if_local(def_id) {
1208                Some(hir::Node::Expr(hir::Expr {
1209                    kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
1210                    ..
1211                })) => {
1212                    err.span_label(*fn_decl_span, "consider calling this closure");
1213                    let Some(name) = self.get_closure_name(def_id, err, msg.clone()) else {
1214                        return false;
1215                    };
1216                    name.to_string()
1217                }
1218                Some(hir::Node::Item(hir::Item {
1219                    kind: hir::ItemKind::Fn { ident, .. }, ..
1220                })) => {
1221                    err.span_label(ident.span, "consider calling this function");
1222                    ident.to_string()
1223                }
1224                Some(hir::Node::Ctor(..)) => {
1225                    let name = self.tcx.def_path_str(def_id);
1226                    err.span_label(
1227                        self.tcx.def_span(def_id),
1228                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider calling the constructor for `{0}`",
                name))
    })format!("consider calling the constructor for `{name}`"),
1229                    );
1230                    name
1231                }
1232                _ => return false,
1233            };
1234            err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: `{1}({2})`", msg, name, args))
    })format!("{msg}: `{name}({args})`"));
1235        }
1236        true
1237    }
1238
1239    pub(super) fn suggest_cast_to_fn_pointer(
1240        &self,
1241        obligation: &PredicateObligation<'tcx>,
1242        err: &mut Diag<'_>,
1243        leaf_trait_predicate: ty::PolyTraitClause<'tcx>,
1244        main_trait_predicate: ty::PolyTraitClause<'tcx>,
1245        span: Span,
1246    ) -> bool {
1247        let &[candidate] = &self.find_similar_impl_candidates(
1248            leaf_trait_predicate.def_id(),
1249            leaf_trait_predicate.self_ty().skip_binder(),
1250        )[..] else {
1251            return false;
1252        };
1253        let candidate = candidate.trait_ref;
1254
1255        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!(
1256            (candidate.self_ty().kind(), main_trait_predicate.self_ty().skip_binder().kind(),),
1257            (ty::FnPtr(..), ty::FnDef(..))
1258        ) {
1259            return false;
1260        }
1261
1262        let parenthesized_cast = |span: Span| {
1263            ::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![
1264                (span.shrink_to_lo(), "(".to_string()),
1265                (span.shrink_to_hi(), format!(" as {})", candidate.self_ty())),
1266            ]
1267        };
1268        // Wrap method receivers and `&`-references in parens.
1269        let suggestion = if self.tcx.sess.source_map().span_followed_by(span, ".").is_some() {
1270            parenthesized_cast(span)
1271        } else if let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id) {
1272            let mut expr_finder = FindExprBySpan::new(span, self.tcx);
1273            expr_finder.visit_expr(&body.value);
1274            if let Some(expr) = expr_finder.result
1275                && let hir::ExprKind::AddrOf(_, _, expr) = expr.kind
1276            {
1277                parenthesized_cast(expr.span)
1278            } else {
1279                ::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()))]
1280            }
1281        } else {
1282            ::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()))]
1283        };
1284
1285        let trait_ = self.tcx.short_string(candidate.print_trait_sugared(), err.long_ty_path());
1286        let self_ty = self.tcx.short_string(candidate.self_ty(), err.long_ty_path());
1287        err.multipart_suggestion(
1288            ::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!(
1289                "the trait `{trait_}` is implemented for fn pointer \
1290                 `{self_ty}`, try casting using `as`",
1291            ),
1292            suggestion,
1293            Applicability::MaybeIncorrect,
1294        );
1295        true
1296    }
1297
1298    pub(super) fn check_for_binding_assigned_block_without_tail_expression(
1299        &self,
1300        obligation: &PredicateObligation<'tcx>,
1301        err: &mut Diag<'_>,
1302        trait_pred: ty::PolyTraitClause<'tcx>,
1303    ) {
1304        let mut span = obligation.cause.span;
1305        while span.from_expansion() {
1306            // Remove all the desugaring and macro contexts.
1307            span.remove_mark();
1308        }
1309        let mut expr_finder = FindExprBySpan::new(span, self.tcx);
1310        let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id) else {
1311            return;
1312        };
1313        expr_finder.visit_expr(&body.value);
1314        let Some(expr) = expr_finder.result else {
1315            return;
1316        };
1317        let Some(typeck) = &self.typeck_results else {
1318            return;
1319        };
1320        let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else {
1321            return;
1322        };
1323        if !ty.is_unit() {
1324            return;
1325        };
1326        let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else {
1327            return;
1328        };
1329        let Res::Local(hir_id) = path.res else {
1330            return;
1331        };
1332        let hir::Node::Pat(pat) = self.tcx.hir_node(hir_id) else {
1333            return;
1334        };
1335        let hir::Node::LetStmt(hir::LetStmt { ty: None, init: Some(init), .. }) =
1336            self.tcx.parent_hir_node(pat.hir_id)
1337        else {
1338            return;
1339        };
1340        let hir::ExprKind::Block(block, None) = init.kind else {
1341            return;
1342        };
1343        if block.expr.is_some() {
1344            return;
1345        }
1346        let [.., stmt] = block.stmts else {
1347            err.span_label(block.span, "this empty block is missing a tail expression");
1348            return;
1349        };
1350        // FIXME expr and stmt have the same span if expr comes from expansion
1351        // cc: https://github.com/rust-lang/rust/pull/147416#discussion_r2499407523
1352        if stmt.span.from_expansion() {
1353            return;
1354        }
1355        let hir::StmtKind::Semi(tail_expr) = stmt.kind else {
1356            return;
1357        };
1358        let Some(ty) = typeck.expr_ty_opt(tail_expr) else {
1359            err.span_label(block.span, "this block is missing a tail expression");
1360            return;
1361        };
1362        let ty =
1363            self.resolve_numeric_literals_with_default(self.deeply_resolve_ignoring_regions(ty));
1364        let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, ty));
1365
1366        let new_obligation =
1367            self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
1368        if !#[allow(non_exhaustive_omitted_patterns)] match tail_expr.kind {
    hir::ExprKind::Err(_) => true,
    _ => false,
}matches!(tail_expr.kind, hir::ExprKind::Err(_))
1369            && self.predicate_must_hold_modulo_regions(&new_obligation)
1370        {
1371            err.span_suggestion_short(
1372                stmt.span.with_lo(tail_expr.span.hi()),
1373                "remove this semicolon",
1374                "",
1375                Applicability::MachineApplicable,
1376            );
1377        } else {
1378            err.span_label(block.span, "this block is missing a tail expression");
1379        }
1380    }
1381
1382    pub(super) fn suggest_add_clone_to_arg(
1383        &self,
1384        obligation: &PredicateObligation<'tcx>,
1385        err: &mut Diag<'_>,
1386        trait_pred: ty::PolyTraitClause<'tcx>,
1387    ) -> bool {
1388        let self_ty = self.deeply_resolve_ignoring_regions(trait_pred.self_ty());
1389        self.enter_forall(self_ty, |ty: Ty<'_>| {
1390            let Some(generics) = self.tcx.hir_get_generics(obligation.cause.body_def_id) else {
1391                return false;
1392            };
1393            let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false };
1394            let ty::Param(param) = inner_ty.kind() else { return false };
1395            let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1396            else {
1397                return false;
1398            };
1399
1400            let clone_trait = self.tcx.require_lang_item(LangItem::Clone, obligation.cause.span);
1401            let has_clone = |ty| {
1402                self.type_implements_trait(clone_trait, [ty], obligation.param_env)
1403                    .must_apply_modulo_regions()
1404            };
1405
1406            let existing_clone_call = match self.tcx.hir_node(*arg_hir_id) {
1407                // It's just a variable. Propose cloning it.
1408                Node::Expr(Expr { kind: hir::ExprKind::Path(_), .. }) => None,
1409                // It's already a call to `clone()`. We might be able to suggest
1410                // adding a `+ Clone` bound, though.
1411                Node::Expr(Expr {
1412                    kind:
1413                        hir::ExprKind::MethodCall(
1414                            hir::PathSegment { ident, .. },
1415                            _receiver,
1416                            [],
1417                            call_span,
1418                        ),
1419                    hir_id,
1420                    ..
1421                }) if ident.name == sym::clone
1422                    && !call_span.from_expansion()
1423                    && !has_clone(*inner_ty) =>
1424                {
1425                    // We only care about method calls corresponding to the real `Clone` trait.
1426                    let Some(typeck_results) = self.typeck_results.as_ref() else { return false };
1427                    let Some((DefKind::AssocFn, did)) = typeck_results.type_dependent_def(*hir_id)
1428                    else {
1429                        return false;
1430                    };
1431                    if self.tcx.trait_of_assoc(did) != Some(clone_trait) {
1432                        return false;
1433                    }
1434                    Some(ident.span)
1435                }
1436                _ => return false,
1437            };
1438
1439            let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1440                obligation.param_env,
1441                trait_pred.map_bound(|trait_pred| (trait_pred, *inner_ty)),
1442            );
1443
1444            if self.predicate_may_hold(&new_obligation) && has_clone(ty) {
1445                if !has_clone(param.to_ty(self.tcx)) {
1446                    suggest_constraining_type_param(
1447                        self.tcx,
1448                        generics,
1449                        err,
1450                        param.name.as_str(),
1451                        "Clone",
1452                        Some(clone_trait),
1453                        None,
1454                    );
1455                }
1456                if let Some(existing_clone_call) = existing_clone_call {
1457                    err.span_note(
1458                        existing_clone_call,
1459                        ::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!(
1460                            "this `clone()` copies the reference, \
1461                            which does not do anything, \
1462                            because `{inner_ty}` does not implement `Clone`"
1463                        ),
1464                    );
1465                } else {
1466                    err.span_suggestion_verbose(
1467                        obligation.cause.span.shrink_to_hi(),
1468                        "consider using clone here",
1469                        ".clone()".to_string(),
1470                        Applicability::MaybeIncorrect,
1471                    );
1472                }
1473                return true;
1474            }
1475            false
1476        })
1477    }
1478
1479    /// Extracts information about a callable type for diagnostics. This is a
1480    /// heuristic -- it doesn't necessarily mean that a type is always callable,
1481    /// because the callable type must also be well-formed to be called.
1482    pub fn extract_callable_info(
1483        &self,
1484        body_def_id: LocalDefId,
1485        param_env: ty::ParamEnv<'tcx>,
1486        found: Ty<'tcx>,
1487    ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
1488        // Autoderef is useful here because sometimes we box callables, etc.
1489        let Some((def_id_or_name, output, inputs)) =
1490            (self.autoderef_steps)(found).into_iter().find_map(|(found, _)| match *found.kind() {
1491                ty::FnPtr(sig_tys, _) => Some((
1492                    DefIdOrName::Name("function pointer"),
1493                    sig_tys.output(),
1494                    sig_tys.inputs(),
1495                )),
1496                ty::FnDef(def_id, _) => {
1497                    let fn_sig = found.fn_sig(self.tcx);
1498                    Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
1499                }
1500                ty::Closure(def_id, args) => {
1501                    let fn_sig = args.as_closure().sig();
1502                    Some((
1503                        DefIdOrName::DefId(def_id),
1504                        fn_sig.output(),
1505                        fn_sig.inputs().map_bound(|inputs| inputs[0].tuple_fields().as_slice()),
1506                    ))
1507                }
1508                ty::CoroutineClosure(def_id, args) => {
1509                    let sig_parts = args.as_coroutine_closure().coroutine_closure_sig();
1510                    Some((
1511                        DefIdOrName::DefId(def_id),
1512                        sig_parts.map_bound(|sig| {
1513                            sig.to_coroutine(
1514                                self.tcx,
1515                                args.as_coroutine_closure().parent_args(),
1516                                // Just use infer vars here, since we  don't really care
1517                                // what these types are, just that we're returning a coroutine.
1518                                self.next_ty_var(DUMMY_SP),
1519                                self.tcx.coroutine_for_closure(def_id),
1520                                self.next_ty_var(DUMMY_SP),
1521                            )
1522                        }),
1523                        sig_parts.map_bound(|sig| sig.tupled_inputs_ty.tuple_fields().as_slice()),
1524                    ))
1525                }
1526                ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
1527                    self.tcx
1528                        .item_self_bounds(def_id)
1529                        .instantiate(self.tcx, args)
1530                        .skip_norm_wip()
1531                        .iter()
1532                        .find_map(|pred| {
1533                            if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder()
1534                            && self
1535                                .tcx
1536                                .is_lang_item(proj.def_id(), LangItem::FnOnceOutput)
1537                            // args tuple will always be args[1]
1538                            && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1539                            {
1540                                Some((
1541                                    DefIdOrName::DefId(def_id),
1542                                    pred.kind().rebind(proj.term.expect_type()),
1543                                    pred.kind().rebind(args.as_slice()),
1544                                ))
1545                            } else {
1546                                None
1547                            }
1548                        })
1549                }
1550                ty::Dynamic(data, _) => data.iter().find_map(|pred| {
1551                    if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
1552                        && self.tcx.is_lang_item(proj.def_id, LangItem::FnOnceOutput)
1553                        // for existential projection, args are shifted over by 1
1554                        && let ty::Tuple(args) = proj.args.type_at(0).kind()
1555                    {
1556                        Some((
1557                            DefIdOrName::Name("trait object"),
1558                            pred.rebind(proj.term.expect_type()),
1559                            pred.rebind(args.as_slice()),
1560                        ))
1561                    } else {
1562                        None
1563                    }
1564                }),
1565                ty::Param(param) => {
1566                    let generics = self.tcx.generics_of(body_def_id);
1567                    let name = if generics.count() > param.index as usize
1568                        && let def = generics.param_at(param.index as usize, self.tcx)
1569                        && #[allow(non_exhaustive_omitted_patterns)] match def.kind {
    ty::GenericParamDefKind::Type { .. } => true,
    _ => false,
}matches!(def.kind, ty::GenericParamDefKind::Type { .. })
1570                        && def.name == param.name
1571                    {
1572                        DefIdOrName::DefId(def.def_id)
1573                    } else {
1574                        DefIdOrName::Name("type parameter")
1575                    };
1576                    param_env.caller_bounds().find_map(|clause| {
1577                        if let ty::ClauseKind::Projection(proj) = clause.kind().skip_binder()
1578                            && self
1579                                .tcx
1580                                .is_lang_item(proj.def_id(), LangItem::FnOnceOutput)
1581                            && proj.projection_term.self_ty() == found
1582                            // args tuple will always be args[1]
1583                            && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1584                        {
1585                            Some((
1586                                name,
1587                                clause.kind().rebind(proj.term.expect_type()),
1588                                clause.kind().rebind(args.as_slice()),
1589                            ))
1590                        } else {
1591                            None
1592                        }
1593                    })
1594                }
1595                _ => None,
1596            })
1597        else {
1598            return None;
1599        };
1600
1601        let output = self.instantiate_binder_with_fresh_vars(
1602            DUMMY_SP,
1603            BoundRegionConversionTime::FnCall,
1604            output,
1605        );
1606        let inputs = inputs
1607            .skip_binder()
1608            .iter()
1609            .map(|ty| {
1610                self.instantiate_binder_with_fresh_vars(
1611                    DUMMY_SP,
1612                    BoundRegionConversionTime::FnCall,
1613                    inputs.rebind(*ty),
1614                )
1615            })
1616            .collect();
1617
1618        // We don't want to register any extra obligations, which should be
1619        // implied by wf, but also because that would possibly result in
1620        // erroneous errors later on.
1621        let InferOk { value: output, obligations: _ } =
1622            self.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(output));
1623
1624        if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
1625    }
1626
1627    pub(super) fn where_clause_expr_matches_failed_self_ty(
1628        &self,
1629        obligation: &PredicateObligation<'tcx>,
1630        old_self_ty: Ty<'tcx>,
1631    ) -> bool {
1632        let ObligationCauseCode::WhereClauseInExpr(..) = obligation.cause.code() else {
1633            return true;
1634        };
1635        let (Some(typeck_results), Some(body)) = (
1636            self.typeck_results.as_ref(),
1637            self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id),
1638        ) else {
1639            return true;
1640        };
1641
1642        let mut expr_finder = FindExprBySpan::new(obligation.cause.span, self.tcx);
1643        expr_finder.visit_expr(&body.value);
1644        let Some(expr) = expr_finder.result else {
1645            return true;
1646        };
1647
1648        let inner_old_self_ty = match old_self_ty.kind() {
1649            ty::Ref(_, inner_ty, _) => Some(*inner_ty),
1650            _ => None,
1651        };
1652
1653        typeck_results.expr_ty_adjusted_opt(expr).is_some_and(|expr_ty| {
1654            self.can_eq(obligation.param_env, expr_ty, old_self_ty)
1655                || inner_old_self_ty
1656                    .is_some_and(|inner_ty| self.can_eq(obligation.param_env, expr_ty, inner_ty))
1657        })
1658    }
1659
1660    pub(super) fn suggest_add_reference_to_arg(
1661        &self,
1662        obligation: &PredicateObligation<'tcx>,
1663        err: &mut Diag<'_>,
1664        poly_trait_pred: ty::PolyTraitClause<'tcx>,
1665        has_custom_message: bool,
1666    ) -> bool {
1667        let span = obligation.cause.span;
1668        let param_env = obligation.param_env;
1669
1670        let mk_result = |trait_pred_and_new_ty| {
1671            let obligation =
1672                self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1673            self.predicate_must_hold_modulo_regions(&obligation)
1674        };
1675
1676        let trait_pred_and_imm_ref = poly_trait_pred.map_bound(|p| {
1677            (p, Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, p.self_ty()))
1678        });
1679        let trait_pred_and_mut_ref = poly_trait_pred.map_bound(|p| {
1680            (p, Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, p.self_ty()))
1681        });
1682
1683        let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1684        let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1685
1686        let mut point_at_relevant_args =
1687            |pred_ty: Ty<'tcx>, args_and_inputs: Vec<(hir::Expr<'_>, Ty<'tcx>)>| {
1688                let Some(typeck_results) = &self.typeck_results else { return false };
1689
1690                let erased_self_ty =
1691                    self.tcx.instantiate_bound_regions_with_erased(poly_trait_pred.self_ty());
1692                let mut spans = ::alloc::vec::Vec::new()vec![];
1693                for (arg, input) in args_and_inputs {
1694                    let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(&arg) else { continue };
1695                    let pred_has_arg_type = self.infcx.can_eq(param_env, arg_ty, erased_self_ty);
1696                    let arg_is_type_param = self.infcx.can_eq(param_env, pred_ty, input);
1697                    if pred_has_arg_type && arg_is_type_param {
1698                        err.span_label(
1699                            arg.span,
1700                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` doesn\'t satisfy the trait bound",
                arg_ty))
    })format!("`{arg_ty}` doesn't satisfy the trait bound"),
1701                        );
1702                        spans.push(arg.span);
1703                    }
1704                }
1705                let this = if spans.len() == 1 { "this" } else { "these" }pluralize!("this", spans.len());
1706                if !spans.is_empty() {
1707                    if imm_ref_self_ty_satisfies_pred {
1708                        err.multipart_suggestion(
1709                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider borrowing {0} argument",
                this))
    })format!("consider borrowing {this} argument"),
1710                            spans.iter().map(|sp| (sp.shrink_to_lo(), "&".into())).collect(),
1711                            Applicability::MaybeIncorrect,
1712                        );
1713                    }
1714                    if mut_ref_self_ty_satisfies_pred {
1715                        err.multipart_suggestion(
1716                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider mutably borrowing {0} argument",
                this))
    })format!("consider mutably borrowing {this} argument"),
1717                            spans.iter().map(|sp| (sp.shrink_to_lo(), "&mut ".into())).collect(),
1718                            Applicability::MaybeIncorrect,
1719                        );
1720                    }
1721                }
1722                !spans.is_empty()
1723            };
1724        let code = match obligation.cause.code() {
1725            ObligationCauseCode::FunctionArg { parent_code, .. } => parent_code,
1726            // FIXME(compiler-errors): This is kind of a mess, but required for obligations
1727            // that come from a path expr to affect the *call* expr.
1728            c @ ObligationCauseCode::WhereClauseInExpr(def_id, _, hir_id, idx)
1729                if self.tcx.hir_span(*hir_id).lo() == span.lo() =>
1730            {
1731                // `hir_id` corresponds to the HIR node that introduced a `where`-clause obligation.
1732                if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(*hir_id) {
1733                    // If that obligation comes from a type in an associated method call, we need
1734                    // special handling here.
1735                    if let hir::ExprKind::Call(base, _) = expr.kind
1736                        && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, segment)) =
1737                            base.kind
1738                        && let hir::Node::Expr(outer) = self.tcx.parent_hir_node(expr.hir_id)
1739                        && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mtbl, _) = outer.kind
1740                        && ty.span == span
1741                    {
1742                        // We've encountered something like `&str::from("")`, where the intended code
1743                        // was likely `<&str>::from("")`. The former is interpreted as "call method
1744                        // `from` on `str` and borrow the result", while the latter means "call method
1745                        // `from` on `&str`".
1746
1747                        let sugg_msg = |pre: &str| {
1748                            ::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!(
1749                                "you likely meant to call the associated function `{FN}` for type \
1750                                 `&{pre}{TY}`, but the code as written calls associated function `{FN}` on \
1751                                 type `{TY}`",
1752                                FN = segment.ident,
1753                                TY = poly_trait_pred.self_ty(),
1754                            )
1755                        };
1756                        match (imm_ref_self_ty_satisfies_pred, mut_ref_self_ty_satisfies_pred, mtbl)
1757                        {
1758                            (true, _, hir::Mutability::Not) | (_, true, hir::Mutability::Mut) => {
1759                                err.multipart_suggestion(
1760                                    sugg_msg(mtbl.prefix_str()),
1761                                    ::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![
1762                                        (outer.span.shrink_to_lo(), "<".to_string()),
1763                                        (span.shrink_to_hi(), ">".to_string()),
1764                                    ],
1765                                    Applicability::MachineApplicable,
1766                                );
1767                            }
1768                            (true, _, hir::Mutability::Mut) => {
1769                                // There's an associated function found on the immutable borrow of the
1770                                err.multipart_suggestion(
1771                                    sugg_msg("mut "),
1772                                    ::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![
1773                                        (outer.span.shrink_to_lo().until(span), "<&".to_string()),
1774                                        (span.shrink_to_hi(), ">".to_string()),
1775                                    ],
1776                                    Applicability::MachineApplicable,
1777                                );
1778                            }
1779                            (_, true, hir::Mutability::Not) => {
1780                                err.multipart_suggestion(
1781                                    sugg_msg(""),
1782                                    ::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![
1783                                        (
1784                                            outer.span.shrink_to_lo().until(span),
1785                                            "<&mut ".to_string(),
1786                                        ),
1787                                        (span.shrink_to_hi(), ">".to_string()),
1788                                    ],
1789                                    Applicability::MachineApplicable,
1790                                );
1791                            }
1792                            _ => {}
1793                        }
1794                        // If we didn't return early here, we would instead suggest `&&str::from("")`.
1795                        return false;
1796                    } else if let hir::ExprKind::Call(_, args) = expr.kind {
1797                        // The `def_id` can point at a struct, which has no fn sig.
1798                        if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(*def_id) {
    DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => true,
    _ => false,
}matches!(
1799                            self.tcx.def_kind(*def_id),
1800                            DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)
1801                        ) && let Some(pred) = self
1802                                .tcx
1803                                .clauses_of(*def_id)
1804                                .instantiate_identity(self.tcx)
1805                                .clauses
1806                                .into_iter()
1807                                .nth(*idx)
1808                            && let Some(pred) = pred.as_trait_clause()
1809                            // This feature allows for `for<T> T: Trait`, which fails
1810                            // `instantiate_bound_regions_with_erased`. Avoid suggesting for now.
1811                            && !self.tcx.features().non_lifetime_binders()
1812                        {
1813                            let pred_ty = self.tcx.instantiate_bound_regions_with_erased(
1814                                pred.self_ty().skip_norm_wip(),
1815                            );
1816                            let fn_sig = self.tcx.instantiate_bound_regions_with_erased(
1817                                self.tcx.fn_sig(*def_id).instantiate_identity().skip_norm_wip(),
1818                            );
1819                            if point_at_relevant_args(
1820                                pred_ty,
1821                                args.into_iter()
1822                                    .zip(fn_sig.inputs())
1823                                    .map(|(e, t)| (*e, *t))
1824                                    .collect(),
1825                            ) {
1826                                return false;
1827                            }
1828                        }
1829                    }
1830                }
1831                c
1832            }
1833            c @ ObligationCauseCode::WhereClauseInExpr(def_id, _, hir_id, idx)
1834                if let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
1835                    && let hir::ExprKind::MethodCall(_segment, rcvr, args, ..) = expr.kind
1836                    // The `def_id` can also point at the impl, which has no fn sig.
1837                    && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(*def_id) {
    DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => true,
    _ => false,
}matches!(
1838                        self.tcx.def_kind(*def_id),
1839                        DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)
1840                    )
1841                    && let Some(pred) = self
1842                        .tcx
1843                        .clauses_of(*def_id)
1844                        .instantiate_identity(self.tcx)
1845                        .clauses
1846                        .into_iter()
1847                        .nth(*idx)
1848                    && let Some(pred) = pred.as_trait_clause()
1849                    // This feature allows for `for<T> T: Trait`, which fails
1850                    // `instantiate_bound_regions_with_erased`. Avoid suggesting for now.
1851                    && !self.tcx.features().non_lifetime_binders() =>
1852            {
1853                let fn_sig = self.tcx.instantiate_bound_regions_with_erased(
1854                    self.tcx.fn_sig(*def_id).instantiate_identity().skip_norm_wip(),
1855                );
1856                // We've got a method call where likely one of the arguments didn't meet a bound.
1857                let pred_ty =
1858                    self.tcx.instantiate_bound_regions_with_erased(pred.self_ty().skip_norm_wip());
1859                if point_at_relevant_args(
1860                    pred_ty,
1861                    [rcvr]
1862                        .into_iter()
1863                        .chain(args.into_iter())
1864                        .zip(fn_sig.inputs())
1865                        .map(|(e, t)| (*e, *t))
1866                        .collect(),
1867                ) {
1868                    return false;
1869                }
1870                c
1871            }
1872            c if #[allow(non_exhaustive_omitted_patterns)] match span.ctxt().outer_expn_data().kind
    {
    ExpnKind::Desugaring(DesugaringKind::ForLoop) => true,
    _ => false,
}matches!(
1873                span.ctxt().outer_expn_data().kind,
1874                ExpnKind::Desugaring(DesugaringKind::ForLoop)
1875            ) =>
1876            {
1877                c
1878            }
1879            _ => return false,
1880        };
1881
1882        // List of traits for which it would be nonsensical to suggest borrowing.
1883        // For instance, immutable references are always Copy, so suggesting to
1884        // borrow would always succeed, but it's probably not what the user wanted.
1885        let mut never_suggest_borrow: Vec<_> =
1886            [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1887                .iter()
1888                .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1889                .collect();
1890
1891        if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1892            never_suggest_borrow.push(def_id);
1893        }
1894
1895        // Try to apply the original trait bound by borrowing.
1896        let mut try_borrowing = |old_pred: ty::PolyTraitClause<'tcx>,
1897                                 blacklist: &[DefId]|
1898         -> bool {
1899            if blacklist.contains(&old_pred.def_id()) {
1900                return false;
1901            }
1902            // We map bounds to `&T` and `&mut T`
1903            let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1904                (
1905                    trait_pred,
1906                    Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1907                )
1908            });
1909            let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1910                (
1911                    trait_pred,
1912                    Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1913                )
1914            });
1915
1916            let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1917            let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1918
1919            let (ref_inner_ty_satisfies_pred, ref_inner_ty_is_mut) =
1920                if let ObligationCauseCode::WhereClauseInExpr(..) = obligation.cause.code()
1921                    && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1922                {
1923                    (
1924                        mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1925                        mutability.is_mut(),
1926                    )
1927                } else {
1928                    (false, false)
1929                };
1930
1931            let is_immut = imm_ref_self_ty_satisfies_pred
1932                || (ref_inner_ty_satisfies_pred && !ref_inner_ty_is_mut);
1933            let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_is_mut;
1934            if !is_immut && !is_mut {
1935                return false;
1936            }
1937            let Ok(_snippet) = self.tcx.sess.source_map().span_to_snippet(span) else {
1938                return false;
1939            };
1940            // We don't want a borrowing suggestion on the fields in structs
1941            // ```
1942            // #[derive(Clone)]
1943            // struct Foo {
1944            //     the_foos: Vec<Foo>
1945            // }
1946            // ```
1947            if !#[allow(non_exhaustive_omitted_patterns)] match span.ctxt().outer_expn_data().kind
    {
    ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => true,
    _ => false,
}matches!(
1948                span.ctxt().outer_expn_data().kind,
1949                ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1950            ) {
1951                return false;
1952            }
1953            // We have a very specific type of error, where just borrowing this argument
1954            // might solve the problem. In cases like this, the important part is the
1955            // original type obligation, not the last one that failed, which is arbitrary.
1956            // Because of this, we modify the error to refer to the original obligation and
1957            // return early in the caller.
1958
1959            let mut label = || {
1960                // Special case `Sized` as `old_pred` will be the trait itself instead of
1961                // `Sized` when the trait bound is the source of the error.
1962                let is_sized = match obligation.predicate.kind().skip_binder() {
1963                    ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) => {
1964                        self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Sized)
1965                    }
1966                    _ => false,
1967                };
1968
1969                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!(
1970                    "the trait bound `{}` is not satisfied",
1971                    self.tcx.short_string(old_pred, err.long_ty_path()),
1972                );
1973                let self_ty_str = self.tcx.short_string(old_pred.self_ty(), err.long_ty_path());
1974                let trait_path = self
1975                    .tcx
1976                    .short_string(old_pred.print_modifiers_and_trait_path(), err.long_ty_path());
1977
1978                if has_custom_message {
1979                    let msg = if is_sized {
1980                        "the trait bound `Sized` is not satisfied".into()
1981                    } else {
1982                        msg
1983                    };
1984                    err.note(msg);
1985                } else {
1986                    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)];
1987                }
1988                if is_sized {
1989                    err.span_label(
1990                        span,
1991                        ::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}`"),
1992                    );
1993                } else {
1994                    err.span_label(
1995                        span,
1996                        ::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}`"),
1997                    );
1998                }
1999            };
2000
2001            let mut sugg_prefixes = ::alloc::vec::Vec::new()vec![];
2002            if is_immut {
2003                sugg_prefixes.push("&");
2004            }
2005            if is_mut {
2006                sugg_prefixes.push("&mut ");
2007            }
2008            let sugg_msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider{0} borrowing here",
                if is_mut && !is_immut { " mutably" } else { "" }))
    })format!(
2009                "consider{} borrowing here",
2010                if is_mut && !is_immut { " mutably" } else { "" },
2011            );
2012
2013            // Issue #104961, we need to add parentheses properly for compound expressions
2014            // for example, `x.starts_with("hi".to_string() + "you")`
2015            // should be `x.starts_with(&("hi".to_string() + "you"))`
2016            let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id) else {
2017                return false;
2018            };
2019            let mut expr_finder = FindExprBySpan::new(span, self.tcx);
2020            expr_finder.visit_expr(&body.value);
2021
2022            if let Some(ty) = expr_finder.ty_result {
2023                if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(ty.hir_id)
2024                    && let hir::ExprKind::Path(hir::QPath::TypeRelative(_, _)) = expr.kind
2025                    && ty.span == span
2026                {
2027                    // We've encountered something like `str::from("")`, where the intended code
2028                    // was likely `<&str>::from("")`. #143393.
2029                    label();
2030                    err.multipart_suggestions(
2031                        sugg_msg,
2032                        sugg_prefixes.into_iter().map(|sugg_prefix| {
2033                            ::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![
2034                                (span.shrink_to_lo(), format!("<{sugg_prefix}")),
2035                                (span.shrink_to_hi(), ">".to_string()),
2036                            ]
2037                        }),
2038                        Applicability::MaybeIncorrect,
2039                    );
2040                    return true;
2041                }
2042                return false;
2043            }
2044            let Some(expr) = expr_finder.result else {
2045                return false;
2046            };
2047            if let hir::ExprKind::AddrOf(_, _, _) = expr.kind {
2048                return false;
2049            }
2050            let old_self_ty = old_pred.skip_binder().self_ty();
2051            if !old_self_ty.has_escaping_bound_vars()
2052                && !self.where_clause_expr_matches_failed_self_ty(
2053                    obligation,
2054                    self.tcx.instantiate_bound_regions_with_erased(old_pred.self_ty()),
2055                )
2056            {
2057                return false;
2058            }
2059            let needs_parens_post = expr_needs_parens(expr);
2060            let needs_parens_pre = match self.tcx.parent_hir_node(expr.hir_id) {
2061                Node::Expr(e)
2062                    if let hir::ExprKind::MethodCall(_, base, _, _) = e.kind
2063                        && base.hir_id == expr.hir_id =>
2064                {
2065                    true
2066                }
2067                _ => false,
2068            };
2069
2070            label();
2071            let suggestions = sugg_prefixes.into_iter().map(|sugg_prefix| {
2072                match (needs_parens_pre, needs_parens_post) {
2073                    (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())],
2074                    // We have something like `foo.bar()`, where we want to bororw foo, so we need
2075                    // to suggest `(&mut foo).bar()`.
2076                    (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![
2077                        (span.shrink_to_lo(), format!("{sugg_prefix}(")),
2078                        (span.shrink_to_hi(), ")".to_string()),
2079                    ],
2080                    // Issue #109436, we need to add parentheses properly for method calls
2081                    // for example, `foo.into()` should be `(&foo).into()`
2082                    (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![
2083                        (span.shrink_to_lo(), format!("({sugg_prefix}")),
2084                        (span.shrink_to_hi(), ")".to_string()),
2085                    ],
2086                    (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![
2087                        (span.shrink_to_lo(), format!("({sugg_prefix}(")),
2088                        (span.shrink_to_hi(), "))".to_string()),
2089                    ],
2090                }
2091            });
2092            err.multipart_suggestions(sugg_msg, suggestions, Applicability::MaybeIncorrect);
2093            return true;
2094        };
2095
2096        if let ObligationCauseCode::ImplDerived(cause) = &*code {
2097            try_borrowing(cause.derived.parent_trait_pred, &[])
2098        } else if let ObligationCauseCode::WhereClause(..)
2099        | ObligationCauseCode::WhereClauseInExpr(..) = code
2100        {
2101            try_borrowing(poly_trait_pred, &never_suggest_borrow)
2102        } else {
2103            false
2104        }
2105    }
2106
2107    // Suggest borrowing the type
2108    pub(super) fn suggest_borrowing_for_object_cast(
2109        &self,
2110        err: &mut Diag<'_>,
2111        obligation: &PredicateObligation<'tcx>,
2112        self_ty: Ty<'tcx>,
2113        target_ty: Ty<'tcx>,
2114    ) {
2115        let ty::Ref(_, object_ty, hir::Mutability::Not) = target_ty.kind() else {
2116            return;
2117        };
2118        let ty::Dynamic(predicates, _) = object_ty.kind() else {
2119            return;
2120        };
2121        let self_ref_ty = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, self_ty);
2122
2123        for predicate in predicates.iter() {
2124            if !self.predicate_must_hold_modulo_regions(
2125                &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
2126            ) {
2127                return;
2128            }
2129        }
2130
2131        err.span_suggestion_verbose(
2132            obligation.cause.span.shrink_to_lo(),
2133            ::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!(
2134                "consider borrowing the value, since `&{self_ty}` can be coerced into `{target_ty}`"
2135            ),
2136            "&",
2137            Applicability::MaybeIncorrect,
2138        );
2139    }
2140
2141    /// Peel `&`-borrows from an expression, following through untyped let-bindings.
2142    /// Returns a list of removable `&` layers (each with the span to remove and the
2143    /// resulting type), plus an optional terminal [`hir::Param`] when the chain ends
2144    /// at a function parameter (including async-fn desugared parameters).
2145    fn peel_expr_refs(
2146        &self,
2147        mut expr: &'tcx hir::Expr<'tcx>,
2148        mut ty: Ty<'tcx>,
2149    ) -> (Vec<PeeledRef<'tcx>>, Option<&'tcx hir::Param<'tcx>>) {
2150        let mut refs = Vec::new();
2151        'outer: loop {
2152            while let hir::ExprKind::AddrOf(_, _, borrowed) = expr.kind {
2153                let span =
2154                    if let Some(borrowed_span) = borrowed.span.find_ancestor_inside(expr.span) {
2155                        expr.span.until(borrowed_span)
2156                    } else {
2157                        break 'outer;
2158                    };
2159
2160                // Double check that the span actually corresponds to a borrow,
2161                // rather than some macro garbage.
2162                // The span may include leading parens from parenthesized expressions
2163                // (e.g., `(&expr)` where HIR removes the Paren but keeps the span).
2164                // In that case, trim the span to start at the `&`.
2165                let span = match self.tcx.sess.source_map().span_to_snippet(span) {
2166                    Ok(ref snippet) if snippet.starts_with("&") => span,
2167                    Ok(ref snippet) if let Some(amp) = snippet.find('&') => {
2168                        span.with_lo(span.lo() + BytePos(amp as u32))
2169                    }
2170                    _ => break 'outer,
2171                };
2172
2173                let ty::Ref(_, inner_ty, _) = ty.kind() else {
2174                    break 'outer;
2175                };
2176                ty = *inner_ty;
2177                refs.push(PeeledRef { span, peeled_ty: ty });
2178                expr = borrowed;
2179            }
2180            if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
2181                && let Res::Local(hir_id) = path.res
2182                && let hir::Node::Pat(binding) = self.tcx.hir_node(hir_id)
2183            {
2184                match self.tcx.parent_hir_node(binding.hir_id) {
2185                    // Untyped let-binding: follow to its initializer.
2186                    hir::Node::LetStmt(local)
2187                        if local.ty.is_none()
2188                            && let Some(init) = local.init =>
2189                    {
2190                        expr = init;
2191                        continue;
2192                    }
2193                    // Async fn desugared parameter: `let x = __arg0;` with AsyncFn source.
2194                    // Follow to the original parameter.
2195                    hir::Node::LetStmt(local)
2196                        if #[allow(non_exhaustive_omitted_patterns)] match local.source {
    hir::LocalSource::AsyncFn => true,
    _ => false,
}matches!(local.source, hir::LocalSource::AsyncFn)
2197                            && let Some(init) = local.init
2198                            && let hir::ExprKind::Path(hir::QPath::Resolved(None, arg_path)) =
2199                                init.kind
2200                            && let Res::Local(arg_hir_id) = arg_path.res
2201                            && let hir::Node::Pat(arg_binding) = self.tcx.hir_node(arg_hir_id)
2202                            && let hir::Node::Param(param) =
2203                                self.tcx.parent_hir_node(arg_binding.hir_id) =>
2204                    {
2205                        return (refs, Some(param));
2206                    }
2207                    // Direct parameter reference.
2208                    hir::Node::Param(param) => {
2209                        return (refs, Some(param));
2210                    }
2211                    _ => break 'outer,
2212                }
2213            } else {
2214                break 'outer;
2215            }
2216        }
2217        (refs, None)
2218    }
2219
2220    /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
2221    /// suggest removing these references until we reach a type that implements the trait.
2222    pub(super) fn suggest_remove_reference(
2223        &self,
2224        obligation: &PredicateObligation<'tcx>,
2225        err: &mut Diag<'_>,
2226        trait_pred: ty::PolyTraitClause<'tcx>,
2227    ) -> bool {
2228        let mut span = obligation.cause.span;
2229        let mut trait_pred = trait_pred;
2230        let mut code = obligation.cause.code();
2231        while let Some((c, Some(parent_trait_pred))) = code.parent_with_predicate() {
2232            // We want the root obligation, in order to detect properly handle
2233            // `for _ in &mut &mut vec![] {}`.
2234            code = c;
2235            trait_pred = parent_trait_pred;
2236        }
2237        while span.desugaring_kind().is_some() {
2238            // Remove all the hir desugaring contexts while maintaining the macro contexts.
2239            span.remove_mark();
2240        }
2241        let mut expr_finder = super::FindExprBySpan::new(span, self.tcx);
2242        let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id) else {
2243            return false;
2244        };
2245        expr_finder.visit_expr(&body.value);
2246        let mut maybe_suggest = |suggested_ty, count, suggestions| {
2247            // Remapping bound vars here
2248            let trait_pred_and_suggested_ty =
2249                trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
2250
2251            let new_obligation = self.mk_trait_obligation_with_new_self_ty(
2252                obligation.param_env,
2253                trait_pred_and_suggested_ty,
2254            );
2255
2256            if self.predicate_may_hold(&new_obligation) {
2257                let msg = if count == 1 {
2258                    "consider removing the leading `&`-reference".to_string()
2259                } else {
2260                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider removing {0} leading `&`-references",
                count))
    })format!("consider removing {count} leading `&`-references")
2261                };
2262
2263                err.multipart_suggestion(msg, suggestions, Applicability::MachineApplicable);
2264                true
2265            } else {
2266                false
2267            }
2268        };
2269
2270        // Maybe suggest removal of borrows from types in type parameters, like in
2271        // `src/test/ui/not-panic/not-panic-safe.rs`.
2272        let mut count = 0;
2273        let mut suggestions = ::alloc::vec::Vec::new()vec![];
2274        // Skipping binder here, remapping below
2275        let mut suggested_ty = trait_pred.self_ty().skip_binder();
2276        if let Some(mut hir_ty) = expr_finder.ty_result {
2277            while let hir::TyKind::Ref(_, ref_ty, _) = &hir_ty.kind {
2278                count += 1;
2279                let span = hir_ty.span.until(ref_ty.span);
2280                suggestions.push((span, String::new()));
2281
2282                let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
2283                    break;
2284                };
2285                suggested_ty = *inner_ty;
2286
2287                hir_ty = ref_ty;
2288
2289                if maybe_suggest(suggested_ty, count, suggestions.clone()) {
2290                    return true;
2291                }
2292            }
2293        }
2294
2295        // Maybe suggest removal of borrows from expressions, like in `for i in &&&foo {}`.
2296        let Some(expr) = expr_finder.result else {
2297            return false;
2298        };
2299        // Skipping binder here, remapping below
2300        let suggested_ty = trait_pred.self_ty().skip_binder();
2301        let (peeled_refs, _) = self.peel_expr_refs(expr, suggested_ty);
2302        for (i, peeled) in peeled_refs.iter().enumerate() {
2303            let suggestions: Vec<_> =
2304                peeled_refs[..=i].iter().map(|r| (r.span, String::new())).collect();
2305            if maybe_suggest(peeled.peeled_ty, i + 1, suggestions) {
2306                return true;
2307            }
2308        }
2309        false
2310    }
2311
2312    /// Suggest removing `&` from a function parameter type like `&impl Future`.
2313    fn suggest_remove_ref_from_param(&self, param: &hir::Param<'_>, err: &mut Diag<'_>) -> bool {
2314        if let Some(decl) = self.tcx.parent_hir_node(param.hir_id).fn_decl()
2315            && let Some(input_ty) = decl.inputs.iter().find(|t| param.ty_span.contains(t.span))
2316            && let hir::TyKind::Ref(_, ty, _) = input_ty.kind
2317        {
2318            let ref_span = input_ty.span.until(ty.span);
2319            match self.tcx.sess.source_map().span_to_snippet(ref_span) {
2320                Ok(snippet) if snippet.starts_with("&") => {
2321                    err.span_suggestion_verbose(
2322                        ref_span,
2323                        "consider removing the `&` from the parameter type",
2324                        "",
2325                        Applicability::MaybeIncorrect,
2326                    );
2327                    return true;
2328                }
2329                _ => {}
2330            }
2331        }
2332        false
2333    }
2334
2335    pub(super) fn suggest_remove_await(
2336        &self,
2337        obligation: &PredicateObligation<'tcx>,
2338        err: &mut Diag<'_>,
2339    ) {
2340        if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives()
2341            && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
2342        {
2343            // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
2344            // and if not maybe suggest doing something else? If we kept the expression around we
2345            // could also check if it is an fn call (very likely) and suggest changing *that*, if
2346            // it is from the local crate.
2347
2348            // If the type is `&..&T` where `T: Future`, suggest removing `&`
2349            // instead of removing `.await`.
2350            if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2351                obligation.predicate.kind().skip_binder()
2352            {
2353                let self_ty = pred.self_ty();
2354                let future_trait =
2355                    self.tcx.require_lang_item(LangItem::Future, obligation.cause.span);
2356
2357                // Peel through references to check if there's a Future underneath.
2358                let has_future = {
2359                    let mut ty = self_ty;
2360                    loop {
2361                        match *ty.kind() {
2362                            ty::Ref(_, inner_ty, _)
2363                                if !#[allow(non_exhaustive_omitted_patterns)] match inner_ty.kind() {
    ty::Dynamic(..) => true,
    _ => false,
}matches!(inner_ty.kind(), ty::Dynamic(..)) =>
2364                            {
2365                                if self
2366                                    .type_implements_trait(
2367                                        future_trait,
2368                                        [inner_ty],
2369                                        obligation.param_env,
2370                                    )
2371                                    .must_apply_modulo_regions()
2372                                {
2373                                    break true;
2374                                }
2375                                ty = inner_ty;
2376                            }
2377                            _ => break false,
2378                        }
2379                    }
2380                };
2381
2382                if has_future {
2383                    let (peeled_refs, terminal_param) = self.peel_expr_refs(expr, self_ty);
2384
2385                    // Try removing `&`s from the expression.
2386                    for (i, peeled) in peeled_refs.iter().enumerate() {
2387                        if self
2388                            .type_implements_trait(
2389                                future_trait,
2390                                [peeled.peeled_ty],
2391                                obligation.param_env,
2392                            )
2393                            .must_apply_modulo_regions()
2394                        {
2395                            let count = i + 1;
2396                            let msg = if count == 1 {
2397                                "consider removing the leading `&`-reference".to_string()
2398                            } else {
2399                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider removing {0} leading `&`-references",
                count))
    })format!("consider removing {count} leading `&`-references")
2400                            };
2401                            let suggestions: Vec<_> =
2402                                peeled_refs[..=i].iter().map(|r| (r.span, String::new())).collect();
2403                            err.multipart_suggestion(
2404                                msg,
2405                                suggestions,
2406                                Applicability::MachineApplicable,
2407                            );
2408                            return;
2409                        }
2410                    }
2411
2412                    // Try removing `&` from the parameter type, but only when there's
2413                    // no `&` in the expression itself (otherwise removing from the param
2414                    // alone wouldn't fix the error).
2415                    if peeled_refs.is_empty()
2416                        && let Some(param) = terminal_param
2417                        && self.suggest_remove_ref_from_param(param, err)
2418                    {
2419                        return;
2420                    }
2421
2422                    // Fallback: emit a help message when we can't provide a specific span.
2423                    err.help(
2424                        "a reference to a future is not a future; \
2425                     consider removing the leading `&`-reference",
2426                    );
2427                    return;
2428                }
2429            }
2430
2431            // use nth(1) to skip one layer of desugaring from `IntoIter::into_iter`
2432            if let Some((_, hir::Node::Expr(await_expr))) = self.tcx.hir_parent_iter(*hir_id).nth(1)
2433                && let Some(expr_span) = expr.span.find_ancestor_inside_same_ctxt(await_expr.span)
2434            {
2435                let removal_span = self
2436                    .tcx
2437                    .sess
2438                    .source_map()
2439                    .span_extend_while_whitespace(expr_span)
2440                    .shrink_to_hi()
2441                    .to(await_expr.span.shrink_to_hi());
2442                err.span_suggestion_verbose(
2443                    removal_span,
2444                    "remove the `.await`",
2445                    "",
2446                    Applicability::MachineApplicable,
2447                );
2448            } else {
2449                err.span_label(obligation.cause.span, "remove the `.await`");
2450            }
2451            // FIXME: account for associated `async fn`s.
2452            if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
2453                if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2454                    obligation.predicate.kind().skip_binder()
2455                {
2456                    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()));
2457                }
2458                if let Some(typeck_results) = &self.typeck_results
2459                    && let ty = typeck_results.expr_ty_adjusted(base)
2460                    && let ty::FnDef(def_id, _args) = ty.kind()
2461                    && let Some(hir::Node::Item(item)) = self.tcx.hir_get_if_local(*def_id)
2462                {
2463                    let (ident, _, _, _) = item.expect_fn();
2464                    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");
2465                    if item.vis_span.is_empty() {
2466                        err.span_suggestion_verbose(
2467                            item.span.shrink_to_lo(),
2468                            msg,
2469                            "async ",
2470                            Applicability::MaybeIncorrect,
2471                        );
2472                    } else {
2473                        err.span_suggestion_verbose(
2474                            item.vis_span.shrink_to_hi(),
2475                            msg,
2476                            " async",
2477                            Applicability::MaybeIncorrect,
2478                        );
2479                    }
2480                }
2481            }
2482        }
2483    }
2484
2485    /// Check if the trait bound is implemented for a different mutability and note it in the
2486    /// final error.
2487    pub(super) fn suggest_change_mut(
2488        &self,
2489        obligation: &PredicateObligation<'tcx>,
2490        err: &mut Diag<'_>,
2491        trait_pred: ty::PolyTraitClause<'tcx>,
2492    ) {
2493        let points_at_arg =
2494            #[allow(non_exhaustive_omitted_patterns)] match obligation.cause.code() {
    ObligationCauseCode::FunctionArg { .. } => true,
    _ => false,
}matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. },);
2495
2496        let span = obligation.cause.span;
2497        if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2498            let refs_number =
2499                snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
2500            if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
2501                // Do not suggest removal of borrow from type arguments.
2502                return;
2503            }
2504            let trait_pred = self.deeply_resolve_ignoring_regions(trait_pred);
2505            if trait_pred.has_non_region_infer() {
2506                // Do not ICE while trying to find if a reborrow would succeed on a trait with
2507                // unresolved bindings.
2508                return;
2509            }
2510
2511            // Skipping binder here, remapping below
2512            if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
2513            {
2514                let suggested_ty = match mutability {
2515                    hir::Mutability::Mut => Ty::new_imm_ref(self.tcx, region, t_type),
2516                    hir::Mutability::Not => Ty::new_mut_ref(self.tcx, region, t_type),
2517                };
2518
2519                // Remapping bound vars here
2520                let trait_pred_and_suggested_ty =
2521                    trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
2522
2523                let new_obligation = self.mk_trait_obligation_with_new_self_ty(
2524                    obligation.param_env,
2525                    trait_pred_and_suggested_ty,
2526                );
2527                let suggested_ty_would_satisfy_obligation = self
2528                    .evaluate_obligation_no_overflow(&new_obligation)
2529                    .must_apply_modulo_regions();
2530                if suggested_ty_would_satisfy_obligation {
2531                    let sp = self
2532                        .tcx
2533                        .sess
2534                        .source_map()
2535                        .span_take_while(span, |c| c.is_whitespace() || *c == '&');
2536                    if points_at_arg
2537                        && mutability.is_not()
2538                        && refs_number > 0
2539                        // The borrow can sit in a macro body, where rewriting it would edit the
2540                        // macro definition and so every one of its call sites, or a crate the user
2541                        // does not own. Fall through to the note in that case.
2542                        && span.can_be_used_for_suggestions()
2543                    {
2544                        // If we have a call like foo(&mut buf), then don't suggest foo(&mut mut buf)
2545                        if snippet
2546                            .trim_start_matches(|c: char| c.is_whitespace() || c == '&')
2547                            .starts_with("mut")
2548                        {
2549                            return;
2550                        }
2551                        err.span_suggestion_verbose(
2552                            sp,
2553                            "consider changing this borrow's mutability",
2554                            "&mut ",
2555                            Applicability::MachineApplicable,
2556                        );
2557                    } else {
2558                        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!(
2559                            "`{}` is implemented for `{}`, but not for `{}`",
2560                            trait_pred.print_modifiers_and_trait_path(),
2561                            suggested_ty,
2562                            trait_pred.skip_binder().self_ty(),
2563                        ));
2564                    }
2565                }
2566            }
2567        }
2568    }
2569
2570    pub(super) fn suggest_semicolon_removal(
2571        &self,
2572        obligation: &PredicateObligation<'tcx>,
2573        err: &mut Diag<'_>,
2574        span: Span,
2575        trait_pred: ty::PolyTraitClause<'tcx>,
2576    ) -> bool {
2577        if !trait_pred.self_ty().skip_binder().is_unit() {
2578            return false;
2579        }
2580        let node = self.tcx.hir_node_by_def_id(obligation.cause.body_def_id);
2581        if let hir::Node::Item(hir::Item {
2582            kind: hir::ItemKind::Fn { sig, body: body_id, .. }, ..
2583        }) = node
2584            && let hir::ExprKind::Block(blk, _) = &self.tcx.hir_body(*body_id).value.kind
2585            && sig.decl.output.span().overlaps(span)
2586            && let Some(candidate) = self.removable_trailing_semicolon(blk, obligation, trait_pred)
2587        {
2588            // A function body has a single return type, so keeping the value can't break any
2589            // other use of it.
2590            self.emit_semicolon_removal_suggestion(
2591                err,
2592                trait_pred,
2593                candidate,
2594                Applicability::MachineApplicable,
2595            );
2596            return true;
2597        }
2598        self.suggest_semicolon_removal_in_closure_arg(obligation, err, trait_pred)
2599    }
2600
2601    /// If the value of `block` is discarded by a trailing semicolon and keeping it would satisfy
2602    /// `trait_pred`, return that statement, its expression and the type of that expression.
2603    fn removable_trailing_semicolon(
2604        &self,
2605        block: &hir::Block<'tcx>,
2606        obligation: &PredicateObligation<'tcx>,
2607        trait_pred: ty::PolyTraitClause<'tcx>,
2608    ) -> Option<(&'tcx hir::Stmt<'tcx>, &'tcx hir::Expr<'tcx>, Ty<'tcx>)> {
2609        if block.expr.is_none()
2610            && let Some(stmt) = block.stmts.last()
2611            && let hir::StmtKind::Semi(expr) = stmt.kind
2612            && !stmt.span.from_expansion()
2613            && !#[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    hir::ExprKind::Err(_) => true,
    _ => false,
}matches!(expr.kind, hir::ExprKind::Err(_))
2614            // Only suggest this if the expression behind the semicolon implements the predicate
2615            && let Some(typeck_results) = &self.typeck_results
2616            && let Some(ty) =
2617                typeck_results.expr_ty_opt(expr).map(|ty| self.deeply_resolve_ignoring_regions(ty))
2618            && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
2619                obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
2620            ))
2621        {
2622            Some((stmt, expr, ty))
2623        } else {
2624            None
2625        }
2626    }
2627
2628    fn emit_semicolon_removal_suggestion(
2629        &self,
2630        err: &mut Diag<'_>,
2631        trait_pred: ty::PolyTraitClause<'tcx>,
2632        (stmt, expr, ty): (&hir::Stmt<'_>, &hir::Expr<'_>, Ty<'tcx>),
2633        applicability: Applicability,
2634    ) {
2635        err.span_label(
2636            expr.span,
2637            ::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!(
2638                "this expression has type `{}`, which implements `{}`",
2639                ty,
2640                trait_pred.print_modifiers_and_trait_path()
2641            ),
2642        );
2643        err.span_suggestion(
2644            self.tcx.sess.source_map().end_point(stmt.span),
2645            "remove this semicolon",
2646            "",
2647            applicability,
2648        );
2649    }
2650
2651    /// Detect when a closure argument returns `()` because of a trailing semicolon and that makes
2652    /// a trait bound on the function's generic param fail, and suggest removing the semicolon:
2653    ///
2654    /// ```text
2655    /// fn bar<R: Bar>(_: impl Fn() -> R) {}
2656    /// bar(|| { 5u8; })
2657    /// //          - help: remove this semicolon
2658    /// ```
2659    fn suggest_semicolon_removal_in_closure_arg(
2660        &self,
2661        obligation: &PredicateObligation<'tcx>,
2662        err: &mut Diag<'_>,
2663        trait_pred: ty::PolyTraitClause<'tcx>,
2664    ) -> bool {
2665        let &ObligationCauseCode::WhereClauseInExpr(callee_def_id, _, hir_id, idx) =
2666            obligation.cause.code().peel_derives()
2667        else {
2668            return false;
2669        };
2670        // This cause code is used for the clauses of any item named in an expression, like an
2671        // associated const or a type alias, and `fn_sig` is only defined for functions.
2672        if !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(callee_def_id)
    {
    DefKind::Fn | DefKind::AssocFn => true,
    _ => false,
}matches!(self.tcx.def_kind(callee_def_id), DefKind::Fn | DefKind::AssocFn) {
2673            return false;
2674        }
2675        let hir::Node::Expr(expr) = self.tcx.hir_node(hir_id) else {
2676            return false;
2677        };
2678        let Some(typeck_results) = &self.typeck_results else {
2679            return false;
2680        };
2681        let args: Vec<&hir::Expr<'_>> =
2682            match expr.kind {
2683                hir::ExprKind::MethodCall(_, receiver, args, _) => {
2684                    iter::once(receiver).chain(args).collect()
2685                }
2686                // For a call like `bar(..)` the obligation is attached to the callee path expression,
2687                // so the arguments live in its parent.
2688                _ => match self.tcx.parent_hir_node(expr.hir_id) {
2689                    hir::Node::Expr(hir::Expr {
2690                        kind: hir::ExprKind::Call(callee, args), ..
2691                    }) if callee.hir_id == expr.hir_id => args.iter().collect(),
2692                    _ => return false,
2693                },
2694            };
2695        // Work with the callee's own clauses and signature, where the failing bound is still
2696        // written in terms of the generic param it was declared on.
2697        let clauses = self.tcx.clauses_of(callee_def_id).instantiate_identity(self.tcx);
2698        let Some(ty::ClauseKind::Trait(failed)) = clauses
2699            .clauses
2700            .get(idx)
2701            .map(|clause| clause.as_ref().skip_norm_wip().kind().skip_binder())
2702        else {
2703            return false;
2704        };
2705        let sig =
2706            self.tcx.fn_sig(callee_def_id).instantiate_identity().skip_norm_wip().skip_binder();
2707        let mut candidates = args.into_iter().enumerate().filter_map(|(i, arg)| {
2708            // The bound has to be on what the closure returns. A bound on an unrelated param that
2709            // also happened to be inferred as `()` would not be satisfied by removing a semicolon.
2710            let declared = sig.inputs().get(i)?.peel_refs();
2711            if !clauses.clauses.iter().any(|clause| {
2712                #[allow(non_exhaustive_omitted_patterns)] match clause.as_ref().skip_norm_wip().kind().skip_binder()
    {
    ty::ClauseKind::Projection(proj) if
        self.tcx.is_lang_item(proj.def_id(), LangItem::FnOnceOutput) &&
                proj.projection_term.self_ty() == declared &&
            proj.term.as_type() == Some(failed.self_ty()) => true,
    _ => false,
}matches!(
2713                    clause.as_ref().skip_norm_wip().kind().skip_binder(),
2714                    ty::ClauseKind::Projection(proj)
2715                        if self.tcx.is_lang_item(proj.def_id(), LangItem::FnOnceOutput)
2716                            && proj.projection_term.self_ty() == declared
2717                            && proj.term.as_type() == Some(failed.self_ty())
2718                )
2719            }) {
2720                return None;
2721            }
2722            // The error can be reported while the closure argument is still being checked, before
2723            // its own type is recorded, so identify closures syntactically and only fall back to
2724            // the argument's type (e.g. for a closure bound to a variable and passed by path).
2725            let closure_def_id = match arg.kind {
2726                hir::ExprKind::Closure(closure) => closure.def_id,
2727                _ => match typeck_results
2728                    .expr_ty_adjusted_opt(arg)
2729                    .map(|ty| *self.deeply_resolve_ignoring_regions(ty).peel_refs().kind())
2730                {
2731                    Some(ty::Closure(def_id, _)) => def_id.as_local()?,
2732                    _ => return None,
2733                },
2734            };
2735            let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) =
2736                self.tcx.hir_node_by_def_id(closure_def_id)
2737            else {
2738                return None;
2739            };
2740            let hir::ExprKind::Block(block, None) = self.tcx.hir_body(closure.body).value.kind
2741            else {
2742                return None;
2743            };
2744            self.removable_trailing_semicolon(block, obligation, trait_pred)
2745        });
2746        // Only emit the suggestion when a single closure argument matches, to avoid pointing at
2747        // an unrelated closure.
2748        if let Some(candidate) = candidates.next()
2749            && candidates.next().is_none()
2750        {
2751            // The same closure can be passed to somewhere else that expects it to return `()`,
2752            // where keeping the value would introduce a new error.
2753            self.emit_semicolon_removal_suggestion(
2754                err,
2755                trait_pred,
2756                candidate,
2757                Applicability::MaybeIncorrect,
2758            );
2759            return true;
2760        }
2761        false
2762    }
2763
2764    pub(super) fn suggest_borrow_for_unsized_closure_return(
2765        &self,
2766        body_def_id: LocalDefId,
2767        err: &mut Diag<'_>,
2768        predicate: ty::Predicate<'tcx>,
2769    ) {
2770        let Some(pred) = predicate.as_trait_clause() else {
2771            return;
2772        };
2773        if !self.tcx.is_lang_item(pred.def_id(), LangItem::Sized) {
2774            return;
2775        }
2776
2777        let Some(span) = err.span.primary_span() else {
2778            return;
2779        };
2780        let Some(body_id) = self.tcx.hir_node_by_def_id(body_def_id).body_id() else {
2781            return;
2782        };
2783        let body = self.tcx.hir_body(body_id);
2784        let mut expr_finder = FindExprBySpan::new(span, self.tcx);
2785        expr_finder.visit_expr(&body.value);
2786        let Some(expr) = expr_finder.result else {
2787            return;
2788        };
2789
2790        let closure = match expr.kind {
2791            hir::ExprKind::Call(_, args) => args.iter().find_map(|arg| match arg.kind {
2792                hir::ExprKind::Closure(closure) => Some(closure),
2793                _ => None,
2794            }),
2795            hir::ExprKind::MethodCall(_, _, args, _) => {
2796                args.iter().find_map(|arg| match arg.kind {
2797                    hir::ExprKind::Closure(closure) => Some(closure),
2798                    _ => None,
2799                })
2800            }
2801            _ => None,
2802        };
2803        let Some(closure) = closure else {
2804            return;
2805        };
2806        if !#[allow(non_exhaustive_omitted_patterns)] match closure.fn_decl.output {
    hir::FnRetTy::DefaultReturn(_) => true,
    _ => false,
}matches!(closure.fn_decl.output, hir::FnRetTy::DefaultReturn(_)) {
2807            return;
2808        }
2809
2810        err.span_suggestion_verbose(
2811            self.tcx.hir_body(closure.body).value.span.shrink_to_lo(),
2812            "consider borrowing the value",
2813            "&",
2814            Applicability::MaybeIncorrect,
2815        );
2816    }
2817
2818    pub(super) fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
2819        let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig, .. }, .. }) =
2820            self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
2821        else {
2822            return None;
2823        };
2824
2825        if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
2826    }
2827
2828    /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
2829    /// applicable and signal that the error has been expanded appropriately and needs to be
2830    /// emitted.
2831    pub(super) fn suggest_impl_trait(
2832        &self,
2833        err: &mut Diag<'_>,
2834        obligation: &PredicateObligation<'tcx>,
2835        trait_pred: ty::PolyTraitClause<'tcx>,
2836    ) -> bool {
2837        let ObligationCauseCode::SizedReturnType = obligation.cause.code() else {
2838            return false;
2839        };
2840        let ty::Dynamic(_, _) = trait_pred.self_ty().skip_binder().kind() else {
2841            return false;
2842        };
2843        if let Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig: fn_sig, .. }, .. })
2844        | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(fn_sig, _), .. })
2845        | Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(fn_sig, _), .. }) =
2846            self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
2847            && let hir::FnRetTy::Return(ty) = fn_sig.decl.output
2848            && let hir::TyKind::Path(qpath) = ty.kind
2849            && let hir::QPath::Resolved(None, path) = qpath
2850            && let Res::Def(DefKind::TyAlias, def_id) = path.res
2851        {
2852            // Do not suggest
2853            // type T = dyn Trait;
2854            // fn foo() -> impl T { .. }
2855            err.span_note(self.tcx.def_span(def_id), "this type alias is unsized");
2856            err.multipart_suggestion(
2857                ::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!(
2858                    "consider boxing the return type, and wrapping all of the returned values in \
2859                    `Box::new`",
2860                ),
2861                ::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![
2862                    (ty.span.shrink_to_lo(), "Box<".to_string()),
2863                    (ty.span.shrink_to_hi(), ">".to_string()),
2864                ],
2865                Applicability::MaybeIncorrect,
2866            );
2867            return false;
2868        }
2869
2870        err.code(E0746);
2871        err.primary_message("return type cannot be a trait object without pointer indirection");
2872        err.children.clear();
2873
2874        let mut span = obligation.cause.span;
2875        let mut is_async_fn_return = false;
2876        if let DefKind::Closure = self.tcx.def_kind(obligation.cause.body_def_id)
2877            && let parent = self.tcx.local_parent(obligation.cause.body_def_id)
2878            && let DefKind::Fn | DefKind::AssocFn = self.tcx.def_kind(parent)
2879            && self.tcx.asyncness(parent).is_async()
2880            && let Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig: fn_sig, .. }, .. })
2881            | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(fn_sig, _), .. })
2882            | Node::TraitItem(hir::TraitItem {
2883                kind: hir::TraitItemKind::Fn(fn_sig, _), ..
2884            }) = self.tcx.hir_node_by_def_id(parent)
2885        {
2886            // Do not suggest (#147894)
2887            // async fn foo() -> dyn Display impl { .. }
2888            // and
2889            // async fn foo() -> dyn Display Box<dyn { .. }>
2890            span = fn_sig.decl.output.span();
2891            is_async_fn_return = true;
2892            err.span(span);
2893        }
2894        let body = self.tcx.hir_body_owned_by(obligation.cause.body_def_id);
2895
2896        if !is_async_fn_return
2897            && let Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) =
2898                self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
2899            && #[allow(non_exhaustive_omitted_patterns)] match closure.fn_decl.output {
    hir::FnRetTy::DefaultReturn(_) => true,
    _ => false,
}matches!(closure.fn_decl.output, hir::FnRetTy::DefaultReturn(_))
2900        {
2901            return true;
2902        }
2903
2904        let mut visitor = ReturnsVisitor::default();
2905        visitor.visit_body(&body);
2906
2907        let (pre, impl_span) = if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span)
2908            && snip.starts_with("dyn ")
2909        {
2910            ("", span.with_hi(span.lo() + BytePos(4)))
2911        } else {
2912            ("dyn ", span.shrink_to_lo())
2913        };
2914
2915        err.span_suggestion_verbose(
2916            impl_span,
2917            "consider returning an `impl Trait` instead of a `dyn Trait`",
2918            "impl ",
2919            Applicability::MaybeIncorrect,
2920        );
2921
2922        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![
2923            (span.shrink_to_lo(), format!("Box<{pre}")),
2924            (span.shrink_to_hi(), ">".to_string()),
2925        ];
2926        sugg.extend(visitor.returns.into_iter().flat_map(|expr| {
2927            let span =
2928                expr.span.find_ancestor_in_same_ctxt(obligation.cause.span).unwrap_or(expr.span);
2929            if !span.can_be_used_for_suggestions() {
2930                ::alloc::vec::Vec::new()vec![]
2931            } else if let hir::ExprKind::Call(path, ..) = expr.kind
2932                && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, method)) = path.kind
2933                && method.ident.name == sym::new
2934                && let hir::TyKind::Path(hir::QPath::Resolved(.., box_path)) = ty.kind
2935                && box_path
2936                    .res
2937                    .opt_def_id()
2938                    .is_some_and(|def_id| self.tcx.is_lang_item(def_id, LangItem::OwnedBox))
2939            {
2940                // Don't box `Box::new`
2941                ::alloc::vec::Vec::new()vec![]
2942            } else {
2943                ::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![
2944                    (span.shrink_to_lo(), "Box::new(".to_string()),
2945                    (span.shrink_to_hi(), ")".to_string()),
2946                ]
2947            }
2948        }));
2949
2950        err.multipart_suggestion(
2951            ::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!(
2952                "alternatively, box the return type, and wrap all of the returned values in \
2953                 `Box::new`",
2954            ),
2955            sugg,
2956            Applicability::MaybeIncorrect,
2957        );
2958
2959        true
2960    }
2961
2962    pub(super) fn report_closure_arg_mismatch(
2963        &self,
2964        span: Span,
2965        found_span: Option<Span>,
2966        found: ty::TraitRef<'tcx>,
2967        expected: ty::TraitRef<'tcx>,
2968        cause: &ObligationCauseCode<'tcx>,
2969        found_node: Option<Node<'_>>,
2970        param_env: ty::ParamEnv<'tcx>,
2971    ) -> Diag<'a> {
2972        pub(crate) fn build_fn_sig_ty<'tcx>(
2973            infcx: &InferCtxt<'tcx>,
2974            trait_ref: ty::TraitRef<'tcx>,
2975        ) -> Ty<'tcx> {
2976            let inputs = trait_ref.args.type_at(1);
2977            let sig = match inputs.kind() {
2978                ty::Tuple(inputs) if infcx.tcx.is_callable_trait(trait_ref.def_id) => {
2979                    infcx.tcx.mk_fn_sig_safe_rust_abi(*inputs, infcx.next_ty_var(DUMMY_SP))
2980                }
2981                _ => infcx.tcx.mk_fn_sig_safe_rust_abi([inputs], infcx.next_ty_var(DUMMY_SP)),
2982            };
2983
2984            Ty::new_fn_ptr(infcx.tcx, ty::Binder::dummy(sig))
2985        }
2986
2987        let argument_kind = match expected.self_ty().kind() {
2988            ty::Closure(..) => "closure",
2989            ty::Coroutine(..) => "coroutine",
2990            _ => "function",
2991        };
2992        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!(
2993            self.dcx(),
2994            span,
2995            E0631,
2996            "type mismatch in {argument_kind} arguments",
2997        );
2998
2999        err.span_label(span, "expected due to this");
3000
3001        let found_span = found_span.unwrap_or(span);
3002        err.span_label(found_span, "found signature defined here");
3003
3004        let expected = build_fn_sig_ty(self, expected);
3005        let found = build_fn_sig_ty(self, found);
3006
3007        let (expected_str, found_str) = self.cmp(expected, found);
3008
3009        let signature_kind = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} signature", argument_kind))
    })format!("{argument_kind} signature");
3010        err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
3011
3012        self.note_conflicting_fn_args(&mut err, cause, expected, found, param_env);
3013        self.note_conflicting_closure_bounds(cause, &mut err);
3014
3015        if let Some(found_node) = found_node {
3016            hint_missing_borrow(self, param_env, span, found, expected, found_node, &mut err);
3017        }
3018
3019        err
3020    }
3021
3022    fn note_conflicting_fn_args(
3023        &self,
3024        err: &mut Diag<'_>,
3025        cause: &ObligationCauseCode<'tcx>,
3026        expected: Ty<'tcx>,
3027        found: Ty<'tcx>,
3028        param_env: ty::ParamEnv<'tcx>,
3029    ) {
3030        let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = cause else {
3031            return;
3032        };
3033        let ty::FnPtr(sig_tys, hdr) = expected.kind() else {
3034            return;
3035        };
3036        let expected = sig_tys.with(*hdr);
3037        let ty::FnPtr(sig_tys, hdr) = found.kind() else {
3038            return;
3039        };
3040        let found = sig_tys.with(*hdr);
3041        let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) else {
3042            return;
3043        };
3044        let hir::ExprKind::Path(path) = arg.kind else {
3045            return;
3046        };
3047        let expected_inputs = self.tcx.instantiate_bound_regions_with_erased(expected).inputs();
3048        let found_inputs = self.tcx.instantiate_bound_regions_with_erased(found).inputs();
3049        let both_tys = expected_inputs.iter().copied().zip(found_inputs.iter().copied());
3050
3051        let arg_expr = |infcx: &InferCtxt<'tcx>, name, expected: Ty<'tcx>, found: Ty<'tcx>| {
3052            let (expected_ty, expected_refs) = get_deref_type_and_refs(expected);
3053            let (found_ty, found_refs) = get_deref_type_and_refs(found);
3054
3055            if infcx.can_eq(param_env, found_ty, expected_ty) {
3056                if found_refs.len() == expected_refs.len()
3057                    && found_refs.iter().eq(expected_refs.iter())
3058                {
3059                    name
3060                } else if found_refs.len() > expected_refs.len() {
3061                    let refs = &found_refs[..found_refs.len() - expected_refs.len()];
3062                    if found_refs[..expected_refs.len()].iter().eq(expected_refs.iter()) {
3063                        ::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!(
3064                            "{}{name}",
3065                            refs.iter()
3066                                .map(|mutbl| format!("&{}", mutbl.prefix_str()))
3067                                .collect::<Vec<_>>()
3068                                .join(""),
3069                        )
3070                    } else {
3071                        // The refs have different mutability.
3072                        ::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!(
3073                            "{}*{name}",
3074                            refs.iter()
3075                                .map(|mutbl| format!("&{}", mutbl.prefix_str()))
3076                                .collect::<Vec<_>>()
3077                                .join(""),
3078                        )
3079                    }
3080                } else if expected_refs.len() > found_refs.len() {
3081                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}",
                (0..(expected_refs.len() -
                                            found_refs.len())).map(|_|
                                "*").collect::<Vec<_>>().join(""), name))
    })format!(
3082                        "{}{name}",
3083                        (0..(expected_refs.len() - found_refs.len()))
3084                            .map(|_| "*")
3085                            .collect::<Vec<_>>()
3086                            .join(""),
3087                    )
3088                } else {
3089                    ::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!(
3090                        "{}{name}",
3091                        found_refs
3092                            .iter()
3093                            .map(|mutbl| format!("&{}", mutbl.prefix_str()))
3094                            .chain(found_refs.iter().map(|_| "*".to_string()))
3095                            .collect::<Vec<_>>()
3096                            .join(""),
3097                    )
3098                }
3099            } else {
3100                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("/* {0} */", found))
    })format!("/* {found} */")
3101            }
3102        };
3103        let args_have_same_underlying_type = both_tys.clone().all(|(expected, found)| {
3104            let (expected_ty, _) = get_deref_type_and_refs(expected);
3105            let (found_ty, _) = get_deref_type_and_refs(found);
3106            self.can_eq(param_env, found_ty, expected_ty)
3107        });
3108        let (closure_names, call_names): (Vec<_>, Vec<_>) = if args_have_same_underlying_type
3109            && !expected_inputs.is_empty()
3110            && expected_inputs.len() == found_inputs.len()
3111            && let Some(typeck) = &self.typeck_results
3112            && let Res::Def(res_kind, fn_def_id) = typeck.qpath_res(&path, *arg_hir_id)
3113            && res_kind.is_fn_like()
3114        {
3115            let closure: Vec<_> = self
3116                .tcx
3117                .fn_arg_idents(fn_def_id)
3118                .iter()
3119                .enumerate()
3120                .map(|(i, ident)| {
3121                    if let Some(ident) = ident
3122                        && !#[allow(non_exhaustive_omitted_patterns)] match ident {
    Ident { name: kw::Underscore | kw::SelfLower, .. } => true,
    _ => false,
}matches!(ident, Ident { name: kw::Underscore | kw::SelfLower, .. })
3123                    {
3124                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", ident))
    })format!("{ident}")
3125                    } else {
3126                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("arg{0}", i))
    })format!("arg{i}")
3127                    }
3128                })
3129                .collect();
3130            let args = closure
3131                .iter()
3132                .zip(both_tys)
3133                .map(|(name, (expected, found))| {
3134                    arg_expr(self.infcx, name.to_owned(), expected, found)
3135                })
3136                .collect();
3137            (closure, args)
3138        } else {
3139            let closure_args = expected_inputs
3140                .iter()
3141                .enumerate()
3142                .map(|(i, _)| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("arg{0}", i))
    })format!("arg{i}"))
3143                .collect::<Vec<_>>();
3144            let call_args = both_tys
3145                .enumerate()
3146                .map(|(i, (expected, found))| {
3147                    arg_expr(self.infcx, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("arg{0}", i))
    })format!("arg{i}"), expected, found)
3148                })
3149                .collect::<Vec<_>>();
3150            (closure_args, call_args)
3151        };
3152        let closure_names: Vec<_> = closure_names
3153            .into_iter()
3154            .zip(expected_inputs.iter())
3155            .map(|(name, ty)| {
3156                ::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!(
3157                    "{name}{}",
3158                    if ty.has_infer_types() {
3159                        String::new()
3160                    } else if ty.references_error() {
3161                        ": /* type */".to_string()
3162                    } else {
3163                        format!(": {ty}")
3164                    }
3165                )
3166            })
3167            .collect();
3168        err.multipart_suggestion(
3169            "consider wrapping the function in a closure",
3170            ::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![
3171                (arg.span.shrink_to_lo(), format!("|{}| ", closure_names.join(", "))),
3172                (arg.span.shrink_to_hi(), format!("({})", call_names.join(", "))),
3173            ],
3174            Applicability::MaybeIncorrect,
3175        );
3176    }
3177
3178    // Add a note if there are two `Fn`-family bounds that have conflicting argument
3179    // requirements, which will always cause a closure to have a type error.
3180    fn note_conflicting_closure_bounds(
3181        &self,
3182        cause: &ObligationCauseCode<'tcx>,
3183        err: &mut Diag<'_>,
3184    ) {
3185        // First, look for a `WhereClauseInExpr`, which means we can get
3186        // the uninstantiated predicate list of the called function. And check
3187        // that the predicate that we failed to satisfy is a `Fn`-like trait.
3188        if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = *cause
3189            && let gen_clauses = self.tcx.clauses_of(def_id).instantiate_identity(self.tcx)
3190            && let Some(clause) = gen_clauses.clauses.get(idx).map(|c| c.as_ref().skip_norm_wip())
3191            && let ty::ClauseKind::Trait(trait_pred) = clause.kind().skip_binder()
3192            && self.tcx.is_fn_trait(trait_pred.def_id())
3193        {
3194            let expected_self =
3195                self.tcx.anonymize_bound_vars(clause.kind().rebind(trait_pred.self_ty()));
3196            let expected_args =
3197                self.tcx.anonymize_bound_vars(clause.kind().rebind(trait_pred.trait_ref.args));
3198
3199            // Find another clause whose self-type is equal to the expected self type,
3200            // but whose args don't match.
3201            let other_clause =
3202                gen_clauses.into_iter().enumerate().find(|&(other_idx, (clause, _))| {
3203                    let clause = clause.skip_norm_wip();
3204                    match clause.kind().skip_binder() {
3205                        ty::ClauseKind::Trait(trait_pred)
3206                            if self.tcx.is_fn_trait(trait_pred.def_id())
3207                            && other_idx != idx
3208                            // Make sure that the self type matches
3209                            // (i.e. constraining this closure)
3210                            && expected_self
3211                                == self.tcx.anonymize_bound_vars(
3212                                    clause.kind().rebind(trait_pred.self_ty()),
3213                                )
3214                            // But the args don't match (i.e. incompatible args)
3215                            && expected_args
3216                                != self.tcx.anonymize_bound_vars(
3217                                    clause.kind().rebind(trait_pred.trait_ref.args),
3218                                ) =>
3219                        {
3220                            true
3221                        }
3222                        _ => false,
3223                    }
3224                });
3225            // If we found one, then it's very likely the cause of the error.
3226            if let Some((_, (_, other_clause_span))) = other_clause {
3227                err.span_note(
3228                    other_clause_span,
3229                    "closure inferred to have a different signature due to this bound",
3230                );
3231            }
3232        }
3233    }
3234
3235    pub(super) fn suggest_fully_qualified_path(
3236        &self,
3237        err: &mut Diag<'_>,
3238        item_def_id: DefId,
3239        span: Span,
3240        trait_ref: DefId,
3241    ) {
3242        if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id)
3243            && let ty::AssocKind::Const { .. } | ty::AssocKind::Type { .. } = assoc_item.kind
3244        {
3245            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!(
3246                "{}s cannot be accessed directly on a `trait`, they can only be \
3247                        accessed through a specific `impl`",
3248                self.tcx.def_kind_descr(assoc_item.as_def_kind(), item_def_id)
3249            ));
3250
3251            if !assoc_item.is_impl_trait_in_trait() {
3252                err.span_suggestion_verbose(
3253                    span,
3254                    "use the fully qualified path to an implementation",
3255                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<Type as {0}>::{1}",
                self.tcx.def_path_str(trait_ref), assoc_item.name()))
    })format!(
3256                        "<Type as {}>::{}",
3257                        self.tcx.def_path_str(trait_ref),
3258                        assoc_item.name()
3259                    ),
3260                    Applicability::HasPlaceholders,
3261                );
3262            }
3263        }
3264    }
3265
3266    /// Adds an async-await specific note to the diagnostic when the future does not implement
3267    /// an auto trait because of a captured type.
3268    ///
3269    /// ```text
3270    /// note: future does not implement `Qux` as this value is used across an await
3271    ///   --> $DIR/issue-64130-3-other.rs:17:5
3272    ///    |
3273    /// LL |     let x = Foo;
3274    ///    |         - has type `Foo`
3275    /// LL |     baz().await;
3276    ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
3277    /// LL | }
3278    ///    | - `x` is later dropped here
3279    /// ```
3280    ///
3281    /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
3282    /// is "replaced" with a different message and a more specific error.
3283    ///
3284    /// ```text
3285    /// error: future cannot be sent between threads safely
3286    ///   --> $DIR/issue-64130-2-send.rs:21:5
3287    ///    |
3288    /// LL | fn is_send<T: Send>(t: T) { }
3289    ///    |               ---- required by this bound in `is_send`
3290    /// ...
3291    /// LL |     is_send(bar());
3292    ///    |     ^^^^^^^ future returned by `bar` is not send
3293    ///    |
3294    ///    = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
3295    ///            implemented for `Foo`
3296    /// note: future is not send as this value is used across an await
3297    ///   --> $DIR/issue-64130-2-send.rs:15:5
3298    ///    |
3299    /// LL |     let x = Foo;
3300    ///    |         - has type `Foo`
3301    /// LL |     baz().await;
3302    ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
3303    /// LL | }
3304    ///    | - `x` is later dropped here
3305    /// ```
3306    ///
3307    /// Returns `true` if an async-await specific note was added to the diagnostic.
3308    {}
#[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("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3308u32),
                                    ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3347",
                                        "rustc_trait_selection::error_reporting::traits::suggestions",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                        ::tracing_core::__macro_support::Option::Some(3347u32),
                                        ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3354",
                                                "rustc_trait_selection::error_reporting::traits::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(3354u32),
                                                ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3384",
                                                "rustc_trait_selection::error_reporting::traits::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(3384u32),
                                                ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3415",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3415u32),
                                    ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3425",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3425u32),
                                    ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3438",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3438u32),
                                    ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3459",
                                                "rustc_trait_selection::error_reporting::traits::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(3459u32),
                                                ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3483",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3483u32),
                                    ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3491",
                                        "rustc_trait_selection::error_reporting::traits::suggestions",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                        ::tracing_core::__macro_support::Option::Some(3491u32),
                                        ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3495",
                                            "rustc_trait_selection::error_reporting::traits::suggestions",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                            ::tracing_core::__macro_support::Option::Some(3495u32),
                                            ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3498",
                                                "rustc_trait_selection::error_reporting::traits::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(3498u32),
                                                ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3519",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3519u32),
                                    ::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))]
3309    pub fn maybe_note_obligation_cause_for_async_await(
3310        &self,
3311        err: &mut Diag<'_>,
3312        obligation: &PredicateObligation<'tcx>,
3313    ) -> bool {
3314        // Attempt to detect an async-await error by looking at the obligation causes, looking
3315        // for a coroutine to be present.
3316        //
3317        // When a future does not implement a trait because of a captured type in one of the
3318        // coroutines somewhere in the call stack, then the result is a chain of obligations.
3319        //
3320        // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
3321        // future is passed as an argument to a function C which requires a `Send` type, then the
3322        // chain looks something like this:
3323        //
3324        // - `BuiltinDerivedObligation` with a coroutine witness (B)
3325        // - `BuiltinDerivedObligation` with a coroutine (B)
3326        // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
3327        // - `BuiltinDerivedObligation` with a coroutine witness (A)
3328        // - `BuiltinDerivedObligation` with a coroutine (A)
3329        // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
3330        // - `BindingObligation` with `impl_send` (Send requirement)
3331        //
3332        // The first obligation in the chain is the most useful and has the coroutine that captured
3333        // the type. The last coroutine (`outer_coroutine` below) has information about where the
3334        // bound was introduced. At least one coroutine should be present for this diagnostic to be
3335        // modified.
3336        let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
3337            ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) => (Some(p), Some(p.self_ty())),
3338            _ => (None, None),
3339        };
3340        let mut coroutine = None;
3341        let mut outer_coroutine = None;
3342        let mut next_code = Some(obligation.cause.code());
3343
3344        let mut seen_upvar_tys_infer_tuple = false;
3345
3346        while let Some(code) = next_code {
3347            debug!(?code);
3348            match code {
3349                ObligationCauseCode::FunctionArg { parent_code, .. } => {
3350                    next_code = Some(parent_code);
3351                }
3352                ObligationCauseCode::ImplDerived(cause) => {
3353                    let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
3354                    debug!(
3355                        parent_trait_ref = ?cause.derived.parent_trait_pred,
3356                        self_ty.kind = ?ty.kind(),
3357                        "ImplDerived",
3358                    );
3359
3360                    match *ty.kind() {
3361                        ty::Coroutine(did, ..) | ty::CoroutineWitness(did, _) => {
3362                            coroutine = coroutine.or(Some(did));
3363                            outer_coroutine = Some(did);
3364                        }
3365                        ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
3366                            // By introducing a tuple of upvar types into the chain of obligations
3367                            // of a coroutine, the first non-coroutine item is now the tuple itself,
3368                            // we shall ignore this.
3369
3370                            seen_upvar_tys_infer_tuple = true;
3371                        }
3372                        _ if coroutine.is_none() => {
3373                            trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
3374                            target_ty = Some(ty);
3375                        }
3376                        _ => {}
3377                    }
3378
3379                    next_code = Some(&cause.derived.parent_code);
3380                }
3381                ObligationCauseCode::WellFormedDerived(derived_obligation)
3382                | ObligationCauseCode::BuiltinDerived(derived_obligation) => {
3383                    let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
3384                    debug!(
3385                        parent_trait_ref = ?derived_obligation.parent_trait_pred,
3386                        self_ty.kind = ?ty.kind(),
3387                    );
3388
3389                    match *ty.kind() {
3390                        ty::Coroutine(did, ..) | ty::CoroutineWitness(did, ..) => {
3391                            coroutine = coroutine.or(Some(did));
3392                            outer_coroutine = Some(did);
3393                        }
3394                        ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
3395                            // By introducing a tuple of upvar types into the chain of obligations
3396                            // of a coroutine, the first non-coroutine item is now the tuple itself,
3397                            // we shall ignore this.
3398
3399                            seen_upvar_tys_infer_tuple = true;
3400                        }
3401                        _ if coroutine.is_none() => {
3402                            trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
3403                            target_ty = Some(ty);
3404                        }
3405                        _ => {}
3406                    }
3407
3408                    next_code = Some(&derived_obligation.parent_code);
3409                }
3410                _ => break,
3411            }
3412        }
3413
3414        // Only continue if a coroutine was found.
3415        debug!(?coroutine, ?trait_ref, ?target_ty);
3416        let (Some(coroutine_did), Some(trait_ref), Some(target_ty)) =
3417            (coroutine, trait_ref, target_ty)
3418        else {
3419            return false;
3420        };
3421
3422        let span = self.tcx.def_span(coroutine_did);
3423
3424        let coroutine_did_root = self.tcx.typeck_root_def_id(coroutine_did);
3425        debug!(
3426            ?coroutine_did,
3427            ?coroutine_did_root,
3428            typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
3429            ?span,
3430        );
3431
3432        let coroutine_body =
3433            coroutine_did.as_local().and_then(|def_id| self.tcx.hir_maybe_body_owned_by(def_id));
3434        let mut visitor = AwaitsVisitor::default();
3435        if let Some(body) = coroutine_body {
3436            visitor.visit_body(&body);
3437        }
3438        debug!(awaits = ?visitor.awaits);
3439
3440        // Look for a type inside the coroutine interior that matches the target type to get
3441        // a span.
3442        let target_ty_erased = self.tcx.erase_and_anonymize_regions(target_ty);
3443        let ty_matches = |ty| -> bool {
3444            // Careful: the regions for types that appear in the
3445            // coroutine interior are not generally known, so we
3446            // want to erase them when comparing (and anyway,
3447            // `Send` and other bounds are generally unaffected by
3448            // the choice of region). When erasing regions, we
3449            // also have to erase late-bound regions. This is
3450            // because the types that appear in the coroutine
3451            // interior generally contain "bound regions" to
3452            // represent regions that are part of the suspended
3453            // coroutine frame. Bound regions are preserved by
3454            // `erase_and_anonymize_regions` and so we must also call
3455            // `instantiate_bound_regions_with_erased`.
3456            let ty_erased = self.tcx.instantiate_bound_regions_with_erased(ty);
3457            let ty_erased = self.tcx.erase_and_anonymize_regions(ty_erased);
3458            let eq = ty_erased == target_ty_erased;
3459            debug!(?ty_erased, ?target_ty_erased, ?eq);
3460            eq
3461        };
3462
3463        // Get the typeck results from the infcx if the coroutine is the function we are currently
3464        // type-checking; otherwise, get them by performing a query. This is needed to avoid
3465        // cycles. If we can't use resolved types because the coroutine comes from another crate,
3466        // we still provide a targeted error but without all the relevant spans.
3467        let coroutine_data = match &self.typeck_results {
3468            Some(t) if t.hir_owner.to_def_id() == coroutine_did_root => CoroutineData(t),
3469            _ if coroutine_did.is_local() => {
3470                CoroutineData(self.tcx.typeck(coroutine_did.expect_local()))
3471            }
3472            _ => return false,
3473        };
3474
3475        let coroutine_within_in_progress_typeck = match &self.typeck_results {
3476            Some(t) => t.hir_owner.to_def_id() == coroutine_did_root,
3477            _ => false,
3478        };
3479
3480        let mut interior_or_upvar_span = None;
3481
3482        let from_awaited_ty = coroutine_data.get_from_await_ty(visitor, self.tcx, ty_matches);
3483        debug!(?from_awaited_ty);
3484
3485        // Avoid disclosing internal information to downstream crates.
3486        if coroutine_did.is_local()
3487            // Try to avoid cycles.
3488            && !coroutine_within_in_progress_typeck
3489            && let Some(coroutine_info) = self.tcx.mir_coroutine_witnesses(coroutine_did)
3490        {
3491            debug!(?coroutine_info);
3492            'find_source: for (variant, source_info) in
3493                coroutine_info.variant_fields.iter().zip(&coroutine_info.variant_source_info)
3494            {
3495                debug!(?variant);
3496                for &local in variant {
3497                    let decl = &coroutine_info.field_tys[local];
3498                    debug!(?decl);
3499                    if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.ignore_for_traits {
3500                        interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(
3501                            decl.source_info.span,
3502                            Some((source_info.span, from_awaited_ty)),
3503                        ));
3504                        break 'find_source;
3505                    }
3506                }
3507            }
3508        }
3509
3510        if interior_or_upvar_span.is_none() {
3511            interior_or_upvar_span =
3512                coroutine_data.try_get_upvar_span(self, coroutine_did, ty_matches);
3513        }
3514
3515        if interior_or_upvar_span.is_none() && !coroutine_did.is_local() {
3516            interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(span, None));
3517        }
3518
3519        debug!(?interior_or_upvar_span);
3520        if let Some(interior_or_upvar_span) = interior_or_upvar_span {
3521            let is_async = self.tcx.coroutine_is_async(coroutine_did);
3522            self.note_obligation_cause_for_async_await(
3523                err,
3524                interior_or_upvar_span,
3525                is_async,
3526                outer_coroutine,
3527                trait_ref,
3528                target_ty,
3529                obligation,
3530                next_code,
3531            );
3532            true
3533        } else {
3534            false
3535        }
3536    }
3537
3538    /// Unconditionally adds the diagnostic note described in
3539    /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
3540    {}
#[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("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3540u32),
                                    ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3763",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3763u32),
                                    ::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)]
3541    fn note_obligation_cause_for_async_await(
3542        &self,
3543        err: &mut Diag<'_>,
3544        interior_or_upvar_span: CoroutineInteriorOrUpvar,
3545        is_async: bool,
3546        outer_coroutine: Option<DefId>,
3547        trait_pred: ty::TraitClause<'tcx>,
3548        target_ty: Ty<'tcx>,
3549        obligation: &PredicateObligation<'tcx>,
3550        next_code: Option<&ObligationCauseCode<'tcx>>,
3551    ) {
3552        let source_map = self.tcx.sess.source_map();
3553
3554        let (await_or_yield, an_await_or_yield) =
3555            if is_async { ("await", "an await") } else { ("yield", "a yield") };
3556        let future_or_coroutine = if is_async { "future" } else { "coroutine" };
3557
3558        // Special case the primary error message when send or sync is the trait that was
3559        // not implemented.
3560        let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
3561            self.tcx.get_diagnostic_name(trait_pred.def_id())
3562        {
3563            let (trait_name, trait_verb) =
3564                if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
3565
3566            err.code = None;
3567            err.primary_message(format!(
3568                "{future_or_coroutine} cannot be {trait_verb} between threads safely"
3569            ));
3570
3571            let original_span = err.span.primary_span().unwrap();
3572            let mut span = MultiSpan::from_span(original_span);
3573
3574            let message = outer_coroutine
3575                .and_then(|coroutine_did| {
3576                    Some(match self.tcx.coroutine_kind(coroutine_did).unwrap() {
3577                        CoroutineKind::Coroutine(_) => format!("coroutine is not {trait_name}"),
3578                        CoroutineKind::Desugared(
3579                            CoroutineDesugaring::Async,
3580                            CoroutineSource::Fn,
3581                        ) => self
3582                            .tcx
3583                            .parent(coroutine_did)
3584                            .as_local()
3585                            .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3586                            .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3587                            .map(|name| {
3588                                format!("future returned by `{name}` is not {trait_name}")
3589                            })?,
3590                        CoroutineKind::Desugared(
3591                            CoroutineDesugaring::Async,
3592                            CoroutineSource::Block,
3593                        ) => {
3594                            format!("future created by async block is not {trait_name}")
3595                        }
3596                        CoroutineKind::Desugared(
3597                            CoroutineDesugaring::Async,
3598                            CoroutineSource::Closure,
3599                        ) => {
3600                            format!("future created by async closure is not {trait_name}")
3601                        }
3602                        CoroutineKind::Desugared(
3603                            CoroutineDesugaring::AsyncGen,
3604                            CoroutineSource::Fn,
3605                        ) => self
3606                            .tcx
3607                            .parent(coroutine_did)
3608                            .as_local()
3609                            .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3610                            .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3611                            .map(|name| {
3612                                format!("async iterator returned by `{name}` is not {trait_name}")
3613                            })?,
3614                        CoroutineKind::Desugared(
3615                            CoroutineDesugaring::AsyncGen,
3616                            CoroutineSource::Block,
3617                        ) => {
3618                            format!("async iterator created by async gen block is not {trait_name}")
3619                        }
3620                        CoroutineKind::Desugared(
3621                            CoroutineDesugaring::AsyncGen,
3622                            CoroutineSource::Closure,
3623                        ) => {
3624                            format!(
3625                                "async iterator created by async gen closure is not {trait_name}"
3626                            )
3627                        }
3628                        CoroutineKind::Desugared(CoroutineDesugaring::Gen, CoroutineSource::Fn) => {
3629                            self.tcx
3630                                .parent(coroutine_did)
3631                                .as_local()
3632                                .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3633                                .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3634                                .map(|name| {
3635                                    format!("iterator returned by `{name}` is not {trait_name}")
3636                                })?
3637                        }
3638                        CoroutineKind::Desugared(
3639                            CoroutineDesugaring::Gen,
3640                            CoroutineSource::Block,
3641                        ) => {
3642                            format!("iterator created by gen block is not {trait_name}")
3643                        }
3644                        CoroutineKind::Desugared(
3645                            CoroutineDesugaring::Gen,
3646                            CoroutineSource::Closure,
3647                        ) => {
3648                            format!("iterator created by gen closure is not {trait_name}")
3649                        }
3650                    })
3651                })
3652                .unwrap_or_else(|| format!("{future_or_coroutine} is not {trait_name}"));
3653
3654            span.push_span_label(original_span, message);
3655            err.span(span);
3656
3657            format!("is not {trait_name}")
3658        } else {
3659            format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
3660        };
3661
3662        let mut explain_yield = |interior_span: Span, yield_span: Span| {
3663            let mut span = MultiSpan::from_span(yield_span);
3664            let snippet = match source_map.span_to_snippet(interior_span) {
3665                // #70935: If snippet contains newlines, display "the value" instead
3666                // so that we do not emit complex diagnostics.
3667                Ok(snippet) if !snippet.contains('\n') => format!("`{snippet}`"),
3668                _ => "the value".to_string(),
3669            };
3670            // note: future is not `Send` as this value is used across an await
3671            //   --> $DIR/issue-70935-complex-spans.rs:13:9
3672            //    |
3673            // LL |            baz(|| async {
3674            //    |  ______________-
3675            //    | |
3676            //    | |
3677            // LL | |              foo(tx.clone());
3678            // LL | |          }).await;
3679            //    | |          - ^^^^^^ await occurs here, with value maybe used later
3680            //    | |__________|
3681            //    |            has type `closure` which is not `Send`
3682            // note: value is later dropped here
3683            // LL | |          }).await;
3684            //    | |                  ^
3685            //
3686            span.push_span_label(
3687                yield_span,
3688                format!("{await_or_yield} occurs here, with {snippet} maybe used later"),
3689            );
3690            span.push_span_label(
3691                interior_span,
3692                format!("has type `{target_ty}` which {trait_explanation}"),
3693            );
3694            err.span_note(
3695                span,
3696                format!("{future_or_coroutine} {trait_explanation} as this value is used across {an_await_or_yield}"),
3697            );
3698        };
3699        match interior_or_upvar_span {
3700            CoroutineInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
3701                if let Some((yield_span, from_awaited_ty)) = interior_extra_info {
3702                    if let Some(await_span) = from_awaited_ty {
3703                        // The type causing this obligation is one being awaited at await_span.
3704                        let mut span = MultiSpan::from_span(await_span);
3705                        span.push_span_label(
3706                            await_span,
3707                            format!(
3708                                "await occurs here on type `{target_ty}`, which {trait_explanation}"
3709                            ),
3710                        );
3711                        err.span_note(
3712                            span,
3713                            format!(
3714                                "future {trait_explanation} as it awaits another future which {trait_explanation}"
3715                            ),
3716                        );
3717                    } else {
3718                        // Look at the last interior type to get a span for the `.await`.
3719                        explain_yield(interior_span, yield_span);
3720                    }
3721                }
3722            }
3723            CoroutineInteriorOrUpvar::Upvar(upvar_span) => {
3724                // `Some((ref_ty, is_mut))` if `target_ty` is `&T` or `&mut T` and fails to impl `Send`
3725                let non_send = match target_ty.kind() {
3726                    ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(obligation) {
3727                        Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
3728                        _ => None,
3729                    },
3730                    _ => None,
3731                };
3732
3733                let (span_label, span_note) = match non_send {
3734                    // if `target_ty` is `&T` or `&mut T` and fails to impl `Send`,
3735                    // include suggestions to make `T: Sync` so that `&T: Send`,
3736                    // or to make `T: Send` so that `&mut T: Send`
3737                    Some((ref_ty, is_mut)) => {
3738                        let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
3739                        let ref_kind = if is_mut { "&mut" } else { "&" };
3740                        (
3741                            format!(
3742                                "has type `{target_ty}` which {trait_explanation}, because `{ref_ty}` is not `{ref_ty_trait}`"
3743                            ),
3744                            format!(
3745                                "captured value {trait_explanation} because `{ref_kind}` references cannot be sent unless their referent is `{ref_ty_trait}`"
3746                            ),
3747                        )
3748                    }
3749                    None => (
3750                        format!("has type `{target_ty}` which {trait_explanation}"),
3751                        format!("captured value {trait_explanation}"),
3752                    ),
3753                };
3754
3755                let mut span = MultiSpan::from_span(upvar_span);
3756                span.push_span_label(upvar_span, span_label);
3757                err.span_note(span, span_note);
3758            }
3759        }
3760
3761        // Add a note for the item obligation that remains - normally a note pointing to the
3762        // bound that introduced the obligation (e.g. `T: Send`).
3763        debug!(?next_code);
3764        self.note_obligation_cause_code(
3765            obligation.cause.body_def_id,
3766            err,
3767            obligation.predicate,
3768            obligation.param_env,
3769            next_code.unwrap(),
3770            &mut Vec::new(),
3771            &mut Default::default(),
3772        );
3773    }
3774
3775    fn note_closure_capture(
3776        &self,
3777        err: &mut Diag<'_>,
3778        closure_def_id: DefId,
3779        upvar_args: ty::UpvarArgs<'tcx>,
3780        capture_ty: Option<Ty<'tcx>>,
3781    ) -> bool {
3782        let Some(closure_def_id) = closure_def_id.as_local() else {
3783            return false;
3784        };
3785        let Some(capture_ty) = capture_ty else {
3786            return false;
3787        };
3788
3789        // This can run while `typeck` for the closure's root is still on the query stack, for
3790        // example when reporting an overflow from inside trait selection, so only the in-progress
3791        // results are safe to look at. Asking for the captures through `tcx.closure_captures`
3792        // would call `typeck` again and replace the error being reported with a cycle error.
3793        let Some(typeck_results) = &self.typeck_results else {
3794            return false;
3795        };
3796        let typeck_root = self.tcx.typeck_root_def_id(closure_def_id.to_def_id());
3797        if typeck_results.hir_owner.to_def_id() != typeck_root {
3798            return false;
3799        }
3800
3801        // Error reporting can run before closure capture analysis has inferred the
3802        // tuple of upvar types. avoid accessing upvar types until they are available.
3803        let upvar_tys = match upvar_args.tupled_upvars_ty().kind() {
3804            ty::Tuple(args) => args,
3805            ty::Error(_) => ty::List::empty(),
3806            ty::Infer(_) => return false,
3807            ty => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unexpected upvar types tuple: {0:?}", ty)));
}unreachable!("unexpected upvar types tuple: {ty:?}"),
3808        };
3809
3810        let captures: Vec<_> =
3811            typeck_results.closure_min_captures_flattened(closure_def_id).collect();
3812        if captures.len() != upvar_tys.len() {
3813            return false;
3814        }
3815
3816        let capture_ty =
3817            self.tcx.erase_and_anonymize_regions(self.deeply_resolve_ignoring_regions(capture_ty));
3818        let Some(capture) = captures.iter().zip(upvar_tys).find_map(|(&capture, upvar_ty)| {
3819            let upvar_ty = self
3820                .tcx
3821                .erase_and_anonymize_regions(self.deeply_resolve_ignoring_regions(upvar_ty));
3822            (upvar_ty == capture_ty).then_some(capture)
3823        }) else {
3824            return false;
3825        };
3826
3827        err.span_note(
3828            capture.get_path_span(self.tcx),
3829            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required because `{0}` is used within this closure",
                capture.to_string(self.tcx)))
    })format!(
3830                "required because `{}` is used within this closure",
3831                capture.to_string(self.tcx)
3832            ),
3833        );
3834        true
3835    }
3836
3837    pub(crate) fn note_obligation_cause_code<T>(
3838        &self,
3839        body_def_id: LocalDefId,
3840        err: &mut Diag<'_>,
3841        predicate: T,
3842        param_env: ty::ParamEnv<'tcx>,
3843        cause_code: &ObligationCauseCode<'tcx>,
3844        obligated_types: &mut Vec<Ty<'tcx>>,
3845        seen_requirements: &mut FxHashSet<DefId>,
3846    ) where
3847        T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
3848    {
3849        let predicate = predicate.upcast(self.tcx);
3850        // Built-in closure obligations pass through a synthetic tuple of upvar types. Remember
3851        // the last constituent before that tuple so it can be matched to a captured place.
3852        let mut closure_capture_ty =
3853            predicate.as_trait_clause().map(|trait_pred| trait_pred.skip_binder().self_ty());
3854        self.note_obligation_cause_code_inner(
3855            body_def_id,
3856            err,
3857            predicate,
3858            param_env,
3859            cause_code,
3860            obligated_types,
3861            seen_requirements,
3862            &mut closure_capture_ty,
3863        );
3864    }
3865
3866    fn note_obligation_cause_code_inner<T>(
3867        &self,
3868        body_def_id: LocalDefId,
3869        err: &mut Diag<'_>,
3870        predicate: T,
3871        param_env: ty::ParamEnv<'tcx>,
3872        cause_code: &ObligationCauseCode<'tcx>,
3873        obligated_types: &mut Vec<Ty<'tcx>>,
3874        seen_requirements: &mut FxHashSet<DefId>,
3875        closure_capture_ty: &mut Option<Ty<'tcx>>,
3876    ) where
3877        T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
3878    {
3879        let tcx = self.tcx;
3880        let predicate = predicate.upcast(tcx);
3881        let suggest_remove_deref = |err: &mut Diag<'_>, expr: &hir::Expr<'_>| {
3882            if let Some(pred) = predicate.as_trait_clause()
3883                && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
3884                && let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind
3885            {
3886                err.span_suggestion_verbose(
3887                    expr.span.until(inner.span),
3888                    "references are always `Sized`, even if they point to unsized data; consider \
3889                     not dereferencing the expression",
3890                    String::new(),
3891                    Applicability::MaybeIncorrect,
3892                );
3893            }
3894        };
3895        match *cause_code {
3896            ObligationCauseCode::ExprAssignable
3897            | ObligationCauseCode::MatchExpressionArm { .. }
3898            | ObligationCauseCode::Pattern { .. }
3899            | ObligationCauseCode::IfExpression { .. }
3900            | ObligationCauseCode::IfExpressionWithNoElse
3901            | ObligationCauseCode::MainFunctionType
3902            | ObligationCauseCode::LangFunctionType(_)
3903            | ObligationCauseCode::IntrinsicType
3904            | ObligationCauseCode::MethodReceiver
3905            | ObligationCauseCode::ReturnNoExpression
3906            | ObligationCauseCode::Misc
3907            | ObligationCauseCode::WellFormed(..)
3908            | ObligationCauseCode::ReturnValue(_)
3909            | ObligationCauseCode::BlockTailExpression(..)
3910            | ObligationCauseCode::AwaitableExpr(_)
3911            | ObligationCauseCode::ForLoopIterator(_)
3912            | ObligationCauseCode::QuestionMark
3913            | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
3914            | ObligationCauseCode::LetElse
3915            | ObligationCauseCode::UnOp { .. }
3916            | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
3917            | ObligationCauseCode::AlwaysApplicableImpl
3918            | ObligationCauseCode::ConstParam(_)
3919            | ObligationCauseCode::ReferenceOutlivesReferent(..)
3920            | ObligationCauseCode::ObjectTypeBound(..) => {}
3921            ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. } => {
3922                if let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
3923                    && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
3924                    && tcx.sess.source_map().lookup_char_pos(lhs.span.lo()).line
3925                        != tcx.sess.source_map().lookup_char_pos(rhs.span.hi()).line
3926                {
3927                    err.span_label(lhs.span, "");
3928                    err.span_label(rhs.span, "");
3929                }
3930            }
3931            ObligationCauseCode::RustCall => {
3932                if let Some(pred) = predicate.as_trait_clause()
3933                    && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
3934                {
3935                    err.note("argument required to be sized due to `extern \"rust-call\"` ABI");
3936                }
3937            }
3938            ObligationCauseCode::SliceOrArrayElem => {
3939                err.note("slice and array elements must have `Sized` type");
3940            }
3941            ObligationCauseCode::ArrayLen(array_ty) => {
3942                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`"));
3943            }
3944            ObligationCauseCode::TupleElem => {
3945                err.note("only the last element of a tuple may have a dynamically sized type");
3946            }
3947            ObligationCauseCode::DynCompatible(span) => {
3948                err.multipart_suggestion(
3949                    "you might have meant to use `Self` to refer to the implementing type",
3950                    ::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())],
3951                    Applicability::MachineApplicable,
3952                );
3953            }
3954            ObligationCauseCode::WhereClause(item_def_id, span)
3955            | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)
3956            | ObligationCauseCode::HostEffectInExpr(item_def_id, span, ..)
3957                if !span.is_dummy() =>
3958            {
3959                if let ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, pos) = &cause_code {
3960                    if let Node::Expr(expr) = tcx.parent_hir_node(*hir_id)
3961                        && let hir::ExprKind::Call(_, args) = expr.kind
3962                        && let Some(expr) = args.get(*pos)
3963                    {
3964                        suggest_remove_deref(err, &expr);
3965                    } else if let Node::Expr(expr) = self.tcx.hir_node(*hir_id)
3966                        && let hir::ExprKind::MethodCall(_, _, args, _) = expr.kind
3967                        && let Some(expr) = args.get(*pos)
3968                    {
3969                        suggest_remove_deref(err, &expr);
3970                    }
3971                }
3972                let item_name = tcx.def_path_str(item_def_id);
3973                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));
3974                let mut multispan = MultiSpan::from(span);
3975                let sm = tcx.sess.source_map();
3976                if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy =
3977                    tcx.def_kind(item_def_id)
3978                {
3979                    let span = tcx.def_span(tcx.parent(item_def_id)).shrink_to_lo();
3980                    multispan.push_span_context(span);
3981                }
3982                if let Some(ident) = tcx.opt_item_ident(item_def_id) {
3983                    multispan.push_span_context(ident.span);
3984                }
3985                let mut a = "a";
3986                let mut this = "this bound";
3987                let mut note = None;
3988                let mut help = None;
3989                if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() {
3990                    match clause {
3991                        ty::ClauseKind::Trait(trait_pred) => {
3992                            let def_id = trait_pred.def_id();
3993                            let visible_item = if let Some(local) = def_id.as_local() {
3994                                let ty = trait_pred.self_ty();
3995                                // when `TraitA: TraitB` and `S` only impl TraitA,
3996                                // we check if `TraitB` can be reachable from `S`
3997                                // to determine whether to note `TraitA` is sealed trait.
3998                                if let ty::Adt(adt, _) = ty.kind() {
3999                                    let visibilities = &tcx.resolutions(()).effective_visibilities;
4000                                    visibilities.effective_vis(local).is_none_or(|v| {
4001                                        v.at_level(Level::Reexported)
4002                                            .is_accessible_from(adt.did(), tcx)
4003                                    })
4004                                } else {
4005                                    // FIXME(xizheyin): if the type is not ADT, we should not suggest it
4006                                    true
4007                                }
4008                            } else {
4009                                // Check for foreign traits being reachable.
4010                                tcx.visible_parent_map(()).get(&def_id).is_some()
4011                            };
4012                            if tcx.is_lang_item(def_id, LangItem::Sized) {
4013                                // Check if this is an implicit bound, even in foreign crates.
4014                                if tcx
4015                                    .generics_of(item_def_id)
4016                                    .own_params
4017                                    .iter()
4018                                    .any(|param| tcx.def_span(param.def_id) == span)
4019                                {
4020                                    a = "an implicit `Sized`";
4021                                    this =
4022                                        "the implicit `Sized` requirement on this type parameter";
4023                                }
4024                                if let Some(hir::Node::TraitItem(hir::TraitItem {
4025                                    generics,
4026                                    kind: hir::TraitItemKind::Type(bounds, None),
4027                                    ..
4028                                })) = tcx.hir_get_if_local(item_def_id)
4029                                    // Do not suggest relaxing if there is an explicit `Sized` obligation.
4030                                    && !bounds.iter()
4031                                        .filter_map(|bound| bound.trait_ref())
4032                                        .any(|tr| tr.trait_def_id().is_some_and(|def_id| tcx.is_lang_item(def_id, LangItem::Sized)))
4033                                    // Only suggest relaxing the implicit `Sized` restriction if the
4034                                    // failing obligation is that restriction. Relaxing it cannot
4035                                    // satisfy an explicit where clause of the item, e.g.
4036                                    // `type Assoc where Self: Sized;`.
4037                                    && !generics.predicates.iter().any(|pred| {
4038                                        pred.kind.in_where_clause() && pred.span.contains(span)
4039                                    })
4040                                {
4041                                    let (span, separator) = if let [.., last] = bounds {
4042                                        (last.span().shrink_to_hi(), " +")
4043                                    } else {
4044                                        (generics.span.shrink_to_hi(), ":")
4045                                    };
4046                                    err.span_suggestion_verbose(
4047                                        span,
4048                                        "consider relaxing the implicit `Sized` restriction",
4049                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ?Sized", separator))
    })format!("{separator} ?Sized"),
4050                                        Applicability::MachineApplicable,
4051                                    );
4052                                }
4053                            }
4054                            if let DefKind::Trait = tcx.def_kind(item_def_id)
4055                                && !visible_item
4056                            {
4057                                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!(
4058                                    "`{short_item_name}` is a \"sealed trait\", because to implement it \
4059                                    you also need to implement `{}`, which is not accessible; this is \
4060                                    usually done to force you to use one of the provided types that \
4061                                    already implement it",
4062                                    with_no_trimmed_paths!(tcx.def_path_str(def_id)),
4063                                ));
4064                                let mut types = tcx
4065                                    .all_impls(def_id)
4066                                    .map(|t| {
4067                                        {
    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!(
4068                                            "  {}",
4069                                            tcx.type_of(t).instantiate_identity().skip_norm_wip(),
4070                                        ))
4071                                    })
4072                                    .collect::<Vec<_>>();
4073                                if !types.is_empty() {
4074                                    let len = types.len();
4075                                    let post = if len > 9 {
4076                                        types.truncate(8);
4077                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\nand {0} others", len - 8))
    })format!("\nand {} others", len - 8)
4078                                    } else {
4079                                        String::new()
4080                                    };
4081                                    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!(
4082                                        "the following type{} implement{} the trait:\n{}{post}",
4083                                        pluralize!(len),
4084                                        if len == 1 { "s" } else { "" },
4085                                        types.join("\n"),
4086                                    ));
4087                                }
4088                            }
4089                        }
4090                        ty::ClauseKind::ConstArgHasType(..) => {
4091                            let descr =
4092                                ::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}`");
4093                            if span.is_visible(sm) {
4094                                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required by this const generic parameter in `{0}`",
                short_item_name))
    })format!(
4095                                    "required by this const generic parameter in `{short_item_name}`"
4096                                );
4097                                multispan.push_span_label(span, msg);
4098                                err.span_note(multispan, descr);
4099                            } else {
4100                                err.span_note(tcx.def_span(item_def_id), descr);
4101                            }
4102                            return;
4103                        }
4104                        _ => (),
4105                    }
4106                }
4107
4108                // If this is from a format string literal desugaring,
4109                // we've already said "required by this formatting parameter"
4110                let is_in_fmt_lit = if let Some(s) = err.span.primary_span() {
4111                    #[allow(non_exhaustive_omitted_patterns)] match s.desugaring_kind() {
    Some(DesugaringKind::FormatLiteral { .. }) => true,
    _ => false,
}matches!(s.desugaring_kind(), Some(DesugaringKind::FormatLiteral { .. }))
4112                } else {
4113                    false
4114                };
4115                if !is_in_fmt_lit {
4116                    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}`");
4117                    if span.is_visible(sm) {
4118                        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}`");
4119                        multispan.push_span_label(span, msg);
4120                        err.span_note(multispan, descr);
4121                    } else {
4122                        err.span_note(tcx.def_span(item_def_id), descr);
4123                    }
4124                }
4125                if let Some(note) = note {
4126                    err.note(note);
4127                }
4128                if let Some(help) = help {
4129                    err.help(help);
4130                }
4131            }
4132            ObligationCauseCode::WhereClause(..)
4133            | ObligationCauseCode::WhereClauseInExpr(..)
4134            | ObligationCauseCode::HostEffectInExpr(..) => {
4135                // We hold the `DefId` of the item introducing the obligation, but displaying it
4136                // doesn't add user usable information. It always point at an associated item.
4137            }
4138            ObligationCauseCode::OpaqueTypeBound(span, definition_def_id) => {
4139                err.span_note(span, "required by a bound in an opaque type");
4140                if let Some(definition_def_id) = definition_def_id
4141                    // If there are any stalled coroutine obligations, then this
4142                    // error may be due to that, and not because the body has more
4143                    // where-clauses.
4144                    && self.tcx.typeck(definition_def_id).coroutine_stalled_predicates.is_empty()
4145                {
4146                    // FIXME(compiler-errors): We could probably point to something
4147                    // specific here if we tried hard enough...
4148                    err.span_note(
4149                        tcx.def_span(definition_def_id),
4150                        "this definition site has more where clauses than the opaque type",
4151                    );
4152                }
4153            }
4154            ObligationCauseCode::Coercion { source, target } => {
4155                let source = tcx
4156                    .short_string(self.deeply_resolve_ignoring_regions(source), err.long_ty_path());
4157                let target = tcx
4158                    .short_string(self.deeply_resolve_ignoring_regions(target), err.long_ty_path());
4159                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!(
4160                    "required for the cast from `{source}` to `{target}`",
4161                )));
4162            }
4163            ObligationCauseCode::RepeatElementCopy { is_constable, elt_span } => {
4164                err.note(
4165                    "the `Copy` trait is required because this value will be copied for each element of the array",
4166                );
4167                let sm = tcx.sess.source_map();
4168                if #[allow(non_exhaustive_omitted_patterns)] match is_constable {
    IsConstable::Fn | IsConstable::Ctor => true,
    _ => false,
}matches!(is_constable, IsConstable::Fn | IsConstable::Ctor)
4169                    && let Ok(_) = sm.span_to_snippet(elt_span)
4170                {
4171                    err.multipart_suggestion(
4172                        "create an inline `const` block",
4173                        ::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![
4174                            (elt_span.shrink_to_lo(), "const { ".to_string()),
4175                            (elt_span.shrink_to_hi(), " }".to_string()),
4176                        ],
4177                        Applicability::MachineApplicable,
4178                    );
4179                } else {
4180                    // FIXME: we may suggest array::repeat instead
4181                    err.help("consider using `core::array::from_fn` to initialize the array");
4182                    err.help("see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html for more information");
4183                }
4184            }
4185            ObligationCauseCode::VariableType(hir_id) => {
4186                if let Some(typeck_results) = &self.typeck_results
4187                    && let Some(ty) = typeck_results.node_type_opt(hir_id)
4188                    && let ty::Error(_) = ty.kind()
4189                {
4190                    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!(
4191                        "`{predicate}` isn't satisfied, but the type of this pattern is \
4192                         `{{type error}}`",
4193                    ));
4194                    err.downgrade_to_delayed_bug();
4195                }
4196                let mut local = true;
4197                match tcx.parent_hir_node(hir_id) {
4198                    Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }) => {
4199                        err.span_suggestion_verbose(
4200                            ty.span.shrink_to_lo(),
4201                            "consider borrowing here",
4202                            "&",
4203                            Applicability::MachineApplicable,
4204                        );
4205                    }
4206                    Node::LetStmt(hir::LetStmt {
4207                        init: Some(hir::Expr { kind: hir::ExprKind::Index(..), span, .. }),
4208                        ..
4209                    }) => {
4210                        // When encountering an assignment of an unsized trait, like
4211                        // `let x = ""[..];`, provide a suggestion to borrow the initializer in
4212                        // order to use have a slice instead.
4213                        err.span_suggestion_verbose(
4214                            span.shrink_to_lo(),
4215                            "consider borrowing here",
4216                            "&",
4217                            Applicability::MachineApplicable,
4218                        );
4219                    }
4220                    Node::LetStmt(hir::LetStmt { init: Some(expr), .. }) => {
4221                        // When encountering an assignment of an unsized trait, like `let x = *"";`,
4222                        // we check if the RHS is a deref operation, to suggest removing it.
4223                        suggest_remove_deref(err, &expr);
4224                    }
4225                    Node::Param(param) => {
4226                        err.span_suggestion_verbose(
4227                            param.ty_span.shrink_to_lo(),
4228                            "function arguments must have a statically known size, borrowed types \
4229                            always have a known size",
4230                            "&",
4231                            Applicability::MachineApplicable,
4232                        );
4233                        local = false;
4234                    }
4235                    _ => {}
4236                }
4237                if local {
4238                    err.note("all local variables must have a statically known size");
4239                }
4240            }
4241            ObligationCauseCode::SizedArgumentType(hir_id) => {
4242                let mut ty = None;
4243                let borrowed_msg = "function arguments must have a statically known size, borrowed \
4244                                    types always have a known size";
4245                if let Some(hir_id) = hir_id
4246                    && let hir::Node::Param(param) = self.tcx.hir_node(hir_id)
4247                    && let Some(decl) = self.tcx.parent_hir_node(hir_id).fn_decl()
4248                    && let Some(t) = decl.inputs.iter().find(|t| param.ty_span.contains(t.span))
4249                {
4250                    // We use `contains` because the type might be surrounded by parentheses,
4251                    // which makes `ty_span` and `t.span` disagree with each other, but one
4252                    // fully contains the other: `foo: (dyn Foo + Bar)`
4253                    //                                 ^-------------^
4254                    //                                 ||
4255                    //                                 |t.span
4256                    //                                 param._ty_span
4257                    ty = Some(t);
4258                } else if let Some(hir_id) = hir_id
4259                    && let hir::Node::Ty(t) = self.tcx.hir_node(hir_id)
4260                {
4261                    ty = Some(t);
4262                }
4263                if let Some(ty) = ty {
4264                    match ty.kind {
4265                        hir::TyKind::TraitObject(traits, _) => {
4266                            let (span, kw) = match traits {
4267                                [first, ..] if first.span.lo() == ty.span.lo() => {
4268                                    // Missing `dyn` in front of trait object.
4269                                    (ty.span.shrink_to_lo(), "dyn ")
4270                                }
4271                                [first, ..] => (ty.span.until(first.span), ""),
4272                                [] => ::rustc_span::macros::bug_impl(Some(ty.span),
    format_args!("trait object with no traits: {0:?}", ty),
    Location::caller())span_bug!(ty.span, "trait object with no traits: {ty:?}"),
4273                            };
4274                            let needs_parens = traits.len() != 1;
4275                            // Don't recommend impl Trait as a closure argument
4276                            if let Some(hir_id) = hir_id
4277                                && #[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!(
4278                                    self.tcx.parent_hir_node(hir_id),
4279                                    hir::Node::Item(hir::Item {
4280                                        kind: hir::ItemKind::Fn { .. },
4281                                        ..
4282                                    })
4283                                )
4284                            {
4285                                err.span_suggestion_verbose(
4286                                    span,
4287                                    "you can use `impl Trait` as the argument type",
4288                                    "impl ",
4289                                    Applicability::MaybeIncorrect,
4290                                );
4291                            }
4292                            let sugg = if !needs_parens {
4293                                ::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}"))]
4294                            } else {
4295                                ::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![
4296                                    (span.shrink_to_lo(), format!("&({kw}")),
4297                                    (ty.span.shrink_to_hi(), ")".to_string()),
4298                                ]
4299                            };
4300                            err.multipart_suggestion(
4301                                borrowed_msg,
4302                                sugg,
4303                                Applicability::MachineApplicable,
4304                            );
4305                        }
4306                        hir::TyKind::Slice(_ty) => {
4307                            err.span_suggestion_verbose(
4308                                ty.span.shrink_to_lo(),
4309                                "function arguments must have a statically known size, borrowed \
4310                                 slices always have a known size",
4311                                "&",
4312                                Applicability::MachineApplicable,
4313                            );
4314                        }
4315                        hir::TyKind::Path(_) => {
4316                            err.span_suggestion_verbose(
4317                                ty.span.shrink_to_lo(),
4318                                borrowed_msg,
4319                                "&",
4320                                Applicability::MachineApplicable,
4321                            );
4322                        }
4323                        _ => {}
4324                    }
4325                } else {
4326                    err.note("all function arguments must have a statically known size");
4327                }
4328                if tcx.sess.opts.unstable_features.is_nightly_build()
4329                    && !tcx.features().unsized_fn_params()
4330                {
4331                    err.help("unsized fn params are gated as an unstable feature");
4332                }
4333            }
4334            ObligationCauseCode::SizedReturnType | ObligationCauseCode::SizedCallReturnType(_) => {
4335                err.note("the return type of a function must have a statically known size");
4336            }
4337            ObligationCauseCode::SizedYieldType => {
4338                err.note("the yield type of a coroutine must have a statically known size");
4339            }
4340            ObligationCauseCode::AssignmentLhsSized => {
4341                err.note("the left-hand-side of an assignment must have a statically known size");
4342            }
4343            ObligationCauseCode::TupleInitializerSized => {
4344                err.note("tuples must have a statically known size to be initialized");
4345            }
4346            ObligationCauseCode::StructInitializerSized => {
4347                err.note("structs must have a statically known size to be initialized");
4348            }
4349            ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
4350                match *item {
4351                    AdtKind::Struct => {
4352                        if last {
4353                            err.note(
4354                                "the last field of a packed struct may only have a \
4355                                dynamically sized type if it does not need drop to be run",
4356                            );
4357                        } else {
4358                            err.note(
4359                                "only the last field of a struct may have a dynamically sized type",
4360                            );
4361                        }
4362                    }
4363                    AdtKind::Union => {
4364                        err.note("no field of a union may have a dynamically sized type");
4365                    }
4366                    AdtKind::Enum => {
4367                        err.note("no field of an enum variant may have a dynamically sized type");
4368                    }
4369                }
4370                err.help("change the field's type to have a statically known size");
4371                err.span_suggestion_verbose(
4372                    span.shrink_to_lo(),
4373                    "borrowed types always have a statically known size",
4374                    "&",
4375                    Applicability::MachineApplicable,
4376                );
4377                err.multipart_suggestion(
4378                    "the `Box` type always has a statically known size and allocates its contents \
4379                     in the heap",
4380                    ::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![
4381                        (span.shrink_to_lo(), "Box<".to_string()),
4382                        (span.shrink_to_hi(), ">".to_string()),
4383                    ],
4384                    Applicability::MachineApplicable,
4385                );
4386            }
4387            ObligationCauseCode::SizedConstOrStatic => {
4388                err.note("statics and constants must have a statically known size");
4389            }
4390            ObligationCauseCode::InlineAsmSized => {
4391                err.note("all inline asm arguments must have a statically known size");
4392            }
4393            ObligationCauseCode::SizedClosureCapture(closure_def_id) => {
4394                err.note(
4395                    "all values captured by value by a closure must have a statically known size",
4396                );
4397                let hir::ExprKind::Closure(closure) =
4398                    tcx.hir_node_by_def_id(closure_def_id).expect_expr().kind
4399                else {
4400                    ::rustc_span::macros::bug_impl(None,
    format_args!("expected closure in SizedClosureCapture obligation"),
    Location::caller());bug!("expected closure in SizedClosureCapture obligation");
4401                };
4402                if let hir::CaptureBy::Value { .. } = closure.capture_clause
4403                    && let Some(span) = closure.fn_arg_span
4404                {
4405                    err.span_label(span, "this closure captures all values by move");
4406                }
4407            }
4408            ObligationCauseCode::SizedCoroutineInterior(coroutine_def_id) => {
4409                let what = match tcx.coroutine_kind(coroutine_def_id) {
4410                    None
4411                    | Some(hir::CoroutineKind::Coroutine(_))
4412                    | Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)) => {
4413                        "yield"
4414                    }
4415                    Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
4416                        "await"
4417                    }
4418                    Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => {
4419                        "yield`/`await"
4420                    }
4421                };
4422                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("all values live across `{0}` must have a statically known size",
                what))
    })format!(
4423                    "all values live across `{what}` must have a statically known size"
4424                ));
4425            }
4426            ObligationCauseCode::SharedStatic => {
4427                err.note("shared static variables must have a type that implements `Sync`");
4428            }
4429            ObligationCauseCode::MatchImpl(ref cause, _) => {
4430                self.note_obligation_cause_code_inner(
4431                    body_def_id,
4432                    err,
4433                    predicate,
4434                    param_env,
4435                    &cause.code(),
4436                    obligated_types,
4437                    seen_requirements,
4438                    closure_capture_ty,
4439                );
4440            }
4441            ObligationCauseCode::BuiltinDerived(ref data) => {
4442                let parent_trait_ref = self.deeply_resolve_ignoring_regions(data.parent_trait_pred);
4443                let ty = parent_trait_ref.skip_binder().self_ty();
4444                if parent_trait_ref.references_error() {
4445                    // NOTE(eddyb) this was `.cancel()`, but `err`
4446                    // is borrowed, so we can't fully defuse it.
4447                    err.downgrade_to_delayed_bug();
4448                    return;
4449                }
4450
4451                // If the obligation for a tuple is set directly by a Coroutine or Closure,
4452                // then the tuple must be the one containing capture types.
4453                let is_upvar_tys_infer_tuple = if !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Tuple(..) => true,
    _ => false,
}matches!(ty.kind(), ty::Tuple(..)) {
4454                    false
4455                } else if let ObligationCauseCode::BuiltinDerived(data) = &*data.parent_code {
4456                    let parent_trait_ref =
4457                        self.deeply_resolve_ignoring_regions(data.parent_trait_pred);
4458                    let nested_ty = parent_trait_ref.skip_binder().self_ty();
4459                    #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
    ty::Coroutine(..) => true,
    _ => false,
}matches!(nested_ty.kind(), ty::Coroutine(..))
4460                        || #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
    ty::Closure(..) => true,
    _ => false,
}matches!(nested_ty.kind(), ty::Closure(..))
4461                        || #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
    ty::CoroutineClosure(..) => true,
    _ => false,
}matches!(nested_ty.kind(), ty::CoroutineClosure(..))
4462                } else {
4463                    false
4464                };
4465
4466                let is_builtin_async_fn_trait =
4467                    tcx.async_fn_trait_kind_from_def_id(data.parent_trait_pred.def_id()).is_some();
4468
4469                if !is_upvar_tys_infer_tuple && !is_builtin_async_fn_trait {
4470                    let mut msg = || {
4471                        let ty_str = tcx.short_string(ty, err.long_ty_path());
4472                        ::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}`")
4473                    };
4474                    match *ty.kind() {
4475                        ty::Adt(def, args) => {
4476                            let msg = msg();
4477                            match tcx.opt_item_ident(def.did()) {
4478                                Some(ident) => {
4479                                    let mut spans = MultiSpan::new();
4480                                    if def.did().is_local()
4481                                        && let Some(pred) = predicate.as_trait_clause()
4482                                    {
4483                                        let field_ty = self.deeply_resolve_ignoring_regions(
4484                                            pred.skip_binder().self_ty(),
4485                                        );
4486                                        for field in def.all_fields() {
4487                                            if field.ty(tcx, args).skip_norm_wip() == field_ty {
4488                                                let sp = tcx.def_span(field.did);
4489                                                spans.push_primary_span(sp);
4490                                                spans.push_span_label(sp, "required by this field");
4491                                            }
4492                                        }
4493                                    }
4494                                    if spans.has_primary_spans() {
4495                                        spans.push_span_context(ident.span);
4496                                    } else {
4497                                        spans.push_primary_span(ident.span);
4498                                        spans.push_span_label(ident.span, "");
4499                                    }
4500                                    err.span_note(spans, msg);
4501                                }
4502                                None => {
4503                                    err.note(msg);
4504                                }
4505                            }
4506                        }
4507                        ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) => {
4508                            // If the previous type is async fn, this is the future generated by the body of an async function.
4509                            // Avoid printing it twice (it was already printed in the `ty::Coroutine` arm below).
4510                            let is_future = tcx.ty_is_opaque_future(ty);
4511                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:4511",
                        "rustc_trait_selection::error_reporting::traits::suggestions",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                        ::tracing_core::__macro_support::Option::Some(4511u32),
                        ::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!(
4512                                ?obligated_types,
4513                                ?is_future,
4514                                "note_obligation_cause_code: check for async fn"
4515                            );
4516                            if is_future
4517                                && obligated_types.last().is_some_and(|ty| match ty.kind() {
4518                                    ty::Coroutine(last_def_id, ..) => {
4519                                        tcx.coroutine_is_async(*last_def_id)
4520                                    }
4521                                    _ => false,
4522                                })
4523                            {
4524                                // See comment above; skip printing twice.
4525                            } else {
4526                                let msg = msg();
4527                                err.span_note(tcx.def_span(def_id), msg);
4528                            }
4529                        }
4530                        ty::Coroutine(def_id, _) => {
4531                            let sp = tcx.def_span(def_id);
4532
4533                            // Special-case this to say "async block" instead of `[static coroutine]`.
4534                            let kind = tcx.coroutine_kind(def_id).unwrap();
4535                            err.span_note(
4536                                sp,
4537                                {
    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!(
4538                                    "required because it's used within this {kind:#}",
4539                                )),
4540                            );
4541                        }
4542                        ty::CoroutineWitness(..) => {
4543                            // Skip printing coroutine-witnesses, since we'll drill into
4544                            // the bad field in another derived obligation cause.
4545                        }
4546                        ty::Closure(def_id, args) => {
4547                            if !self.note_closure_capture(
4548                                err,
4549                                def_id,
4550                                ty::UpvarArgs::Closure(args),
4551                                *closure_capture_ty,
4552                            ) {
4553                                err.span_note(
4554                                    tcx.def_span(def_id),
4555                                    "required because it's used within this closure",
4556                                );
4557                            }
4558                        }
4559                        ty::CoroutineClosure(def_id, args) => {
4560                            if !self.note_closure_capture(
4561                                err,
4562                                def_id,
4563                                ty::UpvarArgs::CoroutineClosure(args),
4564                                *closure_capture_ty,
4565                            ) {
4566                                err.span_note(
4567                                    tcx.def_span(def_id),
4568                                    "required because it's used within this closure",
4569                                );
4570                            }
4571                        }
4572                        ty::Str => {
4573                            err.note("`str` is considered to contain a `[u8]` slice for auto trait purposes");
4574                        }
4575                        _ => {
4576                            let msg = msg();
4577                            err.note(msg);
4578                        }
4579                    };
4580                }
4581
4582                if !is_upvar_tys_infer_tuple {
4583                    *closure_capture_ty = Some(ty);
4584                }
4585
4586                obligated_types.push(ty);
4587
4588                let parent_predicate = parent_trait_ref;
4589                if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
4590                    self.note_obligation_cause_code_inner(
4591                        body_def_id,
4592                        err,
4593                        parent_predicate,
4594                        param_env,
4595                        &data.parent_code,
4596                        obligated_types,
4597                        seen_requirements,
4598                        closure_capture_ty,
4599                    );
4600                } else {
4601                    self.note_obligation_cause_code_inner(
4602                        body_def_id,
4603                        err,
4604                        parent_predicate,
4605                        param_env,
4606                        cause_code.peel_derives(),
4607                        obligated_types,
4608                        seen_requirements,
4609                        closure_capture_ty,
4610                    );
4611                }
4612            }
4613            ObligationCauseCode::ImplDerived(ref data) => {
4614                let mut parent_trait_pred =
4615                    self.deeply_resolve_ignoring_regions(data.derived.parent_trait_pred);
4616                let parent_def_id = parent_trait_pred.def_id();
4617                if tcx.is_diagnostic_item(sym::FromResidual, parent_def_id)
4618                    && !tcx.features().enabled(sym::try_trait_v2)
4619                {
4620                    // If `#![feature(try_trait_v2)]` is not enabled, then there's no point on
4621                    // talking about `FromResidual<Result<A, B>>`, as the end user has nothing they
4622                    // can do about it. As far as they are concerned, `?` is compiler magic.
4623                    return;
4624                }
4625                if tcx.is_diagnostic_item(sym::PinDerefMutHelper, parent_def_id) {
4626                    let parent_predicate =
4627                        self.deeply_resolve_ignoring_regions(data.derived.parent_trait_pred);
4628
4629                    // Skip PinDerefMutHelper in suggestions, but still show downstream suggestions.
4630
4631                    *closure_capture_ty = Some(parent_trait_pred.skip_binder().self_ty());
4632                    self.note_obligation_cause_code_inner(
4633                        body_def_id,
4634                        err,
4635                        parent_predicate,
4636                        param_env,
4637                        &data.derived.parent_code,
4638                        obligated_types,
4639                        seen_requirements,
4640                        closure_capture_ty,
4641                    );
4642                    return;
4643                }
4644                let self_ty_str =
4645                    tcx.short_string(parent_trait_pred.skip_binder().self_ty(), err.long_ty_path());
4646                let trait_name = tcx.short_string(
4647                    parent_trait_pred.print_modifiers_and_trait_path(),
4648                    err.long_ty_path(),
4649                );
4650                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}`");
4651                let mut is_auto_trait = false;
4652                match tcx.hir_get_if_local(data.impl_or_alias_def_id) {
4653                    Some(Node::Item(hir::Item {
4654                        kind: hir::ItemKind::Trait { is_auto, ident, .. },
4655                        ..
4656                    })) => {
4657                        // FIXME: we should do something else so that it works even on crate foreign
4658                        // auto traits.
4659                        is_auto_trait = #[allow(non_exhaustive_omitted_patterns)] match is_auto {
    hir::IsAuto::Yes => true,
    _ => false,
}matches!(is_auto, hir::IsAuto::Yes);
4660                        err.span_note(ident.span, msg);
4661                    }
4662                    Some(Node::Item(hir::Item {
4663                        kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, generics, .. }),
4664                        ..
4665                    })) => {
4666                        let mut spans = Vec::with_capacity(2);
4667                        if let Some(of_trait) = of_trait
4668                            && !of_trait.trait_ref.path.span.in_derive_expansion()
4669                        {
4670                            spans.push(of_trait.trait_ref.path.span);
4671                        }
4672                        spans.push(self_ty.span);
4673                        let mut spans: MultiSpan = spans.into();
4674                        let mut derived = false;
4675                        if #[allow(non_exhaustive_omitted_patterns)] match self_ty.span.ctxt().outer_expn_data().kind
    {
    ExpnKind::Macro(MacroKind::Derive, _) => true,
    _ => false,
}matches!(
4676                            self_ty.span.ctxt().outer_expn_data().kind,
4677                            ExpnKind::Macro(MacroKind::Derive, _)
4678                        ) || #[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!(
4679                            of_trait.map(|t| t.trait_ref.path.span.ctxt().outer_expn_data().kind),
4680                            Some(ExpnKind::Macro(MacroKind::Derive, _))
4681                        ) {
4682                            derived = true;
4683                            spans.push_span_label(
4684                                data.span,
4685                                if data.span.in_derive_expansion() {
4686                                    ::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}`")
4687                                } else {
4688                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unsatisfied trait bound"))
    })format!("unsatisfied trait bound")
4689                                },
4690                            );
4691                        } else if !data.span.is_dummy() && !data.span.overlaps(self_ty.span) {
4692                            // `Sized` may be an explicit or implicit trait bound. If it is
4693                            // implicit, mention it as such.
4694                            if let Some(pred) = predicate.as_trait_clause()
4695                                && self.tcx.is_lang_item(pred.def_id(), LangItem::Sized)
4696                                && self
4697                                    .tcx
4698                                    .generics_of(data.impl_or_alias_def_id)
4699                                    .own_params
4700                                    .iter()
4701                                    .any(|param| self.tcx.def_span(param.def_id) == data.span)
4702                            {
4703                                spans.push_span_label(
4704                                    data.span,
4705                                    "unsatisfied trait bound implicitly introduced here",
4706                                );
4707                            } else {
4708                                spans.push_span_label(
4709                                    data.span,
4710                                    "unsatisfied trait bound introduced here",
4711                                );
4712                            }
4713                        }
4714                        err.span_note(spans, msg);
4715                        if derived
4716                            && self.is_truly_imperfect_derive(
4717                                parent_trait_pred,
4718                                predicate,
4719                                param_env,
4720                            )
4721                        {
4722                            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!(
4723                                "consider manually implementing `{trait_name}` to avoid undesired bounds caused by \"imperfect derives\"",
4724                            ));
4725                            err.note(
4726                                "to learn more, visit <https://github.com/rust-lang/rust/issues/26925>",
4727                            );
4728                        }
4729                        point_at_assoc_type_restriction(
4730                            tcx,
4731                            err,
4732                            &self_ty_str,
4733                            &trait_name,
4734                            predicate,
4735                            &generics,
4736                            &data,
4737                        );
4738                    }
4739                    _ => {
4740                        err.note(msg);
4741                    }
4742                };
4743
4744                let mut parent_predicate = parent_trait_pred;
4745                let mut data = &data.derived;
4746                let mut count = 0;
4747                seen_requirements.insert(parent_def_id);
4748                if is_auto_trait {
4749                    // We don't want to point at the ADT saying "required because it appears within
4750                    // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
4751                    while let ObligationCauseCode::BuiltinDerived(derived) = &*data.parent_code {
4752                        let child_trait_ref =
4753                            self.deeply_resolve_ignoring_regions(derived.parent_trait_pred);
4754                        let child_def_id = child_trait_ref.def_id();
4755                        if seen_requirements.insert(child_def_id) {
4756                            break;
4757                        }
4758                        data = derived;
4759                        parent_predicate = child_trait_ref.upcast(tcx);
4760                        parent_trait_pred = child_trait_ref;
4761                    }
4762                }
4763                while let ObligationCauseCode::ImplDerived(child) = &*data.parent_code {
4764                    // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
4765                    let child_trait_pred =
4766                        self.deeply_resolve_ignoring_regions(child.derived.parent_trait_pred);
4767                    let child_def_id = child_trait_pred.def_id();
4768                    if seen_requirements.insert(child_def_id) {
4769                        break;
4770                    }
4771                    count += 1;
4772                    data = &child.derived;
4773                    parent_predicate = child_trait_pred.upcast(tcx);
4774                    parent_trait_pred = child_trait_pred;
4775                }
4776                if count > 0 {
4777                    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} redundant requirement{1} hidden",
                count, if count == 1 { "" } else { "s" }))
    })format!(
4778                        "{} redundant requirement{} hidden",
4779                        count,
4780                        pluralize!(count)
4781                    ));
4782                    let self_ty = tcx.short_string(
4783                        parent_trait_pred.skip_binder().self_ty(),
4784                        err.long_ty_path(),
4785                    );
4786                    let trait_path = tcx.short_string(
4787                        parent_trait_pred.print_modifiers_and_trait_path(),
4788                        err.long_ty_path(),
4789                    );
4790                    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}`"));
4791                }
4792                *closure_capture_ty = Some(parent_trait_pred.skip_binder().self_ty());
4793                self.note_obligation_cause_code_inner(
4794                    body_def_id,
4795                    err,
4796                    parent_predicate,
4797                    param_env,
4798                    &data.parent_code,
4799                    obligated_types,
4800                    seen_requirements,
4801                    closure_capture_ty,
4802                )
4803            }
4804            ObligationCauseCode::ImplDerivedHost(ref data) => {
4805                let self_ty = tcx.short_string(
4806                    self.deeply_resolve_ignoring_regions(data.derived.parent_host_clause.self_ty()),
4807                    err.long_ty_path(),
4808                );
4809                let trait_path = tcx.short_string(
4810                    data.derived
4811                        .parent_host_clause
4812                        .map_bound(|clause| clause.trait_ref)
4813                        .print_only_trait_path(),
4814                    err.long_ty_path(),
4815                );
4816                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required for `{1}` to implement `{0} {2}`",
                data.derived.parent_host_clause.skip_binder().constness,
                self_ty, trait_path))
    })format!(
4817                    "required for `{self_ty}` to implement `{} {trait_path}`",
4818                    data.derived.parent_host_clause.skip_binder().constness,
4819                );
4820                match tcx.hir_get_if_local(data.impl_def_id) {
4821                    Some(Node::Item(hir::Item {
4822                        kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
4823                        ..
4824                    })) => {
4825                        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];
4826                        spans.extend(of_trait.map(|t| t.trait_ref.path.span));
4827                        let mut spans: MultiSpan = spans.into();
4828                        spans.push_span_label(data.span, "unsatisfied trait bound introduced here");
4829                        err.span_note(spans, msg);
4830                    }
4831                    _ => {
4832                        err.note(msg);
4833                    }
4834                }
4835
4836                self.note_obligation_cause_code_inner(
4837                    body_def_id,
4838                    err,
4839                    data.derived.parent_host_clause,
4840                    param_env,
4841                    &data.derived.parent_code,
4842                    obligated_types,
4843                    seen_requirements,
4844                    closure_capture_ty,
4845                );
4846            }
4847            ObligationCauseCode::BuiltinDerivedHost(ref data) => {
4848                self.note_obligation_cause_code_inner(
4849                    body_def_id,
4850                    err,
4851                    data.parent_host_clause,
4852                    param_env,
4853                    &data.parent_code,
4854                    obligated_types,
4855                    seen_requirements,
4856                    closure_capture_ty,
4857                );
4858            }
4859            ObligationCauseCode::WellFormedDerived(ref data) => {
4860                let parent_trait_ref = self.deeply_resolve_ignoring_regions(data.parent_trait_pred);
4861                let parent_predicate = parent_trait_ref;
4862
4863                *closure_capture_ty = Some(parent_trait_ref.skip_binder().self_ty());
4864                self.note_obligation_cause_code_inner(
4865                    body_def_id,
4866                    err,
4867                    parent_predicate,
4868                    param_env,
4869                    &data.parent_code,
4870                    obligated_types,
4871                    seen_requirements,
4872                    closure_capture_ty,
4873                );
4874            }
4875            ObligationCauseCode::TypeAlias(ref nested, span, def_id) => {
4876                self.note_obligation_cause_code_inner(
4877                    body_def_id,
4878                    err,
4879                    predicate,
4880                    param_env,
4881                    nested,
4882                    obligated_types,
4883                    seen_requirements,
4884                    closure_capture_ty,
4885                );
4886                let mut multispan = MultiSpan::from(span);
4887                multispan.push_span_label(span, "required by this bound");
4888                err.span_note(
4889                    multispan,
4890                    ::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)),
4891                );
4892            }
4893            ObligationCauseCode::FunctionArg {
4894                arg_hir_id, call_hir_id, ref parent_code, ..
4895            } => {
4896                self.note_function_argument_obligation(
4897                    body_def_id,
4898                    err,
4899                    arg_hir_id,
4900                    parent_code,
4901                    param_env,
4902                    predicate,
4903                    call_hir_id,
4904                );
4905
4906                self.note_obligation_cause_code_inner(
4907                    body_def_id,
4908                    err,
4909                    predicate,
4910                    param_env,
4911                    parent_code,
4912                    obligated_types,
4913                    seen_requirements,
4914                    closure_capture_ty,
4915                );
4916            }
4917            // Suppress `compare_type_clause_entailment` errors for RPITITs, since they
4918            // should be implied by the parent method.
4919            ObligationCauseCode::CompareImplItem { trait_item_def_id, .. }
4920                if tcx.is_impl_trait_in_trait(trait_item_def_id) => {}
4921            ObligationCauseCode::CompareImplItem { trait_item_def_id, kind, .. } => {
4922                let item_name = tcx.item_name(trait_item_def_id);
4923                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!(
4924                    "the requirement `{predicate}` appears on the `impl`'s {kind} \
4925                     `{item_name}` but not on the corresponding trait's {kind}",
4926                );
4927                let sp = tcx
4928                    .opt_item_ident(trait_item_def_id)
4929                    .map(|i| i.span)
4930                    .unwrap_or_else(|| tcx.def_span(trait_item_def_id));
4931                let mut assoc_span: MultiSpan = sp.into();
4932                assoc_span.push_span_label(
4933                    sp,
4934                    ::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}`"),
4935                );
4936                if let Some(ident) = tcx
4937                    .opt_associated_item(trait_item_def_id)
4938                    .and_then(|i| tcx.opt_item_ident(i.container_id(tcx)))
4939                {
4940                    assoc_span.push_span_label(ident.span, "in this trait");
4941                }
4942                err.span_note(assoc_span, msg);
4943            }
4944            ObligationCauseCode::TrivialBound => {
4945                tcx.disabled_nightly_features(err, [(String::new(), sym::trivial_bounds)]);
4946            }
4947            ObligationCauseCode::OpaqueReturnType(expr_info) => {
4948                // Point at the method call in the returned expression's chain where an
4949                // associated type diverged from what the signature's opaque type expects,
4950                // regardless of how the failed predicate was derived from that expectation.
4951                if let Some(typeck_results) = self.typeck_results.as_deref() {
4952                    let chain_expr = match expr_info {
4953                        Some((_, hir_id)) => Some(tcx.hir_expect_expr(hir_id)),
4954                        None => tcx.hir_node_by_def_id(body_def_id).body_id().and_then(|body_id| {
4955                            match tcx.hir_body(body_id).value.kind {
4956                                hir::ExprKind::Block(block, _) => block.expr,
4957                                _ => None,
4958                            }
4959                        }),
4960                    };
4961                    if let Some(chain_expr) = chain_expr {
4962                        self.point_at_chain_in_return_position(
4963                            body_def_id,
4964                            chain_expr,
4965                            typeck_results,
4966                            param_env,
4967                            err,
4968                        );
4969                    }
4970                }
4971                let (expr_ty, expr) = if let Some((expr_ty, hir_id)) = expr_info {
4972                    let expr = tcx.hir_expect_expr(hir_id);
4973                    (expr_ty, expr)
4974                } else if let Some(body_id) = tcx.hir_node_by_def_id(body_def_id).body_id()
4975                    && let body = tcx.hir_body(body_id)
4976                    && let hir::ExprKind::Block(block, _) = body.value.kind
4977                    && let Some(expr) = block.expr
4978                    && let Some(expr_ty) = self
4979                        .typeck_results
4980                        .as_ref()
4981                        .and_then(|typeck| typeck.node_type_opt(expr.hir_id))
4982                    && let Some(pred) = predicate.as_clause()
4983                    && let Some(pred) = pred.as_trait_clause()
4984                    && self
4985                        .infcx
4986                        .enter_forall(pred, |pred| self.can_eq(param_env, pred.self_ty(), expr_ty))
4987                {
4988                    (expr_ty, expr)
4989                } else {
4990                    return;
4991                };
4992                let expr_ty_string = tcx.short_string(expr_ty, err.long_ty_path());
4993                if expr_ty.is_never()
4994                    && let span = expr.span.source_callsite()
4995                    && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(span)
4996                    && span != expr.span
4997                {
4998                    err.span_suggestion(
4999                        span,
5000                        "`!` can be coerced to any type; consider casting it to a concrete type that implements the trait",
5001                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} as /* Type */", snippet))
    })format!("{snippet} as /* Type */"),
5002                        Applicability::HasPlaceholders,
5003                    );
5004                }
5005                err.span_label(
5006                    expr.span,
5007                    {
    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!(
5008                        "return type was inferred to be `{expr_ty_string}` here",
5009                    )),
5010                );
5011                suggest_remove_deref(err, &expr);
5012            }
5013            ObligationCauseCode::UnsizedNonPlaceExpr(span) => {
5014                err.span_note(
5015                    span,
5016                    "unsized values must be place expressions and cannot be put in temporaries",
5017                );
5018            }
5019            ObligationCauseCode::CompareEii { .. } => {
5020                {
    ::core::panicking::panic_fmt(format_args!("trait bounds on EII not yet supported "));
}panic!("trait bounds on EII not yet supported ")
5021            }
5022        }
5023    }
5024
5025    {}
#[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("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(5025u32),
                                    ::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.deeply_resolve_ignoring_regions(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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5062",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(5062u32),
                                    ::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.deeply_resolve_ignoring_regions(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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5069",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(5069u32),
                                    ::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(
5026        level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
5027    )]
5028    pub(super) fn suggest_await_before_try(
5029        &self,
5030        err: &mut Diag<'_>,
5031        obligation: &PredicateObligation<'tcx>,
5032        trait_pred: ty::PolyTraitClause<'tcx>,
5033        span: Span,
5034    ) {
5035        let future_trait = self.tcx.require_lang_item(LangItem::Future, span);
5036
5037        let self_ty = self.deeply_resolve_ignoring_regions(trait_pred.self_ty());
5038        let impls_future = self.type_implements_trait(
5039            future_trait,
5040            [self.tcx.instantiate_bound_regions_with_erased(self_ty)],
5041            obligation.param_env,
5042        );
5043        if !impls_future.must_apply_modulo_regions() {
5044            return;
5045        }
5046
5047        let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
5048        // `<T as Future>::Output`
5049        let projection_ty = trait_pred.map_bound(|trait_pred| {
5050            Ty::new_projection(
5051                self.tcx,
5052                ty::IsRigid::No,
5053                item_def_id,
5054                // Future::Output has no args
5055                [trait_pred.self_ty()],
5056            )
5057        });
5058        let InferOk { value: projection_ty, .. } = self
5059            .at(&obligation.cause, obligation.param_env)
5060            .normalize(Unnormalized::new_wip(projection_ty));
5061
5062        debug!(
5063            normalized_projection_type = ?self.deeply_resolve_ignoring_regions(projection_ty)
5064        );
5065        let try_obligation = self.mk_trait_obligation_with_new_self_ty(
5066            obligation.param_env,
5067            trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
5068        );
5069        debug!(try_trait_obligation = ?try_obligation);
5070        if self.predicate_may_hold(&try_obligation)
5071            && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
5072            && snippet.ends_with('?')
5073        {
5074            match self.tcx.coroutine_kind(obligation.cause.body_def_id) {
5075                Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
5076                    err.span_suggestion_verbose(
5077                        span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
5078                        "consider `await`ing on the `Future`",
5079                        ".await",
5080                        Applicability::MaybeIncorrect,
5081                    );
5082                }
5083                _ => {
5084                    let mut span: MultiSpan = span.with_lo(span.hi() - BytePos(1)).into();
5085                    span.push_span_label(
5086                        self.tcx.def_span(obligation.cause.body_def_id),
5087                        "this is not `async`",
5088                    );
5089                    err.span_note(
5090                        span,
5091                        "this implements `Future` and its output type supports \
5092                        `?`, but the future cannot be awaited in a synchronous function",
5093                    );
5094                }
5095            }
5096        }
5097    }
5098
5099    pub(super) fn suggest_floating_point_literal(
5100        &self,
5101        obligation: &PredicateObligation<'tcx>,
5102        err: &mut Diag<'_>,
5103        trait_pred: ty::PolyTraitClause<'tcx>,
5104    ) {
5105        let rhs_span = match obligation.cause.code() {
5106            ObligationCauseCode::BinOp { rhs_span, rhs_is_lit, .. } if *rhs_is_lit => rhs_span,
5107            _ => return,
5108        };
5109        if let ty::Float(_) = trait_pred.skip_binder().self_ty().kind()
5110            && let ty::Infer(InferTy::IntVar(_)) =
5111                trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
5112        {
5113            err.span_suggestion_verbose(
5114                rhs_span.shrink_to_hi(),
5115                "consider using a floating-point literal by writing it with `.0`",
5116                ".0",
5117                Applicability::MaybeIncorrect,
5118            );
5119        }
5120    }
5121
5122    pub fn can_suggest_derive(
5123        &self,
5124        obligation: &PredicateObligation<'tcx>,
5125        trait_pred: ty::PolyTraitClause<'tcx>,
5126    ) -> bool {
5127        if trait_pred.polarity() == ty::ClausePolarity::Negative {
5128            return false;
5129        }
5130        let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
5131            return false;
5132        };
5133        let (adt, args) = match trait_pred.skip_binder().self_ty().kind() {
5134            ty::Adt(adt, args) if adt.did().is_local() => (adt, args),
5135            _ => return false,
5136        };
5137        if !self.tcx.def_span(adt.did()).can_be_used_for_suggestions() {
5138            return false;
5139        }
5140        let is_derivable_trait = match diagnostic_name {
5141            sym::Copy | sym::Clone => true,
5142            _ if adt.is_union() => false,
5143            sym::PartialEq | sym::PartialOrd => {
5144                let rhs_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
5145                trait_pred.skip_binder().self_ty() == rhs_ty
5146            }
5147            sym::Eq | sym::Ord | sym::Hash | sym::Debug | sym::Default => true,
5148            _ => false,
5149        };
5150        is_derivable_trait &&
5151            // Ensure all fields impl the trait.
5152            adt.all_fields().all(|field| {
5153                let field_ty = ty::GenericArg::from(field.ty(self.tcx, args).skip_norm_wip());
5154                let trait_args = match diagnostic_name {
5155                    sym::PartialEq | sym::PartialOrd => {
5156                        Some(field_ty)
5157                    }
5158                    _ => None,
5159                };
5160                let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitClause {
5161                    trait_ref: ty::TraitRef::new(self.tcx,
5162                        trait_pred.def_id(),
5163                        [field_ty].into_iter().chain(trait_args),
5164                    ),
5165                    ..*tr
5166                });
5167                let field_obl = Obligation::new(
5168                    self.tcx,
5169                    obligation.cause.clone(),
5170                    obligation.param_env,
5171                    trait_pred,
5172                );
5173                self.predicate_must_hold_modulo_regions(&field_obl)
5174            })
5175    }
5176
5177    pub fn suggest_derive(
5178        &self,
5179        obligation: &PredicateObligation<'tcx>,
5180        err: &mut Diag<'_>,
5181        trait_pred: ty::PolyTraitClause<'tcx>,
5182    ) {
5183        let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
5184            return;
5185        };
5186        let adt = match trait_pred.skip_binder().self_ty().kind() {
5187            ty::Adt(adt, _) if adt.did().is_local() => adt,
5188            _ => return,
5189        };
5190        if self.can_suggest_derive(obligation, trait_pred) {
5191            err.span_suggestion_verbose(
5192                self.tcx.def_span(adt.did()).shrink_to_lo(),
5193                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider annotating `{0}` with `#[derive({1})]`",
                trait_pred.skip_binder().self_ty(), diagnostic_name))
    })format!(
5194                    "consider annotating `{}` with `#[derive({})]`",
5195                    trait_pred.skip_binder().self_ty(),
5196                    diagnostic_name,
5197                ),
5198                // FIXME(const_trait_impl) derive_const as suggestion?
5199                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#[derive({0})]\n",
                diagnostic_name))
    })format!("#[derive({diagnostic_name})]\n"),
5200                Applicability::MaybeIncorrect,
5201            );
5202        }
5203    }
5204
5205    pub(super) fn suggest_dereferencing_index(
5206        &self,
5207        obligation: &PredicateObligation<'tcx>,
5208        err: &mut Diag<'_>,
5209        trait_pred: ty::PolyTraitClause<'tcx>,
5210    ) {
5211        if let ObligationCauseCode::ImplDerived(_) = obligation.cause.code()
5212            && self
5213                .tcx
5214                .is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
5215            && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
5216            && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
5217            && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
5218        {
5219            // If the index is written as `&i`, suggest removing the borrow instead of
5220            // dereferencing it, i.e. `v[&i]` -> `v[i]` rather than `v[*&i]`.
5221            let span = obligation.cause.span;
5222            if !span.from_expansion()
5223                && let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id)
5224                && let Some(expr) = {
5225                    let mut finder = FindExprBySpan::new(span, self.tcx);
5226                    finder.visit_expr(&body.value);
5227                    finder.result
5228                }
5229                && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, borrowed) =
5230                    expr.kind
5231                && let Some(amp_span) = borrowed
5232                    .span
5233                    .find_ancestor_inside_same_ctxt(expr.span)
5234                    .map(|borrowed_span| expr.span.until(borrowed_span))
5235                && self
5236                    .tcx
5237                    .sess
5238                    .source_map()
5239                    .span_to_snippet(amp_span)
5240                    .is_ok_and(|snippet| snippet.starts_with('&'))
5241            {
5242                err.span_suggestion_verbose(
5243                    amp_span,
5244                    "remove this reference",
5245                    "",
5246                    Applicability::MachineApplicable,
5247                );
5248                return;
5249            }
5250
5251            err.span_suggestion_verbose(
5252                obligation.cause.span.shrink_to_lo(),
5253                "dereference this index",
5254                '*',
5255                Applicability::MachineApplicable,
5256            );
5257        }
5258    }
5259
5260    fn note_function_argument_obligation(
5261        &self,
5262        body_def_id: LocalDefId,
5263        err: &mut Diag<'_>,
5264        arg_hir_id: HirId,
5265        parent_code: &ObligationCauseCode<'tcx>,
5266        param_env: ty::ParamEnv<'tcx>,
5267        failed_pred: ty::Predicate<'tcx>,
5268        call_hir_id: HirId,
5269    ) {
5270        let tcx = self.tcx;
5271        if let Node::Expr(expr) = tcx.hir_node(arg_hir_id)
5272            && let Some(typeck_results) = &self.typeck_results
5273        {
5274            if let hir::Expr { kind: hir::ExprKind::MethodCall(_, rcvr, _, _), .. } = expr
5275                && let Some(ty) = typeck_results.node_type_opt(rcvr.hir_id)
5276                && let Some(failed_pred) = failed_pred.as_trait_clause()
5277                && let pred = failed_pred.map_bound(|pred| pred.with_replaced_self_ty(tcx, ty))
5278                && self.predicate_must_hold_modulo_regions(&Obligation::misc(
5279                    tcx,
5280                    expr.span,
5281                    body_def_id,
5282                    param_env,
5283                    pred,
5284                ))
5285                && expr.span.hi() != rcvr.span.hi()
5286            {
5287                let should_sugg = match tcx.hir_node(call_hir_id) {
5288                    Node::Expr(hir::Expr {
5289                        kind: hir::ExprKind::MethodCall(_, call_receiver, _, _),
5290                        ..
5291                    }) if let Some((DefKind::AssocFn, did)) =
5292                        typeck_results.type_dependent_def(call_hir_id)
5293                        && call_receiver.hir_id == arg_hir_id =>
5294                    {
5295                        // Avoid suggesting removing a method call if the argument is the receiver of the parent call and
5296                        // removing the receiver would make the method inaccessible. i.e. `x.a().b()`, suggesting removing
5297                        // `.a()` could change the type and make `.b()` unavailable.
5298                        if tcx.inherent_impl_of_assoc(did).is_some() {
5299                            // if we're calling an inherent impl method, just try to make sure that the receiver type stays the same.
5300                            Some(ty) == typeck_results.node_type_opt(arg_hir_id)
5301                        } else {
5302                            // we're calling a trait method, so we just check removing the method call still satisfies the trait.
5303                            let trait_id = tcx
5304                                .trait_of_assoc(did)
5305                                .unwrap_or_else(|| tcx.impl_trait_id(tcx.parent(did)));
5306                            let args = typeck_results.node_args(call_hir_id);
5307                            let tr = ty::TraitRef::from_assoc(tcx, trait_id, args)
5308                                .with_replaced_self_ty(tcx, ty);
5309                            self.type_implements_trait(tr.def_id, tr.args, param_env)
5310                                .must_apply_modulo_regions()
5311                        }
5312                    }
5313                    _ => true,
5314                };
5315
5316                if should_sugg {
5317                    err.span_suggestion_verbose(
5318                        expr.span.with_lo(rcvr.span.hi()),
5319                        ::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!(
5320                            "consider removing this method call, as the receiver has type `{ty}` and \
5321                            `{pred}` trivially holds",
5322                        ),
5323                        "",
5324                        Applicability::MaybeIncorrect,
5325                    );
5326                }
5327            }
5328            if let hir::Expr { kind: hir::ExprKind::Block(block, _), .. } = expr {
5329                let inner_expr = expr.peel_blocks();
5330                let ty = typeck_results
5331                    .expr_ty_adjusted_opt(inner_expr)
5332                    .unwrap_or(Ty::new_misc_error(tcx));
5333                let span = inner_expr.span;
5334                if Some(span) != err.span.primary_span()
5335                    && !span.in_external_macro(tcx.sess.source_map())
5336                {
5337                    err.span_label(
5338                        span,
5339                        if ty.references_error() {
5340                            String::new()
5341                        } else {
5342                            let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5343                            ::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}`")
5344                        },
5345                    );
5346                    if let ty::PredicateKind::Clause(clause) = failed_pred.kind().skip_binder()
5347                        && let ty::ClauseKind::Trait(pred) = clause
5348                        && tcx.fn_trait_kind_from_def_id(pred.def_id()).is_some()
5349                    {
5350                        if let [stmt, ..] = block.stmts
5351                            && let hir::StmtKind::Semi(value) = stmt.kind
5352                            && let hir::ExprKind::Closure(hir::Closure {
5353                                body, fn_decl_span, ..
5354                            }) = value.kind
5355                            && let body = tcx.hir_body(*body)
5356                            && !#[allow(non_exhaustive_omitted_patterns)] match body.value.kind {
    hir::ExprKind::Block(..) => true,
    _ => false,
}matches!(body.value.kind, hir::ExprKind::Block(..))
5357                        {
5358                            // Check if the failed predicate was an expectation of a closure type
5359                            // and if there might have been a `{ |args|` typo instead of `|args| {`.
5360                            err.multipart_suggestion(
5361                                "you might have meant to open the closure body instead of placing \
5362                                 a closure within a block",
5363                                ::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![
5364                                    (expr.span.with_hi(value.span.lo()), String::new()),
5365                                    (fn_decl_span.shrink_to_hi(), " {".to_string()),
5366                                ],
5367                                Applicability::MaybeIncorrect,
5368                            );
5369                        } else {
5370                            // Maybe the bare block was meant to be a closure.
5371                            err.span_suggestion_verbose(
5372                                expr.span.shrink_to_lo(),
5373                                "you might have meant to create the closure instead of a block",
5374                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("|{0}| ",
                (0..pred.trait_ref.args.len() -
                                        1).map(|_| "_").collect::<Vec<_>>().join(", ")))
    })format!(
5375                                    "|{}| ",
5376                                    (0..pred.trait_ref.args.len() - 1)
5377                                        .map(|_| "_")
5378                                        .collect::<Vec<_>>()
5379                                        .join(", ")
5380                                ),
5381                                Applicability::MaybeIncorrect,
5382                            );
5383                        }
5384                    }
5385                }
5386            }
5387
5388            // FIXME: visit the ty to see if there's any closure involved, and if there is,
5389            // check whether its evaluated return type is the same as the one corresponding
5390            // to an associated type (as seen from `trait_pred`) in the predicate. Like in
5391            // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
5392            let mut type_diffs = ::alloc::vec::Vec::new()vec![];
5393            if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = *parent_code
5394                && let Some(node_args) = typeck_results.node_args_opt(call_hir_id)
5395                && let where_clauses = self.tcx.clauses_of(def_id).instantiate(self.tcx, node_args)
5396                && let Some(where_pred) = where_clauses.clauses.get(idx)
5397            {
5398                let where_pred = where_pred.as_ref().skip_norm_wip();
5399                if let Some(where_pred) = where_pred.as_trait_clause()
5400                    && let Some(failed_pred) = failed_pred.as_trait_clause()
5401                    && where_pred.def_id() == failed_pred.def_id()
5402                {
5403                    self.enter_forall(where_pred, |where_pred| {
5404                        let failed_pred = self.instantiate_binder_with_fresh_vars(
5405                            expr.span,
5406                            BoundRegionConversionTime::FnCall,
5407                            failed_pred,
5408                        );
5409
5410                        let zipped =
5411                            iter::zip(where_pred.trait_ref.args, failed_pred.trait_ref.args);
5412                        for (expected, actual) in zipped {
5413                            self.probe(|_| {
5414                                match self
5415                                    .at(&ObligationCause::misc(expr.span, body_def_id), param_env)
5416                                    // Doesn't actually matter if we define opaque types here, this is just used for
5417                                    // diagnostics, and the result is never kept around.
5418                                    .eq(DefineOpaqueTypes::Yes, expected, actual)
5419                                {
5420                                    Ok(_) => (), // We ignore nested obligations here for now.
5421                                    Err(err) => type_diffs.push(err),
5422                                }
5423                            })
5424                        }
5425                    })
5426                } else if let Some(where_pred) = where_pred.as_projection_clause()
5427                    && let Some(failed_pred) = failed_pred.as_projection_clause()
5428                    && let Some(found) =
5429                        failed_pred.map_bound(|pred| pred.term.as_type()).transpose().map(|term| {
5430                            self.instantiate_binder_with_fresh_vars(
5431                                expr.span,
5432                                BoundRegionConversionTime::FnCall,
5433                                term,
5434                            )
5435                        })
5436                {
5437                    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 {
5438                        expected: self
5439                            .instantiate_binder_with_fresh_vars(
5440                                expr.span,
5441                                BoundRegionConversionTime::FnCall,
5442                                where_pred.map_bound(|pred| pred.projection_term),
5443                            )
5444                            .expect_ty()
5445                            .to_ty(self.tcx, ty::IsRigid::No),
5446                        found,
5447                    })];
5448                }
5449            }
5450            if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
5451                && let hir::Path { res: Res::Local(hir_id), .. } = path
5452                && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
5453                && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(binding.hir_id)
5454                && let Some(binding_expr) = local.init
5455            {
5456                // If the expression we're calling on is a binding, we want to point at the
5457                // `let` when talking about the type. Otherwise we'll point at every part
5458                // of the method chain with the type.
5459                self.point_at_chain(binding_expr, typeck_results, type_diffs, param_env, err);
5460            } else {
5461                self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
5462            }
5463        }
5464        let call_node = tcx.hir_node(call_hir_id);
5465        if let Node::Expr(hir::Expr { kind: hir::ExprKind::MethodCall(path, rcvr, ..), .. }) =
5466            call_node
5467        {
5468            if Some(rcvr.span) == err.span.primary_span() {
5469                err.replace_span_with(path.ident.span, true);
5470            }
5471        }
5472
5473        if let Node::Expr(expr) = call_node {
5474            if let hir::ExprKind::Call(hir::Expr { span, .. }, _)
5475            | hir::ExprKind::MethodCall(
5476                hir::PathSegment { ident: Ident { span, .. }, .. },
5477                ..,
5478            ) = expr.kind
5479            {
5480                if Some(*span) != err.span.primary_span() {
5481                    let msg = if span.is_desugaring(DesugaringKind::FormatLiteral { source: true })
5482                    {
5483                        "required by this formatting parameter"
5484                    } else if span.is_desugaring(DesugaringKind::FormatLiteral { source: false }) {
5485                        "required by a formatting parameter in this expression"
5486                    } else {
5487                        "required by a bound introduced by this call"
5488                    };
5489                    err.span_label(*span, msg);
5490                }
5491            }
5492
5493            if let hir::ExprKind::MethodCall(_, expr, ..) = expr.kind {
5494                self.suggest_option_method_if_applicable(failed_pred, param_env, err, expr);
5495            }
5496        }
5497    }
5498
5499    fn suggest_option_method_if_applicable(
5500        &self,
5501        failed_pred: ty::Predicate<'tcx>,
5502        param_env: ty::ParamEnv<'tcx>,
5503        err: &mut Diag<'_>,
5504        expr: &hir::Expr<'_>,
5505    ) {
5506        let tcx = self.tcx;
5507        let infcx = self.infcx;
5508        let Some(typeck_results) = self.typeck_results.as_ref() else { return };
5509
5510        // Make sure we're dealing with the `Option` type.
5511        let Some(option_ty_adt) = typeck_results.expr_ty_adjusted(expr).ty_adt_def() else {
5512            return;
5513        };
5514        if !tcx.is_diagnostic_item(sym::Option, option_ty_adt.did()) {
5515            return;
5516        }
5517
5518        // Given the predicate `fn(&T): FnOnce<(U,)>`, extract `fn(&T)` and `(U,)`,
5519        // then suggest `Option::as_deref(_mut)` if `U` can deref to `T`
5520        if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitClause { trait_ref, .. }))
5521            = failed_pred.kind().skip_binder()
5522            && tcx.is_fn_trait(trait_ref.def_id)
5523            && let [self_ty, found_ty] = trait_ref.args.as_slice()
5524            && let Some(fn_ty) = self_ty.as_type().filter(|ty| ty.is_fn())
5525            && let fn_sig @ ty::FnSig {
5526                ..
5527            } = fn_ty.fn_sig(tcx).skip_binder()
5528            // FIXME(splat): this might need to change if the Fn* traits start using/supporting splat
5529            && fn_sig.abi() == ExternAbi::Rust
5530            && !fn_sig.c_variadic()
5531            && fn_sig.safety() == hir::Safety::Safe
5532
5533            // Extract first param of fn sig with peeled refs, e.g. `fn(&T)` -> `T`
5534            && let Some(&ty::Ref(_, target_ty, needs_mut)) = fn_sig.inputs().first().map(|t| t.kind())
5535            && !target_ty.has_escaping_bound_vars()
5536
5537            // Extract first tuple element out of fn trait, e.g. `FnOnce<(U,)>` -> `U`
5538            && let Some(ty::Tuple(tys)) = found_ty.as_type().map(Ty::kind)
5539            && let &[found_ty] = tys.as_slice()
5540            && !found_ty.has_escaping_bound_vars()
5541
5542            // Extract `<U as Deref>::Target` assoc type and check that it is `T`
5543            && let Some(deref_target_did) = tcx.lang_items().deref_target()
5544            && let projection = Ty::new_projection_from_args(tcx,ty::IsRigid::No, deref_target_did, tcx.mk_args(&[ty::GenericArg::from(found_ty)]))
5545            && let InferOk { value: deref_target, obligations } = infcx.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(projection))
5546            && obligations.iter().all(|obligation| infcx.predicate_must_hold_modulo_regions(obligation))
5547            && infcx.can_eq(param_env, deref_target, target_ty)
5548        {
5549            let help = if let hir::Mutability::Mut = needs_mut
5550                && let Some(deref_mut_did) = tcx.lang_items().deref_mut_trait()
5551                && infcx
5552                    .type_implements_trait(deref_mut_did, iter::once(found_ty), param_env)
5553                    .must_apply_modulo_regions()
5554            {
5555                Some(("call `Option::as_deref_mut()` first", ".as_deref_mut()"))
5556            } else if let hir::Mutability::Not = needs_mut {
5557                Some(("call `Option::as_deref()` first", ".as_deref()"))
5558            } else {
5559                None
5560            };
5561
5562            if let Some((msg, sugg)) = help {
5563                err.span_suggestion_with_style(
5564                    expr.span.shrink_to_hi(),
5565                    msg,
5566                    sugg,
5567                    Applicability::MaybeIncorrect,
5568                    SuggestionStyle::ShowAlways,
5569                );
5570            }
5571        }
5572    }
5573
5574    fn look_for_iterator_item_mistakes(
5575        &self,
5576        assocs_in_this_method: &[Option<(Span, (DefId, Ty<'tcx>))>],
5577        typeck_results: &TypeckResults<'tcx>,
5578        type_diffs: &[TypeError<'tcx>],
5579        param_env: ty::ParamEnv<'tcx>,
5580        path_segment: &hir::PathSegment<'_>,
5581        args: &[hir::Expr<'_>],
5582        prev_ty: Ty<'_>,
5583        err: &mut Diag<'_>,
5584    ) {
5585        let tcx = self.tcx;
5586        // Special case for iterator chains, we look at potential failures of `Iterator::Item`
5587        // not being `: Clone` and `Iterator::map` calls with spurious trailing `;`.
5588        for entry in assocs_in_this_method {
5589            let Some((_span, (def_id, ty))) = entry else {
5590                continue;
5591            };
5592            for diff in type_diffs {
5593                let TypeError::Sorts(expected_found) = diff else {
5594                    continue;
5595                };
5596                if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
5597                    && path_segment.ident.name == sym::iter
5598                    && self.can_eq(
5599                        param_env,
5600                        Ty::new_ref(
5601                            tcx,
5602                            tcx.lifetimes.re_erased,
5603                            expected_found.found,
5604                            ty::Mutability::Not,
5605                        ),
5606                        *ty,
5607                    )
5608                    && let [] = args
5609                {
5610                    // Used `.iter()` when `.into_iter()` was likely meant.
5611                    err.span_suggestion_verbose(
5612                        path_segment.ident.span,
5613                        ::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`"),
5614                        "into_iter".to_string(),
5615                        Applicability::MachineApplicable,
5616                    );
5617                }
5618                if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
5619                    && path_segment.ident.name == sym::into_iter
5620                    && self.can_eq(
5621                        param_env,
5622                        expected_found.found,
5623                        Ty::new_ref(tcx, tcx.lifetimes.re_erased, *ty, ty::Mutability::Not),
5624                    )
5625                    && let [] = args
5626                {
5627                    // Used `.into_iter()` when `.iter()` was likely meant.
5628                    err.span_suggestion_verbose(
5629                        path_segment.ident.span,
5630                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider not consuming the `{0}` to construct the `Iterator`",
                prev_ty))
    })format!(
5631                            "consider not consuming the `{prev_ty}` to construct the `Iterator`"
5632                        ),
5633                        "iter".to_string(),
5634                        Applicability::MachineApplicable,
5635                    );
5636                }
5637                if tcx.is_diagnostic_item(sym::IteratorItem, *def_id)
5638                    && path_segment.ident.name == sym::map
5639                    && self.can_eq(param_env, expected_found.found, *ty)
5640                    && let [arg] = args
5641                    && let hir::ExprKind::Closure(closure) = arg.kind
5642                {
5643                    let body = tcx.hir_body(closure.body);
5644                    if let hir::ExprKind::Block(block, None) = body.value.kind
5645                        && let None = block.expr
5646                        && let [.., stmt] = block.stmts
5647                        && let hir::StmtKind::Semi(expr) = stmt.kind
5648                        // FIXME: actually check the expected vs found types, but right now
5649                        // the expected is a projection that we need to resolve.
5650                        // && let Some(tail_ty) = typeck_results.expr_ty_opt(expr)
5651                        && expected_found.found.is_unit()
5652                        // FIXME: this happens with macro calls. Need to figure out why the stmt
5653                        // `println!();` doesn't include the `;` in its `Span`. (#133845)
5654                        // We filter these out to avoid ICEs with debug assertions on caused by
5655                        // empty suggestions.
5656                        && expr.span.hi() != stmt.span.hi()
5657                    {
5658                        err.span_suggestion_verbose(
5659                            expr.span.shrink_to_hi().with_hi(stmt.span.hi()),
5660                            "consider removing this semicolon",
5661                            String::new(),
5662                            Applicability::MachineApplicable,
5663                        );
5664                    }
5665                    let expr = if let hir::ExprKind::Block(block, None) = body.value.kind
5666                        && let Some(expr) = block.expr
5667                    {
5668                        expr
5669                    } else {
5670                        &body.value
5671                    };
5672                    if let hir::ExprKind::MethodCall(path_segment, rcvr, [], span) = expr.kind
5673                        && path_segment.ident.name == sym::clone
5674                        && let Some(expr_ty) = typeck_results.expr_ty_opt(expr)
5675                        && let Some(rcvr_ty) = typeck_results.expr_ty_opt(rcvr)
5676                        && self.can_eq(param_env, expr_ty, rcvr_ty)
5677                        && let ty::Ref(_, ty, _) = expr_ty.kind()
5678                    {
5679                        err.span_label(
5680                            span,
5681                            ::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!(
5682                                "this method call is cloning the reference `{expr_ty}`, not \
5683                                 `{ty}` which doesn't implement `Clone`",
5684                            ),
5685                        );
5686                        let ty::Param(..) = ty.kind() else {
5687                            continue;
5688                        };
5689                        let node =
5690                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(expr.hir_id).def_id);
5691
5692                        let pred = ty::Binder::dummy(ty::TraitClause {
5693                            trait_ref: ty::TraitRef::new(
5694                                tcx,
5695                                tcx.require_lang_item(LangItem::Clone, span),
5696                                [*ty],
5697                            ),
5698                            polarity: ty::ClausePolarity::Positive,
5699                        });
5700                        let Some(generics) = node.generics() else {
5701                            continue;
5702                        };
5703                        let Some(body_id) = node.body_id() else {
5704                            continue;
5705                        };
5706                        suggest_restriction(
5707                            tcx,
5708                            tcx.hir_body_owner_def_id(body_id),
5709                            generics,
5710                            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type parameter `{0}`", ty))
    })format!("type parameter `{ty}`"),
5711                            err,
5712                            node.fn_sig(),
5713                            None,
5714                            pred,
5715                            None,
5716                        );
5717                    }
5718                }
5719            }
5720        }
5721    }
5722
5723    fn point_at_chain(
5724        &self,
5725        expr: &hir::Expr<'_>,
5726        typeck_results: &TypeckResults<'tcx>,
5727        type_diffs: Vec<TypeError<'tcx>>,
5728        param_env: ty::ParamEnv<'tcx>,
5729        err: &mut Diag<'_>,
5730    ) {
5731        let mut primary_spans = ::alloc::vec::Vec::new()vec![];
5732        let mut span_labels = ::alloc::vec::Vec::new()vec![];
5733
5734        let tcx = self.tcx;
5735
5736        let mut print_root_expr = true;
5737        let mut assocs = ::alloc::vec::Vec::new()vec![];
5738        let mut expr = expr;
5739        let mut prev_ty = self.deeply_resolve_ignoring_regions(
5740            typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5741        );
5742        while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
5743            // Point at every method call in the chain with the resulting type.
5744            // vec![1, 2, 3].iter().map(mapper).sum<i32>()
5745            //               ^^^^^^ ^^^^^^^^^^^
5746            expr = rcvr_expr;
5747            let assocs_in_this_method =
5748                self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
5749            prev_ty = self.deeply_resolve_ignoring_regions(
5750                typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5751            );
5752            self.look_for_iterator_item_mistakes(
5753                &assocs_in_this_method,
5754                typeck_results,
5755                &type_diffs,
5756                param_env,
5757                path_segment,
5758                args,
5759                prev_ty,
5760                err,
5761            );
5762            assocs.push(assocs_in_this_method);
5763
5764            if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
5765                && let hir::Path { res: Res::Local(hir_id), .. } = path
5766                && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
5767            {
5768                let parent = self.tcx.parent_hir_node(binding.hir_id);
5769                // We've reached the root of the method call chain...
5770                if let hir::Node::LetStmt(local) = parent
5771                    && let Some(binding_expr) = local.init
5772                {
5773                    // ...and it is a binding. Get the binding creation and continue the chain.
5774                    expr = binding_expr;
5775                }
5776                if let hir::Node::Param(param) = parent {
5777                    // ...and it is an fn argument.
5778                    let prev_ty = self.deeply_resolve_ignoring_regions(
5779                        typeck_results
5780                            .node_type_opt(param.hir_id)
5781                            .unwrap_or(Ty::new_misc_error(tcx)),
5782                    );
5783                    let assocs_in_this_method = self.probe_assoc_types_at_expr(
5784                        &type_diffs,
5785                        param.ty_span,
5786                        prev_ty,
5787                        param.hir_id,
5788                        param_env,
5789                    );
5790                    if assocs_in_this_method.iter().any(|a| a.is_some()) {
5791                        assocs.push(assocs_in_this_method);
5792                        print_root_expr = false;
5793                    }
5794                    break;
5795                }
5796            }
5797        }
5798        // We want the type before deref coercions, otherwise we talk about `&[_]`
5799        // instead of `Vec<_>`.
5800        if let Some(ty) = typeck_results.expr_ty_opt(expr)
5801            && print_root_expr
5802        {
5803            let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5804            // Point at the root expression
5805            // vec![1, 2, 3].iter().map(mapper).sum<i32>()
5806            // ^^^^^^^^^^^^^
5807            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}`")));
5808        };
5809        // Only show this if it is not a "trivial" expression (not a method
5810        // chain) and there are associated types to talk about.
5811        let mut assocs = assocs.into_iter().peekable();
5812        while let Some(assocs_in_method) = assocs.next() {
5813            let Some(prev_assoc_in_method) = assocs.peek() else {
5814                for entry in assocs_in_method {
5815                    let Some((span, (assoc, ty))) = entry else {
5816                        continue;
5817                    };
5818                    if primary_spans.is_empty()
5819                        || type_diffs.iter().any(|diff| {
5820                            let TypeError::Sorts(expected_found) = diff else {
5821                                return false;
5822                            };
5823                            self.can_eq(param_env, expected_found.found, ty)
5824                        })
5825                    {
5826                        // FIXME: this doesn't quite work for `Iterator::collect`
5827                        // because we have `Vec<i32>` and `()`, but we'd want `i32`
5828                        // to point at the `.into_iter()` call, but as long as we
5829                        // still point at the other method calls that might have
5830                        // introduced the issue, this is fine for now.
5831                        primary_spans.push(span);
5832                    }
5833                    span_labels.push((
5834                        span,
5835                        {
    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!(
5836                            "`{}` is `{ty}` here",
5837                            self.tcx.def_path_str(assoc),
5838                        )),
5839                    ));
5840                }
5841                break;
5842            };
5843            for (entry, prev_entry) in
5844                assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
5845            {
5846                match (entry, prev_entry) {
5847                    (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
5848                        let ty_str = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5849
5850                        let assoc = { let _guard = ForceTrimmedGuard::new(); self.tcx.def_path_str(assoc) }with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
5851                        if !self.can_eq(param_env, ty, *prev_ty) {
5852                            if type_diffs.iter().any(|diff| {
5853                                let TypeError::Sorts(expected_found) = diff else {
5854                                    return false;
5855                                };
5856                                self.can_eq(param_env, expected_found.found, ty)
5857                            }) {
5858                                primary_spans.push(span);
5859                            }
5860                            span_labels
5861                                .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")));
5862                        } else {
5863                            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")));
5864                        }
5865                    }
5866                    (Some((span, (assoc, ty))), None) => {
5867                        span_labels.push((
5868                            span,
5869                            {
    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!(
5870                                "`{}` is `{}` here",
5871                                self.tcx.def_path_str(assoc),
5872                                self.ty_to_string(ty),
5873                            )),
5874                        ));
5875                    }
5876                    (None, Some(_)) | (None, None) => {}
5877                }
5878            }
5879        }
5880        if !primary_spans.is_empty() {
5881            let mut multi_span: MultiSpan = primary_spans.into();
5882            for (span, label) in span_labels {
5883                multi_span.push_span_label(span, label);
5884            }
5885            err.span_note(
5886                multi_span,
5887                "the method call chain might not have had the expected associated types",
5888            );
5889        }
5890    }
5891
5892    fn probe_assoc_types_at_expr(
5893        &self,
5894        type_diffs: &[TypeError<'tcx>],
5895        span: Span,
5896        prev_ty: Ty<'tcx>,
5897        body_id: HirId,
5898        param_env: ty::ParamEnv<'tcx>,
5899    ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
5900        let ocx = ObligationCtxt::new(self.infcx);
5901        let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
5902        for diff in type_diffs {
5903            let TypeError::Sorts(expected_found) = diff else {
5904                continue;
5905            };
5906            let &ty::Alias(_, ty::AliasTy { kind: kind @ ty::Projection { def_id }, .. }) =
5907                expected_found.expected.kind()
5908            else {
5909                continue;
5910            };
5911
5912            // Make `Self` be equivalent to the type of the call chain
5913            // expression we're looking at now, so that we can tell what
5914            // for example `Iterator::Item` is at this point in the chain.
5915            let args = GenericArgs::for_item(self.tcx, def_id, |param, _| {
5916                if param.index == 0 {
5917                    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 { .. });
5918                    return prev_ty.into();
5919                }
5920                self.var_for_def(span, param)
5921            });
5922            // This will hold the resolved type of the associated type, if the
5923            // current expression implements the trait that associated type is
5924            // in. For example, this would be what `Iterator::Item` is here.
5925            let ty = self.infcx.next_ty_var(span);
5926            // This corresponds to `<ExprTy as Iterator>::Item = _`.
5927            let projection = ty::Binder::dummy(ty::PredicateKind::Clause(
5928                ty::ClauseKind::Projection(ty::ProjectionClause {
5929                    projection_term: ty::AliasTerm::new_from_args(self.tcx, kind.into(), args),
5930                    term: ty.into(),
5931                }),
5932            ));
5933            let body_def_id = self.tcx.hir_enclosing_body_owner(body_id);
5934            // Add `<ExprTy as Iterator>::Item = _` obligation.
5935            ocx.register_obligation(Obligation::misc(
5936                self.tcx,
5937                span,
5938                body_def_id,
5939                param_env,
5940                projection,
5941            ));
5942            if ocx.try_evaluate_obligations().no_errors()
5943                && let ty = self.deeply_resolve_ignoring_regions(ty)
5944                && !ty.is_ty_var()
5945            {
5946                assocs_in_this_method.push(Some((span, (def_id, ty))));
5947            } else {
5948                // `<ExprTy as Iterator>` didn't select, so likely we've
5949                // reached the end of the iterator chain, like the originating
5950                // `Vec<_>` or the `ty` couldn't be determined.
5951                // Keep the space consistent for later zipping.
5952                assocs_in_this_method.push(None);
5953            }
5954        }
5955        assocs_in_this_method
5956    }
5957
5958    /// When a `-> impl Trait<Assoc = Ty>` return type obligation fails, walk the method call
5959    /// chain in the returned expression to point at where the associated type diverged from
5960    /// what the signature expects.
5961    ///
5962    /// ```text
5963    /// note: the method call chain might not have had the expected associated types
5964    ///   --> $DIR/invalid-iterator-chain-in-return-position.rs:16:18
5965    ///    |
5966    /// LL |     x.iter_mut().map(foo)
5967    ///    |     - ---------- ^^^^^^^^ `Iterator::Item` changed to `()` here
5968    ///    |     | |
5969    ///    |     | `Iterator::Item` is `&mut Vec<u8>` here
5970    ///    |     this expression has type `Vec<Vec<u8>>`
5971    /// ```
5972    fn point_at_chain_in_return_position(
5973        &self,
5974        body_def_id: LocalDefId,
5975        expr: &hir::Expr<'_>,
5976        typeck_results: &TypeckResults<'tcx>,
5977        param_env: ty::ParamEnv<'tcx>,
5978        err: &mut Diag<'_>,
5979    ) {
5980        let tcx = self.tcx;
5981        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) {
5982            return;
5983        }
5984
5985        let binder = tcx.fn_sig(body_def_id).instantiate_identity().skip_norm_wip().output();
5986        self.enter_forall(binder, |output| {
5987            let &ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id: opaque_def_id }, args, .. }) =
5988                output.kind()
5989            else {
5990                return;
5991            };
5992
5993            // The predicate that reaches here has been rewritten through the impls it was
5994            // derived from (e.g. `Iterator for Map<I, F>` turns `Iterator::Item` requirements
5995            // into requirements on `F`'s return type), so the associated types the user wrote
5996            // in the signature are recovered from the opaque's bounds instead.
5997            let mut probe_diffs = ::alloc::vec::Vec::new()vec![];
5998            for clause in tcx.item_bounds(opaque_def_id).instantiate(tcx, args).skip_norm_wip() {
5999                let Some(proj) = clause.as_projection_clause() else { continue };
6000                let proj = self.instantiate_binder_with_fresh_vars(
6001                    expr.span,
6002                    BoundRegionConversionTime::FnCall,
6003                    proj,
6004                );
6005                let Some(expected_term) = proj.term.as_type() else { continue };
6006                // Only the projection (for its `DefId`) is used when probing the chain; the
6007                // bound's own term is carried in `found` for the divergence check below and
6008                // is replaced with the probed type afterwards.
6009                probe_diffs.push(TypeError::Sorts(ty::error::ExpectedFound {
6010                    expected: proj.projection_term.expect_ty().to_ty(tcx, ty::IsRigid::No),
6011                    found: expected_term,
6012                }));
6013            }
6014            if probe_diffs.is_empty() {
6015                return;
6016            }
6017
6018            // If the returned expression is a binding, walk the chain that created it instead.
6019            let expr = if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
6020                && let hir::Path { res: Res::Local(hir_id), .. } = path
6021                && let hir::Node::Pat(binding) = tcx.hir_node(*hir_id)
6022                && let hir::Node::LetStmt(local) = tcx.parent_hir_node(binding.hir_id)
6023                && let Some(binding_expr) = local.init
6024            {
6025                binding_expr
6026            } else {
6027                expr
6028            };
6029
6030            // Resolve what each bound associated type actually is for the returned expression,
6031            // and keep only the ones that diverged from the signature.
6032            let expr_ty = self.deeply_resolve_ignoring_regions(
6033                typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
6034            );
6035            let assocs = self.probe_assoc_types_at_expr(
6036                &probe_diffs,
6037                expr.span,
6038                expr_ty,
6039                expr.hir_id,
6040                param_env,
6041            );
6042            let mut type_diffs = ::alloc::vec::Vec::new()vec![];
6043            for (probe_diff, assoc) in iter::zip(probe_diffs, assocs) {
6044                let TypeError::Sorts(ty::error::ExpectedFound { expected, found: expected_term }) =
6045                    probe_diff
6046                else {
6047                    continue;
6048                };
6049                let Some((_, (_, actual_ty))) = assoc else { continue };
6050                if !self.can_eq(param_env, expected_term, actual_ty) {
6051                    type_diffs.push(TypeError::Sorts(ty::error::ExpectedFound {
6052                        expected,
6053                        found: actual_ty,
6054                    }));
6055                }
6056            }
6057            if !type_diffs.is_empty() {
6058                self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
6059            }
6060        });
6061    }
6062
6063    /// If the type that failed selection is an array or a reference to an array,
6064    /// but the trait is implemented for slices, suggest that the user converts
6065    /// the array into a slice.
6066    pub(super) fn suggest_convert_to_slice(
6067        &self,
6068        err: &mut Diag<'_>,
6069        obligation: &PredicateObligation<'tcx>,
6070        trait_pred: ty::PolyTraitClause<'tcx>,
6071        candidate_impls: &[ImplCandidate<'tcx>],
6072        span: Span,
6073    ) {
6074        if span.in_external_macro(self.tcx.sess.source_map()) {
6075            return;
6076        }
6077        // We can only suggest the slice coercion for function and binary operation arguments,
6078        // since the suggestion would make no sense in turbofish or call
6079        let (ObligationCauseCode::BinOp { .. } | ObligationCauseCode::FunctionArg { .. }) =
6080            obligation.cause.code()
6081        else {
6082            return;
6083        };
6084
6085        // Three cases where we can make a suggestion:
6086        // 1. `[T; _]` (array of T)
6087        // 2. `&[T; _]` (reference to array of T)
6088        // 3. `&mut [T; _]` (mutable reference to array of T)
6089        let (element_ty, mut mutability) = match *trait_pred.skip_binder().self_ty().kind() {
6090            ty::Array(element_ty, _) => (element_ty, None),
6091
6092            ty::Ref(_, pointee_ty, mutability) => match *pointee_ty.kind() {
6093                ty::Array(element_ty, _) => (element_ty, Some(mutability)),
6094                _ => return,
6095            },
6096
6097            _ => return,
6098        };
6099
6100        // Go through all the candidate impls to see if any of them is for
6101        // slices of `element_ty` with `mutability`.
6102        let mut is_slice = |candidate: Ty<'tcx>| match *candidate.kind() {
6103            ty::RawPtr(t, m) | ty::Ref(_, t, m) => {
6104                if let ty::Slice(e) = *t.kind()
6105                    && e == element_ty
6106                    && m == mutability.unwrap_or(m)
6107                {
6108                    // Use the candidate's mutability going forward.
6109                    mutability = Some(m);
6110                    true
6111                } else {
6112                    false
6113                }
6114            }
6115            _ => false,
6116        };
6117
6118        // Grab the first candidate that matches, if any, and make a suggestion.
6119        if let Some(slice_ty) = candidate_impls
6120            .iter()
6121            .map(|trait_ref| trait_ref.trait_ref.self_ty())
6122            .find(|t| is_slice(*t))
6123        {
6124            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");
6125
6126            if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
6127                let mut suggestions = ::alloc::vec::Vec::new()vec![];
6128                if snippet.starts_with('&') {
6129                } else if let Some(hir::Mutability::Mut) = mutability {
6130                    suggestions.push((span.shrink_to_lo(), "&mut ".into()));
6131                } else {
6132                    suggestions.push((span.shrink_to_lo(), "&".into()));
6133                }
6134                suggestions.push((span.shrink_to_hi(), "[..]".into()));
6135                err.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
6136            } else {
6137                err.span_help(span, msg);
6138            }
6139        }
6140    }
6141
6142    /// If the type failed selection but the trait is implemented for `(T,)`, suggest that the user
6143    /// creates a unary tuple
6144    ///
6145    /// This is a common gotcha when using libraries that emulate variadic functions with traits for tuples.
6146    pub(super) fn suggest_tuple_wrapping(
6147        &self,
6148        err: &mut Diag<'_>,
6149        root_obligation: &PredicateObligation<'tcx>,
6150        obligation: &PredicateObligation<'tcx>,
6151    ) {
6152        let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code() else {
6153            return;
6154        };
6155
6156        let Some(root_pred) = root_obligation.predicate.as_trait_clause() else { return };
6157
6158        let trait_ref = root_pred.map_bound(|root_pred| {
6159            root_pred.trait_ref.with_replaced_self_ty(
6160                self.tcx,
6161                Ty::new_tup(self.tcx, &[root_pred.trait_ref.self_ty()]),
6162            )
6163        });
6164
6165        let obligation =
6166            Obligation::new(self.tcx, obligation.cause.clone(), obligation.param_env, trait_ref);
6167
6168        if self.predicate_must_hold_modulo_regions(&obligation) {
6169            let arg_span = self.tcx.hir_span(*arg_hir_id);
6170            err.multipart_suggestion(
6171                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use a unary tuple instead"))
    })format!("use a unary tuple instead"),
6172                ::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())],
6173                Applicability::MaybeIncorrect,
6174            );
6175        }
6176    }
6177
6178    pub(super) fn suggest_shadowed_inherent_method(
6179        &self,
6180        err: &mut Diag<'_>,
6181        obligation: &PredicateObligation<'tcx>,
6182        trait_predicate: ty::PolyTraitClause<'tcx>,
6183    ) {
6184        let ObligationCauseCode::FunctionArg { call_hir_id, .. } = obligation.cause.code() else {
6185            return;
6186        };
6187        let Node::Expr(call) = self.tcx.hir_node(*call_hir_id) else { return };
6188        let hir::ExprKind::MethodCall(segment, rcvr, args, ..) = call.kind else { return };
6189        let Some(typeck) = &self.typeck_results else { return };
6190        let Some(rcvr_ty) = typeck.expr_ty_adjusted_opt(rcvr) else { return };
6191        let rcvr_ty = self.deeply_resolve_ignoring_regions(rcvr_ty);
6192        let autoderef = (self.autoderef_steps)(rcvr_ty);
6193        for (ty, def_id) in autoderef.iter().filter_map(|(ty, obligations)| {
6194            if let ty::Adt(def, _) = ty.kind()
6195                && *ty != rcvr_ty.peel_refs()
6196                && obligations.iter().all(|obligation| self.predicate_may_hold(obligation))
6197            {
6198                Some((ty, def.did()))
6199            } else {
6200                None
6201            }
6202        }) {
6203            for impl_def_id in self.tcx.inherent_impls(def_id) {
6204                if *impl_def_id == trait_predicate.def_id() {
6205                    continue;
6206                }
6207                for m in self
6208                    .tcx
6209                    .provided_trait_methods(*impl_def_id)
6210                    .filter(|m| m.name() == segment.ident.name)
6211                {
6212                    let fn_sig = self.tcx.fn_sig(m.def_id);
6213                    if fn_sig.skip_binder().inputs().skip_binder().len() != args.len() + 1 {
6214                        continue;
6215                    }
6216                    let rcvr_ty = fn_sig.skip_binder().input(0).skip_binder();
6217                    let (mutability, _ty) = match rcvr_ty.kind() {
6218                        ty::Ref(_, ty, hir::Mutability::Mut) => ("&mut ", ty),
6219                        ty::Ref(_, ty, _) => ("&", ty),
6220                        _ => ("", &rcvr_ty),
6221                    };
6222                    let path = self.tcx.def_path_str(def_id);
6223                    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!(
6224                        "there's an inherent method on `{ty}` of the same name, which can be \
6225                         auto-dereferenced from `{rcvr_ty}`"
6226                    ));
6227                    err.multipart_suggestion(
6228                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("to access the inherent method on `{0}`, use the fully-qualified path",
                ty))
    })format!(
6229                            "to access the inherent method on `{ty}`, use the fully-qualified path",
6230                        ),
6231                        ::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![
6232                            (
6233                                call.span.until(rcvr.span),
6234                                format!("{path}::{}({}", m.name(), mutability),
6235                            ),
6236                            match &args {
6237                                [] => (
6238                                    rcvr.span.shrink_to_hi().with_hi(call.span.hi()),
6239                                    ")".to_string(),
6240                                ),
6241                                [first, ..] => (rcvr.span.between(first.span), ", ".to_string()),
6242                            },
6243                        ],
6244                        Applicability::MaybeIncorrect,
6245                    );
6246                }
6247            }
6248        }
6249    }
6250
6251    pub(super) fn explain_hrtb_projection(
6252        &self,
6253        diag: &mut Diag<'_>,
6254        pred: ty::PolyTraitClause<'tcx>,
6255        param_env: ty::ParamEnv<'tcx>,
6256        cause: &ObligationCause<'tcx>,
6257    ) {
6258        if pred.skip_binder().has_escaping_bound_vars() && pred.skip_binder().has_non_region_infer()
6259        {
6260            self.probe(|_| {
6261                let ocx = ObligationCtxt::new(self);
6262                ocx.register_obligation(Obligation::new(
6263                    self.tcx,
6264                    ObligationCause::dummy(),
6265                    param_env,
6266                    pred,
6267                ));
6268                if !ocx.try_evaluate_obligations().no_errors() {
6269                    // encountered errors.
6270                    return;
6271                }
6272
6273                if let ObligationCauseCode::FunctionArg {
6274                    call_hir_id,
6275                    arg_hir_id,
6276                    parent_code: _,
6277                } = cause.code()
6278                {
6279                    let arg_span = self.tcx.hir_span(*arg_hir_id);
6280                    let mut sp: MultiSpan = arg_span.into();
6281
6282                    sp.push_span_label(
6283                        arg_span,
6284                        "the trait solver is unable to infer the \
6285                        generic types that should be inferred from this argument",
6286                    );
6287                    sp.push_span_label(
6288                        self.tcx.hir_span(*call_hir_id),
6289                        "add turbofish arguments to this call to \
6290                        specify the types manually, even if it's redundant",
6291                    );
6292                    diag.span_note(
6293                        sp,
6294                        "this is a known limitation of the trait solver that \
6295                        will be lifted in the future",
6296                    );
6297                } else {
6298                    let mut sp: MultiSpan = cause.span.into();
6299                    sp.push_span_label(
6300                        cause.span,
6301                        "try adding turbofish arguments to this expression to \
6302                        specify the types manually, even if it's redundant",
6303                    );
6304                    diag.span_note(
6305                        sp,
6306                        "this is a known limitation of the trait solver that \
6307                        will be lifted in the future",
6308                    );
6309                }
6310            });
6311        }
6312    }
6313
6314    pub(super) fn suggest_desugaring_async_fn_in_trait(
6315        &self,
6316        err: &mut Diag<'_>,
6317        trait_pred: ty::PolyTraitClause<'tcx>,
6318    ) {
6319        // Don't suggest if RTN is active -- we should prefer a where-clause bound instead.
6320        if self.tcx.features().return_type_notation() {
6321            return;
6322        }
6323
6324        let trait_def_id = trait_pred.def_id();
6325
6326        // Only suggest specifying auto traits
6327        if !self.tcx.trait_is_auto(trait_def_id) {
6328            return;
6329        }
6330
6331        // Look for an RPITIT
6332        let ty::Alias(_, alias_ty @ ty::AliasTy { kind: ty::Projection { def_id }, .. }) =
6333            trait_pred.self_ty().skip_binder().kind()
6334        else {
6335            return;
6336        };
6337        let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, opaque_def_id }) =
6338            self.tcx.opt_rpitit_info(*def_id)
6339        else {
6340            return;
6341        };
6342
6343        let auto_trait = self.tcx.def_path_str(trait_def_id);
6344        // ... which is a local function
6345        let Some(fn_def_id) = fn_def_id.as_local() else {
6346            // If it's not local, we can at least mention that the method is async, if it is.
6347            if self.tcx.asyncness(fn_def_id).is_async() {
6348                let mut span: MultiSpan = self.tcx.def_span(fn_def_id).into();
6349                span.push_span_context(self.tcx.def_span(self.tcx.parent(fn_def_id)));
6350                err.span_note(
6351                    span,
6352                    ::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!(
6353                        "`{}::{}` is an `async fn` in trait, which does not \
6354                    automatically imply that its future is `{auto_trait}`",
6355                        alias_ty.trait_ref(self.tcx),
6356                        self.tcx.item_name(fn_def_id)
6357                    ),
6358                );
6359            }
6360            return;
6361        };
6362        let hir::Node::TraitItem(item) = self.tcx.hir_node_by_def_id(fn_def_id) else {
6363            return;
6364        };
6365
6366        // ... whose signature is `async` (i.e. this is an AFIT)
6367        let (sig, body) = item.expect_fn();
6368        let hir::FnRetTy::Return(hir::Ty { kind: hir::TyKind::OpaqueDef(opaq_def, ..), .. }) =
6369            sig.decl.output
6370        else {
6371            // This should never happen, but let's not ICE.
6372            return;
6373        };
6374
6375        // Check that this is *not* a nested `impl Future` RPIT in an async fn
6376        // (i.e. `async fn foo() -> impl Future`)
6377        if opaq_def.def_id.to_def_id() != opaque_def_id {
6378            return;
6379        }
6380
6381        let Some(sugg) = suggest_desugaring_async_fn_to_impl_future_in_trait(
6382            self.tcx,
6383            *sig,
6384            *body,
6385            opaque_def_id.expect_local(),
6386            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" + {0}", auto_trait))
    })format!(" + {auto_trait}"),
6387        ) else {
6388            return;
6389        };
6390
6391        let function_name = self.tcx.def_path_str(fn_def_id);
6392        err.multipart_suggestion(
6393            ::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!(
6394                "`{auto_trait}` can be made part of the associated future's \
6395                guarantees for all implementations of `{function_name}`"
6396            ),
6397            sugg,
6398            Applicability::MachineApplicable,
6399        );
6400    }
6401
6402    pub fn ty_kind_suggestion(
6403        &self,
6404        param_env: ty::ParamEnv<'tcx>,
6405        ty: Ty<'tcx>,
6406    ) -> Option<String> {
6407        let tcx = self.infcx.tcx;
6408        let implements_default = |ty| {
6409            let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
6410                return false;
6411            };
6412            self.type_implements_trait(default_trait, [ty], param_env).must_apply_modulo_regions()
6413        };
6414
6415        Some(match *ty.kind() {
6416            ty::Never | ty::Error(_) => return None,
6417            ty::Bool => "false".to_string(),
6418            ty::Char => "\'x\'".to_string(),
6419            ty::Int(_) | ty::Uint(_) => "42".into(),
6420            ty::Float(_) => "3.14159".into(),
6421            ty::Slice(_) => "[]".to_string(),
6422            ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => {
6423                "vec![]".to_string()
6424            }
6425            ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::String) => {
6426                "String::new()".to_string()
6427            }
6428            ty::Adt(def, args) if def.is_box() => {
6429                ::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())?)
6430            }
6431            ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Option) => {
6432                "None".to_string()
6433            }
6434            ty::Adt(def, args) if Some(def.did()) == tcx.get_diagnostic_item(sym::Result) => {
6435                ::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())?)
6436            }
6437            ty::Adt(_, _) if implements_default(ty) => "Default::default()".to_string(),
6438            ty::Ref(_, ty, mutability) => {
6439                if let (ty::Str, hir::Mutability::Not) = (ty.kind(), mutability) {
6440                    "\"\"".to_string()
6441                } else {
6442                    let ty = self.ty_kind_suggestion(param_env, ty)?;
6443                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}{1}", mutability.prefix_str(),
                ty))
    })format!("&{}{ty}", mutability.prefix_str())
6444                }
6445            }
6446            ty::Array(ty, len) if let Some(len) = len.try_to_target_usize(tcx) => {
6447                if len == 0 {
6448                    "[]".to_string()
6449                } else if self.type_is_copy_modulo_regions(param_env, ty) || len == 1 {
6450                    // Can only suggest `[ty; 0]` if sz == 1 or copy
6451                    ::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)
6452                } else {
6453                    "/* value */".to_string()
6454                }
6455            }
6456            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!(
6457                "({}{})",
6458                tys.iter()
6459                    .map(|ty| self.ty_kind_suggestion(param_env, ty))
6460                    .collect::<Option<Vec<String>>>()?
6461                    .join(", "),
6462                if tys.len() == 1 { "," } else { "" }
6463            ),
6464            _ => "/* value */".to_string(),
6465        })
6466    }
6467
6468    // For E0277 when use `?` operator, suggest adding
6469    // a suitable return type in `FnSig`, and a default
6470    // return value at the end of the function's body.
6471    pub(super) fn suggest_add_result_as_return_type(
6472        &self,
6473        obligation: &PredicateObligation<'tcx>,
6474        err: &mut Diag<'_>,
6475        trait_pred: ty::PolyTraitClause<'tcx>,
6476    ) {
6477        if ObligationCauseCode::QuestionMark != *obligation.cause.code().peel_derives() {
6478            return;
6479        }
6480
6481        // Only suggest for local function and associated method,
6482        // because this suggest adding both return type in
6483        // the `FnSig` and a default return value in the body, so it
6484        // is not suitable for foreign function without a local body,
6485        // and neither for trait method which may be also implemented
6486        // in other place, so shouldn't change it's FnSig.
6487        fn choose_suggest_items<'tcx, 'hir>(
6488            tcx: TyCtxt<'tcx>,
6489            node: hir::Node<'hir>,
6490        ) -> Option<(&'hir hir::FnDecl<'hir>, hir::BodyId)> {
6491            match node {
6492                hir::Node::Item(item)
6493                    if let hir::ItemKind::Fn { sig, body: body_id, .. } = item.kind =>
6494                {
6495                    Some((sig.decl, body_id))
6496                }
6497                hir::Node::ImplItem(item)
6498                    if let hir::ImplItemKind::Fn(sig, body_id) = item.kind =>
6499                {
6500                    let parent = tcx.parent_hir_node(item.hir_id());
6501                    if let hir::Node::Item(item) = parent
6502                        && let hir::ItemKind::Impl(imp) = item.kind
6503                        && imp.of_trait.is_none()
6504                    {
6505                        return Some((sig.decl, body_id));
6506                    }
6507                    None
6508                }
6509                _ => None,
6510            }
6511        }
6512
6513        let node = self.tcx.hir_node_by_def_id(obligation.cause.body_def_id);
6514        if let Some((fn_decl, body_id)) = choose_suggest_items(self.tcx, node)
6515            && let hir::FnRetTy::DefaultReturn(ret_span) = fn_decl.output
6516            && self.tcx.is_diagnostic_item(sym::FromResidual, trait_pred.def_id())
6517            && trait_pred.skip_binder().trait_ref.args.type_at(0).is_unit()
6518            && let ty::Adt(def, _) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
6519            && self.tcx.is_diagnostic_item(sym::Result, def.did())
6520        {
6521            let mut sugg_spans =
6522                ::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())];
6523            let body = self.tcx.hir_body(body_id);
6524            if let hir::ExprKind::Block(b, _) = body.value.kind
6525                && b.expr.is_none()
6526            {
6527                // The span of '}' in the end of block.
6528                let span = self.tcx.sess.source_map().end_point(b.span);
6529                sugg_spans.push((
6530                    span.shrink_to_lo(),
6531                    ::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!(
6532                        "{}{}",
6533                        "    Ok(())\n",
6534                        self.tcx.sess.source_map().indentation_before(span).unwrap_or_default(),
6535                    ),
6536                ));
6537            }
6538            err.multipart_suggestion(
6539                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider adding return type"))
    })format!("consider adding return type"),
6540                sugg_spans,
6541                Applicability::MaybeIncorrect,
6542            );
6543        }
6544    }
6545
6546    {}
#[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("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(6546u32),
                                    ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6566",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(6566u32),
                                    ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6579",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(6579u32),
                                    ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6580",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(6580u32),
                                    ::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6593",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(6593u32),
                                    ::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)]
6547    pub(super) fn suggest_unsized_bound_if_applicable(
6548        &self,
6549        err: &mut Diag<'_>,
6550        obligation: &PredicateObligation<'tcx>,
6551    ) {
6552        let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
6553            obligation.predicate.kind().skip_binder()
6554        else {
6555            return;
6556        };
6557        let (ObligationCauseCode::WhereClause(item_def_id, span)
6558        | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)) =
6559            *obligation.cause.code().peel_derives()
6560        else {
6561            return;
6562        };
6563        if span.is_dummy() {
6564            return;
6565        }
6566        debug!(?pred, ?item_def_id, ?span);
6567
6568        let (Some(node), true) = (
6569            self.tcx.hir_get_if_local(item_def_id),
6570            self.tcx.is_lang_item(pred.def_id(), LangItem::Sized),
6571        ) else {
6572            return;
6573        };
6574
6575        let Some(generics) = node.generics() else {
6576            return;
6577        };
6578        let sized_trait = self.tcx.lang_items().sized_trait();
6579        debug!(?generics.params);
6580        debug!(?generics.predicates);
6581        let Some(param) = generics.params.iter().find(|param| param.span == span) else {
6582            return;
6583        };
6584        // Check that none of the explicit trait bounds is `Sized`. Assume that an explicit
6585        // `Sized` bound is there intentionally and we don't need to suggest relaxing it.
6586        let explicitly_sized = generics
6587            .bounds_for_param(param.def_id)
6588            .flat_map(|bp| bp.bounds)
6589            .any(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) == sized_trait);
6590        if explicitly_sized {
6591            return;
6592        }
6593        debug!(?param);
6594        match node {
6595            hir::Node::Item(
6596                item @ hir::Item {
6597                    // Only suggest indirection for uses of type parameters in ADTs.
6598                    kind:
6599                        hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..),
6600                    ..
6601                },
6602            ) => {
6603                if self.suggest_indirection_for_unsized(err, item, param) {
6604                    return;
6605                }
6606            }
6607            _ => {}
6608        };
6609
6610        // Didn't add an indirection suggestion, so add a general suggestion to relax `Sized`.
6611        let (span, separator, open_paren_sp) =
6612            if let Some((s, open_paren_sp)) = generics.bounds_span_for_suggestions(param.def_id) {
6613                (s, " +", open_paren_sp)
6614            } else {
6615                (param.name.ident().span.shrink_to_hi(), ":", None)
6616            };
6617
6618        let mut suggs = vec![];
6619        let suggestion = format!("{separator} ?Sized");
6620
6621        if let Some(open_paren_sp) = open_paren_sp {
6622            suggs.push((open_paren_sp, "(".to_string()));
6623            suggs.push((span, format!("){suggestion}")));
6624        } else {
6625            suggs.push((span, suggestion));
6626        }
6627
6628        err.multipart_suggestion(
6629            "consider relaxing the implicit `Sized` restriction",
6630            suggs,
6631            Applicability::MachineApplicable,
6632        );
6633    }
6634
6635    fn suggest_indirection_for_unsized(
6636        &self,
6637        err: &mut Diag<'_>,
6638        item: &hir::Item<'tcx>,
6639        param: &hir::GenericParam<'tcx>,
6640    ) -> bool {
6641        // Suggesting `T: ?Sized` is only valid in an ADT if `T` is only used in a
6642        // borrow. `struct S<'a, T: ?Sized>(&'a T);` is valid, `struct S<T: ?Sized>(T);`
6643        // is not. Look for invalid "bare" parameter uses, and suggest using indirection.
6644        let mut visitor = FindTypeParam { param: param.name.ident().name, .. };
6645        visitor.visit_item(item);
6646        if visitor.invalid_spans.is_empty() {
6647            return false;
6648        }
6649        let mut multispan: MultiSpan = param.span.into();
6650        multispan.push_span_label(
6651            param.span,
6652            ::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()),
6653        );
6654        for sp in visitor.invalid_spans {
6655            multispan.push_span_label(
6656                sp,
6657                ::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()),
6658            );
6659        }
6660        err.span_help(
6661            multispan,
6662            ::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!(
6663                "you could relax the implicit `Sized` bound on `{T}` if it were \
6664                used through indirection like `&{T}` or `Box<{T}>`",
6665                T = param.name.ident(),
6666            ),
6667        );
6668        true
6669    }
6670    pub(crate) fn suggest_swapping_lhs_and_rhs<T>(
6671        &self,
6672        err: &mut Diag<'_>,
6673        predicate: T,
6674        param_env: ty::ParamEnv<'tcx>,
6675        cause_code: &ObligationCauseCode<'tcx>,
6676    ) where
6677        T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
6678    {
6679        let tcx = self.tcx;
6680        let predicate = predicate.upcast(tcx);
6681        match *cause_code {
6682            ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, rhs_span, .. }
6683                if let Some(typeck_results) = &self.typeck_results
6684                    && let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
6685                    && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
6686                    && let Some(lhs_ty) = typeck_results.expr_ty_opt(lhs)
6687                    && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs) =>
6688            {
6689                if let Some(pred) = predicate.as_trait_clause()
6690                    && tcx.is_lang_item(pred.def_id(), LangItem::PartialEq)
6691                    && self
6692                        .infcx
6693                        .type_implements_trait(pred.def_id(), [rhs_ty, lhs_ty], param_env)
6694                        .must_apply_modulo_regions()
6695                {
6696                    let lhs_span = tcx.hir_span(lhs_hir_id);
6697                    let sm = tcx.sess.source_map();
6698                    if let Ok(rhs_snippet) = sm.span_to_snippet(rhs_span)
6699                        && let Ok(lhs_snippet) = sm.span_to_snippet(lhs_span)
6700                    {
6701                        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}>`"));
6702                        err.multipart_suggestion(
6703                            "consider swapping the equality",
6704                            ::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)],
6705                            Applicability::MaybeIncorrect,
6706                        );
6707                    }
6708                }
6709            }
6710            _ => {}
6711        }
6712    }
6713
6714    /// Checks whether the field independently satisfies the trait bound, ignoring
6715    /// the specific generic parameter that caused the original E0277 error.
6716    fn is_truly_imperfect_derive(
6717        &self,
6718        parent_trait_pred: ty::PolyTraitClause<'tcx>,
6719        predicate: ty::Predicate<'tcx>,
6720        param_env: ty::ParamEnv<'tcx>,
6721    ) -> bool {
6722        let tcx = self.tcx;
6723        let ty::Adt(adt_def, parent_args) = parent_trait_pred.skip_binder().self_ty().kind() else {
6724            return false;
6725        };
6726        let Some(trait_clause) = predicate.as_trait_clause() else {
6727            return false;
6728        };
6729        let failing_ty = trait_clause.skip_binder().self_ty();
6730        let trait_def_id = parent_trait_pred.def_id();
6731
6732        let failing_adt_param_indices: FxHashSet<u32> = parent_args
6733            .iter()
6734            .enumerate()
6735            .filter_map(|(idx, arg)| {
6736                if let Some(t) = arg.as_type()
6737                    && t == failing_ty
6738                {
6739                    Some(idx as u32)
6740                } else {
6741                    None
6742                }
6743            })
6744            .collect();
6745
6746        if failing_adt_param_indices.is_empty() {
6747            return false;
6748        }
6749
6750        adt_def.all_fields().all(|field| {
6751            let raw_field_ty = tcx.type_of(field.did).skip_binder();
6752            // If the field type is exactly one of the failing parameters, it is not an imperfect derive.
6753            if let ty::Param(p) = raw_field_ty.kind()
6754                && failing_adt_param_indices.contains(&p.index)
6755            {
6756                return false;
6757            }
6758            // If the field type doesn't mention the parameter at all, it's independent.
6759            if !raw_field_ty.walk().any(|arg| {
6760                #[allow(non_exhaustive_omitted_patterns)] match arg.as_type().map(|t|
            t.kind()) {
    Some(ty::Param(p)) if failing_adt_param_indices.contains(&p.index) =>
        true,
    _ => false,
}matches!(arg.as_type().map(|t| t.kind()), Some(ty::Param(p)) if failing_adt_param_indices.contains(&p.index))
6761            }) {
6762                return true;
6763            }
6764
6765            self.probe(|_| {
6766                // We keep the generic parameters that didn't fail as-is from the parent args,
6767                // but replace the ones that did fail with fresh inference variable placeholders.
6768                let fresh_args = ty::GenericArgs::for_item(tcx, adt_def.did(), |param, _| {
6769                    if failing_adt_param_indices.contains(&param.index) {
6770                        self.var_for_def(DUMMY_SP, param)
6771                    } else {
6772                        parent_args[param.index as usize]
6773                    }
6774                });
6775
6776                let field_ty = field.ty(tcx, fresh_args).skip_norm_wip();
6777                // Substitute the field's type for the bound's `Self` type to check whether
6778                // the field alone would satisfy the trait, independent of other generics.
6779                let parent_trait_args = parent_trait_pred.skip_binder().trait_ref.args;
6780                let trait_args = parent_trait_args.iter().map(|arg| {
6781                    if arg.as_type() == Some(parent_trait_pred.skip_binder().self_ty()) {
6782                        field_ty.into()
6783                    } else {
6784                        arg
6785                    }
6786                });
6787                let obligation = Obligation::new(
6788                    tcx,
6789                    ObligationCause::dummy(),
6790                    param_env,
6791                    ty::TraitRef::new(tcx, trait_def_id, trait_args),
6792                );
6793                self.predicate_may_hold(&obligation)
6794            })
6795        })
6796    }
6797}
6798
6799/// Add a hint to add a missing borrow or remove an unnecessary one.
6800fn hint_missing_borrow<'tcx>(
6801    infcx: &InferCtxt<'tcx>,
6802    param_env: ty::ParamEnv<'tcx>,
6803    span: Span,
6804    found: Ty<'tcx>,
6805    expected: Ty<'tcx>,
6806    found_node: Node<'_>,
6807    err: &mut Diag<'_>,
6808) {
6809    if #[allow(non_exhaustive_omitted_patterns)] match found_node {
    Node::TraitItem(..) => true,
    _ => false,
}matches!(found_node, Node::TraitItem(..)) {
6810        return;
6811    }
6812
6813    let found_args = match found.kind() {
6814        ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
6815        kind => {
6816            ::rustc_span::macros::bug_impl(Some(span),
    format_args!("found was converted to a FnPtr above but is now {0:?}",
        kind), Location::caller())span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
6817        }
6818    };
6819    let expected_args = match expected.kind() {
6820        ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
6821        kind => {
6822            ::rustc_span::macros::bug_impl(Some(span),
    format_args!("expected was converted to a FnPtr above but is now {0:?}",
        kind), Location::caller())span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
6823        }
6824    };
6825
6826    // This could be a variant constructor, for example.
6827    let Some(fn_decl) = found_node.fn_decl() else {
6828        return;
6829    };
6830
6831    let args = fn_decl.inputs.iter();
6832
6833    let mut to_borrow = Vec::new();
6834    let mut remove_borrow = Vec::new();
6835
6836    for ((found_arg, expected_arg), arg) in found_args.zip(expected_args).zip(args) {
6837        let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
6838        let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
6839
6840        if infcx.can_eq(param_env, found_ty, expected_ty) {
6841            // FIXME: This could handle more exotic cases like mutability mismatches too!
6842            if found_refs.len() < expected_refs.len()
6843                && found_refs[..] == expected_refs[expected_refs.len() - found_refs.len()..]
6844            {
6845                to_borrow.push((
6846                    arg.span.shrink_to_lo(),
6847                    expected_refs[..expected_refs.len() - found_refs.len()]
6848                        .iter()
6849                        .map(|mutbl| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
    })format!("&{}", mutbl.prefix_str()))
6850                        .collect::<Vec<_>>()
6851                        .join(""),
6852                ));
6853            } else if found_refs.len() > expected_refs.len() {
6854                let mut span = arg.span.shrink_to_lo();
6855                let mut left = found_refs.len() - expected_refs.len();
6856                let mut ty = arg;
6857                while let hir::TyKind::Ref(_, inner_ty, _) = &ty.kind
6858                    && left > 0
6859                {
6860                    span = span.with_hi(inner_ty.span.lo());
6861                    ty = inner_ty;
6862                    left -= 1;
6863                }
6864                if left == 0 {
6865                    remove_borrow.push((span, String::new()));
6866                }
6867            }
6868        }
6869    }
6870
6871    if !to_borrow.is_empty() {
6872        err.subdiagnostic(diagnostics::AdjustSignatureBorrow::Borrow { to_borrow });
6873    }
6874
6875    if !remove_borrow.is_empty() {
6876        err.subdiagnostic(diagnostics::AdjustSignatureBorrow::RemoveBorrow { remove_borrow });
6877    }
6878}
6879
6880/// Collect all the paths that reference `Self`.
6881/// Used to suggest replacing associated types with an explicit type in `where` clauses.
6882#[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)]
6883pub struct SelfVisitor<'v> {
6884    pub paths: Vec<&'v hir::Ty<'v>> = Vec::new(),
6885    pub name: Option<Symbol>,
6886}
6887
6888impl<'v> Visitor<'v> for SelfVisitor<'v> {
6889    fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
6890        if let hir::TyKind::Path(path) = ty.kind
6891            && let hir::QPath::TypeRelative(inner_ty, segment) = path
6892            && (Some(segment.ident.name) == self.name || self.name.is_none())
6893            && let hir::TyKind::Path(inner_path) = inner_ty.kind
6894            && let hir::QPath::Resolved(None, inner_path) = inner_path
6895            && let Res::SelfTyAlias { .. } = inner_path.res
6896        {
6897            self.paths.push(ty.as_unambig_ty());
6898        }
6899        hir::intravisit::walk_ty(self, ty);
6900    }
6901}
6902
6903/// Collect all the returned expressions within the input expression.
6904/// Used to point at the return spans when we want to suggest some change to them.
6905#[derive(#[automatically_derived]
impl<'v> ::core::default::Default for ReturnsVisitor<'v> {
    #[inline]
    fn default() -> Self {
        ReturnsVisitor {
            returns: ::core::default::Default::default(),
            in_block_tail: ::core::default::Default::default(),
        }
    }
}Default)]
6906pub struct ReturnsVisitor<'v> {
6907    pub returns: Vec<&'v hir::Expr<'v>>,
6908    in_block_tail: bool,
6909}
6910
6911impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
6912    fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
6913        // Visit every expression to detect `return` paths, either through the function's tail
6914        // expression or `return` statements. We walk all nodes to find `return` statements, but
6915        // we only care about tail expressions when `in_block_tail` is `true`, which means that
6916        // they're in the return path of the function body.
6917        match ex.kind {
6918            hir::ExprKind::Ret(Some(ex)) => {
6919                self.returns.push(ex);
6920            }
6921            hir::ExprKind::Block(block, _) if self.in_block_tail => {
6922                self.in_block_tail = false;
6923                for stmt in block.stmts {
6924                    hir::intravisit::walk_stmt(self, stmt);
6925                }
6926                self.in_block_tail = true;
6927                if let Some(expr) = block.expr {
6928                    self.visit_expr(expr);
6929                }
6930            }
6931            hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
6932                self.visit_expr(then);
6933                if let Some(el) = else_opt {
6934                    self.visit_expr(el);
6935                }
6936            }
6937            hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
6938                for arm in arms {
6939                    self.visit_expr(arm.body);
6940                }
6941            }
6942            // We need to walk to find `return`s in the entire body.
6943            _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
6944            _ => self.returns.push(ex),
6945        }
6946    }
6947
6948    fn visit_body(&mut self, body: &'v hir::Body<'v>) {
6949        if !!self.in_block_tail {
    ::core::panicking::panic("assertion failed: !self.in_block_tail")
};assert!(!self.in_block_tail);
6950        self.in_block_tail = true;
6951        hir::intravisit::walk_body(self, body);
6952    }
6953}
6954
6955/// Collect all the awaited expressions within the input expression.
6956#[derive(#[automatically_derived]
impl ::core::default::Default for AwaitsVisitor {
    #[inline]
    fn default() -> Self {
        AwaitsVisitor { awaits: ::core::default::Default::default() }
    }
}Default)]
6957struct AwaitsVisitor {
6958    awaits: Vec<HirId>,
6959}
6960
6961impl<'v> Visitor<'v> for AwaitsVisitor {
6962    fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
6963        if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
6964            self.awaits.push(id)
6965        }
6966        hir::intravisit::walk_expr(self, ex)
6967    }
6968}
6969
6970/// Suggest a new type parameter name for diagnostic purposes.
6971///
6972/// `name` is the preferred name you'd like to suggest if it's not in use already.
6973pub trait NextTypeParamName {
6974    fn next_type_param_name(&self, name: Option<&str>) -> String;
6975}
6976
6977impl NextTypeParamName for &[hir::GenericParam<'_>] {
6978    fn next_type_param_name(&self, name: Option<&str>) -> String {
6979        // Type names are usually single letters in uppercase. So convert the first letter of input string to uppercase.
6980        let name = name.and_then(|n| n.chars().next()).map(|c| c.to_uppercase().to_string());
6981        let name = name.as_deref();
6982
6983        // This is the list of possible parameter names that we might suggest.
6984        let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
6985
6986        // Filter out used names based on `filter_fn`.
6987        let used_names: Vec<Symbol> = self
6988            .iter()
6989            .filter_map(|param| match param.name {
6990                hir::ParamName::Plain(ident) => Some(ident.name),
6991                _ => None,
6992            })
6993            .collect();
6994
6995        // Find a name from `possible_names` that is not in `used_names`.
6996        possible_names
6997            .iter()
6998            .find(|n| !used_names.contains(&Symbol::intern(n)))
6999            .unwrap_or(&"ParamName")
7000            .to_string()
7001    }
7002}
7003
7004/// Collect the spans that we see the generic param `param_did`
7005struct ReplaceImplTraitVisitor<'a> {
7006    ty_spans: &'a mut Vec<Span>,
7007    param_did: DefId,
7008}
7009
7010impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
7011    fn visit_ty(&mut self, t: &'hir hir::Ty<'hir, AmbigArg>) {
7012        if let hir::TyKind::Path(hir::QPath::Resolved(
7013            None,
7014            hir::Path { res: Res::Def(_, segment_did), .. },
7015        )) = t.kind
7016        {
7017            if self.param_did == *segment_did {
7018                // `fn foo(t: impl Trait)`
7019                //            ^^^^^^^^^^ get this to suggest `T` instead
7020
7021                // There might be more than one `impl Trait`.
7022                self.ty_spans.push(t.span);
7023                return;
7024            }
7025        }
7026
7027        hir::intravisit::walk_ty(self, t);
7028    }
7029}
7030
7031pub(super) fn get_explanation_based_on_obligation<'tcx>(
7032    tcx: TyCtxt<'tcx>,
7033    obligation: &PredicateObligation<'tcx>,
7034    trait_predicate: ty::PolyTraitClause<'tcx>,
7035    pre_message: String,
7036    long_ty_path: &mut Option<PathBuf>,
7037) -> String {
7038    if let ObligationCauseCode::MainFunctionType = obligation.cause.code() {
7039        "consider using `()`, or a `Result`".to_owned()
7040    } else {
7041        let ty_desc = match trait_predicate.self_ty().skip_binder().kind() {
7042            ty::FnDef(_, _) => Some("fn item"),
7043            ty::Closure(_, _) => Some("closure"),
7044            _ => None,
7045        };
7046
7047        let desc = match ty_desc {
7048            Some(desc) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {0}", desc))
    })format!(" {desc}"),
7049            None => String::new(),
7050        };
7051        if let ty::ClausePolarity::Positive = trait_predicate.polarity() {
7052            // If the trait in question is unstable, mention that fact in the diagnostic.
7053            // But if we're building with `-Zforce-unstable-if-unmarked` then _any_ trait
7054            // not explicitly marked stable is considered unstable, so the extra text is
7055            // unhelpful noise. See <https://github.com/rust-lang/rust/issues/152692>.
7056            let mention_unstable = !tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
7057                && try { tcx.lookup_stability(trait_predicate.def_id())?.level.is_stable() }
7058                    == Some(false);
7059            let unstable = if mention_unstable { "nightly-only, unstable " } else { "" };
7060
7061            ::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!(
7062                "{pre_message}the {unstable}trait `{}` is not implemented for{desc} `{}`",
7063                trait_predicate.print_modifiers_and_trait_path(),
7064                tcx.short_string(trait_predicate.self_ty().skip_binder(), long_ty_path),
7065            )
7066        } else {
7067            // "the trait bound `T: !Send` is not satisfied" reads better than "`!Send` is
7068            // not implemented for `T`".
7069            // FIXME: add note explaining explicit negative trait bounds.
7070            ::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")
7071        }
7072    }
7073}
7074
7075// Replace `param` with `replace_ty`
7076struct ReplaceImplTraitFolder<'tcx> {
7077    tcx: TyCtxt<'tcx>,
7078    param: &'tcx ty::GenericParamDef,
7079    replace_ty: Ty<'tcx>,
7080}
7081
7082impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceImplTraitFolder<'tcx> {
7083    fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
7084        if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
7085            if self.param.index == *index {
7086                return self.replace_ty;
7087            }
7088        }
7089        t.super_fold_with(self)
7090    }
7091
7092    fn cx(&self) -> TyCtxt<'tcx> {
7093        self.tcx
7094    }
7095}
7096
7097pub fn suggest_desugaring_async_fn_to_impl_future_in_trait<'tcx>(
7098    tcx: TyCtxt<'tcx>,
7099    sig: hir::FnSig<'tcx>,
7100    body: hir::TraitFn<'tcx>,
7101    opaque_def_id: LocalDefId,
7102    add_bounds: &str,
7103) -> Option<Vec<(Span, String)>> {
7104    let hir::IsAsync::Async(async_span) = sig.header.asyncness else {
7105        return None;
7106    };
7107    let async_span = tcx.sess.source_map().span_extend_while_whitespace(async_span);
7108
7109    let future = tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
7110    let [hir::GenericBound::Trait(trait_ref)] = future.bounds else {
7111        // `async fn` should always lower to a single bound... but don't ICE.
7112        return None;
7113    };
7114    let Some(hir::PathSegment { args: Some(args), .. }) = trait_ref.trait_ref.path.segments.last()
7115    else {
7116        // desugaring to a single path segment for `Future<...>`.
7117        return None;
7118    };
7119    let Some(future_output_ty) = args.constraints.first().and_then(|constraint| constraint.ty())
7120    else {
7121        // Also should never happen.
7122        return None;
7123    };
7124
7125    let mut sugg = if future_output_ty.span.is_empty() {
7126        ::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![
7127            (async_span, String::new()),
7128            (
7129                future_output_ty.span,
7130                format!(" -> impl std::future::Future<Output = ()>{add_bounds}"),
7131            ),
7132        ]
7133    } else {
7134        ::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![
7135            (future_output_ty.span.shrink_to_lo(), "impl std::future::Future<Output = ".to_owned()),
7136            (future_output_ty.span.shrink_to_hi(), format!(">{add_bounds}")),
7137            (async_span, String::new()),
7138        ]
7139    };
7140
7141    // If there's a body, we also need to wrap it in `async {}`
7142    if let hir::TraitFn::Provided(body) = body {
7143        let body = tcx.hir_body(body);
7144        let body_span = body.value.span;
7145        let body_span_without_braces =
7146            body_span.with_lo(body_span.lo() + BytePos(1)).with_hi(body_span.hi() - BytePos(1));
7147        if body_span_without_braces.is_empty() {
7148            sugg.push((body_span_without_braces, " async {} ".to_owned()));
7149        } else {
7150            sugg.extend([
7151                (body_span_without_braces.shrink_to_lo(), "async {".to_owned()),
7152                (body_span_without_braces.shrink_to_hi(), "} ".to_owned()),
7153            ]);
7154        }
7155    }
7156
7157    Some(sugg)
7158}
7159
7160/// On `impl` evaluation cycles, look for `Self::AssocTy` restrictions in `where` clauses, explain
7161/// they are not allowed and if possible suggest alternatives.
7162fn point_at_assoc_type_restriction(
7163    tcx: TyCtxt<'_>,
7164    err: &mut Diag<'_>,
7165    self_ty_str: &str,
7166    trait_name: &str,
7167    predicate: ty::Predicate<'_>,
7168    generics: &hir::Generics<'_>,
7169    data: &ImplDerivedCause<'_>,
7170) {
7171    let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() else {
7172        return;
7173    };
7174    let ty::ClauseKind::Projection(proj) = clause else {
7175        return;
7176    };
7177    let Some(name) = tcx
7178        .opt_rpitit_info(proj.def_id())
7179        .and_then(|data| match data {
7180            ty::ImplTraitInTraitData::Trait { fn_def_id, .. } => Some(tcx.item_name(fn_def_id)),
7181            ty::ImplTraitInTraitData::Impl { .. } => None,
7182        })
7183        .or_else(|| tcx.opt_item_name(proj.def_id()))
7184    else {
7185        return;
7186    };
7187    let mut predicates = generics.predicates.iter().peekable();
7188    let mut prev: Option<(&hir::WhereBoundPredicate<'_>, Span)> = None;
7189    while let Some(pred) = predicates.next() {
7190        let curr_span = pred.span;
7191        let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind else {
7192            continue;
7193        };
7194        let mut bounds = pred.bounds.iter();
7195        while let Some(bound) = bounds.next() {
7196            let Some(trait_ref) = bound.trait_ref() else {
7197                continue;
7198            };
7199            if bound.span() != data.span {
7200                continue;
7201            }
7202            if let hir::TyKind::Path(path) = pred.bounded_ty.kind
7203                && let hir::QPath::TypeRelative(ty, segment) = path
7204                && segment.ident.name == name
7205                && let hir::TyKind::Path(inner_path) = ty.kind
7206                && let hir::QPath::Resolved(None, inner_path) = inner_path
7207                && let Res::SelfTyAlias { .. } = inner_path.res
7208            {
7209                // The following block is to determine the right span to delete for this bound
7210                // that will leave valid code after the suggestion is applied.
7211                let span = if pred.origin == hir::PredicateOrigin::WhereClause
7212                    && generics
7213                        .predicates
7214                        .iter()
7215                        .filter(|p| {
7216                            #[allow(non_exhaustive_omitted_patterns)] match p.kind {
    hir::WherePredicateKind::BoundPredicate(p) if
        hir::PredicateOrigin::WhereClause == p.origin => true,
    _ => false,
}matches!(
7217                                p.kind,
7218                                hir::WherePredicateKind::BoundPredicate(p)
7219                                if hir::PredicateOrigin::WhereClause == p.origin
7220                            )
7221                        })
7222                        .count()
7223                        == 1
7224                {
7225                    // There's only one `where` bound, that needs to be removed. Remove the whole
7226                    // `where` clause.
7227                    generics.where_clause_span
7228                } else if let Some(next_pred) = predicates.peek()
7229                    && let hir::WherePredicateKind::BoundPredicate(next) = next_pred.kind
7230                    && pred.origin == next.origin
7231                {
7232                    // There's another bound, include the comma for the current one.
7233                    curr_span.until(next_pred.span)
7234                } else if let Some((prev, prev_span)) = prev
7235                    && pred.origin == prev.origin
7236                {
7237                    // Last bound, try to remove the previous comma.
7238                    prev_span.shrink_to_hi().to(curr_span)
7239                } else if pred.origin == hir::PredicateOrigin::WhereClause {
7240                    curr_span.with_hi(generics.where_clause_span.hi())
7241                } else {
7242                    curr_span
7243                };
7244
7245                err.span_suggestion_verbose(
7246                    span,
7247                    "associated type for the current `impl` cannot be restricted in `where` \
7248                     clauses, remove this bound",
7249                    "",
7250                    Applicability::MaybeIncorrect,
7251                );
7252            }
7253            if let Some(new) =
7254                tcx.associated_items(data.impl_or_alias_def_id).find_by_ident_and_kind(
7255                    tcx,
7256                    Ident::with_dummy_span(name),
7257                    ty::AssocTag::Type,
7258                    data.impl_or_alias_def_id,
7259                )
7260            {
7261                // The associated type is specified in the `impl` we're
7262                // looking at. Point at it.
7263                let span = tcx.def_span(new.def_id);
7264                err.span_label(
7265                    span,
7266                    ::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!(
7267                        "associated type `<{self_ty_str} as {trait_name}>::{name}` is specified \
7268                         here",
7269                    ),
7270                );
7271                // Search for the associated type `Self::{name}`, get
7272                // its type and suggest replacing the bound with it.
7273                let mut visitor = SelfVisitor { name: Some(name), .. };
7274                visitor.visit_trait_ref(trait_ref);
7275                for path in visitor.paths {
7276                    err.span_suggestion_verbose(
7277                        path.span,
7278                        "replace the associated type with the type specified in this `impl`",
7279                        tcx.type_of(new.def_id).skip_binder(),
7280                        Applicability::MachineApplicable,
7281                    );
7282                }
7283            } else {
7284                let mut visitor = SelfVisitor { name: None, .. };
7285                visitor.visit_trait_ref(trait_ref);
7286                let span: MultiSpan =
7287                    visitor.paths.iter().map(|p| p.span).collect::<Vec<Span>>().into();
7288                err.span_note(
7289                    span,
7290                    "associated types for the current `impl` cannot be restricted in `where` \
7291                     clauses",
7292                );
7293            }
7294        }
7295        prev = Some((pred, curr_span));
7296    }
7297}
7298
7299fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec<hir::Mutability>) {
7300    let mut refs = ::alloc::vec::Vec::new()vec![];
7301
7302    while let ty::Ref(_, new_ty, mutbl) = ty.kind() {
7303        ty = *new_ty;
7304        refs.push(*mutbl);
7305    }
7306
7307    (ty, refs)
7308}
7309
7310/// Look for type `param` in an ADT being used only through a reference to confirm that suggesting
7311/// `param: ?Sized` would be a valid constraint.
7312struct FindTypeParam {
7313    param: rustc_span::Symbol,
7314    invalid_spans: Vec<Span> = Vec::new(),
7315    nested: bool = false,
7316}
7317
7318impl<'v> Visitor<'v> for FindTypeParam {
7319    fn visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>) {
7320        // Skip where-clauses, to avoid suggesting indirection for type parameters found there.
7321    }
7322
7323    fn visit_ty(&mut self, ty: &hir::Ty<'_, AmbigArg>) {
7324        // We collect the spans of all uses of the "bare" type param, like in `field: T` or
7325        // `field: (T, T)` where we could make `T: ?Sized` while skipping cases that are known to be
7326        // valid like `field: &'a T` or `field: *mut T` and cases that *might* have further `Sized`
7327        // obligations like `Box<T>` and `Vec<T>`, but we perform no extra analysis for those cases
7328        // and suggest `T: ?Sized` regardless of their obligations. This is fine because the errors
7329        // in that case should make what happened clear enough.
7330        match ty.kind {
7331            hir::TyKind::Ptr(..) | hir::TyKind::Ref(..) | hir::TyKind::TraitObject(..) => {}
7332            hir::TyKind::Path(hir::QPath::Resolved(None, path))
7333                if let [segment] = path.segments
7334                    && segment.ident.name == self.param =>
7335            {
7336                if !self.nested {
7337                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:7337",
                        "rustc_trait_selection::error_reporting::traits::suggestions",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                        ::tracing_core::__macro_support::Option::Some(7337u32),
                        ::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");
7338                    self.invalid_spans.push(ty.span);
7339                }
7340            }
7341            hir::TyKind::Path(_) => {
7342                let prev = self.nested;
7343                self.nested = true;
7344                hir::intravisit::walk_ty(self, ty);
7345                self.nested = prev;
7346            }
7347            _ => {
7348                hir::intravisit::walk_ty(self, ty);
7349            }
7350        }
7351    }
7352}
7353
7354/// Look for type parameters in predicates. We use this to identify whether a bound is suitable in
7355/// on a given item.
7356struct ParamFinder {
7357    params: Vec<Symbol> = Vec::new(),
7358}
7359
7360impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ParamFinder {
7361    fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
7362        match t.kind() {
7363            ty::Param(p) => self.params.push(p.name),
7364            _ => {}
7365        }
7366        t.super_visit_with(self)
7367    }
7368}
7369
7370impl ParamFinder {
7371    /// Whether the `hir::Generics` of the current item can suggest the evaluated bound because its
7372    /// references to type parameters are present in the generics.
7373    fn can_suggest_bound(&self, generics: &hir::Generics<'_>) -> bool {
7374        if self.params.is_empty() {
7375            // There are no references to type parameters at all, so suggesting the bound
7376            // would be reasonable.
7377            return true;
7378        }
7379        generics.params.iter().any(|p| match p.name {
7380            hir::ParamName::Plain(p_name) => {
7381                // All of the parameters in the bound can be referenced in the current item.
7382                self.params.iter().any(|p| *p == p_name.name || *p == kw::SelfUpper)
7383            }
7384            _ => true,
7385        })
7386    }
7387}