Skip to main content

rustc_trait_selection/error_reporting/traits/
suggestions.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: bool = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (mut trait_ref, mut target_ty) =
                match obligation.predicate.kind().skip_binder() {
                    ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) =>
                        (Some(p), Some(p.self_ty())),
                    _ => (None, None),
                };
            let mut coroutine = None;
            let mut outer_coroutine = None;
            let mut next_code = Some(obligation.cause.code());
            let mut seen_upvar_tys_infer_tuple = false;
            while let Some(code) = next_code {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3344",
                                        "rustc_trait_selection::error_reporting::traits::suggestions",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                        ::tracing_core::__macro_support::Option::Some(3344u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                        ::tracing_core::field::FieldSet::new(&[{
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("code")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("code");
                                                            NAME.as_str()
                                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&code)
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                match code {
                    ObligationCauseCode::FunctionArg { parent_code, .. } => {
                        next_code = Some(parent_code);
                    }
                    ObligationCauseCode::ImplDerived(cause) => {
                        let ty =
                            cause.derived.parent_trait_pred.skip_binder().self_ty();
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3351",
                                                "rustc_trait_selection::error_reporting::traits::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(3351u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&["message",
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("parent_trait_ref")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("parent_trait_ref");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("self_ty.kind")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("self_ty.kind");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("ImplDerived")
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause.derived.parent_trait_pred)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty.kind())
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        match *ty.kind() {
                            ty::Coroutine(did, ..) | ty::CoroutineWitness(did, _) => {
                                coroutine = coroutine.or(Some(did));
                                outer_coroutine = Some(did);
                            }
                            ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
                                seen_upvar_tys_infer_tuple = true;
                            }
                            _ if coroutine.is_none() => {
                                trait_ref =
                                    Some(cause.derived.parent_trait_pred.skip_binder());
                                target_ty = Some(ty);
                            }
                            _ => {}
                        }
                        next_code = Some(&cause.derived.parent_code);
                    }
                    ObligationCauseCode::WellFormedDerived(derived_obligation) |
                        ObligationCauseCode::BuiltinDerived(derived_obligation) => {
                        let ty =
                            derived_obligation.parent_trait_pred.skip_binder().self_ty();
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3381",
                                                "rustc_trait_selection::error_reporting::traits::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(3381u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("parent_trait_ref")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("parent_trait_ref");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("self_ty.kind")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("self_ty.kind");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&derived_obligation.parent_trait_pred)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty.kind())
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        match *ty.kind() {
                            ty::Coroutine(did, ..) | ty::CoroutineWitness(did, ..) => {
                                coroutine = coroutine.or(Some(did));
                                outer_coroutine = Some(did);
                            }
                            ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
                                seen_upvar_tys_infer_tuple = true;
                            }
                            _ if coroutine.is_none() => {
                                trait_ref =
                                    Some(derived_obligation.parent_trait_pred.skip_binder());
                                target_ty = Some(ty);
                            }
                            _ => {}
                        }
                        next_code = Some(&derived_obligation.parent_code);
                    }
                    _ => break,
                }
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3412",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3412u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("coroutine")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("coroutine");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_ref");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("target_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("target_ty");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coroutine)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ref)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target_ty)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let (Some(coroutine_did), Some(trait_ref), Some(target_ty)) =
                (coroutine, trait_ref, target_ty) else { return false; };
            let span = self.tcx.def_span(coroutine_did);
            let coroutine_did_root =
                self.tcx.typeck_root_def_id(coroutine_did);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3422",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3422u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("coroutine_did")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("coroutine_did");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("coroutine_did_root")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("coroutine_did_root");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("typeck_results.hir_owner")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("typeck_results.hir_owner");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coroutine_did)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coroutine_did_root)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.typeck_results.as_ref().map(|t|
                                                                            t.hir_owner)) as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let coroutine_body =
                coroutine_did.as_local().and_then(|def_id|
                        self.tcx.hir_maybe_body_owned_by(def_id));
            let mut visitor = AwaitsVisitor::default();
            if let Some(body) = coroutine_body { visitor.visit_body(&body); }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3435",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3435u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("awaits")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("awaits");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&visitor.awaits)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let target_ty_erased =
                self.tcx.erase_and_anonymize_regions(target_ty);
            let ty_matches =
                |ty| -> bool
                    {
                        let ty_erased =
                            self.tcx.instantiate_bound_regions_with_erased(ty);
                        let ty_erased =
                            self.tcx.erase_and_anonymize_regions(ty_erased);
                        let eq = ty_erased == target_ty_erased;
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3456",
                                                "rustc_trait_selection::error_reporting::traits::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(3456u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("ty_erased")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("ty_erased");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("target_ty_erased")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("target_ty_erased");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("eq")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("eq");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty_erased)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target_ty_erased)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&eq)
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        eq
                    };
            let coroutine_data =
                match &self.typeck_results {
                    Some(t) if t.hir_owner.to_def_id() == coroutine_did_root =>
                        CoroutineData(t),
                    _ if coroutine_did.is_local() => {
                        CoroutineData(self.tcx.typeck(coroutine_did.expect_local()))
                    }
                    _ => return false,
                };
            let coroutine_within_in_progress_typeck =
                match &self.typeck_results {
                    Some(t) => t.hir_owner.to_def_id() == coroutine_did_root,
                    _ => false,
                };
            let mut interior_or_upvar_span = None;
            let from_awaited_ty =
                coroutine_data.get_from_await_ty(visitor, self.tcx,
                    ty_matches);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3480",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3480u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("from_awaited_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("from_awaited_ty");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&from_awaited_ty)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if coroutine_did.is_local() &&
                        !coroutine_within_in_progress_typeck &&
                    let Some(coroutine_info) =
                        self.tcx.mir_coroutine_witnesses(coroutine_did) {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3488",
                                        "rustc_trait_selection::error_reporting::traits::suggestions",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                        ::tracing_core::__macro_support::Option::Some(3488u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                        ::tracing_core::field::FieldSet::new(&[{
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("coroutine_info")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("coroutine_info");
                                                            NAME.as_str()
                                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coroutine_info)
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                'find_source:
                    for (variant, source_info) in
                    coroutine_info.variant_fields.iter().zip(&coroutine_info.variant_source_info)
                    {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3492",
                                            "rustc_trait_selection::error_reporting::traits::suggestions",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                            ::tracing_core::__macro_support::Option::Some(3492u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                            ::tracing_core::field::FieldSet::new(&[{
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("variant")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("variant");
                                                                NAME.as_str()
                                                            }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&variant)
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    for &local in variant {
                        let decl = &coroutine_info.field_tys[local];
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3495",
                                                "rustc_trait_selection::error_reporting::traits::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(3495u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("decl")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("decl");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&decl)
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        if ty_matches(ty::Binder::dummy(decl.ty)) &&
                                !decl.ignore_for_traits {
                            interior_or_upvar_span =
                                Some(CoroutineInteriorOrUpvar::Interior(decl.source_info.span,
                                        Some((source_info.span, from_awaited_ty))));
                            break 'find_source;
                        }
                    }
                }
            }
            if interior_or_upvar_span.is_none() {
                interior_or_upvar_span =
                    coroutine_data.try_get_upvar_span(self, coroutine_did,
                        ty_matches);
            }
            if interior_or_upvar_span.is_none() && !coroutine_did.is_local() {
                interior_or_upvar_span =
                    Some(CoroutineInteriorOrUpvar::Interior(span, None));
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3516",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3516u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("interior_or_upvar_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("interior_or_upvar_span");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&interior_or_upvar_span)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if let Some(interior_or_upvar_span) = interior_or_upvar_span {
                let is_async = self.tcx.coroutine_is_async(coroutine_did);
                self.note_obligation_cause_for_async_await(err,
                    interior_or_upvar_span, is_async, outer_coroutine,
                    trait_ref, target_ty, obligation, next_code);
                true
            } else { false }
        }
    }
}#[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
3306    pub fn maybe_note_obligation_cause_for_async_await<G>(
3307        &self,
3308        err: &mut Diag<'_, G>,
3309        obligation: &PredicateObligation<'tcx>,
3310    ) -> bool {
3311        // Attempt to detect an async-await error by looking at the obligation causes, looking
3312        // for a coroutine to be present.
3313        //
3314        // When a future does not implement a trait because of a captured type in one of the
3315        // coroutines somewhere in the call stack, then the result is a chain of obligations.
3316        //
3317        // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
3318        // future is passed as an argument to a function C which requires a `Send` type, then the
3319        // chain looks something like this:
3320        //
3321        // - `BuiltinDerivedObligation` with a coroutine witness (B)
3322        // - `BuiltinDerivedObligation` with a coroutine (B)
3323        // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
3324        // - `BuiltinDerivedObligation` with a coroutine witness (A)
3325        // - `BuiltinDerivedObligation` with a coroutine (A)
3326        // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
3327        // - `BindingObligation` with `impl_send` (Send requirement)
3328        //
3329        // The first obligation in the chain is the most useful and has the coroutine that captured
3330        // the type. The last coroutine (`outer_coroutine` below) has information about where the
3331        // bound was introduced. At least one coroutine should be present for this diagnostic to be
3332        // modified.
3333        let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
3334            ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) => (Some(p), Some(p.self_ty())),
3335            _ => (None, None),
3336        };
3337        let mut coroutine = None;
3338        let mut outer_coroutine = None;
3339        let mut next_code = Some(obligation.cause.code());
3340
3341        let mut seen_upvar_tys_infer_tuple = false;
3342
3343        while let Some(code) = next_code {
3344            debug!(?code);
3345            match code {
3346                ObligationCauseCode::FunctionArg { parent_code, .. } => {
3347                    next_code = Some(parent_code);
3348                }
3349                ObligationCauseCode::ImplDerived(cause) => {
3350                    let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
3351                    debug!(
3352                        parent_trait_ref = ?cause.derived.parent_trait_pred,
3353                        self_ty.kind = ?ty.kind(),
3354                        "ImplDerived",
3355                    );
3356
3357                    match *ty.kind() {
3358                        ty::Coroutine(did, ..) | ty::CoroutineWitness(did, _) => {
3359                            coroutine = coroutine.or(Some(did));
3360                            outer_coroutine = Some(did);
3361                        }
3362                        ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
3363                            // By introducing a tuple of upvar types into the chain of obligations
3364                            // of a coroutine, the first non-coroutine item is now the tuple itself,
3365                            // we shall ignore this.
3366
3367                            seen_upvar_tys_infer_tuple = true;
3368                        }
3369                        _ if coroutine.is_none() => {
3370                            trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
3371                            target_ty = Some(ty);
3372                        }
3373                        _ => {}
3374                    }
3375
3376                    next_code = Some(&cause.derived.parent_code);
3377                }
3378                ObligationCauseCode::WellFormedDerived(derived_obligation)
3379                | ObligationCauseCode::BuiltinDerived(derived_obligation) => {
3380                    let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
3381                    debug!(
3382                        parent_trait_ref = ?derived_obligation.parent_trait_pred,
3383                        self_ty.kind = ?ty.kind(),
3384                    );
3385
3386                    match *ty.kind() {
3387                        ty::Coroutine(did, ..) | ty::CoroutineWitness(did, ..) => {
3388                            coroutine = coroutine.or(Some(did));
3389                            outer_coroutine = Some(did);
3390                        }
3391                        ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
3392                            // By introducing a tuple of upvar types into the chain of obligations
3393                            // of a coroutine, the first non-coroutine item is now the tuple itself,
3394                            // we shall ignore this.
3395
3396                            seen_upvar_tys_infer_tuple = true;
3397                        }
3398                        _ if coroutine.is_none() => {
3399                            trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
3400                            target_ty = Some(ty);
3401                        }
3402                        _ => {}
3403                    }
3404
3405                    next_code = Some(&derived_obligation.parent_code);
3406                }
3407                _ => break,
3408            }
3409        }
3410
3411        // Only continue if a coroutine was found.
3412        debug!(?coroutine, ?trait_ref, ?target_ty);
3413        let (Some(coroutine_did), Some(trait_ref), Some(target_ty)) =
3414            (coroutine, trait_ref, target_ty)
3415        else {
3416            return false;
3417        };
3418
3419        let span = self.tcx.def_span(coroutine_did);
3420
3421        let coroutine_did_root = self.tcx.typeck_root_def_id(coroutine_did);
3422        debug!(
3423            ?coroutine_did,
3424            ?coroutine_did_root,
3425            typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
3426            ?span,
3427        );
3428
3429        let coroutine_body =
3430            coroutine_did.as_local().and_then(|def_id| self.tcx.hir_maybe_body_owned_by(def_id));
3431        let mut visitor = AwaitsVisitor::default();
3432        if let Some(body) = coroutine_body {
3433            visitor.visit_body(&body);
3434        }
3435        debug!(awaits = ?visitor.awaits);
3436
3437        // Look for a type inside the coroutine interior that matches the target type to get
3438        // a span.
3439        let target_ty_erased = self.tcx.erase_and_anonymize_regions(target_ty);
3440        let ty_matches = |ty| -> bool {
3441            // Careful: the regions for types that appear in the
3442            // coroutine interior are not generally known, so we
3443            // want to erase them when comparing (and anyway,
3444            // `Send` and other bounds are generally unaffected by
3445            // the choice of region). When erasing regions, we
3446            // also have to erase late-bound regions. This is
3447            // because the types that appear in the coroutine
3448            // interior generally contain "bound regions" to
3449            // represent regions that are part of the suspended
3450            // coroutine frame. Bound regions are preserved by
3451            // `erase_and_anonymize_regions` and so we must also call
3452            // `instantiate_bound_regions_with_erased`.
3453            let ty_erased = self.tcx.instantiate_bound_regions_with_erased(ty);
3454            let ty_erased = self.tcx.erase_and_anonymize_regions(ty_erased);
3455            let eq = ty_erased == target_ty_erased;
3456            debug!(?ty_erased, ?target_ty_erased, ?eq);
3457            eq
3458        };
3459
3460        // Get the typeck results from the infcx if the coroutine is the function we are currently
3461        // type-checking; otherwise, get them by performing a query. This is needed to avoid
3462        // cycles. If we can't use resolved types because the coroutine comes from another crate,
3463        // we still provide a targeted error but without all the relevant spans.
3464        let coroutine_data = match &self.typeck_results {
3465            Some(t) if t.hir_owner.to_def_id() == coroutine_did_root => CoroutineData(t),
3466            _ if coroutine_did.is_local() => {
3467                CoroutineData(self.tcx.typeck(coroutine_did.expect_local()))
3468            }
3469            _ => return false,
3470        };
3471
3472        let coroutine_within_in_progress_typeck = match &self.typeck_results {
3473            Some(t) => t.hir_owner.to_def_id() == coroutine_did_root,
3474            _ => false,
3475        };
3476
3477        let mut interior_or_upvar_span = None;
3478
3479        let from_awaited_ty = coroutine_data.get_from_await_ty(visitor, self.tcx, ty_matches);
3480        debug!(?from_awaited_ty);
3481
3482        // Avoid disclosing internal information to downstream crates.
3483        if coroutine_did.is_local()
3484            // Try to avoid cycles.
3485            && !coroutine_within_in_progress_typeck
3486            && let Some(coroutine_info) = self.tcx.mir_coroutine_witnesses(coroutine_did)
3487        {
3488            debug!(?coroutine_info);
3489            'find_source: for (variant, source_info) in
3490                coroutine_info.variant_fields.iter().zip(&coroutine_info.variant_source_info)
3491            {
3492                debug!(?variant);
3493                for &local in variant {
3494                    let decl = &coroutine_info.field_tys[local];
3495                    debug!(?decl);
3496                    if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.ignore_for_traits {
3497                        interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(
3498                            decl.source_info.span,
3499                            Some((source_info.span, from_awaited_ty)),
3500                        ));
3501                        break 'find_source;
3502                    }
3503                }
3504            }
3505        }
3506
3507        if interior_or_upvar_span.is_none() {
3508            interior_or_upvar_span =
3509                coroutine_data.try_get_upvar_span(self, coroutine_did, ty_matches);
3510        }
3511
3512        if interior_or_upvar_span.is_none() && !coroutine_did.is_local() {
3513            interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(span, None));
3514        }
3515
3516        debug!(?interior_or_upvar_span);
3517        if let Some(interior_or_upvar_span) = interior_or_upvar_span {
3518            let is_async = self.tcx.coroutine_is_async(coroutine_did);
3519            self.note_obligation_cause_for_async_await(
3520                err,
3521                interior_or_upvar_span,
3522                is_async,
3523                outer_coroutine,
3524                trait_ref,
3525                target_ty,
3526                obligation,
3527                next_code,
3528            );
3529            true
3530        } else {
3531            false
3532        }
3533    }
3534
3535    /// Unconditionally adds the diagnostic note described in
3536    /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
3537    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("note_obligation_cause_for_async_await",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3537u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let source_map = self.tcx.sess.source_map();
            let (await_or_yield, an_await_or_yield) =
                if is_async {
                    ("await", "an await")
                } else { ("yield", "a yield") };
            let future_or_coroutine =
                if is_async { "future" } else { "coroutine" };
            let trait_explanation =
                if let Some(name @ (sym::Send | sym::Sync)) =
                        self.tcx.get_diagnostic_name(trait_pred.def_id()) {
                    let (trait_name, trait_verb) =
                        if name == sym::Send {
                            ("`Send`", "sent")
                        } else { ("`Sync`", "shared") };
                    err.code = None;
                    err.primary_message(::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("{0} cannot be {1} between threads safely",
                                        future_or_coroutine, trait_verb))
                            }));
                    let original_span = err.span.primary_span().unwrap();
                    let mut span = MultiSpan::from_span(original_span);
                    let message =
                        outer_coroutine.and_then(|coroutine_did|
                                    {
                                        Some(match self.tcx.coroutine_kind(coroutine_did).unwrap() {
                                                CoroutineKind::Coroutine(_) =>
                                                    ::alloc::__export::must_use({
                                                            ::alloc::fmt::format(format_args!("coroutine is not {0}",
                                                                    trait_name))
                                                        }),
                                                CoroutineKind::Desugared(CoroutineDesugaring::Async,
                                                    CoroutineSource::Fn) =>
                                                    self.tcx.parent(coroutine_did).as_local().map(|parent_did|
                                                                        self.tcx.local_def_id_to_hir_id(parent_did)).and_then(|parent_hir_id|
                                                                    self.tcx.hir_opt_name(parent_hir_id)).map(|name|
                                                                {
                                                                    ::alloc::__export::must_use({
                                                                            ::alloc::fmt::format(format_args!("future returned by `{0}` is not {1}",
                                                                                    name, trait_name))
                                                                        })
                                                                })?,
                                                CoroutineKind::Desugared(CoroutineDesugaring::Async,
                                                    CoroutineSource::Block) => {
                                                    ::alloc::__export::must_use({
                                                            ::alloc::fmt::format(format_args!("future created by async block is not {0}",
                                                                    trait_name))
                                                        })
                                                }
                                                CoroutineKind::Desugared(CoroutineDesugaring::Async,
                                                    CoroutineSource::Closure) => {
                                                    ::alloc::__export::must_use({
                                                            ::alloc::fmt::format(format_args!("future created by async closure is not {0}",
                                                                    trait_name))
                                                        })
                                                }
                                                CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen,
                                                    CoroutineSource::Fn) =>
                                                    self.tcx.parent(coroutine_did).as_local().map(|parent_did|
                                                                        self.tcx.local_def_id_to_hir_id(parent_did)).and_then(|parent_hir_id|
                                                                    self.tcx.hir_opt_name(parent_hir_id)).map(|name|
                                                                {
                                                                    ::alloc::__export::must_use({
                                                                            ::alloc::fmt::format(format_args!("async iterator returned by `{0}` is not {1}",
                                                                                    name, trait_name))
                                                                        })
                                                                })?,
                                                CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen,
                                                    CoroutineSource::Block) => {
                                                    ::alloc::__export::must_use({
                                                            ::alloc::fmt::format(format_args!("async iterator created by async gen block is not {0}",
                                                                    trait_name))
                                                        })
                                                }
                                                CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen,
                                                    CoroutineSource::Closure) => {
                                                    ::alloc::__export::must_use({
                                                            ::alloc::fmt::format(format_args!("async iterator created by async gen closure is not {0}",
                                                                    trait_name))
                                                        })
                                                }
                                                CoroutineKind::Desugared(CoroutineDesugaring::Gen,
                                                    CoroutineSource::Fn) => {
                                                    self.tcx.parent(coroutine_did).as_local().map(|parent_did|
                                                                        self.tcx.local_def_id_to_hir_id(parent_did)).and_then(|parent_hir_id|
                                                                    self.tcx.hir_opt_name(parent_hir_id)).map(|name|
                                                                {
                                                                    ::alloc::__export::must_use({
                                                                            ::alloc::fmt::format(format_args!("iterator returned by `{0}` is not {1}",
                                                                                    name, trait_name))
                                                                        })
                                                                })?
                                                }
                                                CoroutineKind::Desugared(CoroutineDesugaring::Gen,
                                                    CoroutineSource::Block) => {
                                                    ::alloc::__export::must_use({
                                                            ::alloc::fmt::format(format_args!("iterator created by gen block is not {0}",
                                                                    trait_name))
                                                        })
                                                }
                                                CoroutineKind::Desugared(CoroutineDesugaring::Gen,
                                                    CoroutineSource::Closure) => {
                                                    ::alloc::__export::must_use({
                                                            ::alloc::fmt::format(format_args!("iterator created by gen closure is not {0}",
                                                                    trait_name))
                                                        })
                                                }
                                            })
                                    }).unwrap_or_else(||
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("{0} is not {1}",
                                                future_or_coroutine, trait_name))
                                    }));
                    span.push_span_label(original_span, message);
                    err.span(span);
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("is not {0}", trait_name))
                        })
                } else {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("does not implement `{0}`",
                                    trait_pred.print_modifiers_and_trait_path()))
                        })
                };
            let mut explain_yield =
                |interior_span: Span, yield_span: Span|
                    {
                        let mut span = MultiSpan::from_span(yield_span);
                        let snippet =
                            match source_map.span_to_snippet(interior_span) {
                                Ok(snippet) if !snippet.contains('\n') =>
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("`{0}`", snippet))
                                        }),
                                _ => "the value".to_string(),
                            };
                        span.push_span_label(yield_span,
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("{0} occurs here, with {1} maybe used later",
                                            await_or_yield, snippet))
                                }));
                        span.push_span_label(interior_span,
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("has type `{0}` which {1}",
                                            target_ty, trait_explanation))
                                }));
                        err.span_note(span,
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("{0} {1} as this value is used across {2}",
                                            future_or_coroutine, trait_explanation, an_await_or_yield))
                                }));
                    };
            match interior_or_upvar_span {
                CoroutineInteriorOrUpvar::Interior(interior_span,
                    interior_extra_info) => {
                    if let Some((yield_span, from_awaited_ty)) =
                            interior_extra_info {
                        if let Some(await_span) = from_awaited_ty {
                            let mut span = MultiSpan::from_span(await_span);
                            span.push_span_label(await_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("await occurs here on type `{0}`, which {1}",
                                                target_ty, trait_explanation))
                                    }));
                            err.span_note(span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("future {0} as it awaits another future which {0}",
                                                trait_explanation))
                                    }));
                        } else { explain_yield(interior_span, yield_span); }
                    }
                }
                CoroutineInteriorOrUpvar::Upvar(upvar_span) => {
                    let non_send =
                        match target_ty.kind() {
                            ty::Ref(_, ref_ty, mutability) =>
                                match self.evaluate_obligation(obligation) {
                                    Ok(eval) if !eval.may_apply() =>
                                        Some((ref_ty, mutability.is_mut())),
                                    _ => None,
                                },
                            _ => None,
                        };
                    let (span_label, span_note) =
                        match non_send {
                            Some((ref_ty, is_mut)) => {
                                let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
                                let ref_kind = if is_mut { "&mut" } else { "&" };
                                (::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("has type `{0}` which {1}, because `{2}` is not `{3}`",
                                                    target_ty, trait_explanation, ref_ty, ref_ty_trait))
                                        }),
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("captured value {0} because `{1}` references cannot be sent unless their referent is `{2}`",
                                                    trait_explanation, ref_kind, ref_ty_trait))
                                        }))
                            }
                            None =>
                                (::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("has type `{0}` which {1}",
                                                    target_ty, trait_explanation))
                                        }),
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("captured value {0}",
                                                    trait_explanation))
                                        })),
                        };
                    let mut span = MultiSpan::from_span(upvar_span);
                    span.push_span_label(upvar_span, span_label);
                    err.span_note(span, span_note);
                }
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3760",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3760u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("next_code")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("next_code");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&next_code)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            self.note_obligation_cause_code(obligation.cause.body_def_id, err,
                obligation.predicate, obligation.param_env,
                next_code.unwrap(), &mut Vec::new(), &mut Default::default());
        }
    }
}#[instrument(level = "debug", skip_all)]
3538    fn note_obligation_cause_for_async_await<G>(
3539        &self,
3540        err: &mut Diag<'_, G>,
3541        interior_or_upvar_span: CoroutineInteriorOrUpvar,
3542        is_async: bool,
3543        outer_coroutine: Option<DefId>,
3544        trait_pred: ty::TraitClause<'tcx>,
3545        target_ty: Ty<'tcx>,
3546        obligation: &PredicateObligation<'tcx>,
3547        next_code: Option<&ObligationCauseCode<'tcx>>,
3548    ) {
3549        let source_map = self.tcx.sess.source_map();
3550
3551        let (await_or_yield, an_await_or_yield) =
3552            if is_async { ("await", "an await") } else { ("yield", "a yield") };
3553        let future_or_coroutine = if is_async { "future" } else { "coroutine" };
3554
3555        // Special case the primary error message when send or sync is the trait that was
3556        // not implemented.
3557        let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
3558            self.tcx.get_diagnostic_name(trait_pred.def_id())
3559        {
3560            let (trait_name, trait_verb) =
3561                if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
3562
3563            err.code = None;
3564            err.primary_message(format!(
3565                "{future_or_coroutine} cannot be {trait_verb} between threads safely"
3566            ));
3567
3568            let original_span = err.span.primary_span().unwrap();
3569            let mut span = MultiSpan::from_span(original_span);
3570
3571            let message = outer_coroutine
3572                .and_then(|coroutine_did| {
3573                    Some(match self.tcx.coroutine_kind(coroutine_did).unwrap() {
3574                        CoroutineKind::Coroutine(_) => format!("coroutine is not {trait_name}"),
3575                        CoroutineKind::Desugared(
3576                            CoroutineDesugaring::Async,
3577                            CoroutineSource::Fn,
3578                        ) => self
3579                            .tcx
3580                            .parent(coroutine_did)
3581                            .as_local()
3582                            .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3583                            .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3584                            .map(|name| {
3585                                format!("future returned by `{name}` is not {trait_name}")
3586                            })?,
3587                        CoroutineKind::Desugared(
3588                            CoroutineDesugaring::Async,
3589                            CoroutineSource::Block,
3590                        ) => {
3591                            format!("future created by async block is not {trait_name}")
3592                        }
3593                        CoroutineKind::Desugared(
3594                            CoroutineDesugaring::Async,
3595                            CoroutineSource::Closure,
3596                        ) => {
3597                            format!("future created by async closure is not {trait_name}")
3598                        }
3599                        CoroutineKind::Desugared(
3600                            CoroutineDesugaring::AsyncGen,
3601                            CoroutineSource::Fn,
3602                        ) => self
3603                            .tcx
3604                            .parent(coroutine_did)
3605                            .as_local()
3606                            .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3607                            .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3608                            .map(|name| {
3609                                format!("async iterator returned by `{name}` is not {trait_name}")
3610                            })?,
3611                        CoroutineKind::Desugared(
3612                            CoroutineDesugaring::AsyncGen,
3613                            CoroutineSource::Block,
3614                        ) => {
3615                            format!("async iterator created by async gen block is not {trait_name}")
3616                        }
3617                        CoroutineKind::Desugared(
3618                            CoroutineDesugaring::AsyncGen,
3619                            CoroutineSource::Closure,
3620                        ) => {
3621                            format!(
3622                                "async iterator created by async gen closure is not {trait_name}"
3623                            )
3624                        }
3625                        CoroutineKind::Desugared(CoroutineDesugaring::Gen, CoroutineSource::Fn) => {
3626                            self.tcx
3627                                .parent(coroutine_did)
3628                                .as_local()
3629                                .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3630                                .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3631                                .map(|name| {
3632                                    format!("iterator returned by `{name}` is not {trait_name}")
3633                                })?
3634                        }
3635                        CoroutineKind::Desugared(
3636                            CoroutineDesugaring::Gen,
3637                            CoroutineSource::Block,
3638                        ) => {
3639                            format!("iterator created by gen block is not {trait_name}")
3640                        }
3641                        CoroutineKind::Desugared(
3642                            CoroutineDesugaring::Gen,
3643                            CoroutineSource::Closure,
3644                        ) => {
3645                            format!("iterator created by gen closure is not {trait_name}")
3646                        }
3647                    })
3648                })
3649                .unwrap_or_else(|| format!("{future_or_coroutine} is not {trait_name}"));
3650
3651            span.push_span_label(original_span, message);
3652            err.span(span);
3653
3654            format!("is not {trait_name}")
3655        } else {
3656            format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
3657        };
3658
3659        let mut explain_yield = |interior_span: Span, yield_span: Span| {
3660            let mut span = MultiSpan::from_span(yield_span);
3661            let snippet = match source_map.span_to_snippet(interior_span) {
3662                // #70935: If snippet contains newlines, display "the value" instead
3663                // so that we do not emit complex diagnostics.
3664                Ok(snippet) if !snippet.contains('\n') => format!("`{snippet}`"),
3665                _ => "the value".to_string(),
3666            };
3667            // note: future is not `Send` as this value is used across an await
3668            //   --> $DIR/issue-70935-complex-spans.rs:13:9
3669            //    |
3670            // LL |            baz(|| async {
3671            //    |  ______________-
3672            //    | |
3673            //    | |
3674            // LL | |              foo(tx.clone());
3675            // LL | |          }).await;
3676            //    | |          - ^^^^^^ await occurs here, with value maybe used later
3677            //    | |__________|
3678            //    |            has type `closure` which is not `Send`
3679            // note: value is later dropped here
3680            // LL | |          }).await;
3681            //    | |                  ^
3682            //
3683            span.push_span_label(
3684                yield_span,
3685                format!("{await_or_yield} occurs here, with {snippet} maybe used later"),
3686            );
3687            span.push_span_label(
3688                interior_span,
3689                format!("has type `{target_ty}` which {trait_explanation}"),
3690            );
3691            err.span_note(
3692                span,
3693                format!("{future_or_coroutine} {trait_explanation} as this value is used across {an_await_or_yield}"),
3694            );
3695        };
3696        match interior_or_upvar_span {
3697            CoroutineInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
3698                if let Some((yield_span, from_awaited_ty)) = interior_extra_info {
3699                    if let Some(await_span) = from_awaited_ty {
3700                        // The type causing this obligation is one being awaited at await_span.
3701                        let mut span = MultiSpan::from_span(await_span);
3702                        span.push_span_label(
3703                            await_span,
3704                            format!(
3705                                "await occurs here on type `{target_ty}`, which {trait_explanation}"
3706                            ),
3707                        );
3708                        err.span_note(
3709                            span,
3710                            format!(
3711                                "future {trait_explanation} as it awaits another future which {trait_explanation}"
3712                            ),
3713                        );
3714                    } else {
3715                        // Look at the last interior type to get a span for the `.await`.
3716                        explain_yield(interior_span, yield_span);
3717                    }
3718                }
3719            }
3720            CoroutineInteriorOrUpvar::Upvar(upvar_span) => {
3721                // `Some((ref_ty, is_mut))` if `target_ty` is `&T` or `&mut T` and fails to impl `Send`
3722                let non_send = match target_ty.kind() {
3723                    ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(obligation) {
3724                        Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
3725                        _ => None,
3726                    },
3727                    _ => None,
3728                };
3729
3730                let (span_label, span_note) = match non_send {
3731                    // if `target_ty` is `&T` or `&mut T` and fails to impl `Send`,
3732                    // include suggestions to make `T: Sync` so that `&T: Send`,
3733                    // or to make `T: Send` so that `&mut T: Send`
3734                    Some((ref_ty, is_mut)) => {
3735                        let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
3736                        let ref_kind = if is_mut { "&mut" } else { "&" };
3737                        (
3738                            format!(
3739                                "has type `{target_ty}` which {trait_explanation}, because `{ref_ty}` is not `{ref_ty_trait}`"
3740                            ),
3741                            format!(
3742                                "captured value {trait_explanation} because `{ref_kind}` references cannot be sent unless their referent is `{ref_ty_trait}`"
3743                            ),
3744                        )
3745                    }
3746                    None => (
3747                        format!("has type `{target_ty}` which {trait_explanation}"),
3748                        format!("captured value {trait_explanation}"),
3749                    ),
3750                };
3751
3752                let mut span = MultiSpan::from_span(upvar_span);
3753                span.push_span_label(upvar_span, span_label);
3754                err.span_note(span, span_note);
3755            }
3756        }
3757
3758        // Add a note for the item obligation that remains - normally a note pointing to the
3759        // bound that introduced the obligation (e.g. `T: Send`).
3760        debug!(?next_code);
3761        self.note_obligation_cause_code(
3762            obligation.cause.body_def_id,
3763            err,
3764            obligation.predicate,
3765            obligation.param_env,
3766            next_code.unwrap(),
3767            &mut Vec::new(),
3768            &mut Default::default(),
3769        );
3770    }
3771
3772    fn note_closure_capture<G>(
3773        &self,
3774        err: &mut Diag<'_, G>,
3775        closure_def_id: DefId,
3776        upvar_args: ty::UpvarArgs<'tcx>,
3777        capture_ty: Option<Ty<'tcx>>,
3778    ) -> bool {
3779        let Some(closure_def_id) = closure_def_id.as_local() else {
3780            return false;
3781        };
3782        let Some(capture_ty) = capture_ty else {
3783            return false;
3784        };
3785
3786        // This can run while `typeck` for the closure's root is still on the query stack, for
3787        // example when reporting an overflow from inside trait selection, so only the in-progress
3788        // results are safe to look at. Asking for the captures through `tcx.closure_captures`
3789        // would call `typeck` again and replace the error being reported with a cycle error.
3790        let Some(typeck_results) = &self.typeck_results else {
3791            return false;
3792        };
3793        let typeck_root = self.tcx.typeck_root_def_id(closure_def_id.to_def_id());
3794        if typeck_results.hir_owner.to_def_id() != typeck_root {
3795            return false;
3796        }
3797        let captures: Vec<_> =
3798            typeck_results.closure_min_captures_flattened(closure_def_id).collect();
3799        let upvar_tys = upvar_args.upvar_tys();
3800        if captures.len() != upvar_tys.len() {
3801            return false;
3802        }
3803
3804        let capture_ty =
3805            self.tcx.erase_and_anonymize_regions(self.deeply_resolve_ignoring_regions(capture_ty));
3806        let Some(capture) = captures.iter().zip(upvar_tys).find_map(|(&capture, upvar_ty)| {
3807            let upvar_ty = self
3808                .tcx
3809                .erase_and_anonymize_regions(self.deeply_resolve_ignoring_regions(upvar_ty));
3810            (upvar_ty == capture_ty).then_some(capture)
3811        }) else {
3812            return false;
3813        };
3814
3815        err.span_note(
3816            capture.get_path_span(self.tcx),
3817            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required because `{0}` is used within this closure",
                capture.to_string(self.tcx)))
    })format!(
3818                "required because `{}` is used within this closure",
3819                capture.to_string(self.tcx)
3820            ),
3821        );
3822        true
3823    }
3824
3825    pub(super) fn note_obligation_cause_code<G, T>(
3826        &self,
3827        body_def_id: LocalDefId,
3828        err: &mut Diag<'_, G>,
3829        predicate: T,
3830        param_env: ty::ParamEnv<'tcx>,
3831        cause_code: &ObligationCauseCode<'tcx>,
3832        obligated_types: &mut Vec<Ty<'tcx>>,
3833        seen_requirements: &mut FxHashSet<DefId>,
3834    ) where
3835        T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
3836    {
3837        let predicate = predicate.upcast(self.tcx);
3838        // Built-in closure obligations pass through a synthetic tuple of upvar types. Remember
3839        // the last constituent before that tuple so it can be matched to a captured place.
3840        let mut closure_capture_ty =
3841            predicate.as_trait_clause().map(|trait_pred| trait_pred.skip_binder().self_ty());
3842        self.note_obligation_cause_code_inner(
3843            body_def_id,
3844            err,
3845            predicate,
3846            param_env,
3847            cause_code,
3848            obligated_types,
3849            seen_requirements,
3850            &mut closure_capture_ty,
3851        );
3852    }
3853
3854    fn note_obligation_cause_code_inner<G, T>(
3855        &self,
3856        body_def_id: LocalDefId,
3857        err: &mut Diag<'_, G>,
3858        predicate: T,
3859        param_env: ty::ParamEnv<'tcx>,
3860        cause_code: &ObligationCauseCode<'tcx>,
3861        obligated_types: &mut Vec<Ty<'tcx>>,
3862        seen_requirements: &mut FxHashSet<DefId>,
3863        closure_capture_ty: &mut Option<Ty<'tcx>>,
3864    ) where
3865        T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
3866    {
3867        let tcx = self.tcx;
3868        let predicate = predicate.upcast(tcx);
3869        let suggest_remove_deref = |err: &mut Diag<'_, G>, expr: &hir::Expr<'_>| {
3870            if let Some(pred) = predicate.as_trait_clause()
3871                && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
3872                && let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind
3873            {
3874                err.span_suggestion_verbose(
3875                    expr.span.until(inner.span),
3876                    "references are always `Sized`, even if they point to unsized data; consider \
3877                     not dereferencing the expression",
3878                    String::new(),
3879                    Applicability::MaybeIncorrect,
3880                );
3881            }
3882        };
3883        match *cause_code {
3884            ObligationCauseCode::ExprAssignable
3885            | ObligationCauseCode::MatchExpressionArm { .. }
3886            | ObligationCauseCode::Pattern { .. }
3887            | ObligationCauseCode::IfExpression { .. }
3888            | ObligationCauseCode::IfExpressionWithNoElse
3889            | ObligationCauseCode::MainFunctionType
3890            | ObligationCauseCode::LangFunctionType(_)
3891            | ObligationCauseCode::IntrinsicType
3892            | ObligationCauseCode::MethodReceiver
3893            | ObligationCauseCode::ReturnNoExpression
3894            | ObligationCauseCode::Misc
3895            | ObligationCauseCode::WellFormed(..)
3896            | ObligationCauseCode::MatchImpl(..)
3897            | ObligationCauseCode::ReturnValue(_)
3898            | ObligationCauseCode::BlockTailExpression(..)
3899            | ObligationCauseCode::AwaitableExpr(_)
3900            | ObligationCauseCode::ForLoopIterator(_)
3901            | ObligationCauseCode::QuestionMark
3902            | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
3903            | ObligationCauseCode::LetElse
3904            | ObligationCauseCode::UnOp { .. }
3905            | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
3906            | ObligationCauseCode::AlwaysApplicableImpl
3907            | ObligationCauseCode::ConstParam(_)
3908            | ObligationCauseCode::ReferenceOutlivesReferent(..)
3909            | ObligationCauseCode::ObjectTypeBound(..) => {}
3910            ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. } => {
3911                if let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
3912                    && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
3913                    && tcx.sess.source_map().lookup_char_pos(lhs.span.lo()).line
3914                        != tcx.sess.source_map().lookup_char_pos(rhs.span.hi()).line
3915                {
3916                    err.span_label(lhs.span, "");
3917                    err.span_label(rhs.span, "");
3918                }
3919            }
3920            ObligationCauseCode::RustCall => {
3921                if let Some(pred) = predicate.as_trait_clause()
3922                    && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
3923                {
3924                    err.note("argument required to be sized due to `extern \"rust-call\"` ABI");
3925                }
3926            }
3927            ObligationCauseCode::SliceOrArrayElem => {
3928                err.note("slice and array elements must have `Sized` type");
3929            }
3930            ObligationCauseCode::ArrayLen(array_ty) => {
3931                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`"));
3932            }
3933            ObligationCauseCode::TupleElem => {
3934                err.note("only the last element of a tuple may have a dynamically sized type");
3935            }
3936            ObligationCauseCode::DynCompatible(span) => {
3937                err.multipart_suggestion(
3938                    "you might have meant to use `Self` to refer to the implementing type",
3939                    ::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())],
3940                    Applicability::MachineApplicable,
3941                );
3942            }
3943            ObligationCauseCode::WhereClause(item_def_id, span)
3944            | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)
3945            | ObligationCauseCode::HostEffectInExpr(item_def_id, span, ..)
3946                if !span.is_dummy() =>
3947            {
3948                if let ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, pos) = &cause_code {
3949                    if let Node::Expr(expr) = tcx.parent_hir_node(*hir_id)
3950                        && let hir::ExprKind::Call(_, args) = expr.kind
3951                        && let Some(expr) = args.get(*pos)
3952                    {
3953                        suggest_remove_deref(err, &expr);
3954                    } else if let Node::Expr(expr) = self.tcx.hir_node(*hir_id)
3955                        && let hir::ExprKind::MethodCall(_, _, args, _) = expr.kind
3956                        && let Some(expr) = args.get(*pos)
3957                    {
3958                        suggest_remove_deref(err, &expr);
3959                    }
3960                }
3961                let item_name = tcx.def_path_str(item_def_id);
3962                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));
3963                let mut multispan = MultiSpan::from(span);
3964                let sm = tcx.sess.source_map();
3965                if let Some(ident) = tcx.opt_item_ident(item_def_id) {
3966                    let same_line =
3967                        match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
3968                            (Ok(l), Ok(r)) => l.line == r.line,
3969                            _ => true,
3970                        };
3971                    if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
3972                        multispan.push_span_label(
3973                            ident.span,
3974                            ::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!(
3975                                "required by a bound in this {}",
3976                                tcx.def_kind(item_def_id).descr(item_def_id)
3977                            ),
3978                        );
3979                    }
3980                }
3981                let mut a = "a";
3982                let mut this = "this bound";
3983                let mut note = None;
3984                let mut help = None;
3985                if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() {
3986                    match clause {
3987                        ty::ClauseKind::Trait(trait_pred) => {
3988                            let def_id = trait_pred.def_id();
3989                            let visible_item = if let Some(local) = def_id.as_local() {
3990                                let ty = trait_pred.self_ty();
3991                                // when `TraitA: TraitB` and `S` only impl TraitA,
3992                                // we check if `TraitB` can be reachable from `S`
3993                                // to determine whether to note `TraitA` is sealed trait.
3994                                if let ty::Adt(adt, _) = ty.kind() {
3995                                    let visibilities = &tcx.resolutions(()).effective_visibilities;
3996                                    visibilities.effective_vis(local).is_none_or(|v| {
3997                                        v.at_level(Level::Reexported)
3998                                            .is_accessible_from(adt.did(), tcx)
3999                                    })
4000                                } else {
4001                                    // FIXME(xizheyin): if the type is not ADT, we should not suggest it
4002                                    true
4003                                }
4004                            } else {
4005                                // Check for foreign traits being reachable.
4006                                tcx.visible_parent_map(()).get(&def_id).is_some()
4007                            };
4008                            if tcx.is_lang_item(def_id, LangItem::Sized) {
4009                                // Check if this is an implicit bound, even in foreign crates.
4010                                if tcx
4011                                    .generics_of(item_def_id)
4012                                    .own_params
4013                                    .iter()
4014                                    .any(|param| tcx.def_span(param.def_id) == span)
4015                                {
4016                                    a = "an implicit `Sized`";
4017                                    this =
4018                                        "the implicit `Sized` requirement on this type parameter";
4019                                }
4020                                if let Some(hir::Node::TraitItem(hir::TraitItem {
4021                                    generics,
4022                                    kind: hir::TraitItemKind::Type(bounds, None),
4023                                    ..
4024                                })) = tcx.hir_get_if_local(item_def_id)
4025                                    // Do not suggest relaxing if there is an explicit `Sized` obligation.
4026                                    && !bounds.iter()
4027                                        .filter_map(|bound| bound.trait_ref())
4028                                        .any(|tr| tr.trait_def_id().is_some_and(|def_id| tcx.is_lang_item(def_id, LangItem::Sized)))
4029                                {
4030                                    let (span, separator) = if let [.., last] = bounds {
4031                                        (last.span().shrink_to_hi(), " +")
4032                                    } else {
4033                                        (generics.span.shrink_to_hi(), ":")
4034                                    };
4035                                    err.span_suggestion_verbose(
4036                                        span,
4037                                        "consider relaxing the implicit `Sized` restriction",
4038                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ?Sized", separator))
    })format!("{separator} ?Sized"),
4039                                        Applicability::MachineApplicable,
4040                                    );
4041                                }
4042                            }
4043                            if let DefKind::Trait = tcx.def_kind(item_def_id)
4044                                && !visible_item
4045                            {
4046                                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!(
4047                                    "`{short_item_name}` is a \"sealed trait\", because to implement it \
4048                                    you also need to implement `{}`, which is not accessible; this is \
4049                                    usually done to force you to use one of the provided types that \
4050                                    already implement it",
4051                                    with_no_trimmed_paths!(tcx.def_path_str(def_id)),
4052                                ));
4053                                let mut types = tcx
4054                                    .all_impls(def_id)
4055                                    .map(|t| {
4056                                        {
    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!(
4057                                            "  {}",
4058                                            tcx.type_of(t).instantiate_identity().skip_norm_wip(),
4059                                        ))
4060                                    })
4061                                    .collect::<Vec<_>>();
4062                                if !types.is_empty() {
4063                                    let len = types.len();
4064                                    let post = if len > 9 {
4065                                        types.truncate(8);
4066                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\nand {0} others", len - 8))
    })format!("\nand {} others", len - 8)
4067                                    } else {
4068                                        String::new()
4069                                    };
4070                                    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!(
4071                                        "the following type{} implement{} the trait:\n{}{post}",
4072                                        pluralize!(len),
4073                                        if len == 1 { "s" } else { "" },
4074                                        types.join("\n"),
4075                                    ));
4076                                }
4077                            }
4078                        }
4079                        ty::ClauseKind::ConstArgHasType(..) => {
4080                            let descr =
4081                                ::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}`");
4082                            if span.is_visible(sm) {
4083                                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required by this const generic parameter in `{0}`",
                short_item_name))
    })format!(
4084                                    "required by this const generic parameter in `{short_item_name}`"
4085                                );
4086                                multispan.push_span_label(span, msg);
4087                                err.span_note(multispan, descr);
4088                            } else {
4089                                err.span_note(tcx.def_span(item_def_id), descr);
4090                            }
4091                            return;
4092                        }
4093                        _ => (),
4094                    }
4095                }
4096
4097                // If this is from a format string literal desugaring,
4098                // we've already said "required by this formatting parameter"
4099                let is_in_fmt_lit = if let Some(s) = err.span.primary_span() {
4100                    #[allow(non_exhaustive_omitted_patterns)] match s.desugaring_kind() {
    Some(DesugaringKind::FormatLiteral { .. }) => true,
    _ => false,
}matches!(s.desugaring_kind(), Some(DesugaringKind::FormatLiteral { .. }))
4101                } else {
4102                    false
4103                };
4104                if !is_in_fmt_lit {
4105                    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}`");
4106                    if span.is_visible(sm) {
4107                        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}`");
4108                        multispan.push_span_label(span, msg);
4109                        err.span_note(multispan, descr);
4110                    } else {
4111                        err.span_note(tcx.def_span(item_def_id), descr);
4112                    }
4113                }
4114                if let Some(note) = note {
4115                    err.note(note);
4116                }
4117                if let Some(help) = help {
4118                    err.help(help);
4119                }
4120            }
4121            ObligationCauseCode::WhereClause(..)
4122            | ObligationCauseCode::WhereClauseInExpr(..)
4123            | ObligationCauseCode::HostEffectInExpr(..) => {
4124                // We hold the `DefId` of the item introducing the obligation, but displaying it
4125                // doesn't add user usable information. It always point at an associated item.
4126            }
4127            ObligationCauseCode::OpaqueTypeBound(span, definition_def_id) => {
4128                err.span_note(span, "required by a bound in an opaque type");
4129                if let Some(definition_def_id) = definition_def_id
4130                    // If there are any stalled coroutine obligations, then this
4131                    // error may be due to that, and not because the body has more
4132                    // where-clauses.
4133                    && self.tcx.typeck(definition_def_id).coroutine_stalled_predicates.is_empty()
4134                {
4135                    // FIXME(compiler-errors): We could probably point to something
4136                    // specific here if we tried hard enough...
4137                    err.span_note(
4138                        tcx.def_span(definition_def_id),
4139                        "this definition site has more where clauses than the opaque type",
4140                    );
4141                }
4142            }
4143            ObligationCauseCode::Coercion { source, target } => {
4144                let source = tcx
4145                    .short_string(self.deeply_resolve_ignoring_regions(source), err.long_ty_path());
4146                let target = tcx
4147                    .short_string(self.deeply_resolve_ignoring_regions(target), err.long_ty_path());
4148                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!(
4149                    "required for the cast from `{source}` to `{target}`",
4150                )));
4151            }
4152            ObligationCauseCode::RepeatElementCopy { is_constable, elt_span } => {
4153                err.note(
4154                    "the `Copy` trait is required because this value will be copied for each element of the array",
4155                );
4156                let sm = tcx.sess.source_map();
4157                if #[allow(non_exhaustive_omitted_patterns)] match is_constable {
    IsConstable::Fn | IsConstable::Ctor => true,
    _ => false,
}matches!(is_constable, IsConstable::Fn | IsConstable::Ctor)
4158                    && let Ok(_) = sm.span_to_snippet(elt_span)
4159                {
4160                    err.multipart_suggestion(
4161                        "create an inline `const` block",
4162                        ::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![
4163                            (elt_span.shrink_to_lo(), "const { ".to_string()),
4164                            (elt_span.shrink_to_hi(), " }".to_string()),
4165                        ],
4166                        Applicability::MachineApplicable,
4167                    );
4168                } else {
4169                    // FIXME: we may suggest array::repeat instead
4170                    err.help("consider using `core::array::from_fn` to initialize the array");
4171                    err.help("see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html for more information");
4172                }
4173            }
4174            ObligationCauseCode::VariableType(hir_id) => {
4175                if let Some(typeck_results) = &self.typeck_results
4176                    && let Some(ty) = typeck_results.node_type_opt(hir_id)
4177                    && let ty::Error(_) = ty.kind()
4178                {
4179                    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!(
4180                        "`{predicate}` isn't satisfied, but the type of this pattern is \
4181                         `{{type error}}`",
4182                    ));
4183                    err.downgrade_to_delayed_bug();
4184                }
4185                let mut local = true;
4186                match tcx.parent_hir_node(hir_id) {
4187                    Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }) => {
4188                        err.span_suggestion_verbose(
4189                            ty.span.shrink_to_lo(),
4190                            "consider borrowing here",
4191                            "&",
4192                            Applicability::MachineApplicable,
4193                        );
4194                    }
4195                    Node::LetStmt(hir::LetStmt {
4196                        init: Some(hir::Expr { kind: hir::ExprKind::Index(..), span, .. }),
4197                        ..
4198                    }) => {
4199                        // When encountering an assignment of an unsized trait, like
4200                        // `let x = ""[..];`, provide a suggestion to borrow the initializer in
4201                        // order to use have a slice instead.
4202                        err.span_suggestion_verbose(
4203                            span.shrink_to_lo(),
4204                            "consider borrowing here",
4205                            "&",
4206                            Applicability::MachineApplicable,
4207                        );
4208                    }
4209                    Node::LetStmt(hir::LetStmt { init: Some(expr), .. }) => {
4210                        // When encountering an assignment of an unsized trait, like `let x = *"";`,
4211                        // we check if the RHS is a deref operation, to suggest removing it.
4212                        suggest_remove_deref(err, &expr);
4213                    }
4214                    Node::Param(param) => {
4215                        err.span_suggestion_verbose(
4216                            param.ty_span.shrink_to_lo(),
4217                            "function arguments must have a statically known size, borrowed types \
4218                            always have a known size",
4219                            "&",
4220                            Applicability::MachineApplicable,
4221                        );
4222                        local = false;
4223                    }
4224                    _ => {}
4225                }
4226                if local {
4227                    err.note("all local variables must have a statically known size");
4228                }
4229            }
4230            ObligationCauseCode::SizedArgumentType(hir_id) => {
4231                let mut ty = None;
4232                let borrowed_msg = "function arguments must have a statically known size, borrowed \
4233                                    types always have a known size";
4234                if let Some(hir_id) = hir_id
4235                    && let hir::Node::Param(param) = self.tcx.hir_node(hir_id)
4236                    && let Some(decl) = self.tcx.parent_hir_node(hir_id).fn_decl()
4237                    && let Some(t) = decl.inputs.iter().find(|t| param.ty_span.contains(t.span))
4238                {
4239                    // We use `contains` because the type might be surrounded by parentheses,
4240                    // which makes `ty_span` and `t.span` disagree with each other, but one
4241                    // fully contains the other: `foo: (dyn Foo + Bar)`
4242                    //                                 ^-------------^
4243                    //                                 ||
4244                    //                                 |t.span
4245                    //                                 param._ty_span
4246                    ty = Some(t);
4247                } else if let Some(hir_id) = hir_id
4248                    && let hir::Node::Ty(t) = self.tcx.hir_node(hir_id)
4249                {
4250                    ty = Some(t);
4251                }
4252                if let Some(ty) = ty {
4253                    match ty.kind {
4254                        hir::TyKind::TraitObject(traits, _) => {
4255                            let (span, kw) = match traits {
4256                                [first, ..] if first.span.lo() == ty.span.lo() => {
4257                                    // Missing `dyn` in front of trait object.
4258                                    (ty.span.shrink_to_lo(), "dyn ")
4259                                }
4260                                [first, ..] => (ty.span.until(first.span), ""),
4261                                [] => bug_impl(Some(ty.span),
    format_args!("trait object with no traits: {0:?}", ty),
    Location::caller())span_bug!(ty.span, "trait object with no traits: {ty:?}"),
4262                            };
4263                            let needs_parens = traits.len() != 1;
4264                            // Don't recommend impl Trait as a closure argument
4265                            if let Some(hir_id) = hir_id
4266                                && #[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!(
4267                                    self.tcx.parent_hir_node(hir_id),
4268                                    hir::Node::Item(hir::Item {
4269                                        kind: hir::ItemKind::Fn { .. },
4270                                        ..
4271                                    })
4272                                )
4273                            {
4274                                err.span_suggestion_verbose(
4275                                    span,
4276                                    "you can use `impl Trait` as the argument type",
4277                                    "impl ",
4278                                    Applicability::MaybeIncorrect,
4279                                );
4280                            }
4281                            let sugg = if !needs_parens {
4282                                ::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}"))]
4283                            } else {
4284                                ::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![
4285                                    (span.shrink_to_lo(), format!("&({kw}")),
4286                                    (ty.span.shrink_to_hi(), ")".to_string()),
4287                                ]
4288                            };
4289                            err.multipart_suggestion(
4290                                borrowed_msg,
4291                                sugg,
4292                                Applicability::MachineApplicable,
4293                            );
4294                        }
4295                        hir::TyKind::Slice(_ty) => {
4296                            err.span_suggestion_verbose(
4297                                ty.span.shrink_to_lo(),
4298                                "function arguments must have a statically known size, borrowed \
4299                                 slices always have a known size",
4300                                "&",
4301                                Applicability::MachineApplicable,
4302                            );
4303                        }
4304                        hir::TyKind::Path(_) => {
4305                            err.span_suggestion_verbose(
4306                                ty.span.shrink_to_lo(),
4307                                borrowed_msg,
4308                                "&",
4309                                Applicability::MachineApplicable,
4310                            );
4311                        }
4312                        _ => {}
4313                    }
4314                } else {
4315                    err.note("all function arguments must have a statically known size");
4316                }
4317                if tcx.sess.opts.unstable_features.is_nightly_build()
4318                    && !tcx.features().unsized_fn_params()
4319                {
4320                    err.help("unsized fn params are gated as an unstable feature");
4321                }
4322            }
4323            ObligationCauseCode::SizedReturnType | ObligationCauseCode::SizedCallReturnType => {
4324                err.note("the return type of a function must have a statically known size");
4325            }
4326            ObligationCauseCode::SizedYieldType => {
4327                err.note("the yield type of a coroutine must have a statically known size");
4328            }
4329            ObligationCauseCode::AssignmentLhsSized => {
4330                err.note("the left-hand-side of an assignment must have a statically known size");
4331            }
4332            ObligationCauseCode::TupleInitializerSized => {
4333                err.note("tuples must have a statically known size to be initialized");
4334            }
4335            ObligationCauseCode::StructInitializerSized => {
4336                err.note("structs must have a statically known size to be initialized");
4337            }
4338            ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
4339                match *item {
4340                    AdtKind::Struct => {
4341                        if last {
4342                            err.note(
4343                                "the last field of a packed struct may only have a \
4344                                dynamically sized type if it does not need drop to be run",
4345                            );
4346                        } else {
4347                            err.note(
4348                                "only the last field of a struct may have a dynamically sized type",
4349                            );
4350                        }
4351                    }
4352                    AdtKind::Union => {
4353                        err.note("no field of a union may have a dynamically sized type");
4354                    }
4355                    AdtKind::Enum => {
4356                        err.note("no field of an enum variant may have a dynamically sized type");
4357                    }
4358                }
4359                err.help("change the field's type to have a statically known size");
4360                err.span_suggestion_verbose(
4361                    span.shrink_to_lo(),
4362                    "borrowed types always have a statically known size",
4363                    "&",
4364                    Applicability::MachineApplicable,
4365                );
4366                err.multipart_suggestion(
4367                    "the `Box` type always has a statically known size and allocates its contents \
4368                     in the heap",
4369                    ::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![
4370                        (span.shrink_to_lo(), "Box<".to_string()),
4371                        (span.shrink_to_hi(), ">".to_string()),
4372                    ],
4373                    Applicability::MachineApplicable,
4374                );
4375            }
4376            ObligationCauseCode::SizedConstOrStatic => {
4377                err.note("statics and constants must have a statically known size");
4378            }
4379            ObligationCauseCode::InlineAsmSized => {
4380                err.note("all inline asm arguments must have a statically known size");
4381            }
4382            ObligationCauseCode::SizedClosureCapture(closure_def_id) => {
4383                err.note(
4384                    "all values captured by value by a closure must have a statically known size",
4385                );
4386                let hir::ExprKind::Closure(closure) =
4387                    tcx.hir_node_by_def_id(closure_def_id).expect_expr().kind
4388                else {
4389                    bug_impl(None,
    format_args!("expected closure in SizedClosureCapture obligation"),
    Location::caller());bug!("expected closure in SizedClosureCapture obligation");
4390                };
4391                if let hir::CaptureBy::Value { .. } = closure.capture_clause
4392                    && let Some(span) = closure.fn_arg_span
4393                {
4394                    err.span_label(span, "this closure captures all values by move");
4395                }
4396            }
4397            ObligationCauseCode::SizedCoroutineInterior(coroutine_def_id) => {
4398                let what = match tcx.coroutine_kind(coroutine_def_id) {
4399                    None
4400                    | Some(hir::CoroutineKind::Coroutine(_))
4401                    | Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)) => {
4402                        "yield"
4403                    }
4404                    Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
4405                        "await"
4406                    }
4407                    Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => {
4408                        "yield`/`await"
4409                    }
4410                };
4411                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("all values live across `{0}` must have a statically known size",
                what))
    })format!(
4412                    "all values live across `{what}` must have a statically known size"
4413                ));
4414            }
4415            ObligationCauseCode::SharedStatic => {
4416                err.note("shared static variables must have a type that implements `Sync`");
4417            }
4418            ObligationCauseCode::BuiltinDerived(ref data) => {
4419                let parent_trait_ref = self.deeply_resolve_ignoring_regions(data.parent_trait_pred);
4420                let ty = parent_trait_ref.skip_binder().self_ty();
4421                if parent_trait_ref.references_error() {
4422                    // NOTE(eddyb) this was `.cancel()`, but `err`
4423                    // is borrowed, so we can't fully defuse it.
4424                    err.downgrade_to_delayed_bug();
4425                    return;
4426                }
4427
4428                // If the obligation for a tuple is set directly by a Coroutine or Closure,
4429                // then the tuple must be the one containing capture types.
4430                let is_upvar_tys_infer_tuple = if !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Tuple(..) => true,
    _ => false,
}matches!(ty.kind(), ty::Tuple(..)) {
4431                    false
4432                } else if let ObligationCauseCode::BuiltinDerived(data) = &*data.parent_code {
4433                    let parent_trait_ref =
4434                        self.deeply_resolve_ignoring_regions(data.parent_trait_pred);
4435                    let nested_ty = parent_trait_ref.skip_binder().self_ty();
4436                    #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
    ty::Coroutine(..) => true,
    _ => false,
}matches!(nested_ty.kind(), ty::Coroutine(..))
4437                        || #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
    ty::Closure(..) => true,
    _ => false,
}matches!(nested_ty.kind(), ty::Closure(..))
4438                        || #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
    ty::CoroutineClosure(..) => true,
    _ => false,
}matches!(nested_ty.kind(), ty::CoroutineClosure(..))
4439                } else {
4440                    false
4441                };
4442
4443                let is_builtin_async_fn_trait =
4444                    tcx.async_fn_trait_kind_from_def_id(data.parent_trait_pred.def_id()).is_some();
4445
4446                if !is_upvar_tys_infer_tuple && !is_builtin_async_fn_trait {
4447                    let mut msg = || {
4448                        let ty_str = tcx.short_string(ty, err.long_ty_path());
4449                        ::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}`")
4450                    };
4451                    match *ty.kind() {
4452                        ty::Adt(def, _) => {
4453                            let msg = msg();
4454                            match tcx.opt_item_ident(def.did()) {
4455                                Some(ident) => {
4456                                    err.span_note(ident.span, msg);
4457                                }
4458                                None => {
4459                                    err.note(msg);
4460                                }
4461                            }
4462                        }
4463                        ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) => {
4464                            // If the previous type is async fn, this is the future generated by the body of an async function.
4465                            // Avoid printing it twice (it was already printed in the `ty::Coroutine` arm below).
4466                            let is_future = tcx.ty_is_opaque_future(ty);
4467                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:4467",
                        "rustc_trait_selection::error_reporting::traits::suggestions",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                        ::tracing_core::__macro_support::Option::Some(4467u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("obligated_types")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("obligated_types");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("is_future")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("is_future");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("note_obligation_cause_code: check for async fn")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligated_types)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&is_future)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
4468                                ?obligated_types,
4469                                ?is_future,
4470                                "note_obligation_cause_code: check for async fn"
4471                            );
4472                            if is_future
4473                                && obligated_types.last().is_some_and(|ty| match ty.kind() {
4474                                    ty::Coroutine(last_def_id, ..) => {
4475                                        tcx.coroutine_is_async(*last_def_id)
4476                                    }
4477                                    _ => false,
4478                                })
4479                            {
4480                                // See comment above; skip printing twice.
4481                            } else {
4482                                let msg = msg();
4483                                err.span_note(tcx.def_span(def_id), msg);
4484                            }
4485                        }
4486                        ty::Coroutine(def_id, _) => {
4487                            let sp = tcx.def_span(def_id);
4488
4489                            // Special-case this to say "async block" instead of `[static coroutine]`.
4490                            let kind = tcx.coroutine_kind(def_id).unwrap();
4491                            err.span_note(
4492                                sp,
4493                                {
    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!(
4494                                    "required because it's used within this {kind:#}",
4495                                )),
4496                            );
4497                        }
4498                        ty::CoroutineWitness(..) => {
4499                            // Skip printing coroutine-witnesses, since we'll drill into
4500                            // the bad field in another derived obligation cause.
4501                        }
4502                        ty::Closure(def_id, args) => {
4503                            if !self.note_closure_capture(
4504                                err,
4505                                def_id,
4506                                ty::UpvarArgs::Closure(args),
4507                                *closure_capture_ty,
4508                            ) {
4509                                err.span_note(
4510                                    tcx.def_span(def_id),
4511                                    "required because it's used within this closure",
4512                                );
4513                            }
4514                        }
4515                        ty::CoroutineClosure(def_id, args) => {
4516                            if !self.note_closure_capture(
4517                                err,
4518                                def_id,
4519                                ty::UpvarArgs::CoroutineClosure(args),
4520                                *closure_capture_ty,
4521                            ) {
4522                                err.span_note(
4523                                    tcx.def_span(def_id),
4524                                    "required because it's used within this closure",
4525                                );
4526                            }
4527                        }
4528                        ty::Str => {
4529                            err.note("`str` is considered to contain a `[u8]` slice for auto trait purposes");
4530                        }
4531                        _ => {
4532                            let msg = msg();
4533                            err.note(msg);
4534                        }
4535                    };
4536                }
4537
4538                if !is_upvar_tys_infer_tuple {
4539                    *closure_capture_ty = Some(ty);
4540                }
4541
4542                obligated_types.push(ty);
4543
4544                let parent_predicate = parent_trait_ref;
4545                if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
4546                    self.note_obligation_cause_code_inner(
4547                        body_def_id,
4548                        err,
4549                        parent_predicate,
4550                        param_env,
4551                        &data.parent_code,
4552                        obligated_types,
4553                        seen_requirements,
4554                        closure_capture_ty,
4555                    );
4556                } else {
4557                    self.note_obligation_cause_code_inner(
4558                        body_def_id,
4559                        err,
4560                        parent_predicate,
4561                        param_env,
4562                        cause_code.peel_derives(),
4563                        obligated_types,
4564                        seen_requirements,
4565                        closure_capture_ty,
4566                    );
4567                }
4568            }
4569            ObligationCauseCode::ImplDerived(ref data) => {
4570                let mut parent_trait_pred =
4571                    self.deeply_resolve_ignoring_regions(data.derived.parent_trait_pred);
4572                let parent_def_id = parent_trait_pred.def_id();
4573                if tcx.is_diagnostic_item(sym::FromResidual, parent_def_id)
4574                    && !tcx.features().enabled(sym::try_trait_v2)
4575                {
4576                    // If `#![feature(try_trait_v2)]` is not enabled, then there's no point on
4577                    // talking about `FromResidual<Result<A, B>>`, as the end user has nothing they
4578                    // can do about it. As far as they are concerned, `?` is compiler magic.
4579                    return;
4580                }
4581                if tcx.is_diagnostic_item(sym::PinDerefMutHelper, parent_def_id) {
4582                    let parent_predicate =
4583                        self.deeply_resolve_ignoring_regions(data.derived.parent_trait_pred);
4584
4585                    // Skip PinDerefMutHelper in suggestions, but still show downstream suggestions.
4586
4587                    *closure_capture_ty = Some(parent_trait_pred.skip_binder().self_ty());
4588                    self.note_obligation_cause_code_inner(
4589                        body_def_id,
4590                        err,
4591                        parent_predicate,
4592                        param_env,
4593                        &data.derived.parent_code,
4594                        obligated_types,
4595                        seen_requirements,
4596                        closure_capture_ty,
4597                    );
4598                    return;
4599                }
4600                let self_ty_str =
4601                    tcx.short_string(parent_trait_pred.skip_binder().self_ty(), err.long_ty_path());
4602                let trait_name = tcx.short_string(
4603                    parent_trait_pred.print_modifiers_and_trait_path(),
4604                    err.long_ty_path(),
4605                );
4606                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}`");
4607                let mut is_auto_trait = false;
4608                match tcx.hir_get_if_local(data.impl_or_alias_def_id) {
4609                    Some(Node::Item(hir::Item {
4610                        kind: hir::ItemKind::Trait { is_auto, ident, .. },
4611                        ..
4612                    })) => {
4613                        // FIXME: we should do something else so that it works even on crate foreign
4614                        // auto traits.
4615                        is_auto_trait = #[allow(non_exhaustive_omitted_patterns)] match is_auto {
    hir::IsAuto::Yes => true,
    _ => false,
}matches!(is_auto, hir::IsAuto::Yes);
4616                        err.span_note(ident.span, msg);
4617                    }
4618                    Some(Node::Item(hir::Item {
4619                        kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, generics, .. }),
4620                        ..
4621                    })) => {
4622                        let mut spans = Vec::with_capacity(2);
4623                        if let Some(of_trait) = of_trait
4624                            && !of_trait.trait_ref.path.span.in_derive_expansion()
4625                        {
4626                            spans.push(of_trait.trait_ref.path.span);
4627                        }
4628                        spans.push(self_ty.span);
4629                        let mut spans: MultiSpan = spans.into();
4630                        let mut derived = false;
4631                        if #[allow(non_exhaustive_omitted_patterns)] match self_ty.span.ctxt().outer_expn_data().kind
    {
    ExpnKind::Macro(MacroKind::Derive, _) => true,
    _ => false,
}matches!(
4632                            self_ty.span.ctxt().outer_expn_data().kind,
4633                            ExpnKind::Macro(MacroKind::Derive, _)
4634                        ) || #[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!(
4635                            of_trait.map(|t| t.trait_ref.path.span.ctxt().outer_expn_data().kind),
4636                            Some(ExpnKind::Macro(MacroKind::Derive, _))
4637                        ) {
4638                            derived = true;
4639                            spans.push_span_label(
4640                                data.span,
4641                                if data.span.in_derive_expansion() {
4642                                    ::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}`")
4643                                } else {
4644                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unsatisfied trait bound"))
    })format!("unsatisfied trait bound")
4645                                },
4646                            );
4647                        } else if !data.span.is_dummy() && !data.span.overlaps(self_ty.span) {
4648                            // `Sized` may be an explicit or implicit trait bound. If it is
4649                            // implicit, mention it as such.
4650                            if let Some(pred) = predicate.as_trait_clause()
4651                                && self.tcx.is_lang_item(pred.def_id(), LangItem::Sized)
4652                                && self
4653                                    .tcx
4654                                    .generics_of(data.impl_or_alias_def_id)
4655                                    .own_params
4656                                    .iter()
4657                                    .any(|param| self.tcx.def_span(param.def_id) == data.span)
4658                            {
4659                                spans.push_span_label(
4660                                    data.span,
4661                                    "unsatisfied trait bound implicitly introduced here",
4662                                );
4663                            } else {
4664                                spans.push_span_label(
4665                                    data.span,
4666                                    "unsatisfied trait bound introduced here",
4667                                );
4668                            }
4669                        }
4670                        err.span_note(spans, msg);
4671                        if derived
4672                            && self.is_truly_imperfect_derive(
4673                                parent_trait_pred,
4674                                predicate,
4675                                param_env,
4676                            )
4677                        {
4678                            err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider manually implementing `{0}` to avoid undesired bounds caused by \"imperfect derives\"",
                trait_name))
    })format!(
4679                                "consider manually implementing `{trait_name}` to avoid undesired bounds caused by \"imperfect derives\"",
4680                            ));
4681                            err.note(
4682                                "to learn more, visit <https://github.com/rust-lang/rust/issues/26925>",
4683                            );
4684                        }
4685                        point_at_assoc_type_restriction(
4686                            tcx,
4687                            err,
4688                            &self_ty_str,
4689                            &trait_name,
4690                            predicate,
4691                            &generics,
4692                            &data,
4693                        );
4694                    }
4695                    _ => {
4696                        err.note(msg);
4697                    }
4698                };
4699
4700                let mut parent_predicate = parent_trait_pred;
4701                let mut data = &data.derived;
4702                let mut count = 0;
4703                seen_requirements.insert(parent_def_id);
4704                if is_auto_trait {
4705                    // We don't want to point at the ADT saying "required because it appears within
4706                    // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
4707                    while let ObligationCauseCode::BuiltinDerived(derived) = &*data.parent_code {
4708                        let child_trait_ref =
4709                            self.deeply_resolve_ignoring_regions(derived.parent_trait_pred);
4710                        let child_def_id = child_trait_ref.def_id();
4711                        if seen_requirements.insert(child_def_id) {
4712                            break;
4713                        }
4714                        data = derived;
4715                        parent_predicate = child_trait_ref.upcast(tcx);
4716                        parent_trait_pred = child_trait_ref;
4717                    }
4718                }
4719                while let ObligationCauseCode::ImplDerived(child) = &*data.parent_code {
4720                    // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
4721                    let child_trait_pred =
4722                        self.deeply_resolve_ignoring_regions(child.derived.parent_trait_pred);
4723                    let child_def_id = child_trait_pred.def_id();
4724                    if seen_requirements.insert(child_def_id) {
4725                        break;
4726                    }
4727                    count += 1;
4728                    data = &child.derived;
4729                    parent_predicate = child_trait_pred.upcast(tcx);
4730                    parent_trait_pred = child_trait_pred;
4731                }
4732                if count > 0 {
4733                    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} redundant requirement{1} hidden",
                count, if count == 1 { "" } else { "s" }))
    })format!(
4734                        "{} redundant requirement{} hidden",
4735                        count,
4736                        pluralize!(count)
4737                    ));
4738                    let self_ty = tcx.short_string(
4739                        parent_trait_pred.skip_binder().self_ty(),
4740                        err.long_ty_path(),
4741                    );
4742                    let trait_path = tcx.short_string(
4743                        parent_trait_pred.print_modifiers_and_trait_path(),
4744                        err.long_ty_path(),
4745                    );
4746                    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}`"));
4747                }
4748                *closure_capture_ty = Some(parent_trait_pred.skip_binder().self_ty());
4749                self.note_obligation_cause_code_inner(
4750                    body_def_id,
4751                    err,
4752                    parent_predicate,
4753                    param_env,
4754                    &data.parent_code,
4755                    obligated_types,
4756                    seen_requirements,
4757                    closure_capture_ty,
4758                )
4759            }
4760            ObligationCauseCode::ImplDerivedHost(ref data) => {
4761                let self_ty = tcx.short_string(
4762                    self.deeply_resolve_ignoring_regions(data.derived.parent_host_clause.self_ty()),
4763                    err.long_ty_path(),
4764                );
4765                let trait_path = tcx.short_string(
4766                    data.derived
4767                        .parent_host_clause
4768                        .map_bound(|clause| clause.trait_ref)
4769                        .print_only_trait_path(),
4770                    err.long_ty_path(),
4771                );
4772                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("required for `{1}` to implement `{0} {2}`",
                data.derived.parent_host_clause.skip_binder().constness,
                self_ty, trait_path))
    })format!(
4773                    "required for `{self_ty}` to implement `{} {trait_path}`",
4774                    data.derived.parent_host_clause.skip_binder().constness,
4775                );
4776                match tcx.hir_get_if_local(data.impl_def_id) {
4777                    Some(Node::Item(hir::Item {
4778                        kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
4779                        ..
4780                    })) => {
4781                        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];
4782                        spans.extend(of_trait.map(|t| t.trait_ref.path.span));
4783                        let mut spans: MultiSpan = spans.into();
4784                        spans.push_span_label(data.span, "unsatisfied trait bound introduced here");
4785                        err.span_note(spans, msg);
4786                    }
4787                    _ => {
4788                        err.note(msg);
4789                    }
4790                }
4791
4792                self.note_obligation_cause_code_inner(
4793                    body_def_id,
4794                    err,
4795                    data.derived.parent_host_clause,
4796                    param_env,
4797                    &data.derived.parent_code,
4798                    obligated_types,
4799                    seen_requirements,
4800                    closure_capture_ty,
4801                );
4802            }
4803            ObligationCauseCode::BuiltinDerivedHost(ref data) => {
4804                self.note_obligation_cause_code_inner(
4805                    body_def_id,
4806                    err,
4807                    data.parent_host_clause,
4808                    param_env,
4809                    &data.parent_code,
4810                    obligated_types,
4811                    seen_requirements,
4812                    closure_capture_ty,
4813                );
4814            }
4815            ObligationCauseCode::WellFormedDerived(ref data) => {
4816                let parent_trait_ref = self.deeply_resolve_ignoring_regions(data.parent_trait_pred);
4817                let parent_predicate = parent_trait_ref;
4818
4819                *closure_capture_ty = Some(parent_trait_ref.skip_binder().self_ty());
4820                self.note_obligation_cause_code_inner(
4821                    body_def_id,
4822                    err,
4823                    parent_predicate,
4824                    param_env,
4825                    &data.parent_code,
4826                    obligated_types,
4827                    seen_requirements,
4828                    closure_capture_ty,
4829                );
4830            }
4831            ObligationCauseCode::TypeAlias(ref nested, span, def_id) => {
4832                self.note_obligation_cause_code_inner(
4833                    body_def_id,
4834                    err,
4835                    predicate,
4836                    param_env,
4837                    nested,
4838                    obligated_types,
4839                    seen_requirements,
4840                    closure_capture_ty,
4841                );
4842                let mut multispan = MultiSpan::from(span);
4843                multispan.push_span_label(span, "required by this bound");
4844                err.span_note(
4845                    multispan,
4846                    ::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)),
4847                );
4848            }
4849            ObligationCauseCode::FunctionArg {
4850                arg_hir_id, call_hir_id, ref parent_code, ..
4851            } => {
4852                self.note_function_argument_obligation(
4853                    body_def_id,
4854                    err,
4855                    arg_hir_id,
4856                    parent_code,
4857                    param_env,
4858                    predicate,
4859                    call_hir_id,
4860                );
4861
4862                self.note_obligation_cause_code_inner(
4863                    body_def_id,
4864                    err,
4865                    predicate,
4866                    param_env,
4867                    parent_code,
4868                    obligated_types,
4869                    seen_requirements,
4870                    closure_capture_ty,
4871                );
4872            }
4873            // Suppress `compare_type_clause_entailment` errors for RPITITs, since they
4874            // should be implied by the parent method.
4875            ObligationCauseCode::CompareImplItem { trait_item_def_id, .. }
4876                if tcx.is_impl_trait_in_trait(trait_item_def_id) => {}
4877            ObligationCauseCode::CompareImplItem { trait_item_def_id, kind, .. } => {
4878                let item_name = tcx.item_name(trait_item_def_id);
4879                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!(
4880                    "the requirement `{predicate}` appears on the `impl`'s {kind} \
4881                     `{item_name}` but not on the corresponding trait's {kind}",
4882                );
4883                let sp = tcx
4884                    .opt_item_ident(trait_item_def_id)
4885                    .map(|i| i.span)
4886                    .unwrap_or_else(|| tcx.def_span(trait_item_def_id));
4887                let mut assoc_span: MultiSpan = sp.into();
4888                assoc_span.push_span_label(
4889                    sp,
4890                    ::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}`"),
4891                );
4892                if let Some(ident) = tcx
4893                    .opt_associated_item(trait_item_def_id)
4894                    .and_then(|i| tcx.opt_item_ident(i.container_id(tcx)))
4895                {
4896                    assoc_span.push_span_label(ident.span, "in this trait");
4897                }
4898                err.span_note(assoc_span, msg);
4899            }
4900            ObligationCauseCode::TrivialBound => {
4901                tcx.disabled_nightly_features(err, [(String::new(), sym::trivial_bounds)]);
4902            }
4903            ObligationCauseCode::OpaqueReturnType(expr_info) => {
4904                // Point at the method call in the returned expression's chain where an
4905                // associated type diverged from what the signature's opaque type expects,
4906                // regardless of how the failed predicate was derived from that expectation.
4907                if let Some(typeck_results) = self.typeck_results.as_deref() {
4908                    let chain_expr = match expr_info {
4909                        Some((_, hir_id)) => Some(tcx.hir_expect_expr(hir_id)),
4910                        None => tcx.hir_node_by_def_id(body_def_id).body_id().and_then(|body_id| {
4911                            match tcx.hir_body(body_id).value.kind {
4912                                hir::ExprKind::Block(block, _) => block.expr,
4913                                _ => None,
4914                            }
4915                        }),
4916                    };
4917                    if let Some(chain_expr) = chain_expr {
4918                        self.point_at_chain_in_return_position(
4919                            body_def_id,
4920                            chain_expr,
4921                            typeck_results,
4922                            param_env,
4923                            err,
4924                        );
4925                    }
4926                }
4927                let (expr_ty, expr) = if let Some((expr_ty, hir_id)) = expr_info {
4928                    let expr = tcx.hir_expect_expr(hir_id);
4929                    (expr_ty, expr)
4930                } else if let Some(body_id) = tcx.hir_node_by_def_id(body_def_id).body_id()
4931                    && let body = tcx.hir_body(body_id)
4932                    && let hir::ExprKind::Block(block, _) = body.value.kind
4933                    && let Some(expr) = block.expr
4934                    && let Some(expr_ty) = self
4935                        .typeck_results
4936                        .as_ref()
4937                        .and_then(|typeck| typeck.node_type_opt(expr.hir_id))
4938                    && let Some(pred) = predicate.as_clause()
4939                    && let ty::ClauseKind::Trait(pred) = pred.kind().skip_binder()
4940                    && self.can_eq(param_env, pred.self_ty(), expr_ty)
4941                {
4942                    (expr_ty, expr)
4943                } else {
4944                    return;
4945                };
4946                let expr_ty_string = tcx.short_string(expr_ty, err.long_ty_path());
4947                if expr_ty.is_never()
4948                    && let span = expr.span.source_callsite()
4949                    && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(span)
4950                    && span != expr.span
4951                {
4952                    err.span_suggestion(
4953                        span,
4954                        "`!` can be coerced to any type; consider casting it to a concrete type that implements the trait",
4955                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} as /* Type */", snippet))
    })format!("{snippet} as /* Type */"),
4956                        Applicability::HasPlaceholders,
4957                    );
4958                }
4959                err.span_label(
4960                    expr.span,
4961                    {
    let _guard = ForceTrimmedGuard::new();
    ::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("return type was inferred to be `{0}` here",
                    expr_ty_string))
        })
}with_forced_trimmed_paths!(format!(
4962                        "return type was inferred to be `{expr_ty_string}` here",
4963                    )),
4964                );
4965                suggest_remove_deref(err, &expr);
4966            }
4967            ObligationCauseCode::UnsizedNonPlaceExpr(span) => {
4968                err.span_note(
4969                    span,
4970                    "unsized values must be place expressions and cannot be put in temporaries",
4971                );
4972            }
4973            ObligationCauseCode::CompareEii { .. } => {
4974                {
    ::core::panicking::panic_fmt(format_args!("trait bounds on EII not yet supported "));
}panic!("trait bounds on EII not yet supported ")
4975            }
4976        }
4977    }
4978
4979    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("suggest_await_before_try",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(4979u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("obligation")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("obligation");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_pred")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_pred");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_pred.self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_pred.self_ty");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_pred)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_pred.self_ty())
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let future_trait =
                self.tcx.require_lang_item(LangItem::Future, span);
            let self_ty =
                self.deeply_resolve_ignoring_regions(trait_pred.self_ty());
            let impls_future =
                self.type_implements_trait(future_trait,
                    [self.tcx.instantiate_bound_regions_with_erased(self_ty)],
                    obligation.param_env);
            if !impls_future.must_apply_modulo_regions() { return; }
            let item_def_id =
                self.tcx.associated_item_def_ids(future_trait)[0];
            let projection_ty =
                trait_pred.map_bound(|trait_pred|
                        {
                            Ty::new_projection(self.tcx, ty::IsRigid::No, item_def_id,
                                [trait_pred.self_ty()])
                        });
            let InferOk { value: projection_ty, .. } =
                self.at(&obligation.cause,
                        obligation.param_env).normalize(Unnormalized::new_wip(projection_ty));
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5016",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(5016u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("normalized_projection_type")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("normalized_projection_type");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.deeply_resolve_ignoring_regions(projection_ty))
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let try_obligation =
                self.mk_trait_obligation_with_new_self_ty(obligation.param_env,
                    trait_pred.map_bound(|trait_pred|
                            (trait_pred, projection_ty.skip_binder())));
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5023",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(5023u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("try_trait_obligation")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("try_trait_obligation");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&try_obligation)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if self.predicate_may_hold(&try_obligation) &&
                        let Ok(snippet) =
                            self.tcx.sess.source_map().span_to_snippet(span) &&
                    snippet.ends_with('?') {
                match self.tcx.coroutine_kind(obligation.cause.body_def_id) {
                    Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
                        _)) => {
                        err.span_suggestion_verbose(span.with_hi(span.hi() -
                                        BytePos(1)).shrink_to_hi(),
                            "consider `await`ing on the `Future`", ".await",
                            Applicability::MaybeIncorrect);
                    }
                    _ => {
                        let mut span: MultiSpan =
                            span.with_lo(span.hi() - BytePos(1)).into();
                        span.push_span_label(self.tcx.def_span(obligation.cause.body_def_id),
                            "this is not `async`");
                        err.span_note(span,
                            "this implements `Future` and its output type supports \
                        `?`, but the future cannot be awaited in a synchronous function");
                    }
                }
            }
        }
    }
}#[instrument(
4980        level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
4981    )]
4982    pub(super) fn suggest_await_before_try(
4983        &self,
4984        err: &mut Diag<'_>,
4985        obligation: &PredicateObligation<'tcx>,
4986        trait_pred: ty::PolyTraitClause<'tcx>,
4987        span: Span,
4988    ) {
4989        let future_trait = self.tcx.require_lang_item(LangItem::Future, span);
4990
4991        let self_ty = self.deeply_resolve_ignoring_regions(trait_pred.self_ty());
4992        let impls_future = self.type_implements_trait(
4993            future_trait,
4994            [self.tcx.instantiate_bound_regions_with_erased(self_ty)],
4995            obligation.param_env,
4996        );
4997        if !impls_future.must_apply_modulo_regions() {
4998            return;
4999        }
5000
5001        let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
5002        // `<T as Future>::Output`
5003        let projection_ty = trait_pred.map_bound(|trait_pred| {
5004            Ty::new_projection(
5005                self.tcx,
5006                ty::IsRigid::No,
5007                item_def_id,
5008                // Future::Output has no args
5009                [trait_pred.self_ty()],
5010            )
5011        });
5012        let InferOk { value: projection_ty, .. } = self
5013            .at(&obligation.cause, obligation.param_env)
5014            .normalize(Unnormalized::new_wip(projection_ty));
5015
5016        debug!(
5017            normalized_projection_type = ?self.deeply_resolve_ignoring_regions(projection_ty)
5018        );
5019        let try_obligation = self.mk_trait_obligation_with_new_self_ty(
5020            obligation.param_env,
5021            trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
5022        );
5023        debug!(try_trait_obligation = ?try_obligation);
5024        if self.predicate_may_hold(&try_obligation)
5025            && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
5026            && snippet.ends_with('?')
5027        {
5028            match self.tcx.coroutine_kind(obligation.cause.body_def_id) {
5029                Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
5030                    err.span_suggestion_verbose(
5031                        span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
5032                        "consider `await`ing on the `Future`",
5033                        ".await",
5034                        Applicability::MaybeIncorrect,
5035                    );
5036                }
5037                _ => {
5038                    let mut span: MultiSpan = span.with_lo(span.hi() - BytePos(1)).into();
5039                    span.push_span_label(
5040                        self.tcx.def_span(obligation.cause.body_def_id),
5041                        "this is not `async`",
5042                    );
5043                    err.span_note(
5044                        span,
5045                        "this implements `Future` and its output type supports \
5046                        `?`, but the future cannot be awaited in a synchronous function",
5047                    );
5048                }
5049            }
5050        }
5051    }
5052
5053    pub(super) fn suggest_floating_point_literal(
5054        &self,
5055        obligation: &PredicateObligation<'tcx>,
5056        err: &mut Diag<'_>,
5057        trait_pred: ty::PolyTraitClause<'tcx>,
5058    ) {
5059        let rhs_span = match obligation.cause.code() {
5060            ObligationCauseCode::BinOp { rhs_span, rhs_is_lit, .. } if *rhs_is_lit => rhs_span,
5061            _ => return,
5062        };
5063        if let ty::Float(_) = trait_pred.skip_binder().self_ty().kind()
5064            && let ty::Infer(InferTy::IntVar(_)) =
5065                trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
5066        {
5067            err.span_suggestion_verbose(
5068                rhs_span.shrink_to_hi(),
5069                "consider using a floating-point literal by writing it with `.0`",
5070                ".0",
5071                Applicability::MaybeIncorrect,
5072            );
5073        }
5074    }
5075
5076    pub fn can_suggest_derive(
5077        &self,
5078        obligation: &PredicateObligation<'tcx>,
5079        trait_pred: ty::PolyTraitClause<'tcx>,
5080    ) -> bool {
5081        if trait_pred.polarity() == ty::ClausePolarity::Negative {
5082            return false;
5083        }
5084        let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
5085            return false;
5086        };
5087        let (adt, args) = match trait_pred.skip_binder().self_ty().kind() {
5088            ty::Adt(adt, args) if adt.did().is_local() => (adt, args),
5089            _ => return false,
5090        };
5091        let is_derivable_trait = match diagnostic_name {
5092            sym::Copy | sym::Clone => true,
5093            _ if adt.is_union() => false,
5094            sym::PartialEq | sym::PartialOrd => {
5095                let rhs_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
5096                trait_pred.skip_binder().self_ty() == rhs_ty
5097            }
5098            sym::Eq | sym::Ord | sym::Hash | sym::Debug | sym::Default => true,
5099            _ => false,
5100        };
5101        is_derivable_trait &&
5102            // Ensure all fields impl the trait.
5103            adt.all_fields().all(|field| {
5104                let field_ty = ty::GenericArg::from(field.ty(self.tcx, args).skip_norm_wip());
5105                let trait_args = match diagnostic_name {
5106                    sym::PartialEq | sym::PartialOrd => {
5107                        Some(field_ty)
5108                    }
5109                    _ => None,
5110                };
5111                let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitClause {
5112                    trait_ref: ty::TraitRef::new(self.tcx,
5113                        trait_pred.def_id(),
5114                        [field_ty].into_iter().chain(trait_args),
5115                    ),
5116                    ..*tr
5117                });
5118                let field_obl = Obligation::new(
5119                    self.tcx,
5120                    obligation.cause.clone(),
5121                    obligation.param_env,
5122                    trait_pred,
5123                );
5124                self.predicate_must_hold_modulo_regions(&field_obl)
5125            })
5126    }
5127
5128    pub fn suggest_derive(
5129        &self,
5130        obligation: &PredicateObligation<'tcx>,
5131        err: &mut Diag<'_>,
5132        trait_pred: ty::PolyTraitClause<'tcx>,
5133    ) {
5134        let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
5135            return;
5136        };
5137        let adt = match trait_pred.skip_binder().self_ty().kind() {
5138            ty::Adt(adt, _) if adt.did().is_local() => adt,
5139            _ => return,
5140        };
5141        if self.can_suggest_derive(obligation, trait_pred) {
5142            err.span_suggestion_verbose(
5143                self.tcx.def_span(adt.did()).shrink_to_lo(),
5144                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider annotating `{0}` with `#[derive({1})]`",
                trait_pred.skip_binder().self_ty(), diagnostic_name))
    })format!(
5145                    "consider annotating `{}` with `#[derive({})]`",
5146                    trait_pred.skip_binder().self_ty(),
5147                    diagnostic_name,
5148                ),
5149                // FIXME(const_trait_impl) derive_const as suggestion?
5150                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#[derive({0})]\n",
                diagnostic_name))
    })format!("#[derive({diagnostic_name})]\n"),
5151                Applicability::MaybeIncorrect,
5152            );
5153        }
5154    }
5155
5156    pub(super) fn suggest_dereferencing_index(
5157        &self,
5158        obligation: &PredicateObligation<'tcx>,
5159        err: &mut Diag<'_>,
5160        trait_pred: ty::PolyTraitClause<'tcx>,
5161    ) {
5162        if let ObligationCauseCode::ImplDerived(_) = obligation.cause.code()
5163            && self
5164                .tcx
5165                .is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
5166            && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
5167            && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
5168            && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
5169        {
5170            // If the index is written as `&i`, suggest removing the borrow instead of
5171            // dereferencing it, i.e. `v[&i]` -> `v[i]` rather than `v[*&i]`.
5172            let span = obligation.cause.span;
5173            if !span.from_expansion()
5174                && let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id)
5175                && let Some(expr) = {
5176                    let mut finder = FindExprBySpan::new(span, self.tcx);
5177                    finder.visit_expr(body.value);
5178                    finder.result
5179                }
5180                && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, borrowed) =
5181                    expr.kind
5182                && let Some(amp_span) = borrowed
5183                    .span
5184                    .find_ancestor_inside_same_ctxt(expr.span)
5185                    .map(|borrowed_span| expr.span.until(borrowed_span))
5186                && self
5187                    .tcx
5188                    .sess
5189                    .source_map()
5190                    .span_to_snippet(amp_span)
5191                    .is_ok_and(|snippet| snippet.starts_with('&'))
5192            {
5193                err.span_suggestion_verbose(
5194                    amp_span,
5195                    "remove this reference",
5196                    "",
5197                    Applicability::MachineApplicable,
5198                );
5199                return;
5200            }
5201
5202            err.span_suggestion_verbose(
5203                obligation.cause.span.shrink_to_lo(),
5204                "dereference this index",
5205                '*',
5206                Applicability::MachineApplicable,
5207            );
5208        }
5209    }
5210
5211    fn note_function_argument_obligation<G>(
5212        &self,
5213        body_def_id: LocalDefId,
5214        err: &mut Diag<'_, G>,
5215        arg_hir_id: HirId,
5216        parent_code: &ObligationCauseCode<'tcx>,
5217        param_env: ty::ParamEnv<'tcx>,
5218        failed_pred: ty::Predicate<'tcx>,
5219        call_hir_id: HirId,
5220    ) {
5221        let tcx = self.tcx;
5222        if let Node::Expr(expr) = tcx.hir_node(arg_hir_id)
5223            && let Some(typeck_results) = &self.typeck_results
5224        {
5225            if let hir::Expr { kind: hir::ExprKind::MethodCall(_, rcvr, _, _), .. } = expr
5226                && let Some(ty) = typeck_results.node_type_opt(rcvr.hir_id)
5227                && let Some(failed_pred) = failed_pred.as_trait_clause()
5228                && let pred = failed_pred.map_bound(|pred| pred.with_replaced_self_ty(tcx, ty))
5229                && self.predicate_must_hold_modulo_regions(&Obligation::misc(
5230                    tcx,
5231                    expr.span,
5232                    body_def_id,
5233                    param_env,
5234                    pred,
5235                ))
5236                && expr.span.hi() != rcvr.span.hi()
5237            {
5238                let should_sugg = match tcx.hir_node(call_hir_id) {
5239                    Node::Expr(hir::Expr {
5240                        kind: hir::ExprKind::MethodCall(_, call_receiver, _, _),
5241                        ..
5242                    }) if let Some((DefKind::AssocFn, did)) =
5243                        typeck_results.type_dependent_def(call_hir_id)
5244                        && call_receiver.hir_id == arg_hir_id =>
5245                    {
5246                        // Avoid suggesting removing a method call if the argument is the receiver of the parent call and
5247                        // removing the receiver would make the method inaccessible. i.e. `x.a().b()`, suggesting removing
5248                        // `.a()` could change the type and make `.b()` unavailable.
5249                        if tcx.inherent_impl_of_assoc(did).is_some() {
5250                            // if we're calling an inherent impl method, just try to make sure that the receiver type stays the same.
5251                            Some(ty) == typeck_results.node_type_opt(arg_hir_id)
5252                        } else {
5253                            // we're calling a trait method, so we just check removing the method call still satisfies the trait.
5254                            let trait_id = tcx
5255                                .trait_of_assoc(did)
5256                                .unwrap_or_else(|| tcx.impl_trait_id(tcx.parent(did)));
5257                            let args = typeck_results.node_args(call_hir_id);
5258                            let tr = ty::TraitRef::from_assoc(tcx, trait_id, args)
5259                                .with_replaced_self_ty(tcx, ty);
5260                            self.type_implements_trait(tr.def_id, tr.args, param_env)
5261                                .must_apply_modulo_regions()
5262                        }
5263                    }
5264                    _ => true,
5265                };
5266
5267                if should_sugg {
5268                    err.span_suggestion_verbose(
5269                        expr.span.with_lo(rcvr.span.hi()),
5270                        ::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!(
5271                            "consider removing this method call, as the receiver has type `{ty}` and \
5272                            `{pred}` trivially holds",
5273                        ),
5274                        "",
5275                        Applicability::MaybeIncorrect,
5276                    );
5277                }
5278            }
5279            if let hir::Expr { kind: hir::ExprKind::Block(block, _), .. } = expr {
5280                let inner_expr = expr.peel_blocks();
5281                let ty = typeck_results
5282                    .expr_ty_adjusted_opt(inner_expr)
5283                    .unwrap_or(Ty::new_misc_error(tcx));
5284                let span = inner_expr.span;
5285                if Some(span) != err.span.primary_span()
5286                    && !span.in_external_macro(tcx.sess.source_map())
5287                {
5288                    err.span_label(
5289                        span,
5290                        if ty.references_error() {
5291                            String::new()
5292                        } else {
5293                            let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5294                            ::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}`")
5295                        },
5296                    );
5297                    if let ty::PredicateKind::Clause(clause) = failed_pred.kind().skip_binder()
5298                        && let ty::ClauseKind::Trait(pred) = clause
5299                        && tcx.fn_trait_kind_from_def_id(pred.def_id()).is_some()
5300                    {
5301                        if let [stmt, ..] = block.stmts
5302                            && let hir::StmtKind::Semi(value) = stmt.kind
5303                            && let hir::ExprKind::Closure(hir::Closure {
5304                                body, fn_decl_span, ..
5305                            }) = value.kind
5306                            && let body = tcx.hir_body(*body)
5307                            && !#[allow(non_exhaustive_omitted_patterns)] match body.value.kind {
    hir::ExprKind::Block(..) => true,
    _ => false,
}matches!(body.value.kind, hir::ExprKind::Block(..))
5308                        {
5309                            // Check if the failed predicate was an expectation of a closure type
5310                            // and if there might have been a `{ |args|` typo instead of `|args| {`.
5311                            err.multipart_suggestion(
5312                                "you might have meant to open the closure body instead of placing \
5313                                 a closure within a block",
5314                                ::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![
5315                                    (expr.span.with_hi(value.span.lo()), String::new()),
5316                                    (fn_decl_span.shrink_to_hi(), " {".to_string()),
5317                                ],
5318                                Applicability::MaybeIncorrect,
5319                            );
5320                        } else {
5321                            // Maybe the bare block was meant to be a closure.
5322                            err.span_suggestion_verbose(
5323                                expr.span.shrink_to_lo(),
5324                                "you might have meant to create the closure instead of a block",
5325                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("|{0}| ",
                (0..pred.trait_ref.args.len() -
                                        1).map(|_| "_").collect::<Vec<_>>().join(", ")))
    })format!(
5326                                    "|{}| ",
5327                                    (0..pred.trait_ref.args.len() - 1)
5328                                        .map(|_| "_")
5329                                        .collect::<Vec<_>>()
5330                                        .join(", ")
5331                                ),
5332                                Applicability::MaybeIncorrect,
5333                            );
5334                        }
5335                    }
5336                }
5337            }
5338
5339            // FIXME: visit the ty to see if there's any closure involved, and if there is,
5340            // check whether its evaluated return type is the same as the one corresponding
5341            // to an associated type (as seen from `trait_pred`) in the predicate. Like in
5342            // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
5343            let mut type_diffs = ::alloc::vec::Vec::new()vec![];
5344            if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = *parent_code
5345                && let Some(node_args) = typeck_results.node_args_opt(call_hir_id)
5346                && let where_clauses = self.tcx.clauses_of(def_id).instantiate(self.tcx, node_args)
5347                && let Some(where_pred) = where_clauses.clauses.get(idx)
5348            {
5349                let where_pred = where_pred.as_ref().skip_norm_wip();
5350                if let Some(where_pred) = where_pred.as_trait_clause()
5351                    && let Some(failed_pred) = failed_pred.as_trait_clause()
5352                    && where_pred.def_id() == failed_pred.def_id()
5353                {
5354                    self.enter_forall(where_pred, |where_pred| {
5355                        let failed_pred = self.instantiate_binder_with_fresh_vars(
5356                            expr.span,
5357                            BoundRegionConversionTime::FnCall,
5358                            failed_pred,
5359                        );
5360
5361                        let zipped =
5362                            iter::zip(where_pred.trait_ref.args, failed_pred.trait_ref.args);
5363                        for (expected, actual) in zipped {
5364                            self.probe(|_| {
5365                                match self
5366                                    .at(&ObligationCause::misc(expr.span, body_def_id), param_env)
5367                                    // Doesn't actually matter if we define opaque types here, this is just used for
5368                                    // diagnostics, and the result is never kept around.
5369                                    .eq(DefineOpaqueTypes::Yes, expected, actual)
5370                                {
5371                                    Ok(_) => (), // We ignore nested obligations here for now.
5372                                    Err(err) => type_diffs.push(err),
5373                                }
5374                            })
5375                        }
5376                    })
5377                } else if let Some(where_pred) = where_pred.as_projection_clause()
5378                    && let Some(failed_pred) = failed_pred.as_projection_clause()
5379                    && let Some(found) =
5380                        failed_pred.map_bound(|pred| pred.term.as_type()).transpose().map(|term| {
5381                            self.instantiate_binder_with_fresh_vars(
5382                                expr.span,
5383                                BoundRegionConversionTime::FnCall,
5384                                term,
5385                            )
5386                        })
5387                {
5388                    type_diffs = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [TypeError::Sorts(ty::error::ExpectedFound {
                        expected: self.instantiate_binder_with_fresh_vars(expr.span,
                                    BoundRegionConversionTime::FnCall,
                                    where_pred.map_bound(|pred|
                                            pred.projection_term)).expect_ty().to_ty(self.tcx,
                            ty::IsRigid::No),
                        found,
                    })]))vec![TypeError::Sorts(ty::error::ExpectedFound {
5389                        expected: self
5390                            .instantiate_binder_with_fresh_vars(
5391                                expr.span,
5392                                BoundRegionConversionTime::FnCall,
5393                                where_pred.map_bound(|pred| pred.projection_term),
5394                            )
5395                            .expect_ty()
5396                            .to_ty(self.tcx, ty::IsRigid::No),
5397                        found,
5398                    })];
5399                }
5400            }
5401            if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
5402                && let hir::Path { res: Res::Local(hir_id), .. } = path
5403                && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
5404                && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(binding.hir_id)
5405                && let Some(binding_expr) = local.init
5406            {
5407                // If the expression we're calling on is a binding, we want to point at the
5408                // `let` when talking about the type. Otherwise we'll point at every part
5409                // of the method chain with the type.
5410                self.point_at_chain(binding_expr, typeck_results, type_diffs, param_env, err);
5411            } else {
5412                self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
5413            }
5414        }
5415        let call_node = tcx.hir_node(call_hir_id);
5416        if let Node::Expr(hir::Expr { kind: hir::ExprKind::MethodCall(path, rcvr, ..), .. }) =
5417            call_node
5418        {
5419            if Some(rcvr.span) == err.span.primary_span() {
5420                err.replace_span_with(path.ident.span, true);
5421            }
5422        }
5423
5424        if let Node::Expr(expr) = call_node {
5425            if let hir::ExprKind::Call(hir::Expr { span, .. }, _)
5426            | hir::ExprKind::MethodCall(
5427                hir::PathSegment { ident: Ident { span, .. }, .. },
5428                ..,
5429            ) = expr.kind
5430            {
5431                if Some(*span) != err.span.primary_span() {
5432                    let msg = if span.is_desugaring(DesugaringKind::FormatLiteral { source: true })
5433                    {
5434                        "required by this formatting parameter"
5435                    } else if span.is_desugaring(DesugaringKind::FormatLiteral { source: false }) {
5436                        "required by a formatting parameter in this expression"
5437                    } else {
5438                        "required by a bound introduced by this call"
5439                    };
5440                    err.span_label(*span, msg);
5441                }
5442            }
5443
5444            if let hir::ExprKind::MethodCall(_, expr, ..) = expr.kind {
5445                self.suggest_option_method_if_applicable(failed_pred, param_env, err, expr);
5446            }
5447        }
5448    }
5449
5450    fn suggest_option_method_if_applicable<G>(
5451        &self,
5452        failed_pred: ty::Predicate<'tcx>,
5453        param_env: ty::ParamEnv<'tcx>,
5454        err: &mut Diag<'_, G>,
5455        expr: &hir::Expr<'_>,
5456    ) {
5457        let tcx = self.tcx;
5458        let infcx = self.infcx;
5459        let Some(typeck_results) = self.typeck_results.as_ref() else { return };
5460
5461        // Make sure we're dealing with the `Option` type.
5462        let Some(option_ty_adt) = typeck_results.expr_ty_adjusted(expr).ty_adt_def() else {
5463            return;
5464        };
5465        if !tcx.is_diagnostic_item(sym::Option, option_ty_adt.did()) {
5466            return;
5467        }
5468
5469        // Given the predicate `fn(&T): FnOnce<(U,)>`, extract `fn(&T)` and `(U,)`,
5470        // then suggest `Option::as_deref(_mut)` if `U` can deref to `T`
5471        if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitClause { trait_ref, .. }))
5472            = failed_pred.kind().skip_binder()
5473            && tcx.is_fn_trait(trait_ref.def_id)
5474            && let [self_ty, found_ty] = trait_ref.args.as_slice()
5475            && let Some(fn_ty) = self_ty.as_type().filter(|ty| ty.is_fn())
5476            && let fn_sig @ ty::FnSig {
5477                ..
5478            } = fn_ty.fn_sig(tcx).skip_binder()
5479            // FIXME(splat): this might need to change if the Fn* traits start using/supporting splat
5480            && fn_sig.abi() == ExternAbi::Rust
5481            && !fn_sig.c_variadic()
5482            && fn_sig.safety() == hir::Safety::Safe
5483
5484            // Extract first param of fn sig with peeled refs, e.g. `fn(&T)` -> `T`
5485            && let Some(&ty::Ref(_, target_ty, needs_mut)) = fn_sig.inputs().first().map(|t| t.kind())
5486            && !target_ty.has_escaping_bound_vars()
5487
5488            // Extract first tuple element out of fn trait, e.g. `FnOnce<(U,)>` -> `U`
5489            && let Some(ty::Tuple(tys)) = found_ty.as_type().map(Ty::kind)
5490            && let &[found_ty] = tys.as_slice()
5491            && !found_ty.has_escaping_bound_vars()
5492
5493            // Extract `<U as Deref>::Target` assoc type and check that it is `T`
5494            && let Some(deref_target_did) = tcx.lang_items().deref_target()
5495            && let projection = Ty::new_projection_from_args(tcx,ty::IsRigid::No, deref_target_did, tcx.mk_args(&[ty::GenericArg::from(found_ty)]))
5496            && let InferOk { value: deref_target, obligations } = infcx.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(projection))
5497            && obligations.iter().all(|obligation| infcx.predicate_must_hold_modulo_regions(obligation))
5498            && infcx.can_eq(param_env, deref_target, target_ty)
5499        {
5500            let help = if let hir::Mutability::Mut = needs_mut
5501                && let Some(deref_mut_did) = tcx.lang_items().deref_mut_trait()
5502                && infcx
5503                    .type_implements_trait(deref_mut_did, iter::once(found_ty), param_env)
5504                    .must_apply_modulo_regions()
5505            {
5506                Some(("call `Option::as_deref_mut()` first", ".as_deref_mut()"))
5507            } else if let hir::Mutability::Not = needs_mut {
5508                Some(("call `Option::as_deref()` first", ".as_deref()"))
5509            } else {
5510                None
5511            };
5512
5513            if let Some((msg, sugg)) = help {
5514                err.span_suggestion_with_style(
5515                    expr.span.shrink_to_hi(),
5516                    msg,
5517                    sugg,
5518                    Applicability::MaybeIncorrect,
5519                    SuggestionStyle::ShowAlways,
5520                );
5521            }
5522        }
5523    }
5524
5525    fn look_for_iterator_item_mistakes<G>(
5526        &self,
5527        assocs_in_this_method: &[Option<(Span, (DefId, Ty<'tcx>))>],
5528        typeck_results: &TypeckResults<'tcx>,
5529        type_diffs: &[TypeError<'tcx>],
5530        param_env: ty::ParamEnv<'tcx>,
5531        path_segment: &hir::PathSegment<'_>,
5532        args: &[hir::Expr<'_>],
5533        prev_ty: Ty<'_>,
5534        err: &mut Diag<'_, G>,
5535    ) {
5536        let tcx = self.tcx;
5537        // Special case for iterator chains, we look at potential failures of `Iterator::Item`
5538        // not being `: Clone` and `Iterator::map` calls with spurious trailing `;`.
5539        for entry in assocs_in_this_method {
5540            let Some((_span, (def_id, ty))) = entry else {
5541                continue;
5542            };
5543            for diff in type_diffs {
5544                let TypeError::Sorts(expected_found) = diff else {
5545                    continue;
5546                };
5547                if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
5548                    && path_segment.ident.name == sym::iter
5549                    && self.can_eq(
5550                        param_env,
5551                        Ty::new_ref(
5552                            tcx,
5553                            tcx.lifetimes.re_erased,
5554                            expected_found.found,
5555                            ty::Mutability::Not,
5556                        ),
5557                        *ty,
5558                    )
5559                    && let [] = args
5560                {
5561                    // Used `.iter()` when `.into_iter()` was likely meant.
5562                    err.span_suggestion_verbose(
5563                        path_segment.ident.span,
5564                        ::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`"),
5565                        "into_iter".to_string(),
5566                        Applicability::MachineApplicable,
5567                    );
5568                }
5569                if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
5570                    && path_segment.ident.name == sym::into_iter
5571                    && self.can_eq(
5572                        param_env,
5573                        expected_found.found,
5574                        Ty::new_ref(tcx, tcx.lifetimes.re_erased, *ty, ty::Mutability::Not),
5575                    )
5576                    && let [] = args
5577                {
5578                    // Used `.into_iter()` when `.iter()` was likely meant.
5579                    err.span_suggestion_verbose(
5580                        path_segment.ident.span,
5581                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider not consuming the `{0}` to construct the `Iterator`",
                prev_ty))
    })format!(
5582                            "consider not consuming the `{prev_ty}` to construct the `Iterator`"
5583                        ),
5584                        "iter".to_string(),
5585                        Applicability::MachineApplicable,
5586                    );
5587                }
5588                if tcx.is_diagnostic_item(sym::IteratorItem, *def_id)
5589                    && path_segment.ident.name == sym::map
5590                    && self.can_eq(param_env, expected_found.found, *ty)
5591                    && let [arg] = args
5592                    && let hir::ExprKind::Closure(closure) = arg.kind
5593                {
5594                    let body = tcx.hir_body(closure.body);
5595                    if let hir::ExprKind::Block(block, None) = body.value.kind
5596                        && let None = block.expr
5597                        && let [.., stmt] = block.stmts
5598                        && let hir::StmtKind::Semi(expr) = stmt.kind
5599                        // FIXME: actually check the expected vs found types, but right now
5600                        // the expected is a projection that we need to resolve.
5601                        // && let Some(tail_ty) = typeck_results.expr_ty_opt(expr)
5602                        && expected_found.found.is_unit()
5603                        // FIXME: this happens with macro calls. Need to figure out why the stmt
5604                        // `println!();` doesn't include the `;` in its `Span`. (#133845)
5605                        // We filter these out to avoid ICEs with debug assertions on caused by
5606                        // empty suggestions.
5607                        && expr.span.hi() != stmt.span.hi()
5608                    {
5609                        err.span_suggestion_verbose(
5610                            expr.span.shrink_to_hi().with_hi(stmt.span.hi()),
5611                            "consider removing this semicolon",
5612                            String::new(),
5613                            Applicability::MachineApplicable,
5614                        );
5615                    }
5616                    let expr = if let hir::ExprKind::Block(block, None) = body.value.kind
5617                        && let Some(expr) = block.expr
5618                    {
5619                        expr
5620                    } else {
5621                        body.value
5622                    };
5623                    if let hir::ExprKind::MethodCall(path_segment, rcvr, [], span) = expr.kind
5624                        && path_segment.ident.name == sym::clone
5625                        && let Some(expr_ty) = typeck_results.expr_ty_opt(expr)
5626                        && let Some(rcvr_ty) = typeck_results.expr_ty_opt(rcvr)
5627                        && self.can_eq(param_env, expr_ty, rcvr_ty)
5628                        && let ty::Ref(_, ty, _) = expr_ty.kind()
5629                    {
5630                        err.span_label(
5631                            span,
5632                            ::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!(
5633                                "this method call is cloning the reference `{expr_ty}`, not \
5634                                 `{ty}` which doesn't implement `Clone`",
5635                            ),
5636                        );
5637                        let ty::Param(..) = ty.kind() else {
5638                            continue;
5639                        };
5640                        let node =
5641                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(expr.hir_id).def_id);
5642
5643                        let pred = ty::Binder::dummy(ty::TraitClause {
5644                            trait_ref: ty::TraitRef::new(
5645                                tcx,
5646                                tcx.require_lang_item(LangItem::Clone, span),
5647                                [*ty],
5648                            ),
5649                            polarity: ty::ClausePolarity::Positive,
5650                        });
5651                        let Some(generics) = node.generics() else {
5652                            continue;
5653                        };
5654                        let Some(body_id) = node.body_id() else {
5655                            continue;
5656                        };
5657                        suggest_restriction(
5658                            tcx,
5659                            tcx.hir_body_owner_def_id(body_id),
5660                            generics,
5661                            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type parameter `{0}`", ty))
    })format!("type parameter `{ty}`"),
5662                            err,
5663                            node.fn_sig(),
5664                            None,
5665                            pred,
5666                            None,
5667                        );
5668                    }
5669                }
5670            }
5671        }
5672    }
5673
5674    fn point_at_chain<G>(
5675        &self,
5676        expr: &hir::Expr<'_>,
5677        typeck_results: &TypeckResults<'tcx>,
5678        type_diffs: Vec<TypeError<'tcx>>,
5679        param_env: ty::ParamEnv<'tcx>,
5680        err: &mut Diag<'_, G>,
5681    ) {
5682        let mut primary_spans = ::alloc::vec::Vec::new()vec![];
5683        let mut span_labels = ::alloc::vec::Vec::new()vec![];
5684
5685        let tcx = self.tcx;
5686
5687        let mut print_root_expr = true;
5688        let mut assocs = ::alloc::vec::Vec::new()vec![];
5689        let mut expr = expr;
5690        let mut prev_ty = self.deeply_resolve_ignoring_regions(
5691            typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5692        );
5693        while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
5694            // Point at every method call in the chain with the resulting type.
5695            // vec![1, 2, 3].iter().map(mapper).sum<i32>()
5696            //               ^^^^^^ ^^^^^^^^^^^
5697            expr = rcvr_expr;
5698            let assocs_in_this_method =
5699                self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
5700            prev_ty = self.deeply_resolve_ignoring_regions(
5701                typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5702            );
5703            self.look_for_iterator_item_mistakes(
5704                &assocs_in_this_method,
5705                typeck_results,
5706                &type_diffs,
5707                param_env,
5708                path_segment,
5709                args,
5710                prev_ty,
5711                err,
5712            );
5713            assocs.push(assocs_in_this_method);
5714
5715            if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
5716                && let hir::Path { res: Res::Local(hir_id), .. } = path
5717                && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
5718            {
5719                let parent = self.tcx.parent_hir_node(binding.hir_id);
5720                // We've reached the root of the method call chain...
5721                if let hir::Node::LetStmt(local) = parent
5722                    && let Some(binding_expr) = local.init
5723                {
5724                    // ...and it is a binding. Get the binding creation and continue the chain.
5725                    expr = binding_expr;
5726                }
5727                if let hir::Node::Param(param) = parent {
5728                    // ...and it is an fn argument.
5729                    let prev_ty = self.deeply_resolve_ignoring_regions(
5730                        typeck_results
5731                            .node_type_opt(param.hir_id)
5732                            .unwrap_or(Ty::new_misc_error(tcx)),
5733                    );
5734                    let assocs_in_this_method = self.probe_assoc_types_at_expr(
5735                        &type_diffs,
5736                        param.ty_span,
5737                        prev_ty,
5738                        param.hir_id,
5739                        param_env,
5740                    );
5741                    if assocs_in_this_method.iter().any(|a| a.is_some()) {
5742                        assocs.push(assocs_in_this_method);
5743                        print_root_expr = false;
5744                    }
5745                    break;
5746                }
5747            }
5748        }
5749        // We want the type before deref coercions, otherwise we talk about `&[_]`
5750        // instead of `Vec<_>`.
5751        if let Some(ty) = typeck_results.expr_ty_opt(expr)
5752            && print_root_expr
5753        {
5754            let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5755            // Point at the root expression
5756            // vec![1, 2, 3].iter().map(mapper).sum<i32>()
5757            // ^^^^^^^^^^^^^
5758            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}`")));
5759        };
5760        // Only show this if it is not a "trivial" expression (not a method
5761        // chain) and there are associated types to talk about.
5762        let mut assocs = assocs.into_iter().peekable();
5763        while let Some(assocs_in_method) = assocs.next() {
5764            let Some(prev_assoc_in_method) = assocs.peek() else {
5765                for entry in assocs_in_method {
5766                    let Some((span, (assoc, ty))) = entry else {
5767                        continue;
5768                    };
5769                    if primary_spans.is_empty()
5770                        || type_diffs.iter().any(|diff| {
5771                            let TypeError::Sorts(expected_found) = diff else {
5772                                return false;
5773                            };
5774                            self.can_eq(param_env, expected_found.found, ty)
5775                        })
5776                    {
5777                        // FIXME: this doesn't quite work for `Iterator::collect`
5778                        // because we have `Vec<i32>` and `()`, but we'd want `i32`
5779                        // to point at the `.into_iter()` call, but as long as we
5780                        // still point at the other method calls that might have
5781                        // introduced the issue, this is fine for now.
5782                        primary_spans.push(span);
5783                    }
5784                    span_labels.push((
5785                        span,
5786                        {
    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!(
5787                            "`{}` is `{ty}` here",
5788                            self.tcx.def_path_str(assoc),
5789                        )),
5790                    ));
5791                }
5792                break;
5793            };
5794            for (entry, prev_entry) in
5795                assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
5796            {
5797                match (entry, prev_entry) {
5798                    (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
5799                        let ty_str = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5800
5801                        let assoc = { let _guard = ForceTrimmedGuard::new(); self.tcx.def_path_str(assoc) }with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
5802                        if !self.can_eq(param_env, ty, *prev_ty) {
5803                            if type_diffs.iter().any(|diff| {
5804                                let TypeError::Sorts(expected_found) = diff else {
5805                                    return false;
5806                                };
5807                                self.can_eq(param_env, expected_found.found, ty)
5808                            }) {
5809                                primary_spans.push(span);
5810                            }
5811                            span_labels
5812                                .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")));
5813                        } else {
5814                            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")));
5815                        }
5816                    }
5817                    (Some((span, (assoc, ty))), None) => {
5818                        span_labels.push((
5819                            span,
5820                            {
    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!(
5821                                "`{}` is `{}` here",
5822                                self.tcx.def_path_str(assoc),
5823                                self.ty_to_string(ty),
5824                            )),
5825                        ));
5826                    }
5827                    (None, Some(_)) | (None, None) => {}
5828                }
5829            }
5830        }
5831        if !primary_spans.is_empty() {
5832            let mut multi_span: MultiSpan = primary_spans.into();
5833            for (span, label) in span_labels {
5834                multi_span.push_span_label(span, label);
5835            }
5836            err.span_note(
5837                multi_span,
5838                "the method call chain might not have had the expected associated types",
5839            );
5840        }
5841    }
5842
5843    fn probe_assoc_types_at_expr(
5844        &self,
5845        type_diffs: &[TypeError<'tcx>],
5846        span: Span,
5847        prev_ty: Ty<'tcx>,
5848        body_id: HirId,
5849        param_env: ty::ParamEnv<'tcx>,
5850    ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
5851        let ocx = ObligationCtxt::new(self.infcx);
5852        let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
5853        for diff in type_diffs {
5854            let TypeError::Sorts(expected_found) = diff else {
5855                continue;
5856            };
5857            let &ty::Alias(_, ty::AliasTy { kind: kind @ ty::Projection { def_id }, .. }) =
5858                expected_found.expected.kind()
5859            else {
5860                continue;
5861            };
5862
5863            // Make `Self` be equivalent to the type of the call chain
5864            // expression we're looking at now, so that we can tell what
5865            // for example `Iterator::Item` is at this point in the chain.
5866            let args = GenericArgs::for_item(self.tcx, def_id, |param, _| {
5867                if param.index == 0 {
5868                    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 { .. });
5869                    return prev_ty.into();
5870                }
5871                self.var_for_def(span, param)
5872            });
5873            // This will hold the resolved type of the associated type, if the
5874            // current expression implements the trait that associated type is
5875            // in. For example, this would be what `Iterator::Item` is here.
5876            let ty = self.infcx.next_ty_var(span);
5877            // This corresponds to `<ExprTy as Iterator>::Item = _`.
5878            let projection = ty::Binder::dummy(ty::PredicateKind::Clause(
5879                ty::ClauseKind::Projection(ty::ProjectionClause {
5880                    projection_term: ty::AliasTerm::new_from_args(self.tcx, kind.into(), args),
5881                    term: ty.into(),
5882                }),
5883            ));
5884            let body_def_id = self.tcx.hir_enclosing_body_owner(body_id);
5885            // Add `<ExprTy as Iterator>::Item = _` obligation.
5886            ocx.register_obligation(Obligation::misc(
5887                self.tcx,
5888                span,
5889                body_def_id,
5890                param_env,
5891                projection,
5892            ));
5893            if ocx.try_evaluate_obligations().no_errors()
5894                && let ty = self.deeply_resolve_ignoring_regions(ty)
5895                && !ty.is_ty_var()
5896            {
5897                assocs_in_this_method.push(Some((span, (def_id, ty))));
5898            } else {
5899                // `<ExprTy as Iterator>` didn't select, so likely we've
5900                // reached the end of the iterator chain, like the originating
5901                // `Vec<_>` or the `ty` couldn't be determined.
5902                // Keep the space consistent for later zipping.
5903                assocs_in_this_method.push(None);
5904            }
5905        }
5906        assocs_in_this_method
5907    }
5908
5909    /// When a `-> impl Trait<Assoc = Ty>` return type obligation fails, walk the method call
5910    /// chain in the returned expression to point at where the associated type diverged from
5911    /// what the signature expects.
5912    ///
5913    /// ```text
5914    /// note: the method call chain might not have had the expected associated types
5915    ///   --> $DIR/invalid-iterator-chain-in-return-position.rs:16:18
5916    ///    |
5917    /// LL |     x.iter_mut().map(foo)
5918    ///    |     - ---------- ^^^^^^^^ `Iterator::Item` changed to `()` here
5919    ///    |     | |
5920    ///    |     | `Iterator::Item` is `&mut Vec<u8>` here
5921    ///    |     this expression has type `Vec<Vec<u8>>`
5922    /// ```
5923    fn point_at_chain_in_return_position<G>(
5924        &self,
5925        body_def_id: LocalDefId,
5926        expr: &hir::Expr<'_>,
5927        typeck_results: &TypeckResults<'tcx>,
5928        param_env: ty::ParamEnv<'tcx>,
5929        err: &mut Diag<'_, G>,
5930    ) {
5931        let tcx = self.tcx;
5932        if !#[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(body_def_id) {
    DefKind::Fn | DefKind::AssocFn => true,
    _ => false,
}matches!(tcx.def_kind(body_def_id), DefKind::Fn | DefKind::AssocFn) {
5933            return;
5934        }
5935
5936        let binder = tcx.fn_sig(body_def_id).instantiate_identity().skip_norm_wip().output();
5937        self.enter_forall(binder, |output| {
5938            let &ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id: opaque_def_id }, args, .. }) =
5939                output.kind()
5940            else {
5941                return;
5942            };
5943
5944            // The predicate that reaches here has been rewritten through the impls it was
5945            // derived from (e.g. `Iterator for Map<I, F>` turns `Iterator::Item` requirements
5946            // into requirements on `F`'s return type), so the associated types the user wrote
5947            // in the signature are recovered from the opaque's bounds instead.
5948            let mut probe_diffs = ::alloc::vec::Vec::new()vec![];
5949            for clause in tcx.item_bounds(opaque_def_id).instantiate(tcx, args).skip_norm_wip() {
5950                let Some(proj) = clause.as_projection_clause() else { continue };
5951                let proj = self.instantiate_binder_with_fresh_vars(
5952                    expr.span,
5953                    BoundRegionConversionTime::FnCall,
5954                    proj,
5955                );
5956                let Some(expected_term) = proj.term.as_type() else { continue };
5957                // Only the projection (for its `DefId`) is used when probing the chain; the
5958                // bound's own term is carried in `found` for the divergence check below and
5959                // is replaced with the probed type afterwards.
5960                probe_diffs.push(TypeError::Sorts(ty::error::ExpectedFound {
5961                    expected: proj.projection_term.expect_ty().to_ty(tcx, ty::IsRigid::No),
5962                    found: expected_term,
5963                }));
5964            }
5965            if probe_diffs.is_empty() {
5966                return;
5967            }
5968
5969            // If the returned expression is a binding, walk the chain that created it instead.
5970            let expr = if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
5971                && let hir::Path { res: Res::Local(hir_id), .. } = path
5972                && let hir::Node::Pat(binding) = tcx.hir_node(*hir_id)
5973                && let hir::Node::LetStmt(local) = tcx.parent_hir_node(binding.hir_id)
5974                && let Some(binding_expr) = local.init
5975            {
5976                binding_expr
5977            } else {
5978                expr
5979            };
5980
5981            // Resolve what each bound associated type actually is for the returned expression,
5982            // and keep only the ones that diverged from the signature.
5983            let expr_ty = self.deeply_resolve_ignoring_regions(
5984                typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5985            );
5986            let assocs = self.probe_assoc_types_at_expr(
5987                &probe_diffs,
5988                expr.span,
5989                expr_ty,
5990                expr.hir_id,
5991                param_env,
5992            );
5993            let mut type_diffs = ::alloc::vec::Vec::new()vec![];
5994            for (probe_diff, assoc) in iter::zip(probe_diffs, assocs) {
5995                let TypeError::Sorts(ty::error::ExpectedFound { expected, found: expected_term }) =
5996                    probe_diff
5997                else {
5998                    continue;
5999                };
6000                let Some((_, (_, actual_ty))) = assoc else { continue };
6001                if !self.can_eq(param_env, expected_term, actual_ty) {
6002                    type_diffs.push(TypeError::Sorts(ty::error::ExpectedFound {
6003                        expected,
6004                        found: actual_ty,
6005                    }));
6006                }
6007            }
6008            if !type_diffs.is_empty() {
6009                self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
6010            }
6011        });
6012    }
6013
6014    /// If the type that failed selection is an array or a reference to an array,
6015    /// but the trait is implemented for slices, suggest that the user converts
6016    /// the array into a slice.
6017    pub(super) fn suggest_convert_to_slice(
6018        &self,
6019        err: &mut Diag<'_>,
6020        obligation: &PredicateObligation<'tcx>,
6021        trait_pred: ty::PolyTraitClause<'tcx>,
6022        candidate_impls: &[ImplCandidate<'tcx>],
6023        span: Span,
6024    ) {
6025        if span.in_external_macro(self.tcx.sess.source_map()) {
6026            return;
6027        }
6028        // We can only suggest the slice coercion for function and binary operation arguments,
6029        // since the suggestion would make no sense in turbofish or call
6030        let (ObligationCauseCode::BinOp { .. } | ObligationCauseCode::FunctionArg { .. }) =
6031            obligation.cause.code()
6032        else {
6033            return;
6034        };
6035
6036        // Three cases where we can make a suggestion:
6037        // 1. `[T; _]` (array of T)
6038        // 2. `&[T; _]` (reference to array of T)
6039        // 3. `&mut [T; _]` (mutable reference to array of T)
6040        let (element_ty, mut mutability) = match *trait_pred.skip_binder().self_ty().kind() {
6041            ty::Array(element_ty, _) => (element_ty, None),
6042
6043            ty::Ref(_, pointee_ty, mutability) => match *pointee_ty.kind() {
6044                ty::Array(element_ty, _) => (element_ty, Some(mutability)),
6045                _ => return,
6046            },
6047
6048            _ => return,
6049        };
6050
6051        // Go through all the candidate impls to see if any of them is for
6052        // slices of `element_ty` with `mutability`.
6053        let mut is_slice = |candidate: Ty<'tcx>| match *candidate.kind() {
6054            ty::RawPtr(t, m) | ty::Ref(_, t, m) => {
6055                if let ty::Slice(e) = *t.kind()
6056                    && e == element_ty
6057                    && m == mutability.unwrap_or(m)
6058                {
6059                    // Use the candidate's mutability going forward.
6060                    mutability = Some(m);
6061                    true
6062                } else {
6063                    false
6064                }
6065            }
6066            _ => false,
6067        };
6068
6069        // Grab the first candidate that matches, if any, and make a suggestion.
6070        if let Some(slice_ty) = candidate_impls
6071            .iter()
6072            .map(|trait_ref| trait_ref.trait_ref.self_ty())
6073            .find(|t| is_slice(*t))
6074        {
6075            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");
6076
6077            if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
6078                let mut suggestions = ::alloc::vec::Vec::new()vec![];
6079                if snippet.starts_with('&') {
6080                } else if let Some(hir::Mutability::Mut) = mutability {
6081                    suggestions.push((span.shrink_to_lo(), "&mut ".into()));
6082                } else {
6083                    suggestions.push((span.shrink_to_lo(), "&".into()));
6084                }
6085                suggestions.push((span.shrink_to_hi(), "[..]".into()));
6086                err.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
6087            } else {
6088                err.span_help(span, msg);
6089            }
6090        }
6091    }
6092
6093    /// If the type failed selection but the trait is implemented for `(T,)`, suggest that the user
6094    /// creates a unary tuple
6095    ///
6096    /// This is a common gotcha when using libraries that emulate variadic functions with traits for tuples.
6097    pub(super) fn suggest_tuple_wrapping(
6098        &self,
6099        err: &mut Diag<'_>,
6100        root_obligation: &PredicateObligation<'tcx>,
6101        obligation: &PredicateObligation<'tcx>,
6102    ) {
6103        let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code() else {
6104            return;
6105        };
6106
6107        let Some(root_pred) = root_obligation.predicate.as_trait_clause() else { return };
6108
6109        let trait_ref = root_pred.map_bound(|root_pred| {
6110            root_pred.trait_ref.with_replaced_self_ty(
6111                self.tcx,
6112                Ty::new_tup(self.tcx, &[root_pred.trait_ref.self_ty()]),
6113            )
6114        });
6115
6116        let obligation =
6117            Obligation::new(self.tcx, obligation.cause.clone(), obligation.param_env, trait_ref);
6118
6119        if self.predicate_must_hold_modulo_regions(&obligation) {
6120            let arg_span = self.tcx.hir_span(*arg_hir_id);
6121            err.multipart_suggestion(
6122                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use a unary tuple instead"))
    })format!("use a unary tuple instead"),
6123                ::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())],
6124                Applicability::MaybeIncorrect,
6125            );
6126        }
6127    }
6128
6129    pub(super) fn suggest_shadowed_inherent_method(
6130        &self,
6131        err: &mut Diag<'_>,
6132        obligation: &PredicateObligation<'tcx>,
6133        trait_predicate: ty::PolyTraitClause<'tcx>,
6134    ) {
6135        let ObligationCauseCode::FunctionArg { call_hir_id, .. } = obligation.cause.code() else {
6136            return;
6137        };
6138        let Node::Expr(call) = self.tcx.hir_node(*call_hir_id) else { return };
6139        let hir::ExprKind::MethodCall(segment, rcvr, args, ..) = call.kind else { return };
6140        let Some(typeck) = &self.typeck_results else { return };
6141        let Some(rcvr_ty) = typeck.expr_ty_adjusted_opt(rcvr) else { return };
6142        let rcvr_ty = self.deeply_resolve_ignoring_regions(rcvr_ty);
6143        let autoderef = (self.autoderef_steps)(rcvr_ty);
6144        for (ty, def_id) in autoderef.iter().filter_map(|(ty, obligations)| {
6145            if let ty::Adt(def, _) = ty.kind()
6146                && *ty != rcvr_ty.peel_refs()
6147                && obligations.iter().all(|obligation| self.predicate_may_hold(obligation))
6148            {
6149                Some((ty, def.did()))
6150            } else {
6151                None
6152            }
6153        }) {
6154            for impl_def_id in self.tcx.inherent_impls(def_id) {
6155                if *impl_def_id == trait_predicate.def_id() {
6156                    continue;
6157                }
6158                for m in self
6159                    .tcx
6160                    .provided_trait_methods(*impl_def_id)
6161                    .filter(|m| m.name() == segment.ident.name)
6162                {
6163                    let fn_sig = self.tcx.fn_sig(m.def_id);
6164                    if fn_sig.skip_binder().inputs().skip_binder().len() != args.len() + 1 {
6165                        continue;
6166                    }
6167                    let rcvr_ty = fn_sig.skip_binder().input(0).skip_binder();
6168                    let (mutability, _ty) = match rcvr_ty.kind() {
6169                        ty::Ref(_, ty, hir::Mutability::Mut) => ("&mut ", ty),
6170                        ty::Ref(_, ty, _) => ("&", ty),
6171                        _ => ("", &rcvr_ty),
6172                    };
6173                    let path = self.tcx.def_path_str(def_id);
6174                    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!(
6175                        "there's an inherent method on `{ty}` of the same name, which can be \
6176                         auto-dereferenced from `{rcvr_ty}`"
6177                    ));
6178                    err.multipart_suggestion(
6179                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("to access the inherent method on `{0}`, use the fully-qualified path",
                ty))
    })format!(
6180                            "to access the inherent method on `{ty}`, use the fully-qualified path",
6181                        ),
6182                        ::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![
6183                            (
6184                                call.span.until(rcvr.span),
6185                                format!("{path}::{}({}", m.name(), mutability),
6186                            ),
6187                            match &args {
6188                                [] => (
6189                                    rcvr.span.shrink_to_hi().with_hi(call.span.hi()),
6190                                    ")".to_string(),
6191                                ),
6192                                [first, ..] => (rcvr.span.between(first.span), ", ".to_string()),
6193                            },
6194                        ],
6195                        Applicability::MaybeIncorrect,
6196                    );
6197                }
6198            }
6199        }
6200    }
6201
6202    pub(super) fn explain_hrtb_projection(
6203        &self,
6204        diag: &mut Diag<'_>,
6205        pred: ty::PolyTraitClause<'tcx>,
6206        param_env: ty::ParamEnv<'tcx>,
6207        cause: &ObligationCause<'tcx>,
6208    ) {
6209        if pred.skip_binder().has_escaping_bound_vars() && pred.skip_binder().has_non_region_infer()
6210        {
6211            self.probe(|_| {
6212                let ocx = ObligationCtxt::new(self);
6213                ocx.register_obligation(Obligation::new(
6214                    self.tcx,
6215                    ObligationCause::dummy(),
6216                    param_env,
6217                    pred,
6218                ));
6219                if !ocx.try_evaluate_obligations().no_errors() {
6220                    // encountered errors.
6221                    return;
6222                }
6223
6224                if let ObligationCauseCode::FunctionArg {
6225                    call_hir_id,
6226                    arg_hir_id,
6227                    parent_code: _,
6228                } = cause.code()
6229                {
6230                    let arg_span = self.tcx.hir_span(*arg_hir_id);
6231                    let mut sp: MultiSpan = arg_span.into();
6232
6233                    sp.push_span_label(
6234                        arg_span,
6235                        "the trait solver is unable to infer the \
6236                        generic types that should be inferred from this argument",
6237                    );
6238                    sp.push_span_label(
6239                        self.tcx.hir_span(*call_hir_id),
6240                        "add turbofish arguments to this call to \
6241                        specify the types manually, even if it's redundant",
6242                    );
6243                    diag.span_note(
6244                        sp,
6245                        "this is a known limitation of the trait solver that \
6246                        will be lifted in the future",
6247                    );
6248                } else {
6249                    let mut sp: MultiSpan = cause.span.into();
6250                    sp.push_span_label(
6251                        cause.span,
6252                        "try adding turbofish arguments to this expression to \
6253                        specify the types manually, even if it's redundant",
6254                    );
6255                    diag.span_note(
6256                        sp,
6257                        "this is a known limitation of the trait solver that \
6258                        will be lifted in the future",
6259                    );
6260                }
6261            });
6262        }
6263    }
6264
6265    pub(super) fn suggest_desugaring_async_fn_in_trait(
6266        &self,
6267        err: &mut Diag<'_>,
6268        trait_pred: ty::PolyTraitClause<'tcx>,
6269    ) {
6270        // Don't suggest if RTN is active -- we should prefer a where-clause bound instead.
6271        if self.tcx.features().return_type_notation() {
6272            return;
6273        }
6274
6275        let trait_def_id = trait_pred.def_id();
6276
6277        // Only suggest specifying auto traits
6278        if !self.tcx.trait_is_auto(trait_def_id) {
6279            return;
6280        }
6281
6282        // Look for an RPITIT
6283        let ty::Alias(_, alias_ty @ ty::AliasTy { kind: ty::Projection { def_id }, .. }) =
6284            trait_pred.self_ty().skip_binder().kind()
6285        else {
6286            return;
6287        };
6288        let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, opaque_def_id }) =
6289            self.tcx.opt_rpitit_info(*def_id)
6290        else {
6291            return;
6292        };
6293
6294        let auto_trait = self.tcx.def_path_str(trait_def_id);
6295        // ... which is a local function
6296        let Some(fn_def_id) = fn_def_id.as_local() else {
6297            // If it's not local, we can at least mention that the method is async, if it is.
6298            if self.tcx.asyncness(fn_def_id).is_async() {
6299                err.span_note(
6300                    self.tcx.def_span(fn_def_id),
6301                    ::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!(
6302                        "`{}::{}` is an `async fn` in trait, which does not \
6303                    automatically imply that its future is `{auto_trait}`",
6304                        alias_ty.trait_ref(self.tcx),
6305                        self.tcx.item_name(fn_def_id)
6306                    ),
6307                );
6308            }
6309            return;
6310        };
6311        let hir::Node::TraitItem(item) = self.tcx.hir_node_by_def_id(fn_def_id) else {
6312            return;
6313        };
6314
6315        // ... whose signature is `async` (i.e. this is an AFIT)
6316        let (sig, body) = item.expect_fn();
6317        let hir::FnRetTy::Return(hir::Ty { kind: hir::TyKind::OpaqueDef(opaq_def, ..), .. }) =
6318            sig.decl.output
6319        else {
6320            // This should never happen, but let's not ICE.
6321            return;
6322        };
6323
6324        // Check that this is *not* a nested `impl Future` RPIT in an async fn
6325        // (i.e. `async fn foo() -> impl Future`)
6326        if opaq_def.def_id.to_def_id() != opaque_def_id {
6327            return;
6328        }
6329
6330        let Some(sugg) = suggest_desugaring_async_fn_to_impl_future_in_trait(
6331            self.tcx,
6332            *sig,
6333            *body,
6334            opaque_def_id.expect_local(),
6335            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" + {0}", auto_trait))
    })format!(" + {auto_trait}"),
6336        ) else {
6337            return;
6338        };
6339
6340        let function_name = self.tcx.def_path_str(fn_def_id);
6341        err.multipart_suggestion(
6342            ::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!(
6343                "`{auto_trait}` can be made part of the associated future's \
6344                guarantees for all implementations of `{function_name}`"
6345            ),
6346            sugg,
6347            Applicability::MachineApplicable,
6348        );
6349    }
6350
6351    pub fn ty_kind_suggestion(
6352        &self,
6353        param_env: ty::ParamEnv<'tcx>,
6354        ty: Ty<'tcx>,
6355    ) -> Option<String> {
6356        let tcx = self.infcx.tcx;
6357        let implements_default = |ty| {
6358            let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
6359                return false;
6360            };
6361            self.type_implements_trait(default_trait, [ty], param_env).must_apply_modulo_regions()
6362        };
6363
6364        Some(match *ty.kind() {
6365            ty::Never | ty::Error(_) => return None,
6366            ty::Bool => "false".to_string(),
6367            ty::Char => "\'x\'".to_string(),
6368            ty::Int(_) | ty::Uint(_) => "42".into(),
6369            ty::Float(_) => "3.14159".into(),
6370            ty::Slice(_) => "[]".to_string(),
6371            ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => {
6372                "vec![]".to_string()
6373            }
6374            ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::String) => {
6375                "String::new()".to_string()
6376            }
6377            ty::Adt(def, args) if def.is_box() => {
6378                ::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())?)
6379            }
6380            ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Option) => {
6381                "None".to_string()
6382            }
6383            ty::Adt(def, args) if Some(def.did()) == tcx.get_diagnostic_item(sym::Result) => {
6384                ::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())?)
6385            }
6386            ty::Adt(_, _) if implements_default(ty) => "Default::default()".to_string(),
6387            ty::Ref(_, ty, mutability) => {
6388                if let (ty::Str, hir::Mutability::Not) = (ty.kind(), mutability) {
6389                    "\"\"".to_string()
6390                } else {
6391                    let ty = self.ty_kind_suggestion(param_env, ty)?;
6392                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}{1}", mutability.prefix_str(),
                ty))
    })format!("&{}{ty}", mutability.prefix_str())
6393                }
6394            }
6395            ty::Array(ty, len) if let Some(len) = len.try_to_target_usize(tcx) => {
6396                if len == 0 {
6397                    "[]".to_string()
6398                } else if self.type_is_copy_modulo_regions(param_env, ty) || len == 1 {
6399                    // Can only suggest `[ty; 0]` if sz == 1 or copy
6400                    ::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)
6401                } else {
6402                    "/* value */".to_string()
6403                }
6404            }
6405            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!(
6406                "({}{})",
6407                tys.iter()
6408                    .map(|ty| self.ty_kind_suggestion(param_env, ty))
6409                    .collect::<Option<Vec<String>>>()?
6410                    .join(", "),
6411                if tys.len() == 1 { "," } else { "" }
6412            ),
6413            _ => "/* value */".to_string(),
6414        })
6415    }
6416
6417    // For E0277 when use `?` operator, suggest adding
6418    // a suitable return type in `FnSig`, and a default
6419    // return value at the end of the function's body.
6420    pub(super) fn suggest_add_result_as_return_type(
6421        &self,
6422        obligation: &PredicateObligation<'tcx>,
6423        err: &mut Diag<'_>,
6424        trait_pred: ty::PolyTraitClause<'tcx>,
6425    ) {
6426        if ObligationCauseCode::QuestionMark != *obligation.cause.code().peel_derives() {
6427            return;
6428        }
6429
6430        // Only suggest for local function and associated method,
6431        // because this suggest adding both return type in
6432        // the `FnSig` and a default return value in the body, so it
6433        // is not suitable for foreign function without a local body,
6434        // and neither for trait method which may be also implemented
6435        // in other place, so shouldn't change it's FnSig.
6436        fn choose_suggest_items<'tcx, 'hir>(
6437            tcx: TyCtxt<'tcx>,
6438            node: hir::Node<'hir>,
6439        ) -> Option<(&'hir hir::FnDecl<'hir>, hir::BodyId)> {
6440            match node {
6441                hir::Node::Item(item)
6442                    if let hir::ItemKind::Fn { sig, body: body_id, .. } = item.kind =>
6443                {
6444                    Some((sig.decl, body_id))
6445                }
6446                hir::Node::ImplItem(item)
6447                    if let hir::ImplItemKind::Fn(sig, body_id) = item.kind =>
6448                {
6449                    let parent = tcx.parent_hir_node(item.hir_id());
6450                    if let hir::Node::Item(item) = parent
6451                        && let hir::ItemKind::Impl(imp) = item.kind
6452                        && imp.of_trait.is_none()
6453                    {
6454                        return Some((sig.decl, body_id));
6455                    }
6456                    None
6457                }
6458                _ => None,
6459            }
6460        }
6461
6462        let node = self.tcx.hir_node_by_def_id(obligation.cause.body_def_id);
6463        if let Some((fn_decl, body_id)) = choose_suggest_items(self.tcx, node)
6464            && let hir::FnRetTy::DefaultReturn(ret_span) = fn_decl.output
6465            && self.tcx.is_diagnostic_item(sym::FromResidual, trait_pred.def_id())
6466            && trait_pred.skip_binder().trait_ref.args.type_at(0).is_unit()
6467            && let ty::Adt(def, _) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
6468            && self.tcx.is_diagnostic_item(sym::Result, def.did())
6469        {
6470            let mut sugg_spans =
6471                ::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())];
6472            let body = self.tcx.hir_body(body_id);
6473            if let hir::ExprKind::Block(b, _) = body.value.kind
6474                && b.expr.is_none()
6475            {
6476                // The span of '}' in the end of block.
6477                let span = self.tcx.sess.source_map().end_point(b.span);
6478                sugg_spans.push((
6479                    span.shrink_to_lo(),
6480                    ::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!(
6481                        "{}{}",
6482                        "    Ok(())\n",
6483                        self.tcx.sess.source_map().indentation_before(span).unwrap_or_default(),
6484                    ),
6485                ));
6486            }
6487            err.multipart_suggestion(
6488                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider adding return type"))
    })format!("consider adding return type"),
6489                sugg_spans,
6490                Applicability::MaybeIncorrect,
6491            );
6492        }
6493    }
6494
6495    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("suggest_unsized_bound_if_applicable",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(6495u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
                obligation.predicate.kind().skip_binder() else { return; };
            let (ObligationCauseCode::WhereClause(item_def_id, span) |
                    ObligationCauseCode::WhereClauseInExpr(item_def_id, span,
                    ..)) =
                *obligation.cause.code().peel_derives() else { return; };
            if span.is_dummy() { return; }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6515",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(6515u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("pred")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("pred");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pred)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_def_id)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let (Some(node), true) =
                (self.tcx.hir_get_if_local(item_def_id),
                    self.tcx.is_lang_item(pred.def_id(),
                        LangItem::Sized)) else { return; };
            let Some(generics) = node.generics() else { return; };
            let sized_trait = self.tcx.lang_items().sized_trait();
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6528",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(6528u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("generics.params")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("generics.params");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generics.params)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6529",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(6529u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("generics.predicates")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("generics.predicates");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generics.predicates)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let Some(param) =
                generics.params.iter().find(|param|
                        param.span == span) else { return; };
            let explicitly_sized =
                generics.bounds_for_param(param.def_id).flat_map(|bp|
                            bp.bounds).any(|bound|
                        bound.trait_ref().and_then(|tr| tr.trait_def_id()) ==
                            sized_trait);
            if explicitly_sized { return; }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6542",
                                    "rustc_trait_selection::error_reporting::traits::suggestions",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(6542u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("param")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("param");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            match node {
                hir::Node::Item(item @ hir::Item {
                    kind: hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) |
                        hir::ItemKind::Union(..), .. }) => {
                    if self.suggest_indirection_for_unsized(err, item, param) {
                        return;
                    }
                }
                _ => {}
            };
            let (span, separator, open_paren_sp) =
                if let Some((s, open_paren_sp)) =
                        generics.bounds_span_for_suggestions(param.def_id) {
                    (s, " +", open_paren_sp)
                } else {
                    (param.name.ident().span.shrink_to_hi(), ":", None)
                };
            let mut suggs = ::alloc::vec::Vec::new();
            let suggestion =
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("{0} ?Sized", separator))
                    });
            if let Some(open_paren_sp) = open_paren_sp {
                suggs.push((open_paren_sp, "(".to_string()));
                suggs.push((span,
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("){0}", suggestion))
                            })));
            } else { suggs.push((span, suggestion)); }
            err.multipart_suggestion("consider relaxing the implicit `Sized` restriction",
                suggs, Applicability::MachineApplicable);
        }
    }
}#[instrument(level = "debug", skip_all)]
6496    pub(super) fn suggest_unsized_bound_if_applicable(
6497        &self,
6498        err: &mut Diag<'_>,
6499        obligation: &PredicateObligation<'tcx>,
6500    ) {
6501        let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
6502            obligation.predicate.kind().skip_binder()
6503        else {
6504            return;
6505        };
6506        let (ObligationCauseCode::WhereClause(item_def_id, span)
6507        | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)) =
6508            *obligation.cause.code().peel_derives()
6509        else {
6510            return;
6511        };
6512        if span.is_dummy() {
6513            return;
6514        }
6515        debug!(?pred, ?item_def_id, ?span);
6516
6517        let (Some(node), true) = (
6518            self.tcx.hir_get_if_local(item_def_id),
6519            self.tcx.is_lang_item(pred.def_id(), LangItem::Sized),
6520        ) else {
6521            return;
6522        };
6523
6524        let Some(generics) = node.generics() else {
6525            return;
6526        };
6527        let sized_trait = self.tcx.lang_items().sized_trait();
6528        debug!(?generics.params);
6529        debug!(?generics.predicates);
6530        let Some(param) = generics.params.iter().find(|param| param.span == span) else {
6531            return;
6532        };
6533        // Check that none of the explicit trait bounds is `Sized`. Assume that an explicit
6534        // `Sized` bound is there intentionally and we don't need to suggest relaxing it.
6535        let explicitly_sized = generics
6536            .bounds_for_param(param.def_id)
6537            .flat_map(|bp| bp.bounds)
6538            .any(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) == sized_trait);
6539        if explicitly_sized {
6540            return;
6541        }
6542        debug!(?param);
6543        match node {
6544            hir::Node::Item(
6545                item @ hir::Item {
6546                    // Only suggest indirection for uses of type parameters in ADTs.
6547                    kind:
6548                        hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..),
6549                    ..
6550                },
6551            ) => {
6552                if self.suggest_indirection_for_unsized(err, item, param) {
6553                    return;
6554                }
6555            }
6556            _ => {}
6557        };
6558
6559        // Didn't add an indirection suggestion, so add a general suggestion to relax `Sized`.
6560        let (span, separator, open_paren_sp) =
6561            if let Some((s, open_paren_sp)) = generics.bounds_span_for_suggestions(param.def_id) {
6562                (s, " +", open_paren_sp)
6563            } else {
6564                (param.name.ident().span.shrink_to_hi(), ":", None)
6565            };
6566
6567        let mut suggs = vec![];
6568        let suggestion = format!("{separator} ?Sized");
6569
6570        if let Some(open_paren_sp) = open_paren_sp {
6571            suggs.push((open_paren_sp, "(".to_string()));
6572            suggs.push((span, format!("){suggestion}")));
6573        } else {
6574            suggs.push((span, suggestion));
6575        }
6576
6577        err.multipart_suggestion(
6578            "consider relaxing the implicit `Sized` restriction",
6579            suggs,
6580            Applicability::MachineApplicable,
6581        );
6582    }
6583
6584    fn suggest_indirection_for_unsized(
6585        &self,
6586        err: &mut Diag<'_>,
6587        item: &hir::Item<'tcx>,
6588        param: &hir::GenericParam<'tcx>,
6589    ) -> bool {
6590        // Suggesting `T: ?Sized` is only valid in an ADT if `T` is only used in a
6591        // borrow. `struct S<'a, T: ?Sized>(&'a T);` is valid, `struct S<T: ?Sized>(T);`
6592        // is not. Look for invalid "bare" parameter uses, and suggest using indirection.
6593        let mut visitor = FindTypeParam { param: param.name.ident().name, .. };
6594        visitor.visit_item(item);
6595        if visitor.invalid_spans.is_empty() {
6596            return false;
6597        }
6598        let mut multispan: MultiSpan = param.span.into();
6599        multispan.push_span_label(
6600            param.span,
6601            ::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()),
6602        );
6603        for sp in visitor.invalid_spans {
6604            multispan.push_span_label(
6605                sp,
6606                ::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()),
6607            );
6608        }
6609        err.span_help(
6610            multispan,
6611            ::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!(
6612                "you could relax the implicit `Sized` bound on `{T}` if it were \
6613                used through indirection like `&{T}` or `Box<{T}>`",
6614                T = param.name.ident(),
6615            ),
6616        );
6617        true
6618    }
6619    pub(crate) fn suggest_swapping_lhs_and_rhs<T>(
6620        &self,
6621        err: &mut Diag<'_>,
6622        predicate: T,
6623        param_env: ty::ParamEnv<'tcx>,
6624        cause_code: &ObligationCauseCode<'tcx>,
6625    ) where
6626        T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
6627    {
6628        let tcx = self.tcx;
6629        let predicate = predicate.upcast(tcx);
6630        match *cause_code {
6631            ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, rhs_span, .. }
6632                if let Some(typeck_results) = &self.typeck_results
6633                    && let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
6634                    && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
6635                    && let Some(lhs_ty) = typeck_results.expr_ty_opt(lhs)
6636                    && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs) =>
6637            {
6638                if let Some(pred) = predicate.as_trait_clause()
6639                    && tcx.is_lang_item(pred.def_id(), LangItem::PartialEq)
6640                    && self
6641                        .infcx
6642                        .type_implements_trait(pred.def_id(), [rhs_ty, lhs_ty], param_env)
6643                        .must_apply_modulo_regions()
6644                {
6645                    let lhs_span = tcx.hir_span(lhs_hir_id);
6646                    let sm = tcx.sess.source_map();
6647                    if let Ok(rhs_snippet) = sm.span_to_snippet(rhs_span)
6648                        && let Ok(lhs_snippet) = sm.span_to_snippet(lhs_span)
6649                    {
6650                        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}>`"));
6651                        err.multipart_suggestion(
6652                            "consider swapping the equality",
6653                            ::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)],
6654                            Applicability::MaybeIncorrect,
6655                        );
6656                    }
6657                }
6658            }
6659            _ => {}
6660        }
6661    }
6662
6663    /// Checks whether the field independently satisfies the trait bound, ignoring
6664    /// the specific generic parameter that caused the original E0277 error.
6665    fn is_truly_imperfect_derive(
6666        &self,
6667        parent_trait_pred: ty::PolyTraitClause<'tcx>,
6668        predicate: ty::Predicate<'tcx>,
6669        param_env: ty::ParamEnv<'tcx>,
6670    ) -> bool {
6671        let tcx = self.tcx;
6672        let ty::Adt(adt_def, parent_args) = parent_trait_pred.skip_binder().self_ty().kind() else {
6673            return false;
6674        };
6675        let Some(trait_clause) = predicate.as_trait_clause() else {
6676            return false;
6677        };
6678        let failing_ty = trait_clause.skip_binder().self_ty();
6679        let trait_def_id = parent_trait_pred.def_id();
6680
6681        let failing_adt_param_indices: FxHashSet<u32> = parent_args
6682            .iter()
6683            .enumerate()
6684            .filter_map(|(idx, arg)| {
6685                if let Some(t) = arg.as_type()
6686                    && t == failing_ty
6687                {
6688                    Some(idx as u32)
6689                } else {
6690                    None
6691                }
6692            })
6693            .collect();
6694
6695        if failing_adt_param_indices.is_empty() {
6696            return false;
6697        }
6698
6699        adt_def.all_fields().all(|field| {
6700            let raw_field_ty = tcx.type_of(field.did).skip_binder();
6701            // If the field type is exactly one of the failing parameters, it is not an imperfect derive.
6702            if let ty::Param(p) = raw_field_ty.kind()
6703                && failing_adt_param_indices.contains(&p.index)
6704            {
6705                return false;
6706            }
6707            // If the field type doesn't mention the parameter at all, it's independent.
6708            if !raw_field_ty.walk().any(|arg| {
6709                #[allow(non_exhaustive_omitted_patterns)] match arg.as_type().map(|t|
            t.kind()) {
    Some(ty::Param(p)) if failing_adt_param_indices.contains(&p.index) =>
        true,
    _ => false,
}matches!(arg.as_type().map(|t| t.kind()), Some(ty::Param(p)) if failing_adt_param_indices.contains(&p.index))
6710            }) {
6711                return true;
6712            }
6713
6714            self.probe(|_| {
6715                // We keep the generic parameters that didn't fail as-is from the parent args,
6716                // but replace the ones that did fail with fresh inference variable placeholders.
6717                let fresh_args = ty::GenericArgs::for_item(tcx, adt_def.did(), |param, _| {
6718                    if failing_adt_param_indices.contains(&param.index) {
6719                        self.var_for_def(DUMMY_SP, param)
6720                    } else {
6721                        parent_args[param.index as usize]
6722                    }
6723                });
6724
6725                let field_ty = field.ty(tcx, fresh_args).skip_norm_wip();
6726                // Substitute the field's type for the bound's `Self` type to check whether
6727                // the field alone would satisfy the trait, independent of other generics.
6728                let parent_trait_args = parent_trait_pred.skip_binder().trait_ref.args;
6729                let trait_args = parent_trait_args.iter().map(|arg| {
6730                    if arg.as_type() == Some(parent_trait_pred.skip_binder().self_ty()) {
6731                        field_ty.into()
6732                    } else {
6733                        arg
6734                    }
6735                });
6736                let obligation = Obligation::new(
6737                    tcx,
6738                    ObligationCause::dummy(),
6739                    param_env,
6740                    ty::TraitRef::new(tcx, trait_def_id, trait_args),
6741                );
6742                self.predicate_may_hold(&obligation)
6743            })
6744        })
6745    }
6746}
6747
6748/// Add a hint to add a missing borrow or remove an unnecessary one.
6749fn hint_missing_borrow<'tcx>(
6750    infcx: &InferCtxt<'tcx>,
6751    param_env: ty::ParamEnv<'tcx>,
6752    span: Span,
6753    found: Ty<'tcx>,
6754    expected: Ty<'tcx>,
6755    found_node: Node<'_>,
6756    err: &mut Diag<'_>,
6757) {
6758    if #[allow(non_exhaustive_omitted_patterns)] match found_node {
    Node::TraitItem(..) => true,
    _ => false,
}matches!(found_node, Node::TraitItem(..)) {
6759        return;
6760    }
6761
6762    let found_args = match found.kind() {
6763        ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
6764        kind => {
6765            bug_impl(Some(span),
    format_args!("found was converted to a FnPtr above but is now {0:?}",
        kind), Location::caller())span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
6766        }
6767    };
6768    let expected_args = match expected.kind() {
6769        ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
6770        kind => {
6771            bug_impl(Some(span),
    format_args!("expected was converted to a FnPtr above but is now {0:?}",
        kind), Location::caller())span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
6772        }
6773    };
6774
6775    // This could be a variant constructor, for example.
6776    let Some(fn_decl) = found_node.fn_decl() else {
6777        return;
6778    };
6779
6780    let args = fn_decl.inputs.iter();
6781
6782    let mut to_borrow = Vec::new();
6783    let mut remove_borrow = Vec::new();
6784
6785    for ((found_arg, expected_arg), arg) in found_args.zip(expected_args).zip(args) {
6786        let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
6787        let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
6788
6789        if infcx.can_eq(param_env, found_ty, expected_ty) {
6790            // FIXME: This could handle more exotic cases like mutability mismatches too!
6791            if found_refs.len() < expected_refs.len()
6792                && found_refs[..] == expected_refs[expected_refs.len() - found_refs.len()..]
6793            {
6794                to_borrow.push((
6795                    arg.span.shrink_to_lo(),
6796                    expected_refs[..expected_refs.len() - found_refs.len()]
6797                        .iter()
6798                        .map(|mutbl| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
    })format!("&{}", mutbl.prefix_str()))
6799                        .collect::<Vec<_>>()
6800                        .join(""),
6801                ));
6802            } else if found_refs.len() > expected_refs.len() {
6803                let mut span = arg.span.shrink_to_lo();
6804                let mut left = found_refs.len() - expected_refs.len();
6805                let mut ty = arg;
6806                while let hir::TyKind::Ref(_, mut_ty) = &ty.kind
6807                    && left > 0
6808                {
6809                    span = span.with_hi(mut_ty.ty.span.lo());
6810                    ty = mut_ty.ty;
6811                    left -= 1;
6812                }
6813                if left == 0 {
6814                    remove_borrow.push((span, String::new()));
6815                }
6816            }
6817        }
6818    }
6819
6820    if !to_borrow.is_empty() {
6821        err.subdiagnostic(diagnostics::AdjustSignatureBorrow::Borrow { to_borrow });
6822    }
6823
6824    if !remove_borrow.is_empty() {
6825        err.subdiagnostic(diagnostics::AdjustSignatureBorrow::RemoveBorrow { remove_borrow });
6826    }
6827}
6828
6829/// Collect all the paths that reference `Self`.
6830/// Used to suggest replacing associated types with an explicit type in `where` clauses.
6831#[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)]
6832pub struct SelfVisitor<'v> {
6833    pub paths: Vec<&'v hir::Ty<'v>> = Vec::new(),
6834    pub name: Option<Symbol>,
6835}
6836
6837impl<'v> Visitor<'v> for SelfVisitor<'v> {
6838    fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
6839        if let hir::TyKind::Path(path) = ty.kind
6840            && let hir::QPath::TypeRelative(inner_ty, segment) = path
6841            && (Some(segment.ident.name) == self.name || self.name.is_none())
6842            && let hir::TyKind::Path(inner_path) = inner_ty.kind
6843            && let hir::QPath::Resolved(None, inner_path) = inner_path
6844            && let Res::SelfTyAlias { .. } = inner_path.res
6845        {
6846            self.paths.push(ty.as_unambig_ty());
6847        }
6848        hir::intravisit::walk_ty(self, ty);
6849    }
6850}
6851
6852/// Collect all the returned expressions within the input expression.
6853/// Used to point at the return spans when we want to suggest some change to them.
6854#[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)]
6855pub struct ReturnsVisitor<'v> {
6856    pub returns: Vec<&'v hir::Expr<'v>>,
6857    in_block_tail: bool,
6858}
6859
6860impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
6861    fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
6862        // Visit every expression to detect `return` paths, either through the function's tail
6863        // expression or `return` statements. We walk all nodes to find `return` statements, but
6864        // we only care about tail expressions when `in_block_tail` is `true`, which means that
6865        // they're in the return path of the function body.
6866        match ex.kind {
6867            hir::ExprKind::Ret(Some(ex)) => {
6868                self.returns.push(ex);
6869            }
6870            hir::ExprKind::Block(block, _) if self.in_block_tail => {
6871                self.in_block_tail = false;
6872                for stmt in block.stmts {
6873                    hir::intravisit::walk_stmt(self, stmt);
6874                }
6875                self.in_block_tail = true;
6876                if let Some(expr) = block.expr {
6877                    self.visit_expr(expr);
6878                }
6879            }
6880            hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
6881                self.visit_expr(then);
6882                if let Some(el) = else_opt {
6883                    self.visit_expr(el);
6884                }
6885            }
6886            hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
6887                for arm in arms {
6888                    self.visit_expr(arm.body);
6889                }
6890            }
6891            // We need to walk to find `return`s in the entire body.
6892            _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
6893            _ => self.returns.push(ex),
6894        }
6895    }
6896
6897    fn visit_body(&mut self, body: &hir::Body<'v>) {
6898        if !!self.in_block_tail {
    ::core::panicking::panic("assertion failed: !self.in_block_tail")
};assert!(!self.in_block_tail);
6899        self.in_block_tail = true;
6900        hir::intravisit::walk_body(self, body);
6901    }
6902}
6903
6904/// Collect all the awaited expressions within the input expression.
6905#[derive(#[automatically_derived]
impl ::core::default::Default for AwaitsVisitor {
    #[inline]
    fn default() -> AwaitsVisitor {
        AwaitsVisitor { awaits: ::core::default::Default::default() }
    }
}Default)]
6906struct AwaitsVisitor {
6907    awaits: Vec<HirId>,
6908}
6909
6910impl<'v> Visitor<'v> for AwaitsVisitor {
6911    fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
6912        if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
6913            self.awaits.push(id)
6914        }
6915        hir::intravisit::walk_expr(self, ex)
6916    }
6917}
6918
6919/// Suggest a new type parameter name for diagnostic purposes.
6920///
6921/// `name` is the preferred name you'd like to suggest if it's not in use already.
6922pub trait NextTypeParamName {
6923    fn next_type_param_name(&self, name: Option<&str>) -> String;
6924}
6925
6926impl NextTypeParamName for &[hir::GenericParam<'_>] {
6927    fn next_type_param_name(&self, name: Option<&str>) -> String {
6928        // Type names are usually single letters in uppercase. So convert the first letter of input string to uppercase.
6929        let name = name.and_then(|n| n.chars().next()).map(|c| c.to_uppercase().to_string());
6930        let name = name.as_deref();
6931
6932        // This is the list of possible parameter names that we might suggest.
6933        let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
6934
6935        // Filter out used names based on `filter_fn`.
6936        let used_names: Vec<Symbol> = self
6937            .iter()
6938            .filter_map(|param| match param.name {
6939                hir::ParamName::Plain(ident) => Some(ident.name),
6940                _ => None,
6941            })
6942            .collect();
6943
6944        // Find a name from `possible_names` that is not in `used_names`.
6945        possible_names
6946            .iter()
6947            .find(|n| !used_names.contains(&Symbol::intern(n)))
6948            .unwrap_or(&"ParamName")
6949            .to_string()
6950    }
6951}
6952
6953/// Collect the spans that we see the generic param `param_did`
6954struct ReplaceImplTraitVisitor<'a> {
6955    ty_spans: &'a mut Vec<Span>,
6956    param_did: DefId,
6957}
6958
6959impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
6960    fn visit_ty(&mut self, t: &'hir hir::Ty<'hir, AmbigArg>) {
6961        if let hir::TyKind::Path(hir::QPath::Resolved(
6962            None,
6963            hir::Path { res: Res::Def(_, segment_did), .. },
6964        )) = t.kind
6965        {
6966            if self.param_did == *segment_did {
6967                // `fn foo(t: impl Trait)`
6968                //            ^^^^^^^^^^ get this to suggest `T` instead
6969
6970                // There might be more than one `impl Trait`.
6971                self.ty_spans.push(t.span);
6972                return;
6973            }
6974        }
6975
6976        hir::intravisit::walk_ty(self, t);
6977    }
6978}
6979
6980pub(super) fn get_explanation_based_on_obligation<'tcx>(
6981    tcx: TyCtxt<'tcx>,
6982    obligation: &PredicateObligation<'tcx>,
6983    trait_predicate: ty::PolyTraitClause<'tcx>,
6984    pre_message: String,
6985    long_ty_path: &mut Option<PathBuf>,
6986) -> String {
6987    if let ObligationCauseCode::MainFunctionType = obligation.cause.code() {
6988        "consider using `()`, or a `Result`".to_owned()
6989    } else {
6990        let ty_desc = match trait_predicate.self_ty().skip_binder().kind() {
6991            ty::FnDef(_, _) => Some("fn item"),
6992            ty::Closure(_, _) => Some("closure"),
6993            _ => None,
6994        };
6995
6996        let desc = match ty_desc {
6997            Some(desc) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {0}", desc))
    })format!(" {desc}"),
6998            None => String::new(),
6999        };
7000        if let ty::ClausePolarity::Positive = trait_predicate.polarity() {
7001            // If the trait in question is unstable, mention that fact in the diagnostic.
7002            // But if we're building with `-Zforce-unstable-if-unmarked` then _any_ trait
7003            // not explicitly marked stable is considered unstable, so the extra text is
7004            // unhelpful noise. See <https://github.com/rust-lang/rust/issues/152692>.
7005            let mention_unstable = !tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
7006                && try { tcx.lookup_stability(trait_predicate.def_id())?.level.is_stable() }
7007                    == Some(false);
7008            let unstable = if mention_unstable { "nightly-only, unstable " } else { "" };
7009
7010            ::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!(
7011                "{pre_message}the {unstable}trait `{}` is not implemented for{desc} `{}`",
7012                trait_predicate.print_modifiers_and_trait_path(),
7013                tcx.short_string(trait_predicate.self_ty().skip_binder(), long_ty_path),
7014            )
7015        } else {
7016            // "the trait bound `T: !Send` is not satisfied" reads better than "`!Send` is
7017            // not implemented for `T`".
7018            // FIXME: add note explaining explicit negative trait bounds.
7019            ::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")
7020        }
7021    }
7022}
7023
7024// Replace `param` with `replace_ty`
7025struct ReplaceImplTraitFolder<'tcx> {
7026    tcx: TyCtxt<'tcx>,
7027    param: &'tcx ty::GenericParamDef,
7028    replace_ty: Ty<'tcx>,
7029}
7030
7031impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceImplTraitFolder<'tcx> {
7032    fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
7033        if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
7034            if self.param.index == *index {
7035                return self.replace_ty;
7036            }
7037        }
7038        t.super_fold_with(self)
7039    }
7040
7041    fn cx(&self) -> TyCtxt<'tcx> {
7042        self.tcx
7043    }
7044}
7045
7046pub fn suggest_desugaring_async_fn_to_impl_future_in_trait<'tcx>(
7047    tcx: TyCtxt<'tcx>,
7048    sig: hir::FnSig<'tcx>,
7049    body: hir::TraitFn<'tcx>,
7050    opaque_def_id: LocalDefId,
7051    add_bounds: &str,
7052) -> Option<Vec<(Span, String)>> {
7053    let hir::IsAsync::Async(async_span) = sig.header.asyncness else {
7054        return None;
7055    };
7056    let async_span = tcx.sess.source_map().span_extend_while_whitespace(async_span);
7057
7058    let future = tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
7059    let [hir::GenericBound::Trait(trait_ref)] = future.bounds else {
7060        // `async fn` should always lower to a single bound... but don't ICE.
7061        return None;
7062    };
7063    let Some(hir::PathSegment { args: Some(args), .. }) = trait_ref.trait_ref.path.segments.last()
7064    else {
7065        // desugaring to a single path segment for `Future<...>`.
7066        return None;
7067    };
7068    let Some(future_output_ty) = args.constraints.first().and_then(|constraint| constraint.ty())
7069    else {
7070        // Also should never happen.
7071        return None;
7072    };
7073
7074    let mut sugg = if future_output_ty.span.is_empty() {
7075        ::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![
7076            (async_span, String::new()),
7077            (
7078                future_output_ty.span,
7079                format!(" -> impl std::future::Future<Output = ()>{add_bounds}"),
7080            ),
7081        ]
7082    } else {
7083        ::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![
7084            (future_output_ty.span.shrink_to_lo(), "impl std::future::Future<Output = ".to_owned()),
7085            (future_output_ty.span.shrink_to_hi(), format!(">{add_bounds}")),
7086            (async_span, String::new()),
7087        ]
7088    };
7089
7090    // If there's a body, we also need to wrap it in `async {}`
7091    if let hir::TraitFn::Provided(body) = body {
7092        let body = tcx.hir_body(body);
7093        let body_span = body.value.span;
7094        let body_span_without_braces =
7095            body_span.with_lo(body_span.lo() + BytePos(1)).with_hi(body_span.hi() - BytePos(1));
7096        if body_span_without_braces.is_empty() {
7097            sugg.push((body_span_without_braces, " async {} ".to_owned()));
7098        } else {
7099            sugg.extend([
7100                (body_span_without_braces.shrink_to_lo(), "async {".to_owned()),
7101                (body_span_without_braces.shrink_to_hi(), "} ".to_owned()),
7102            ]);
7103        }
7104    }
7105
7106    Some(sugg)
7107}
7108
7109/// On `impl` evaluation cycles, look for `Self::AssocTy` restrictions in `where` clauses, explain
7110/// they are not allowed and if possible suggest alternatives.
7111fn point_at_assoc_type_restriction<G>(
7112    tcx: TyCtxt<'_>,
7113    err: &mut Diag<'_, G>,
7114    self_ty_str: &str,
7115    trait_name: &str,
7116    predicate: ty::Predicate<'_>,
7117    generics: &hir::Generics<'_>,
7118    data: &ImplDerivedCause<'_>,
7119) {
7120    let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() else {
7121        return;
7122    };
7123    let ty::ClauseKind::Projection(proj) = clause else {
7124        return;
7125    };
7126    let Some(name) = tcx
7127        .opt_rpitit_info(proj.def_id())
7128        .and_then(|data| match data {
7129            ty::ImplTraitInTraitData::Trait { fn_def_id, .. } => Some(tcx.item_name(fn_def_id)),
7130            ty::ImplTraitInTraitData::Impl { .. } => None,
7131        })
7132        .or_else(|| tcx.opt_item_name(proj.def_id()))
7133    else {
7134        return;
7135    };
7136    let mut predicates = generics.predicates.iter().peekable();
7137    let mut prev: Option<(&hir::WhereBoundPredicate<'_>, Span)> = None;
7138    while let Some(pred) = predicates.next() {
7139        let curr_span = pred.span;
7140        let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind else {
7141            continue;
7142        };
7143        let mut bounds = pred.bounds.iter();
7144        while let Some(bound) = bounds.next() {
7145            let Some(trait_ref) = bound.trait_ref() else {
7146                continue;
7147            };
7148            if bound.span() != data.span {
7149                continue;
7150            }
7151            if let hir::TyKind::Path(path) = pred.bounded_ty.kind
7152                && let hir::QPath::TypeRelative(ty, segment) = path
7153                && segment.ident.name == name
7154                && let hir::TyKind::Path(inner_path) = ty.kind
7155                && let hir::QPath::Resolved(None, inner_path) = inner_path
7156                && let Res::SelfTyAlias { .. } = inner_path.res
7157            {
7158                // The following block is to determine the right span to delete for this bound
7159                // that will leave valid code after the suggestion is applied.
7160                let span = if pred.origin == hir::PredicateOrigin::WhereClause
7161                    && generics
7162                        .predicates
7163                        .iter()
7164                        .filter(|p| {
7165                            #[allow(non_exhaustive_omitted_patterns)] match p.kind {
    hir::WherePredicateKind::BoundPredicate(p) if
        hir::PredicateOrigin::WhereClause == p.origin => true,
    _ => false,
}matches!(
7166                                p.kind,
7167                                hir::WherePredicateKind::BoundPredicate(p)
7168                                if hir::PredicateOrigin::WhereClause == p.origin
7169                            )
7170                        })
7171                        .count()
7172                        == 1
7173                {
7174                    // There's only one `where` bound, that needs to be removed. Remove the whole
7175                    // `where` clause.
7176                    generics.where_clause_span
7177                } else if let Some(next_pred) = predicates.peek()
7178                    && let hir::WherePredicateKind::BoundPredicate(next) = next_pred.kind
7179                    && pred.origin == next.origin
7180                {
7181                    // There's another bound, include the comma for the current one.
7182                    curr_span.until(next_pred.span)
7183                } else if let Some((prev, prev_span)) = prev
7184                    && pred.origin == prev.origin
7185                {
7186                    // Last bound, try to remove the previous comma.
7187                    prev_span.shrink_to_hi().to(curr_span)
7188                } else if pred.origin == hir::PredicateOrigin::WhereClause {
7189                    curr_span.with_hi(generics.where_clause_span.hi())
7190                } else {
7191                    curr_span
7192                };
7193
7194                err.span_suggestion_verbose(
7195                    span,
7196                    "associated type for the current `impl` cannot be restricted in `where` \
7197                     clauses, remove this bound",
7198                    "",
7199                    Applicability::MaybeIncorrect,
7200                );
7201            }
7202            if let Some(new) =
7203                tcx.associated_items(data.impl_or_alias_def_id).find_by_ident_and_kind(
7204                    tcx,
7205                    Ident::with_dummy_span(name),
7206                    ty::AssocTag::Type,
7207                    data.impl_or_alias_def_id,
7208                )
7209            {
7210                // The associated type is specified in the `impl` we're
7211                // looking at. Point at it.
7212                let span = tcx.def_span(new.def_id);
7213                err.span_label(
7214                    span,
7215                    ::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!(
7216                        "associated type `<{self_ty_str} as {trait_name}>::{name}` is specified \
7217                         here",
7218                    ),
7219                );
7220                // Search for the associated type `Self::{name}`, get
7221                // its type and suggest replacing the bound with it.
7222                let mut visitor = SelfVisitor { name: Some(name), .. };
7223                visitor.visit_trait_ref(trait_ref);
7224                for path in visitor.paths {
7225                    err.span_suggestion_verbose(
7226                        path.span,
7227                        "replace the associated type with the type specified in this `impl`",
7228                        tcx.type_of(new.def_id).skip_binder(),
7229                        Applicability::MachineApplicable,
7230                    );
7231                }
7232            } else {
7233                let mut visitor = SelfVisitor { name: None, .. };
7234                visitor.visit_trait_ref(trait_ref);
7235                let span: MultiSpan =
7236                    visitor.paths.iter().map(|p| p.span).collect::<Vec<Span>>().into();
7237                err.span_note(
7238                    span,
7239                    "associated types for the current `impl` cannot be restricted in `where` \
7240                     clauses",
7241                );
7242            }
7243        }
7244        prev = Some((pred, curr_span));
7245    }
7246}
7247
7248fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec<hir::Mutability>) {
7249    let mut refs = ::alloc::vec::Vec::new()vec![];
7250
7251    while let ty::Ref(_, new_ty, mutbl) = ty.kind() {
7252        ty = *new_ty;
7253        refs.push(*mutbl);
7254    }
7255
7256    (ty, refs)
7257}
7258
7259/// Look for type `param` in an ADT being used only through a reference to confirm that suggesting
7260/// `param: ?Sized` would be a valid constraint.
7261struct FindTypeParam {
7262    param: rustc_span::Symbol,
7263    invalid_spans: Vec<Span> = Vec::new(),
7264    nested: bool = false,
7265}
7266
7267impl<'v> Visitor<'v> for FindTypeParam {
7268    fn visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>) {
7269        // Skip where-clauses, to avoid suggesting indirection for type parameters found there.
7270    }
7271
7272    fn visit_ty(&mut self, ty: &hir::Ty<'_, AmbigArg>) {
7273        // We collect the spans of all uses of the "bare" type param, like in `field: T` or
7274        // `field: (T, T)` where we could make `T: ?Sized` while skipping cases that are known to be
7275        // valid like `field: &'a T` or `field: *mut T` and cases that *might* have further `Sized`
7276        // obligations like `Box<T>` and `Vec<T>`, but we perform no extra analysis for those cases
7277        // and suggest `T: ?Sized` regardless of their obligations. This is fine because the errors
7278        // in that case should make what happened clear enough.
7279        match ty.kind {
7280            hir::TyKind::Ptr(_) | hir::TyKind::Ref(..) | hir::TyKind::TraitObject(..) => {}
7281            hir::TyKind::Path(hir::QPath::Resolved(None, path))
7282                if let [segment] = path.segments
7283                    && segment.ident.name == self.param =>
7284            {
7285                if !self.nested {
7286                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:7286",
                        "rustc_trait_selection::error_reporting::traits::suggestions",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
                        ::tracing_core::__macro_support::Option::Some(7286u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("ty")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("ty");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("FindTypeParam::visit_ty")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?ty, "FindTypeParam::visit_ty");
7287                    self.invalid_spans.push(ty.span);
7288                }
7289            }
7290            hir::TyKind::Path(_) => {
7291                let prev = self.nested;
7292                self.nested = true;
7293                hir::intravisit::walk_ty(self, ty);
7294                self.nested = prev;
7295            }
7296            _ => {
7297                hir::intravisit::walk_ty(self, ty);
7298            }
7299        }
7300    }
7301}
7302
7303/// Look for type parameters in predicates. We use this to identify whether a bound is suitable in
7304/// on a given item.
7305struct ParamFinder {
7306    params: Vec<Symbol> = Vec::new(),
7307}
7308
7309impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ParamFinder {
7310    fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
7311        match t.kind() {
7312            ty::Param(p) => self.params.push(p.name),
7313            _ => {}
7314        }
7315        t.super_visit_with(self)
7316    }
7317}
7318
7319impl ParamFinder {
7320    /// Whether the `hir::Generics` of the current item can suggest the evaluated bound because its
7321    /// references to type parameters are present in the generics.
7322    fn can_suggest_bound(&self, generics: &hir::Generics<'_>) -> bool {
7323        if self.params.is_empty() {
7324            // There are no references to type parameters at all, so suggesting the bound
7325            // would be reasonable.
7326            return true;
7327        }
7328        generics.params.iter().any(|p| match p.name {
7329            hir::ParamName::Plain(p_name) => {
7330                // All of the parameters in the bound can be referenced in the current item.
7331                self.params.iter().any(|p| *p == p_name.name || *p == kw::SelfUpper)
7332            }
7333            _ => true,
7334        })
7335    }
7336}