Skip to main content

rustc_trait_selection/error_reporting/traits/
suggestions.rs

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