Skip to main content

rustc_trait_selection/error_reporting/traits/
suggestions.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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