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