rustc_trait_selection/error_reporting/traits/
suggestions.rs

1// ignore-tidy-filelength
2
3use std::assert_matches::debug_assert_matches;
4use std::borrow::Cow;
5use std::iter;
6
7use itertools::{EitherOrBoth, Itertools};
8use rustc_abi::ExternAbi;
9use rustc_data_structures::fx::FxHashSet;
10use rustc_data_structures::stack::ensure_sufficient_stack;
11use rustc_errors::codes::*;
12use rustc_errors::{
13    Applicability, Diag, EmissionGuarantee, MultiSpan, Style, SuggestionStyle, pluralize,
14    struct_span_code_err,
15};
16use rustc_hir::def::{CtorOf, DefKind, Res};
17use rustc_hir::def_id::DefId;
18use rustc_hir::intravisit::{Visitor, VisitorExt};
19use rustc_hir::lang_items::LangItem;
20use rustc_hir::{
21    self as hir, AmbigArg, CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, HirId, Node,
22    expr_needs_parens, is_range_literal,
23};
24use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferCtxt, InferOk};
25use rustc_middle::traits::IsConstable;
26use rustc_middle::ty::error::TypeError;
27use rustc_middle::ty::print::{
28    PrintPolyTraitPredicateExt as _, PrintPolyTraitRefExt, PrintTraitPredicateExt as _,
29    with_forced_trimmed_paths, with_no_trimmed_paths, with_types_for_suggestion,
30};
31use rustc_middle::ty::{
32    self, AdtKind, GenericArgs, InferTy, IsSuggestable, Ty, TyCtxt, TypeFoldable, TypeFolder,
33    TypeSuperFoldable, TypeVisitableExt, TypeckResults, Upcast, suggest_arbitrary_trait_bound,
34    suggest_constraining_type_param,
35};
36use rustc_middle::{bug, span_bug};
37use rustc_span::def_id::LocalDefId;
38use rustc_span::{
39    BytePos, DUMMY_SP, DesugaringKind, ExpnKind, Ident, MacroKind, Span, Symbol, kw, sym,
40};
41use tracing::{debug, instrument};
42
43use super::{
44    DefIdOrName, FindExprBySpan, ImplCandidate, Obligation, ObligationCause, ObligationCauseCode,
45    PredicateObligation,
46};
47use crate::error_reporting::TypeErrCtxt;
48use crate::errors;
49use crate::infer::InferCtxtExt as _;
50use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
51use crate::traits::{ImplDerivedCause, NormalizeExt, ObligationCtxt};
52
53#[derive(Debug)]
54pub enum CoroutineInteriorOrUpvar {
55    // span of interior type
56    Interior(Span, Option<(Span, Option<Span>)>),
57    // span of upvar
58    Upvar(Span),
59}
60
61// This type provides a uniform interface to retrieve data on coroutines, whether it originated from
62// the local crate being compiled or from a foreign crate.
63#[derive(Debug)]
64struct CoroutineData<'a, 'tcx>(&'a TypeckResults<'tcx>);
65
66impl<'a, 'tcx> CoroutineData<'a, 'tcx> {
67    /// Try to get information about variables captured by the coroutine that matches a type we are
68    /// looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
69    /// meet an obligation
70    fn try_get_upvar_span<F>(
71        &self,
72        infer_context: &InferCtxt<'tcx>,
73        coroutine_did: DefId,
74        ty_matches: F,
75    ) -> Option<CoroutineInteriorOrUpvar>
76    where
77        F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
78    {
79        infer_context.tcx.upvars_mentioned(coroutine_did).and_then(|upvars| {
80            upvars.iter().find_map(|(upvar_id, upvar)| {
81                let upvar_ty = self.0.node_type(*upvar_id);
82                let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
83                ty_matches(ty::Binder::dummy(upvar_ty))
84                    .then(|| CoroutineInteriorOrUpvar::Upvar(upvar.span))
85            })
86        })
87    }
88
89    /// Try to get the span of a type being awaited on that matches the type we are looking with the
90    /// `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
91    /// obligation
92    fn get_from_await_ty<F>(
93        &self,
94        visitor: AwaitsVisitor,
95        tcx: TyCtxt<'tcx>,
96        ty_matches: F,
97    ) -> Option<Span>
98    where
99        F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
100    {
101        visitor
102            .awaits
103            .into_iter()
104            .map(|id| tcx.hir_expect_expr(id))
105            .find(|await_expr| ty_matches(ty::Binder::dummy(self.0.expr_ty_adjusted(await_expr))))
106            .map(|expr| expr.span)
107    }
108}
109
110fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
111    (
112        generics.tail_span_for_predicate_suggestion(),
113        with_types_for_suggestion!(format!("{} {}", generics.add_where_or_trailing_comma(), pred)),
114    )
115}
116
117/// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
118/// it can also be an `impl Trait` param that needs to be decomposed to a type
119/// param for cleaner code.
120pub fn suggest_restriction<'tcx, G: EmissionGuarantee>(
121    tcx: TyCtxt<'tcx>,
122    item_id: LocalDefId,
123    hir_generics: &hir::Generics<'tcx>,
124    msg: &str,
125    err: &mut Diag<'_, G>,
126    fn_sig: Option<&hir::FnSig<'_>>,
127    projection: Option<ty::AliasTy<'_>>,
128    trait_pred: ty::PolyTraitPredicate<'tcx>,
129    // When we are dealing with a trait, `super_traits` will be `Some`:
130    // Given `trait T: A + B + C {}`
131    //              -  ^^^^^^^^^ GenericBounds
132    //              |
133    //              &Ident
134    super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
135) {
136    if hir_generics.where_clause_span.from_expansion()
137        || hir_generics.where_clause_span.desugaring_kind().is_some()
138        || projection.is_some_and(|projection| {
139            (tcx.is_impl_trait_in_trait(projection.def_id)
140                && !tcx.features().return_type_notation())
141                || tcx.lookup_stability(projection.def_id).is_some_and(|stab| stab.is_unstable())
142        })
143    {
144        return;
145    }
146    let generics = tcx.generics_of(item_id);
147    // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
148    if let Some((param, bound_str, fn_sig)) =
149        fn_sig.zip(projection).and_then(|(sig, p)| match *p.self_ty().kind() {
150            // Shenanigans to get the `Trait` from the `impl Trait`.
151            ty::Param(param) => {
152                let param_def = generics.type_param(param, tcx);
153                if param_def.kind.is_synthetic() {
154                    let bound_str =
155                        param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
156                    return Some((param_def, bound_str, sig));
157                }
158                None
159            }
160            _ => None,
161        })
162    {
163        let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
164        let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
165            tcx,
166            param,
167            replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
168                .to_ty(tcx),
169        });
170        if !trait_pred.is_suggestable(tcx, false) {
171            return;
172        }
173        // We know we have an `impl Trait` that doesn't satisfy a required projection.
174
175        // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
176        // types. There should be at least one, but there might be *more* than one. In that
177        // case we could just ignore it and try to identify which one needs the restriction,
178        // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
179        // where `T: Trait`.
180        let mut ty_spans = vec![];
181        for input in fn_sig.decl.inputs {
182            ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
183                .visit_ty_unambig(input);
184        }
185        // The type param `T: Trait` we will suggest to introduce.
186        let type_param = format!("{type_param_name}: {bound_str}");
187
188        let mut sugg = vec![
189            if let Some(span) = hir_generics.span_for_param_suggestion() {
190                (span, format!(", {type_param}"))
191            } else {
192                (hir_generics.span, format!("<{type_param}>"))
193            },
194            // `fn foo(t: impl Trait)`
195            //                       ^ suggest `where <T as Trait>::A: Bound`
196            predicate_constraint(hir_generics, trait_pred.upcast(tcx)),
197        ];
198        sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
199
200        // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
201        // FIXME: we should suggest `fn foo(t: impl Trait<A: Bound>)` instead.
202        err.multipart_suggestion(
203            "introduce a type parameter with a trait bound instead of using `impl Trait`",
204            sugg,
205            Applicability::MaybeIncorrect,
206        );
207    } else {
208        if !trait_pred.is_suggestable(tcx, false) {
209            return;
210        }
211        // Trivial case: `T` needs an extra bound: `T: Bound`.
212        let (sp, suggestion) = match (
213            hir_generics
214                .params
215                .iter()
216                .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
217            super_traits,
218        ) {
219            (_, None) => predicate_constraint(hir_generics, trait_pred.upcast(tcx)),
220            (None, Some((ident, []))) => (
221                ident.span.shrink_to_hi(),
222                format!(": {}", trait_pred.print_modifiers_and_trait_path()),
223            ),
224            (_, Some((_, [.., bounds]))) => (
225                bounds.span().shrink_to_hi(),
226                format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
227            ),
228            (Some(_), Some((_, []))) => (
229                hir_generics.span.shrink_to_hi(),
230                format!(": {}", trait_pred.print_modifiers_and_trait_path()),
231            ),
232        };
233
234        err.span_suggestion_verbose(
235            sp,
236            format!("consider further restricting {msg}"),
237            suggestion,
238            Applicability::MachineApplicable,
239        );
240    }
241}
242
243impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
244    pub fn suggest_restricting_param_bound(
245        &self,
246        err: &mut Diag<'_>,
247        trait_pred: ty::PolyTraitPredicate<'tcx>,
248        associated_ty: Option<(&'static str, Ty<'tcx>)>,
249        mut body_id: LocalDefId,
250    ) {
251        if trait_pred.skip_binder().polarity != ty::PredicatePolarity::Positive {
252            return;
253        }
254
255        let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
256
257        let self_ty = trait_pred.skip_binder().self_ty();
258        let (param_ty, projection) = match *self_ty.kind() {
259            ty::Param(_) => (true, None),
260            ty::Alias(ty::Projection, projection) => (false, Some(projection)),
261            _ => (false, None),
262        };
263
264        // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
265        //        don't suggest `T: Sized + ?Sized`.
266        loop {
267            let node = self.tcx.hir_node_by_def_id(body_id);
268            match node {
269                hir::Node::Item(hir::Item {
270                    kind: hir::ItemKind::Trait(_, _, ident, generics, bounds, _),
271                    ..
272                }) if self_ty == self.tcx.types.self_param => {
273                    assert!(param_ty);
274                    // Restricting `Self` for a single method.
275                    suggest_restriction(
276                        self.tcx,
277                        body_id,
278                        generics,
279                        "`Self`",
280                        err,
281                        None,
282                        projection,
283                        trait_pred,
284                        Some((&ident, bounds)),
285                    );
286                    return;
287                }
288
289                hir::Node::TraitItem(hir::TraitItem {
290                    generics,
291                    kind: hir::TraitItemKind::Fn(..),
292                    ..
293                }) if self_ty == self.tcx.types.self_param => {
294                    assert!(param_ty);
295                    // Restricting `Self` for a single method.
296                    suggest_restriction(
297                        self.tcx, body_id, generics, "`Self`", err, None, projection, trait_pred,
298                        None,
299                    );
300                    return;
301                }
302
303                hir::Node::TraitItem(hir::TraitItem {
304                    generics,
305                    kind: hir::TraitItemKind::Fn(fn_sig, ..),
306                    ..
307                })
308                | hir::Node::ImplItem(hir::ImplItem {
309                    generics,
310                    kind: hir::ImplItemKind::Fn(fn_sig, ..),
311                    ..
312                })
313                | hir::Node::Item(hir::Item {
314                    kind: hir::ItemKind::Fn { sig: fn_sig, generics, .. },
315                    ..
316                }) if projection.is_some() => {
317                    // Missing restriction on associated type of type parameter (unmet projection).
318                    suggest_restriction(
319                        self.tcx,
320                        body_id,
321                        generics,
322                        "the associated type",
323                        err,
324                        Some(fn_sig),
325                        projection,
326                        trait_pred,
327                        None,
328                    );
329                    return;
330                }
331                hir::Node::Item(hir::Item {
332                    kind:
333                        hir::ItemKind::Trait(_, _, _, generics, ..)
334                        | hir::ItemKind::Impl(hir::Impl { generics, .. }),
335                    ..
336                }) if projection.is_some() => {
337                    // Missing restriction on associated type of type parameter (unmet projection).
338                    suggest_restriction(
339                        self.tcx,
340                        body_id,
341                        generics,
342                        "the associated type",
343                        err,
344                        None,
345                        projection,
346                        trait_pred,
347                        None,
348                    );
349                    return;
350                }
351
352                hir::Node::Item(hir::Item {
353                    kind:
354                        hir::ItemKind::Struct(_, _, generics)
355                        | hir::ItemKind::Enum(_, _, generics)
356                        | hir::ItemKind::Union(_, _, generics)
357                        | hir::ItemKind::Trait(_, _, _, generics, ..)
358                        | hir::ItemKind::Impl(hir::Impl { generics, .. })
359                        | hir::ItemKind::Fn { generics, .. }
360                        | hir::ItemKind::TyAlias(_, _, generics)
361                        | hir::ItemKind::Const(_, _, generics, _)
362                        | hir::ItemKind::TraitAlias(_, generics, _),
363                    ..
364                })
365                | hir::Node::TraitItem(hir::TraitItem { generics, .. })
366                | hir::Node::ImplItem(hir::ImplItem { generics, .. })
367                    if param_ty =>
368                {
369                    // We skip the 0'th arg (self) because we do not want
370                    // to consider the predicate as not suggestible if the
371                    // self type is an arg position `impl Trait` -- instead,
372                    // we handle that by adding ` + Bound` below.
373                    // FIXME(compiler-errors): It would be nice to do the same
374                    // this that we do in `suggest_restriction` and pull the
375                    // `impl Trait` into a new generic if it shows up somewhere
376                    // else in the predicate.
377                    if !trait_pred.skip_binder().trait_ref.args[1..]
378                        .iter()
379                        .all(|g| g.is_suggestable(self.tcx, false))
380                    {
381                        return;
382                    }
383                    // Missing generic type parameter bound.
384                    let param_name = self_ty.to_string();
385                    let mut constraint = with_no_trimmed_paths!(
386                        trait_pred.print_modifiers_and_trait_path().to_string()
387                    );
388
389                    if let Some((name, term)) = associated_ty {
390                        // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
391                        // That should be extracted into a helper function.
392                        if let Some(stripped) = constraint.strip_suffix('>') {
393                            constraint = format!("{stripped}, {name} = {term}>");
394                        } else {
395                            constraint.push_str(&format!("<{name} = {term}>"));
396                        }
397                    }
398
399                    if suggest_constraining_type_param(
400                        self.tcx,
401                        generics,
402                        err,
403                        &param_name,
404                        &constraint,
405                        Some(trait_pred.def_id()),
406                        None,
407                    ) {
408                        return;
409                    }
410                }
411
412                hir::Node::Item(hir::Item {
413                    kind:
414                        hir::ItemKind::Struct(_, _, generics)
415                        | hir::ItemKind::Enum(_, _, generics)
416                        | hir::ItemKind::Union(_, _, generics)
417                        | hir::ItemKind::Trait(_, _, _, generics, ..)
418                        | hir::ItemKind::Impl(hir::Impl { generics, .. })
419                        | hir::ItemKind::Fn { generics, .. }
420                        | hir::ItemKind::TyAlias(_, _, generics)
421                        | hir::ItemKind::Const(_, _, generics, _)
422                        | hir::ItemKind::TraitAlias(_, generics, _),
423                    ..
424                }) if !param_ty => {
425                    // Missing generic type parameter bound.
426                    if suggest_arbitrary_trait_bound(
427                        self.tcx,
428                        generics,
429                        err,
430                        trait_pred,
431                        associated_ty,
432                    ) {
433                        return;
434                    }
435                }
436                hir::Node::Crate(..) => return,
437
438                _ => {}
439            }
440            body_id = self.tcx.local_parent(body_id);
441        }
442    }
443
444    /// Provide a suggestion to dereference arguments to functions and binary operators, if that
445    /// would satisfy trait bounds.
446    pub(super) fn suggest_dereferences(
447        &self,
448        obligation: &PredicateObligation<'tcx>,
449        err: &mut Diag<'_>,
450        trait_pred: ty::PolyTraitPredicate<'tcx>,
451    ) -> bool {
452        let mut code = obligation.cause.code();
453        if let ObligationCauseCode::FunctionArg { arg_hir_id, call_hir_id, .. } = code
454            && let Some(typeck_results) = &self.typeck_results
455            && let hir::Node::Expr(expr) = self.tcx.hir_node(*arg_hir_id)
456            && let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
457        {
458            // Suggest dereferencing the argument to a function/method call if possible
459
460            // Get the root obligation, since the leaf obligation we have may be unhelpful (#87437)
461            let mut real_trait_pred = trait_pred;
462            while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
463                code = parent_code;
464                if let Some(parent_trait_pred) = parent_trait_pred {
465                    real_trait_pred = parent_trait_pred;
466                }
467            }
468
469            // We `instantiate_bound_regions_with_erased` here because `make_subregion` does not handle
470            // `ReBound`, and we don't particularly care about the regions.
471            let real_ty = self.tcx.instantiate_bound_regions_with_erased(real_trait_pred.self_ty());
472            if !self.can_eq(obligation.param_env, real_ty, arg_ty) {
473                return false;
474            }
475
476            // Potentially, we'll want to place our dereferences under a `&`. We don't try this for
477            // `&mut`, since we can't be sure users will get the side-effects they want from it.
478            // If this doesn't work, we'll try removing the `&` in `suggest_remove_reference`.
479            // FIXME(dianne): this misses the case where users need both to deref and remove `&`s.
480            // This method could be combined with `TypeErrCtxt::suggest_remove_reference` to handle
481            // that, similar to what `FnCtxt::suggest_deref_or_ref` does.
482            let (is_under_ref, base_ty, span) = match expr.kind {
483                hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, subexpr)
484                    if let &ty::Ref(region, base_ty, hir::Mutability::Not) = real_ty.kind() =>
485                {
486                    (Some(region), base_ty, subexpr.span)
487                }
488                // Don't suggest `*&mut`, etc.
489                hir::ExprKind::AddrOf(..) => return false,
490                _ => (None, real_ty, obligation.cause.span),
491            };
492
493            let autoderef = (self.autoderef_steps)(base_ty);
494            let mut is_boxed = base_ty.is_box();
495            if let Some(steps) = autoderef.into_iter().position(|(mut ty, obligations)| {
496                // Ensure one of the following for dereferencing to be valid: we're passing by
497                // reference, `ty` is `Copy`, or we're moving out of a (potentially nested) `Box`.
498                let can_deref = is_under_ref.is_some()
499                    || self.type_is_copy_modulo_regions(obligation.param_env, ty)
500                    || ty.is_numeric() // for inference vars (presumably but not provably `Copy`)
501                    || is_boxed && self.type_is_sized_modulo_regions(obligation.param_env, ty);
502                is_boxed &= ty.is_box();
503
504                // Re-add the `&` if necessary
505                if let Some(region) = is_under_ref {
506                    ty = Ty::new_ref(self.tcx, region, ty, hir::Mutability::Not);
507                }
508
509                // Remapping bound vars here
510                let real_trait_pred_and_ty =
511                    real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
512                let obligation = self.mk_trait_obligation_with_new_self_ty(
513                    obligation.param_env,
514                    real_trait_pred_and_ty,
515                );
516
517                can_deref
518                    && obligations
519                        .iter()
520                        .chain([&obligation])
521                        .all(|obligation| self.predicate_may_hold(obligation))
522            }) && steps > 0
523            {
524                let derefs = "*".repeat(steps);
525                let msg = "consider dereferencing here";
526                let call_node = self.tcx.hir_node(*call_hir_id);
527                let is_receiver = matches!(
528                    call_node,
529                    Node::Expr(hir::Expr {
530                        kind: hir::ExprKind::MethodCall(_, receiver_expr, ..),
531                        ..
532                    })
533                    if receiver_expr.hir_id == *arg_hir_id
534                );
535                if is_receiver {
536                    err.multipart_suggestion_verbose(
537                        msg,
538                        vec![
539                            (span.shrink_to_lo(), format!("({derefs}")),
540                            (span.shrink_to_hi(), ")".to_string()),
541                        ],
542                        Applicability::MachineApplicable,
543                    )
544                } else {
545                    err.span_suggestion_verbose(
546                        span.shrink_to_lo(),
547                        msg,
548                        derefs,
549                        Applicability::MachineApplicable,
550                    )
551                };
552                return true;
553            }
554        } else if let (
555            ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id: Some(rhs_hir_id), .. },
556            predicate,
557        ) = code.peel_derives_with_predicate()
558            && let Some(typeck_results) = &self.typeck_results
559            && let hir::Node::Expr(lhs) = self.tcx.hir_node(*lhs_hir_id)
560            && let hir::Node::Expr(rhs) = self.tcx.hir_node(*rhs_hir_id)
561            && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs)
562            && let trait_pred = predicate.unwrap_or(trait_pred)
563            // Only run this code on binary operators
564            && hir::lang_items::BINARY_OPERATORS
565                .iter()
566                .filter_map(|&op| self.tcx.lang_items().get(op))
567                .any(|op| {
568                    op == trait_pred.skip_binder().trait_ref.def_id
569                })
570        {
571            // Suggest dereferencing the LHS, RHS, or both terms of a binop if possible
572
573            let trait_pred = predicate.unwrap_or(trait_pred);
574            let lhs_ty = self.tcx.instantiate_bound_regions_with_erased(trait_pred.self_ty());
575            let lhs_autoderef = (self.autoderef_steps)(lhs_ty);
576            let rhs_autoderef = (self.autoderef_steps)(rhs_ty);
577            let first_lhs = lhs_autoderef.first().unwrap().clone();
578            let first_rhs = rhs_autoderef.first().unwrap().clone();
579            let mut autoderefs = lhs_autoderef
580                .into_iter()
581                .enumerate()
582                .rev()
583                .zip_longest(rhs_autoderef.into_iter().enumerate().rev())
584                .map(|t| match t {
585                    EitherOrBoth::Both(a, b) => (a, b),
586                    EitherOrBoth::Left(a) => (a, (0, first_rhs.clone())),
587                    EitherOrBoth::Right(b) => ((0, first_lhs.clone()), b),
588                })
589                .rev();
590            if let Some((lsteps, rsteps)) =
591                autoderefs.find_map(|((lsteps, (l_ty, _)), (rsteps, (r_ty, _)))| {
592                    // Create a new predicate with the dereferenced LHS and RHS
593                    // We simultaneously dereference both sides rather than doing them
594                    // one at a time to account for cases such as &Box<T> == &&T
595                    let trait_pred_and_ty = trait_pred.map_bound(|inner| {
596                        (
597                            ty::TraitPredicate {
598                                trait_ref: ty::TraitRef::new_from_args(
599                                    self.tcx,
600                                    inner.trait_ref.def_id,
601                                    self.tcx.mk_args(
602                                        &[&[l_ty.into(), r_ty.into()], &inner.trait_ref.args[2..]]
603                                            .concat(),
604                                    ),
605                                ),
606                                ..inner
607                            },
608                            l_ty,
609                        )
610                    });
611                    let obligation = self.mk_trait_obligation_with_new_self_ty(
612                        obligation.param_env,
613                        trait_pred_and_ty,
614                    );
615                    self.predicate_may_hold(&obligation).then_some(match (lsteps, rsteps) {
616                        (_, 0) => (Some(lsteps), None),
617                        (0, _) => (None, Some(rsteps)),
618                        _ => (Some(lsteps), Some(rsteps)),
619                    })
620                })
621            {
622                let make_sugg = |mut expr: &Expr<'_>, mut steps| {
623                    let mut prefix_span = expr.span.shrink_to_lo();
624                    let mut msg = "consider dereferencing here";
625                    if let hir::ExprKind::AddrOf(_, _, inner) = expr.kind {
626                        msg = "consider removing the borrow and dereferencing instead";
627                        if let hir::ExprKind::AddrOf(..) = inner.kind {
628                            msg = "consider removing the borrows and dereferencing instead";
629                        }
630                    }
631                    while let hir::ExprKind::AddrOf(_, _, inner) = expr.kind
632                        && steps > 0
633                    {
634                        prefix_span = prefix_span.with_hi(inner.span.lo());
635                        expr = inner;
636                        steps -= 1;
637                    }
638                    // Empty suggestions with empty spans ICE with debug assertions
639                    if steps == 0 {
640                        return (
641                            msg.trim_end_matches(" and dereferencing instead"),
642                            vec![(prefix_span, String::new())],
643                        );
644                    }
645                    let derefs = "*".repeat(steps);
646                    let needs_parens = steps > 0
647                        && match expr.kind {
648                            hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => true,
649                            _ if is_range_literal(expr) => true,
650                            _ => false,
651                        };
652                    let mut suggestion = if needs_parens {
653                        vec![
654                            (
655                                expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
656                                format!("{derefs}("),
657                            ),
658                            (expr.span.shrink_to_hi(), ")".to_string()),
659                        ]
660                    } else {
661                        vec![(
662                            expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
663                            format!("{derefs}"),
664                        )]
665                    };
666                    // Empty suggestions with empty spans ICE with debug assertions
667                    if !prefix_span.is_empty() {
668                        suggestion.push((prefix_span, String::new()));
669                    }
670                    (msg, suggestion)
671                };
672
673                if let Some(lsteps) = lsteps
674                    && let Some(rsteps) = rsteps
675                    && lsteps > 0
676                    && rsteps > 0
677                {
678                    let mut suggestion = make_sugg(lhs, lsteps).1;
679                    suggestion.append(&mut make_sugg(rhs, rsteps).1);
680                    err.multipart_suggestion_verbose(
681                        "consider dereferencing both sides of the expression",
682                        suggestion,
683                        Applicability::MachineApplicable,
684                    );
685                    return true;
686                } else if let Some(lsteps) = lsteps
687                    && lsteps > 0
688                {
689                    let (msg, suggestion) = make_sugg(lhs, lsteps);
690                    err.multipart_suggestion_verbose(
691                        msg,
692                        suggestion,
693                        Applicability::MachineApplicable,
694                    );
695                    return true;
696                } else if let Some(rsteps) = rsteps
697                    && rsteps > 0
698                {
699                    let (msg, suggestion) = make_sugg(rhs, rsteps);
700                    err.multipart_suggestion_verbose(
701                        msg,
702                        suggestion,
703                        Applicability::MachineApplicable,
704                    );
705                    return true;
706                }
707            }
708        }
709        false
710    }
711
712    /// Given a closure's `DefId`, return the given name of the closure.
713    ///
714    /// This doesn't account for reassignments, but it's only used for suggestions.
715    fn get_closure_name(
716        &self,
717        def_id: DefId,
718        err: &mut Diag<'_>,
719        msg: Cow<'static, str>,
720    ) -> Option<Symbol> {
721        let get_name = |err: &mut Diag<'_>, kind: &hir::PatKind<'_>| -> Option<Symbol> {
722            // Get the local name of this closure. This can be inaccurate because
723            // of the possibility of reassignment, but this should be good enough.
724            match &kind {
725                hir::PatKind::Binding(hir::BindingMode::NONE, _, ident, None) => Some(ident.name),
726                _ => {
727                    err.note(msg);
728                    None
729                }
730            }
731        };
732
733        let hir_id = self.tcx.local_def_id_to_hir_id(def_id.as_local()?);
734        match self.tcx.parent_hir_node(hir_id) {
735            hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Let(local), .. }) => {
736                get_name(err, &local.pat.kind)
737            }
738            // Different to previous arm because one is `&hir::Local` and the other
739            // is `P<hir::Local>`.
740            hir::Node::LetStmt(local) => get_name(err, &local.pat.kind),
741            _ => None,
742        }
743    }
744
745    /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
746    /// evaluate to a type that *would* satisfy the trait bound. If it would, suggest calling
747    /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
748    pub(super) fn suggest_fn_call(
749        &self,
750        obligation: &PredicateObligation<'tcx>,
751        err: &mut Diag<'_>,
752        trait_pred: ty::PolyTraitPredicate<'tcx>,
753    ) -> bool {
754        // It doesn't make sense to make this suggestion outside of typeck...
755        // (also autoderef will ICE...)
756        if self.typeck_results.is_none() {
757            return false;
758        }
759
760        if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) =
761            obligation.predicate.kind().skip_binder()
762            && self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Sized)
763        {
764            // Don't suggest calling to turn an unsized type into a sized type
765            return false;
766        }
767
768        let self_ty = self.instantiate_binder_with_fresh_vars(
769            DUMMY_SP,
770            BoundRegionConversionTime::FnCall,
771            trait_pred.self_ty(),
772        );
773
774        let Some((def_id_or_name, output, inputs)) =
775            self.extract_callable_info(obligation.cause.body_id, obligation.param_env, self_ty)
776        else {
777            return false;
778        };
779
780        // Remapping bound vars here
781        let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
782
783        let new_obligation =
784            self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
785        if !self.predicate_must_hold_modulo_regions(&new_obligation) {
786            return false;
787        }
788
789        // Get the name of the callable and the arguments to be used in the suggestion.
790        let msg = match def_id_or_name {
791            DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
792                DefKind::Ctor(CtorOf::Struct, _) => {
793                    Cow::from("use parentheses to construct this tuple struct")
794                }
795                DefKind::Ctor(CtorOf::Variant, _) => {
796                    Cow::from("use parentheses to construct this tuple variant")
797                }
798                kind => Cow::from(format!(
799                    "use parentheses to call this {}",
800                    self.tcx.def_kind_descr(kind, def_id)
801                )),
802            },
803            DefIdOrName::Name(name) => Cow::from(format!("use parentheses to call this {name}")),
804        };
805
806        let args = inputs
807            .into_iter()
808            .map(|ty| {
809                if ty.is_suggestable(self.tcx, false) {
810                    format!("/* {ty} */")
811                } else {
812                    "/* value */".to_string()
813                }
814            })
815            .collect::<Vec<_>>()
816            .join(", ");
817
818        if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. })
819            && obligation.cause.span.can_be_used_for_suggestions()
820        {
821            // When the obligation error has been ensured to have been caused by
822            // an argument, the `obligation.cause.span` points at the expression
823            // of the argument, so we can provide a suggestion. Otherwise, we give
824            // a more general note.
825            err.span_suggestion_verbose(
826                obligation.cause.span.shrink_to_hi(),
827                msg,
828                format!("({args})"),
829                Applicability::HasPlaceholders,
830            );
831        } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
832            let name = match self.tcx.hir_get_if_local(def_id) {
833                Some(hir::Node::Expr(hir::Expr {
834                    kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
835                    ..
836                })) => {
837                    err.span_label(*fn_decl_span, "consider calling this closure");
838                    let Some(name) = self.get_closure_name(def_id, err, msg.clone()) else {
839                        return false;
840                    };
841                    name.to_string()
842                }
843                Some(hir::Node::Item(hir::Item {
844                    kind: hir::ItemKind::Fn { ident, .. }, ..
845                })) => {
846                    err.span_label(ident.span, "consider calling this function");
847                    ident.to_string()
848                }
849                Some(hir::Node::Ctor(..)) => {
850                    let name = self.tcx.def_path_str(def_id);
851                    err.span_label(
852                        self.tcx.def_span(def_id),
853                        format!("consider calling the constructor for `{name}`"),
854                    );
855                    name
856                }
857                _ => return false,
858            };
859            err.help(format!("{msg}: `{name}({args})`"));
860        }
861        true
862    }
863
864    pub(super) fn check_for_binding_assigned_block_without_tail_expression(
865        &self,
866        obligation: &PredicateObligation<'tcx>,
867        err: &mut Diag<'_>,
868        trait_pred: ty::PolyTraitPredicate<'tcx>,
869    ) {
870        let mut span = obligation.cause.span;
871        while span.from_expansion() {
872            // Remove all the desugaring and macro contexts.
873            span.remove_mark();
874        }
875        let mut expr_finder = FindExprBySpan::new(span, self.tcx);
876        let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_id) else {
877            return;
878        };
879        expr_finder.visit_expr(body.value);
880        let Some(expr) = expr_finder.result else {
881            return;
882        };
883        let Some(typeck) = &self.typeck_results else {
884            return;
885        };
886        let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else {
887            return;
888        };
889        if !ty.is_unit() {
890            return;
891        };
892        let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else {
893            return;
894        };
895        let Res::Local(hir_id) = path.res else {
896            return;
897        };
898        let hir::Node::Pat(pat) = self.tcx.hir_node(hir_id) else {
899            return;
900        };
901        let hir::Node::LetStmt(hir::LetStmt { ty: None, init: Some(init), .. }) =
902            self.tcx.parent_hir_node(pat.hir_id)
903        else {
904            return;
905        };
906        let hir::ExprKind::Block(block, None) = init.kind else {
907            return;
908        };
909        if block.expr.is_some() {
910            return;
911        }
912        let [.., stmt] = block.stmts else {
913            err.span_label(block.span, "this empty block is missing a tail expression");
914            return;
915        };
916        let hir::StmtKind::Semi(tail_expr) = stmt.kind else {
917            return;
918        };
919        let Some(ty) = typeck.expr_ty_opt(tail_expr) else {
920            err.span_label(block.span, "this block is missing a tail expression");
921            return;
922        };
923        let ty = self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(ty));
924        let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, ty));
925
926        let new_obligation =
927            self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
928        if self.predicate_must_hold_modulo_regions(&new_obligation) {
929            err.span_suggestion_short(
930                stmt.span.with_lo(tail_expr.span.hi()),
931                "remove this semicolon",
932                "",
933                Applicability::MachineApplicable,
934            );
935        } else {
936            err.span_label(block.span, "this block is missing a tail expression");
937        }
938    }
939
940    pub(super) fn suggest_add_clone_to_arg(
941        &self,
942        obligation: &PredicateObligation<'tcx>,
943        err: &mut Diag<'_>,
944        trait_pred: ty::PolyTraitPredicate<'tcx>,
945    ) -> bool {
946        let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
947        self.enter_forall(self_ty, |ty: Ty<'_>| {
948            let Some(generics) = self.tcx.hir_get_generics(obligation.cause.body_id) else {
949                return false;
950            };
951            let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false };
952            let ty::Param(param) = inner_ty.kind() else { return false };
953            let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
954            else {
955                return false;
956            };
957
958            let clone_trait = self.tcx.require_lang_item(LangItem::Clone, None);
959            let has_clone = |ty| {
960                self.type_implements_trait(clone_trait, [ty], obligation.param_env)
961                    .must_apply_modulo_regions()
962            };
963
964            let existing_clone_call = match self.tcx.hir_node(*arg_hir_id) {
965                // It's just a variable. Propose cloning it.
966                Node::Expr(Expr { kind: hir::ExprKind::Path(_), .. }) => None,
967                // It's already a call to `clone()`. We might be able to suggest
968                // adding a `+ Clone` bound, though.
969                Node::Expr(Expr {
970                    kind:
971                        hir::ExprKind::MethodCall(
972                            hir::PathSegment { ident, .. },
973                            _receiver,
974                            [],
975                            call_span,
976                        ),
977                    hir_id,
978                    ..
979                }) if ident.name == sym::clone
980                    && !call_span.from_expansion()
981                    && !has_clone(*inner_ty) =>
982                {
983                    // We only care about method calls corresponding to the real `Clone` trait.
984                    let Some(typeck_results) = self.typeck_results.as_ref() else { return false };
985                    let Some((DefKind::AssocFn, did)) = typeck_results.type_dependent_def(*hir_id)
986                    else {
987                        return false;
988                    };
989                    if self.tcx.trait_of_item(did) != Some(clone_trait) {
990                        return false;
991                    }
992                    Some(ident.span)
993                }
994                _ => return false,
995            };
996
997            let new_obligation = self.mk_trait_obligation_with_new_self_ty(
998                obligation.param_env,
999                trait_pred.map_bound(|trait_pred| (trait_pred, *inner_ty)),
1000            );
1001
1002            if self.predicate_may_hold(&new_obligation) && has_clone(ty) {
1003                if !has_clone(param.to_ty(self.tcx)) {
1004                    suggest_constraining_type_param(
1005                        self.tcx,
1006                        generics,
1007                        err,
1008                        param.name.as_str(),
1009                        "Clone",
1010                        Some(clone_trait),
1011                        None,
1012                    );
1013                }
1014                if let Some(existing_clone_call) = existing_clone_call {
1015                    err.span_note(
1016                        existing_clone_call,
1017                        format!(
1018                            "this `clone()` copies the reference, \
1019                            which does not do anything, \
1020                            because `{inner_ty}` does not implement `Clone`"
1021                        ),
1022                    );
1023                } else {
1024                    err.span_suggestion_verbose(
1025                        obligation.cause.span.shrink_to_hi(),
1026                        "consider using clone here",
1027                        ".clone()".to_string(),
1028                        Applicability::MaybeIncorrect,
1029                    );
1030                }
1031                return true;
1032            }
1033            false
1034        })
1035    }
1036
1037    /// Extracts information about a callable type for diagnostics. This is a
1038    /// heuristic -- it doesn't necessarily mean that a type is always callable,
1039    /// because the callable type must also be well-formed to be called.
1040    pub fn extract_callable_info(
1041        &self,
1042        body_id: LocalDefId,
1043        param_env: ty::ParamEnv<'tcx>,
1044        found: Ty<'tcx>,
1045    ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
1046        // Autoderef is useful here because sometimes we box callables, etc.
1047        let Some((def_id_or_name, output, inputs)) =
1048            (self.autoderef_steps)(found).into_iter().find_map(|(found, _)| match *found.kind() {
1049                ty::FnPtr(sig_tys, _) => Some((
1050                    DefIdOrName::Name("function pointer"),
1051                    sig_tys.output(),
1052                    sig_tys.inputs(),
1053                )),
1054                ty::FnDef(def_id, _) => {
1055                    let fn_sig = found.fn_sig(self.tcx);
1056                    Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
1057                }
1058                ty::Closure(def_id, args) => {
1059                    let fn_sig = args.as_closure().sig();
1060                    Some((
1061                        DefIdOrName::DefId(def_id),
1062                        fn_sig.output(),
1063                        fn_sig.inputs().map_bound(|inputs| inputs[0].tuple_fields().as_slice()),
1064                    ))
1065                }
1066                ty::CoroutineClosure(def_id, args) => {
1067                    let sig_parts = args.as_coroutine_closure().coroutine_closure_sig();
1068                    Some((
1069                        DefIdOrName::DefId(def_id),
1070                        sig_parts.map_bound(|sig| {
1071                            sig.to_coroutine(
1072                                self.tcx,
1073                                args.as_coroutine_closure().parent_args(),
1074                                // Just use infer vars here, since we  don't really care
1075                                // what these types are, just that we're returning a coroutine.
1076                                self.next_ty_var(DUMMY_SP),
1077                                self.tcx.coroutine_for_closure(def_id),
1078                                self.next_ty_var(DUMMY_SP),
1079                            )
1080                        }),
1081                        sig_parts.map_bound(|sig| sig.tupled_inputs_ty.tuple_fields().as_slice()),
1082                    ))
1083                }
1084                ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
1085                    self.tcx.item_self_bounds(def_id).instantiate(self.tcx, args).iter().find_map(
1086                        |pred| {
1087                            if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder()
1088                            && self
1089                                .tcx
1090                                .is_lang_item(proj.projection_term.def_id, LangItem::FnOnceOutput)
1091                            // args tuple will always be args[1]
1092                            && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1093                            {
1094                                Some((
1095                                    DefIdOrName::DefId(def_id),
1096                                    pred.kind().rebind(proj.term.expect_type()),
1097                                    pred.kind().rebind(args.as_slice()),
1098                                ))
1099                            } else {
1100                                None
1101                            }
1102                        },
1103                    )
1104                }
1105                ty::Dynamic(data, _, ty::Dyn) => data.iter().find_map(|pred| {
1106                    if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
1107                        && self.tcx.is_lang_item(proj.def_id, LangItem::FnOnceOutput)
1108                        // for existential projection, args are shifted over by 1
1109                        && let ty::Tuple(args) = proj.args.type_at(0).kind()
1110                    {
1111                        Some((
1112                            DefIdOrName::Name("trait object"),
1113                            pred.rebind(proj.term.expect_type()),
1114                            pred.rebind(args.as_slice()),
1115                        ))
1116                    } else {
1117                        None
1118                    }
1119                }),
1120                ty::Param(param) => {
1121                    let generics = self.tcx.generics_of(body_id);
1122                    let name = if generics.count() > param.index as usize
1123                        && let def = generics.param_at(param.index as usize, self.tcx)
1124                        && matches!(def.kind, ty::GenericParamDefKind::Type { .. })
1125                        && def.name == param.name
1126                    {
1127                        DefIdOrName::DefId(def.def_id)
1128                    } else {
1129                        DefIdOrName::Name("type parameter")
1130                    };
1131                    param_env.caller_bounds().iter().find_map(|pred| {
1132                        if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder()
1133                            && self
1134                                .tcx
1135                                .is_lang_item(proj.projection_term.def_id, LangItem::FnOnceOutput)
1136                            && proj.projection_term.self_ty() == found
1137                            // args tuple will always be args[1]
1138                            && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1139                        {
1140                            Some((
1141                                name,
1142                                pred.kind().rebind(proj.term.expect_type()),
1143                                pred.kind().rebind(args.as_slice()),
1144                            ))
1145                        } else {
1146                            None
1147                        }
1148                    })
1149                }
1150                _ => None,
1151            })
1152        else {
1153            return None;
1154        };
1155
1156        let output = self.instantiate_binder_with_fresh_vars(
1157            DUMMY_SP,
1158            BoundRegionConversionTime::FnCall,
1159            output,
1160        );
1161        let inputs = inputs
1162            .skip_binder()
1163            .iter()
1164            .map(|ty| {
1165                self.instantiate_binder_with_fresh_vars(
1166                    DUMMY_SP,
1167                    BoundRegionConversionTime::FnCall,
1168                    inputs.rebind(*ty),
1169                )
1170            })
1171            .collect();
1172
1173        // We don't want to register any extra obligations, which should be
1174        // implied by wf, but also because that would possibly result in
1175        // erroneous errors later on.
1176        let InferOk { value: output, obligations: _ } =
1177            self.at(&ObligationCause::dummy(), param_env).normalize(output);
1178
1179        if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
1180    }
1181
1182    pub(super) fn suggest_add_reference_to_arg(
1183        &self,
1184        obligation: &PredicateObligation<'tcx>,
1185        err: &mut Diag<'_>,
1186        poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
1187        has_custom_message: bool,
1188    ) -> bool {
1189        let span = obligation.cause.span;
1190
1191        let code = match obligation.cause.code() {
1192            ObligationCauseCode::FunctionArg { parent_code, .. } => parent_code,
1193            // FIXME(compiler-errors): This is kind of a mess, but required for obligations
1194            // that come from a path expr to affect the *call* expr.
1195            c @ ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, _)
1196                if self.tcx.hir().span(*hir_id).lo() == span.lo() =>
1197            {
1198                c
1199            }
1200            c if matches!(
1201                span.ctxt().outer_expn_data().kind,
1202                ExpnKind::Desugaring(DesugaringKind::ForLoop)
1203            ) =>
1204            {
1205                c
1206            }
1207            _ => return false,
1208        };
1209
1210        // List of traits for which it would be nonsensical to suggest borrowing.
1211        // For instance, immutable references are always Copy, so suggesting to
1212        // borrow would always succeed, but it's probably not what the user wanted.
1213        let mut never_suggest_borrow: Vec<_> =
1214            [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1215                .iter()
1216                .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1217                .collect();
1218
1219        if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1220            never_suggest_borrow.push(def_id);
1221        }
1222
1223        let param_env = obligation.param_env;
1224
1225        // Try to apply the original trait bound by borrowing.
1226        let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1227                                 blacklist: &[DefId]|
1228         -> bool {
1229            if blacklist.contains(&old_pred.def_id()) {
1230                return false;
1231            }
1232            // We map bounds to `&T` and `&mut T`
1233            let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1234                (
1235                    trait_pred,
1236                    Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1237                )
1238            });
1239            let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1240                (
1241                    trait_pred,
1242                    Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1243                )
1244            });
1245
1246            let mk_result = |trait_pred_and_new_ty| {
1247                let obligation =
1248                    self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1249                self.predicate_must_hold_modulo_regions(&obligation)
1250            };
1251            let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1252            let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1253
1254            let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1255                if let ObligationCauseCode::WhereClauseInExpr(..) = obligation.cause.code()
1256                    && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1257                {
1258                    (
1259                        mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1260                        mutability.is_mut(),
1261                    )
1262                } else {
1263                    (false, false)
1264                };
1265
1266            if imm_ref_self_ty_satisfies_pred
1267                || mut_ref_self_ty_satisfies_pred
1268                || ref_inner_ty_satisfies_pred
1269            {
1270                if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1271                    // We don't want a borrowing suggestion on the fields in structs,
1272                    // ```
1273                    // struct Foo {
1274                    //  the_foos: Vec<Foo>
1275                    // }
1276                    // ```
1277                    if !matches!(
1278                        span.ctxt().outer_expn_data().kind,
1279                        ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1280                    ) {
1281                        return false;
1282                    }
1283                    if snippet.starts_with('&') {
1284                        // This is already a literal borrow and the obligation is failing
1285                        // somewhere else in the obligation chain. Do not suggest non-sense.
1286                        return false;
1287                    }
1288                    // We have a very specific type of error, where just borrowing this argument
1289                    // might solve the problem. In cases like this, the important part is the
1290                    // original type obligation, not the last one that failed, which is arbitrary.
1291                    // Because of this, we modify the error to refer to the original obligation and
1292                    // return early in the caller.
1293
1294                    let msg = format!(
1295                        "the trait bound `{}` is not satisfied",
1296                        self.tcx.short_string(old_pred, err.long_ty_path()),
1297                    );
1298                    let self_ty_str =
1299                        self.tcx.short_string(old_pred.self_ty().skip_binder(), err.long_ty_path());
1300                    if has_custom_message {
1301                        err.note(msg);
1302                    } else {
1303                        err.messages = vec![(rustc_errors::DiagMessage::from(msg), Style::NoStyle)];
1304                    }
1305                    err.span_label(
1306                        span,
1307                        format!(
1308                            "the trait `{}` is not implemented for `{self_ty_str}`",
1309                            old_pred.print_modifiers_and_trait_path()
1310                        ),
1311                    );
1312
1313                    if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1314                        err.span_suggestions(
1315                            span.shrink_to_lo(),
1316                            "consider borrowing here",
1317                            ["&".to_string(), "&mut ".to_string()],
1318                            Applicability::MaybeIncorrect,
1319                        );
1320                    } else {
1321                        let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1322                        let sugg_prefix = format!("&{}", if is_mut { "mut " } else { "" });
1323                        let sugg_msg = format!(
1324                            "consider{} borrowing here",
1325                            if is_mut { " mutably" } else { "" }
1326                        );
1327
1328                        // Issue #109436, we need to add parentheses properly for method calls
1329                        // for example, `foo.into()` should be `(&foo).into()`
1330                        if let Some(_) =
1331                            self.tcx.sess.source_map().span_look_ahead(span, ".", Some(50))
1332                        {
1333                            err.multipart_suggestion_verbose(
1334                                sugg_msg,
1335                                vec![
1336                                    (span.shrink_to_lo(), format!("({sugg_prefix}")),
1337                                    (span.shrink_to_hi(), ")".to_string()),
1338                                ],
1339                                Applicability::MaybeIncorrect,
1340                            );
1341                            return true;
1342                        }
1343
1344                        // Issue #104961, we need to add parentheses properly for compound expressions
1345                        // for example, `x.starts_with("hi".to_string() + "you")`
1346                        // should be `x.starts_with(&("hi".to_string() + "you"))`
1347                        let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_id)
1348                        else {
1349                            return false;
1350                        };
1351                        let mut expr_finder = FindExprBySpan::new(span, self.tcx);
1352                        expr_finder.visit_expr(body.value);
1353                        let Some(expr) = expr_finder.result else {
1354                            return false;
1355                        };
1356                        let needs_parens = expr_needs_parens(expr);
1357
1358                        let span = if needs_parens { span } else { span.shrink_to_lo() };
1359                        let suggestions = if !needs_parens {
1360                            vec![(span.shrink_to_lo(), sugg_prefix)]
1361                        } else {
1362                            vec![
1363                                (span.shrink_to_lo(), format!("{sugg_prefix}(")),
1364                                (span.shrink_to_hi(), ")".to_string()),
1365                            ]
1366                        };
1367                        err.multipart_suggestion_verbose(
1368                            sugg_msg,
1369                            suggestions,
1370                            Applicability::MaybeIncorrect,
1371                        );
1372                    }
1373                    return true;
1374                }
1375            }
1376            return false;
1377        };
1378
1379        if let ObligationCauseCode::ImplDerived(cause) = &*code {
1380            try_borrowing(cause.derived.parent_trait_pred, &[])
1381        } else if let ObligationCauseCode::WhereClause(..)
1382        | ObligationCauseCode::WhereClauseInExpr(..) = code
1383        {
1384            try_borrowing(poly_trait_pred, &never_suggest_borrow)
1385        } else {
1386            false
1387        }
1388    }
1389
1390    // Suggest borrowing the type
1391    pub(super) fn suggest_borrowing_for_object_cast(
1392        &self,
1393        err: &mut Diag<'_>,
1394        obligation: &PredicateObligation<'tcx>,
1395        self_ty: Ty<'tcx>,
1396        target_ty: Ty<'tcx>,
1397    ) {
1398        let ty::Ref(_, object_ty, hir::Mutability::Not) = target_ty.kind() else {
1399            return;
1400        };
1401        let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else {
1402            return;
1403        };
1404        let self_ref_ty = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, self_ty);
1405
1406        for predicate in predicates.iter() {
1407            if !self.predicate_must_hold_modulo_regions(
1408                &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1409            ) {
1410                return;
1411            }
1412        }
1413
1414        err.span_suggestion(
1415            obligation.cause.span.shrink_to_lo(),
1416            format!(
1417                "consider borrowing the value, since `&{self_ty}` can be coerced into `{target_ty}`"
1418            ),
1419            "&",
1420            Applicability::MaybeIncorrect,
1421        );
1422    }
1423
1424    /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1425    /// suggest removing these references until we reach a type that implements the trait.
1426    pub(super) fn suggest_remove_reference(
1427        &self,
1428        obligation: &PredicateObligation<'tcx>,
1429        err: &mut Diag<'_>,
1430        trait_pred: ty::PolyTraitPredicate<'tcx>,
1431    ) -> bool {
1432        let mut span = obligation.cause.span;
1433        let mut trait_pred = trait_pred;
1434        let mut code = obligation.cause.code();
1435        while let Some((c, Some(parent_trait_pred))) = code.parent_with_predicate() {
1436            // We want the root obligation, in order to detect properly handle
1437            // `for _ in &mut &mut vec![] {}`.
1438            code = c;
1439            trait_pred = parent_trait_pred;
1440        }
1441        while span.desugaring_kind().is_some() {
1442            // Remove all the hir desugaring contexts while maintaining the macro contexts.
1443            span.remove_mark();
1444        }
1445        let mut expr_finder = super::FindExprBySpan::new(span, self.tcx);
1446        let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_id) else {
1447            return false;
1448        };
1449        expr_finder.visit_expr(body.value);
1450        let mut maybe_suggest = |suggested_ty, count, suggestions| {
1451            // Remapping bound vars here
1452            let trait_pred_and_suggested_ty =
1453                trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1454
1455            let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1456                obligation.param_env,
1457                trait_pred_and_suggested_ty,
1458            );
1459
1460            if self.predicate_may_hold(&new_obligation) {
1461                let msg = if count == 1 {
1462                    "consider removing the leading `&`-reference".to_string()
1463                } else {
1464                    format!("consider removing {count} leading `&`-references")
1465                };
1466
1467                err.multipart_suggestion_verbose(
1468                    msg,
1469                    suggestions,
1470                    Applicability::MachineApplicable,
1471                );
1472                true
1473            } else {
1474                false
1475            }
1476        };
1477
1478        // Maybe suggest removal of borrows from types in type parameters, like in
1479        // `src/test/ui/not-panic/not-panic-safe.rs`.
1480        let mut count = 0;
1481        let mut suggestions = vec![];
1482        // Skipping binder here, remapping below
1483        let mut suggested_ty = trait_pred.self_ty().skip_binder();
1484        if let Some(mut hir_ty) = expr_finder.ty_result {
1485            while let hir::TyKind::Ref(_, mut_ty) = &hir_ty.kind {
1486                count += 1;
1487                let span = hir_ty.span.until(mut_ty.ty.span);
1488                suggestions.push((span, String::new()));
1489
1490                let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1491                    break;
1492                };
1493                suggested_ty = *inner_ty;
1494
1495                hir_ty = mut_ty.ty;
1496
1497                if maybe_suggest(suggested_ty, count, suggestions.clone()) {
1498                    return true;
1499                }
1500            }
1501        }
1502
1503        // Maybe suggest removal of borrows from expressions, like in `for i in &&&foo {}`.
1504        let Some(mut expr) = expr_finder.result else {
1505            return false;
1506        };
1507        let mut count = 0;
1508        let mut suggestions = vec![];
1509        // Skipping binder here, remapping below
1510        let mut suggested_ty = trait_pred.self_ty().skip_binder();
1511        'outer: loop {
1512            while let hir::ExprKind::AddrOf(_, _, borrowed) = expr.kind {
1513                count += 1;
1514                let span = if expr.span.eq_ctxt(borrowed.span) {
1515                    expr.span.until(borrowed.span)
1516                } else {
1517                    expr.span.with_hi(expr.span.lo() + BytePos(1))
1518                };
1519                suggestions.push((span, String::new()));
1520
1521                let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1522                    break 'outer;
1523                };
1524                suggested_ty = *inner_ty;
1525
1526                expr = borrowed;
1527
1528                if maybe_suggest(suggested_ty, count, suggestions.clone()) {
1529                    return true;
1530                }
1531            }
1532            if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1533                && let Res::Local(hir_id) = path.res
1534                && let hir::Node::Pat(binding) = self.tcx.hir_node(hir_id)
1535                && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(binding.hir_id)
1536                && let None = local.ty
1537                && let Some(binding_expr) = local.init
1538            {
1539                expr = binding_expr;
1540            } else {
1541                break 'outer;
1542            }
1543        }
1544        false
1545    }
1546
1547    pub(super) fn suggest_remove_await(
1548        &self,
1549        obligation: &PredicateObligation<'tcx>,
1550        err: &mut Diag<'_>,
1551    ) {
1552        if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives()
1553            && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
1554        {
1555            // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1556            // and if not maybe suggest doing something else? If we kept the expression around we
1557            // could also check if it is an fn call (very likely) and suggest changing *that*, if
1558            // it is from the local crate.
1559
1560            // use nth(1) to skip one layer of desugaring from `IntoIter::into_iter`
1561            if let Some((_, hir::Node::Expr(await_expr))) = self.tcx.hir_parent_iter(*hir_id).nth(1)
1562                && let Some(expr_span) = expr.span.find_ancestor_inside_same_ctxt(await_expr.span)
1563            {
1564                let removal_span = self
1565                    .tcx
1566                    .sess
1567                    .source_map()
1568                    .span_extend_while_whitespace(expr_span)
1569                    .shrink_to_hi()
1570                    .to(await_expr.span.shrink_to_hi());
1571                err.span_suggestion(
1572                    removal_span,
1573                    "remove the `.await`",
1574                    "",
1575                    Applicability::MachineApplicable,
1576                );
1577            } else {
1578                err.span_label(obligation.cause.span, "remove the `.await`");
1579            }
1580            // FIXME: account for associated `async fn`s.
1581            if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1582                if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
1583                    obligation.predicate.kind().skip_binder()
1584                {
1585                    err.span_label(*span, format!("this call returns `{}`", pred.self_ty()));
1586                }
1587                if let Some(typeck_results) = &self.typeck_results
1588                    && let ty = typeck_results.expr_ty_adjusted(base)
1589                    && let ty::FnDef(def_id, _args) = ty.kind()
1590                    && let Some(hir::Node::Item(item)) = self.tcx.hir_get_if_local(*def_id)
1591                {
1592                    let (ident, _, _, _) = item.expect_fn();
1593                    let msg = format!("alternatively, consider making `fn {ident}` asynchronous");
1594                    if item.vis_span.is_empty() {
1595                        err.span_suggestion_verbose(
1596                            item.span.shrink_to_lo(),
1597                            msg,
1598                            "async ",
1599                            Applicability::MaybeIncorrect,
1600                        );
1601                    } else {
1602                        err.span_suggestion_verbose(
1603                            item.vis_span.shrink_to_hi(),
1604                            msg,
1605                            " async",
1606                            Applicability::MaybeIncorrect,
1607                        );
1608                    }
1609                }
1610            }
1611        }
1612    }
1613
1614    /// Check if the trait bound is implemented for a different mutability and note it in the
1615    /// final error.
1616    pub(super) fn suggest_change_mut(
1617        &self,
1618        obligation: &PredicateObligation<'tcx>,
1619        err: &mut Diag<'_>,
1620        trait_pred: ty::PolyTraitPredicate<'tcx>,
1621    ) {
1622        let points_at_arg =
1623            matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. },);
1624
1625        let span = obligation.cause.span;
1626        if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1627            let refs_number =
1628                snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1629            if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1630                // Do not suggest removal of borrow from type arguments.
1631                return;
1632            }
1633            let trait_pred = self.resolve_vars_if_possible(trait_pred);
1634            if trait_pred.has_non_region_infer() {
1635                // Do not ICE while trying to find if a reborrow would succeed on a trait with
1636                // unresolved bindings.
1637                return;
1638            }
1639
1640            // Skipping binder here, remapping below
1641            if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1642            {
1643                let suggested_ty = match mutability {
1644                    hir::Mutability::Mut => Ty::new_imm_ref(self.tcx, region, t_type),
1645                    hir::Mutability::Not => Ty::new_mut_ref(self.tcx, region, t_type),
1646                };
1647
1648                // Remapping bound vars here
1649                let trait_pred_and_suggested_ty =
1650                    trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1651
1652                let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1653                    obligation.param_env,
1654                    trait_pred_and_suggested_ty,
1655                );
1656                let suggested_ty_would_satisfy_obligation = self
1657                    .evaluate_obligation_no_overflow(&new_obligation)
1658                    .must_apply_modulo_regions();
1659                if suggested_ty_would_satisfy_obligation {
1660                    let sp = self
1661                        .tcx
1662                        .sess
1663                        .source_map()
1664                        .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1665                    if points_at_arg && mutability.is_not() && refs_number > 0 {
1666                        // If we have a call like foo(&mut buf), then don't suggest foo(&mut mut buf)
1667                        if snippet
1668                            .trim_start_matches(|c: char| c.is_whitespace() || c == '&')
1669                            .starts_with("mut")
1670                        {
1671                            return;
1672                        }
1673                        err.span_suggestion_verbose(
1674                            sp,
1675                            "consider changing this borrow's mutability",
1676                            "&mut ",
1677                            Applicability::MachineApplicable,
1678                        );
1679                    } else {
1680                        err.note(format!(
1681                            "`{}` is implemented for `{}`, but not for `{}`",
1682                            trait_pred.print_modifiers_and_trait_path(),
1683                            suggested_ty,
1684                            trait_pred.skip_binder().self_ty(),
1685                        ));
1686                    }
1687                }
1688            }
1689        }
1690    }
1691
1692    pub(super) fn suggest_semicolon_removal(
1693        &self,
1694        obligation: &PredicateObligation<'tcx>,
1695        err: &mut Diag<'_>,
1696        span: Span,
1697        trait_pred: ty::PolyTraitPredicate<'tcx>,
1698    ) -> bool {
1699        let node = self.tcx.hir_node_by_def_id(obligation.cause.body_id);
1700        if let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn {sig, body: body_id, .. }, .. }) = node
1701            && let hir::ExprKind::Block(blk, _) = &self.tcx.hir_body(*body_id).value.kind
1702            && sig.decl.output.span().overlaps(span)
1703            && blk.expr.is_none()
1704            && trait_pred.self_ty().skip_binder().is_unit()
1705            && let Some(stmt) = blk.stmts.last()
1706            && let hir::StmtKind::Semi(expr) = stmt.kind
1707            // Only suggest this if the expression behind the semicolon implements the predicate
1708            && let Some(typeck_results) = &self.typeck_results
1709            && let Some(ty) = typeck_results.expr_ty_opt(expr)
1710            && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1711                obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1712            ))
1713        {
1714            err.span_label(
1715                expr.span,
1716                format!(
1717                    "this expression has type `{}`, which implements `{}`",
1718                    ty,
1719                    trait_pred.print_modifiers_and_trait_path()
1720                ),
1721            );
1722            err.span_suggestion(
1723                self.tcx.sess.source_map().end_point(stmt.span),
1724                "remove this semicolon",
1725                "",
1726                Applicability::MachineApplicable,
1727            );
1728            return true;
1729        }
1730        false
1731    }
1732
1733    pub(super) fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1734        let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig, .. }, .. }) =
1735            self.tcx.hir_node_by_def_id(obligation.cause.body_id)
1736        else {
1737            return None;
1738        };
1739
1740        if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1741    }
1742
1743    /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1744    /// applicable and signal that the error has been expanded appropriately and needs to be
1745    /// emitted.
1746    pub(super) fn suggest_impl_trait(
1747        &self,
1748        err: &mut Diag<'_>,
1749        obligation: &PredicateObligation<'tcx>,
1750        trait_pred: ty::PolyTraitPredicate<'tcx>,
1751    ) -> bool {
1752        let ObligationCauseCode::SizedReturnType = obligation.cause.code() else {
1753            return false;
1754        };
1755        let ty::Dynamic(_, _, ty::Dyn) = trait_pred.self_ty().skip_binder().kind() else {
1756            return false;
1757        };
1758
1759        err.code(E0746);
1760        err.primary_message("return type cannot be a trait object without pointer indirection");
1761        err.children.clear();
1762
1763        let span = obligation.cause.span;
1764        let body = self.tcx.hir_body_owned_by(obligation.cause.body_id);
1765
1766        let mut visitor = ReturnsVisitor::default();
1767        visitor.visit_body(&body);
1768
1769        let (pre, impl_span) = if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span)
1770            && snip.starts_with("dyn ")
1771        {
1772            ("", span.with_hi(span.lo() + BytePos(4)))
1773        } else {
1774            ("dyn ", span.shrink_to_lo())
1775        };
1776
1777        err.span_suggestion_verbose(
1778            impl_span,
1779            "consider returning an `impl Trait` instead of a `dyn Trait`",
1780            "impl ",
1781            Applicability::MaybeIncorrect,
1782        );
1783
1784        let mut sugg = vec![
1785            (span.shrink_to_lo(), format!("Box<{pre}")),
1786            (span.shrink_to_hi(), ">".to_string()),
1787        ];
1788        sugg.extend(visitor.returns.into_iter().flat_map(|expr| {
1789            let span =
1790                expr.span.find_ancestor_in_same_ctxt(obligation.cause.span).unwrap_or(expr.span);
1791            if !span.can_be_used_for_suggestions() {
1792                vec![]
1793            } else if let hir::ExprKind::Call(path, ..) = expr.kind
1794                && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, method)) = path.kind
1795                && method.ident.name == sym::new
1796                && let hir::TyKind::Path(hir::QPath::Resolved(.., box_path)) = ty.kind
1797                && box_path
1798                    .res
1799                    .opt_def_id()
1800                    .is_some_and(|def_id| self.tcx.is_lang_item(def_id, LangItem::OwnedBox))
1801            {
1802                // Don't box `Box::new`
1803                vec![]
1804            } else {
1805                vec![
1806                    (span.shrink_to_lo(), "Box::new(".to_string()),
1807                    (span.shrink_to_hi(), ")".to_string()),
1808                ]
1809            }
1810        }));
1811
1812        err.multipart_suggestion(
1813            format!(
1814                "alternatively, box the return type, and wrap all of the returned values in \
1815                 `Box::new`",
1816            ),
1817            sugg,
1818            Applicability::MaybeIncorrect,
1819        );
1820
1821        true
1822    }
1823
1824    pub(super) fn report_closure_arg_mismatch(
1825        &self,
1826        span: Span,
1827        found_span: Option<Span>,
1828        found: ty::TraitRef<'tcx>,
1829        expected: ty::TraitRef<'tcx>,
1830        cause: &ObligationCauseCode<'tcx>,
1831        found_node: Option<Node<'_>>,
1832        param_env: ty::ParamEnv<'tcx>,
1833    ) -> Diag<'a> {
1834        pub(crate) fn build_fn_sig_ty<'tcx>(
1835            infcx: &InferCtxt<'tcx>,
1836            trait_ref: ty::TraitRef<'tcx>,
1837        ) -> Ty<'tcx> {
1838            let inputs = trait_ref.args.type_at(1);
1839            let sig = match inputs.kind() {
1840                ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id) => {
1841                    infcx.tcx.mk_fn_sig(
1842                        *inputs,
1843                        infcx.next_ty_var(DUMMY_SP),
1844                        false,
1845                        hir::Safety::Safe,
1846                        ExternAbi::Rust,
1847                    )
1848                }
1849                _ => infcx.tcx.mk_fn_sig(
1850                    [inputs],
1851                    infcx.next_ty_var(DUMMY_SP),
1852                    false,
1853                    hir::Safety::Safe,
1854                    ExternAbi::Rust,
1855                ),
1856            };
1857
1858            Ty::new_fn_ptr(infcx.tcx, ty::Binder::dummy(sig))
1859        }
1860
1861        let argument_kind = match expected.self_ty().kind() {
1862            ty::Closure(..) => "closure",
1863            ty::Coroutine(..) => "coroutine",
1864            _ => "function",
1865        };
1866        let mut err = struct_span_code_err!(
1867            self.dcx(),
1868            span,
1869            E0631,
1870            "type mismatch in {argument_kind} arguments",
1871        );
1872
1873        err.span_label(span, "expected due to this");
1874
1875        let found_span = found_span.unwrap_or(span);
1876        err.span_label(found_span, "found signature defined here");
1877
1878        let expected = build_fn_sig_ty(self, expected);
1879        let found = build_fn_sig_ty(self, found);
1880
1881        let (expected_str, found_str) = self.cmp(expected, found);
1882
1883        let signature_kind = format!("{argument_kind} signature");
1884        err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
1885
1886        self.note_conflicting_fn_args(&mut err, cause, expected, found, param_env);
1887        self.note_conflicting_closure_bounds(cause, &mut err);
1888
1889        if let Some(found_node) = found_node {
1890            hint_missing_borrow(self, param_env, span, found, expected, found_node, &mut err);
1891        }
1892
1893        err
1894    }
1895
1896    fn note_conflicting_fn_args(
1897        &self,
1898        err: &mut Diag<'_>,
1899        cause: &ObligationCauseCode<'tcx>,
1900        expected: Ty<'tcx>,
1901        found: Ty<'tcx>,
1902        param_env: ty::ParamEnv<'tcx>,
1903    ) {
1904        let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = cause else {
1905            return;
1906        };
1907        let ty::FnPtr(sig_tys, hdr) = expected.kind() else {
1908            return;
1909        };
1910        let expected = sig_tys.with(*hdr);
1911        let ty::FnPtr(sig_tys, hdr) = found.kind() else {
1912            return;
1913        };
1914        let found = sig_tys.with(*hdr);
1915        let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) else {
1916            return;
1917        };
1918        let hir::ExprKind::Path(path) = arg.kind else {
1919            return;
1920        };
1921        let expected_inputs = self.tcx.instantiate_bound_regions_with_erased(expected).inputs();
1922        let found_inputs = self.tcx.instantiate_bound_regions_with_erased(found).inputs();
1923        let both_tys = expected_inputs.iter().copied().zip(found_inputs.iter().copied());
1924
1925        let arg_expr = |infcx: &InferCtxt<'tcx>, name, expected: Ty<'tcx>, found: Ty<'tcx>| {
1926            let (expected_ty, expected_refs) = get_deref_type_and_refs(expected);
1927            let (found_ty, found_refs) = get_deref_type_and_refs(found);
1928
1929            if infcx.can_eq(param_env, found_ty, expected_ty) {
1930                if found_refs.len() == expected_refs.len()
1931                    && found_refs.iter().eq(expected_refs.iter())
1932                {
1933                    name
1934                } else if found_refs.len() > expected_refs.len() {
1935                    let refs = &found_refs[..found_refs.len() - expected_refs.len()];
1936                    if found_refs[..expected_refs.len()].iter().eq(expected_refs.iter()) {
1937                        format!(
1938                            "{}{name}",
1939                            refs.iter()
1940                                .map(|mutbl| format!("&{}", mutbl.prefix_str()))
1941                                .collect::<Vec<_>>()
1942                                .join(""),
1943                        )
1944                    } else {
1945                        // The refs have different mutability.
1946                        format!(
1947                            "{}*{name}",
1948                            refs.iter()
1949                                .map(|mutbl| format!("&{}", mutbl.prefix_str()))
1950                                .collect::<Vec<_>>()
1951                                .join(""),
1952                        )
1953                    }
1954                } else if expected_refs.len() > found_refs.len() {
1955                    format!(
1956                        "{}{name}",
1957                        (0..(expected_refs.len() - found_refs.len()))
1958                            .map(|_| "*")
1959                            .collect::<Vec<_>>()
1960                            .join(""),
1961                    )
1962                } else {
1963                    format!(
1964                        "{}{name}",
1965                        found_refs
1966                            .iter()
1967                            .map(|mutbl| format!("&{}", mutbl.prefix_str()))
1968                            .chain(found_refs.iter().map(|_| "*".to_string()))
1969                            .collect::<Vec<_>>()
1970                            .join(""),
1971                    )
1972                }
1973            } else {
1974                format!("/* {found} */")
1975            }
1976        };
1977        let args_have_same_underlying_type = both_tys.clone().all(|(expected, found)| {
1978            let (expected_ty, _) = get_deref_type_and_refs(expected);
1979            let (found_ty, _) = get_deref_type_and_refs(found);
1980            self.can_eq(param_env, found_ty, expected_ty)
1981        });
1982        let (closure_names, call_names): (Vec<_>, Vec<_>) = if args_have_same_underlying_type
1983            && !expected_inputs.is_empty()
1984            && expected_inputs.len() == found_inputs.len()
1985            && let Some(typeck) = &self.typeck_results
1986            && let Res::Def(res_kind, fn_def_id) = typeck.qpath_res(&path, *arg_hir_id)
1987            && res_kind.is_fn_like()
1988        {
1989            let closure: Vec<_> = self
1990                .tcx
1991                .fn_arg_names(fn_def_id)
1992                .iter()
1993                .enumerate()
1994                .map(|(i, ident)| {
1995                    if let Some(ident) = ident
1996                        && !matches!(ident, Ident { name: kw::Underscore | kw::SelfLower, .. })
1997                    {
1998                        format!("{ident}")
1999                    } else {
2000                        format!("arg{i}")
2001                    }
2002                })
2003                .collect();
2004            let args = closure
2005                .iter()
2006                .zip(both_tys)
2007                .map(|(name, (expected, found))| {
2008                    arg_expr(self.infcx, name.to_owned(), expected, found)
2009                })
2010                .collect();
2011            (closure, args)
2012        } else {
2013            let closure_args = expected_inputs
2014                .iter()
2015                .enumerate()
2016                .map(|(i, _)| format!("arg{i}"))
2017                .collect::<Vec<_>>();
2018            let call_args = both_tys
2019                .enumerate()
2020                .map(|(i, (expected, found))| {
2021                    arg_expr(self.infcx, format!("arg{i}"), expected, found)
2022                })
2023                .collect::<Vec<_>>();
2024            (closure_args, call_args)
2025        };
2026        let closure_names: Vec<_> = closure_names
2027            .into_iter()
2028            .zip(expected_inputs.iter())
2029            .map(|(name, ty)| {
2030                format!(
2031                    "{name}{}",
2032                    if ty.has_infer_types() {
2033                        String::new()
2034                    } else if ty.references_error() {
2035                        ": /* type */".to_string()
2036                    } else {
2037                        format!(": {ty}")
2038                    }
2039                )
2040            })
2041            .collect();
2042        err.multipart_suggestion(
2043            "consider wrapping the function in a closure",
2044            vec![
2045                (arg.span.shrink_to_lo(), format!("|{}| ", closure_names.join(", "))),
2046                (arg.span.shrink_to_hi(), format!("({})", call_names.join(", "))),
2047            ],
2048            Applicability::MaybeIncorrect,
2049        );
2050    }
2051
2052    // Add a note if there are two `Fn`-family bounds that have conflicting argument
2053    // requirements, which will always cause a closure to have a type error.
2054    fn note_conflicting_closure_bounds(
2055        &self,
2056        cause: &ObligationCauseCode<'tcx>,
2057        err: &mut Diag<'_>,
2058    ) {
2059        // First, look for an `WhereClauseInExpr`, which means we can get
2060        // the uninstantiated predicate list of the called function. And check
2061        // that the predicate that we failed to satisfy is a `Fn`-like trait.
2062        if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = cause
2063            && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
2064            && let Some(pred) = predicates.predicates.get(*idx)
2065            && let ty::ClauseKind::Trait(trait_pred) = pred.kind().skip_binder()
2066            && self.tcx.is_fn_trait(trait_pred.def_id())
2067        {
2068            let expected_self =
2069                self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.self_ty()));
2070            let expected_args =
2071                self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.trait_ref.args));
2072
2073            // Find another predicate whose self-type is equal to the expected self type,
2074            // but whose args don't match.
2075            let other_pred = predicates.into_iter().enumerate().find(|(other_idx, (pred, _))| {
2076                match pred.kind().skip_binder() {
2077                    ty::ClauseKind::Trait(trait_pred)
2078                        if self.tcx.is_fn_trait(trait_pred.def_id())
2079                            && other_idx != idx
2080                            // Make sure that the self type matches
2081                            // (i.e. constraining this closure)
2082                            && expected_self
2083                                == self.tcx.anonymize_bound_vars(
2084                                    pred.kind().rebind(trait_pred.self_ty()),
2085                                )
2086                            // But the args don't match (i.e. incompatible args)
2087                            && expected_args
2088                                != self.tcx.anonymize_bound_vars(
2089                                    pred.kind().rebind(trait_pred.trait_ref.args),
2090                                ) =>
2091                    {
2092                        true
2093                    }
2094                    _ => false,
2095                }
2096            });
2097            // If we found one, then it's very likely the cause of the error.
2098            if let Some((_, (_, other_pred_span))) = other_pred {
2099                err.span_note(
2100                    other_pred_span,
2101                    "closure inferred to have a different signature due to this bound",
2102                );
2103            }
2104        }
2105    }
2106
2107    pub(super) fn suggest_fully_qualified_path(
2108        &self,
2109        err: &mut Diag<'_>,
2110        item_def_id: DefId,
2111        span: Span,
2112        trait_ref: DefId,
2113    ) {
2114        if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
2115            if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
2116                err.note(format!(
2117                    "{}s cannot be accessed directly on a `trait`, they can only be \
2118                        accessed through a specific `impl`",
2119                    self.tcx.def_kind_descr(assoc_item.kind.as_def_kind(), item_def_id)
2120                ));
2121                err.span_suggestion(
2122                    span,
2123                    "use the fully qualified path to an implementation",
2124                    format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
2125                    Applicability::HasPlaceholders,
2126                );
2127            }
2128        }
2129    }
2130
2131    /// Adds an async-await specific note to the diagnostic when the future does not implement
2132    /// an auto trait because of a captured type.
2133    ///
2134    /// ```text
2135    /// note: future does not implement `Qux` as this value is used across an await
2136    ///   --> $DIR/issue-64130-3-other.rs:17:5
2137    ///    |
2138    /// LL |     let x = Foo;
2139    ///    |         - has type `Foo`
2140    /// LL |     baz().await;
2141    ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2142    /// LL | }
2143    ///    | - `x` is later dropped here
2144    /// ```
2145    ///
2146    /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
2147    /// is "replaced" with a different message and a more specific error.
2148    ///
2149    /// ```text
2150    /// error: future cannot be sent between threads safely
2151    ///   --> $DIR/issue-64130-2-send.rs:21:5
2152    ///    |
2153    /// LL | fn is_send<T: Send>(t: T) { }
2154    ///    |               ---- required by this bound in `is_send`
2155    /// ...
2156    /// LL |     is_send(bar());
2157    ///    |     ^^^^^^^ future returned by `bar` is not send
2158    ///    |
2159    ///    = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
2160    ///            implemented for `Foo`
2161    /// note: future is not send as this value is used across an await
2162    ///   --> $DIR/issue-64130-2-send.rs:15:5
2163    ///    |
2164    /// LL |     let x = Foo;
2165    ///    |         - has type `Foo`
2166    /// LL |     baz().await;
2167    ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2168    /// LL | }
2169    ///    | - `x` is later dropped here
2170    /// ```
2171    ///
2172    /// Returns `true` if an async-await specific note was added to the diagnostic.
2173    #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
2174    pub fn maybe_note_obligation_cause_for_async_await<G: EmissionGuarantee>(
2175        &self,
2176        err: &mut Diag<'_, G>,
2177        obligation: &PredicateObligation<'tcx>,
2178    ) -> bool {
2179        // Attempt to detect an async-await error by looking at the obligation causes, looking
2180        // for a coroutine to be present.
2181        //
2182        // When a future does not implement a trait because of a captured type in one of the
2183        // coroutines somewhere in the call stack, then the result is a chain of obligations.
2184        //
2185        // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
2186        // future is passed as an argument to a function C which requires a `Send` type, then the
2187        // chain looks something like this:
2188        //
2189        // - `BuiltinDerivedObligation` with a coroutine witness (B)
2190        // - `BuiltinDerivedObligation` with a coroutine (B)
2191        // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2192        // - `BuiltinDerivedObligation` with a coroutine witness (A)
2193        // - `BuiltinDerivedObligation` with a coroutine (A)
2194        // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2195        // - `BindingObligation` with `impl_send` (Send requirement)
2196        //
2197        // The first obligation in the chain is the most useful and has the coroutine that captured
2198        // the type. The last coroutine (`outer_coroutine` below) has information about where the
2199        // bound was introduced. At least one coroutine should be present for this diagnostic to be
2200        // modified.
2201        let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
2202            ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) => (Some(p), Some(p.self_ty())),
2203            _ => (None, None),
2204        };
2205        let mut coroutine = None;
2206        let mut outer_coroutine = None;
2207        let mut next_code = Some(obligation.cause.code());
2208
2209        let mut seen_upvar_tys_infer_tuple = false;
2210
2211        while let Some(code) = next_code {
2212            debug!(?code);
2213            match code {
2214                ObligationCauseCode::FunctionArg { parent_code, .. } => {
2215                    next_code = Some(parent_code);
2216                }
2217                ObligationCauseCode::ImplDerived(cause) => {
2218                    let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
2219                    debug!(
2220                        parent_trait_ref = ?cause.derived.parent_trait_pred,
2221                        self_ty.kind = ?ty.kind(),
2222                        "ImplDerived",
2223                    );
2224
2225                    match *ty.kind() {
2226                        ty::Coroutine(did, ..) | ty::CoroutineWitness(did, _) => {
2227                            coroutine = coroutine.or(Some(did));
2228                            outer_coroutine = Some(did);
2229                        }
2230                        ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2231                            // By introducing a tuple of upvar types into the chain of obligations
2232                            // of a coroutine, the first non-coroutine item is now the tuple itself,
2233                            // we shall ignore this.
2234
2235                            seen_upvar_tys_infer_tuple = true;
2236                        }
2237                        _ if coroutine.is_none() => {
2238                            trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
2239                            target_ty = Some(ty);
2240                        }
2241                        _ => {}
2242                    }
2243
2244                    next_code = Some(&cause.derived.parent_code);
2245                }
2246                ObligationCauseCode::WellFormedDerived(derived_obligation)
2247                | ObligationCauseCode::BuiltinDerived(derived_obligation) => {
2248                    let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
2249                    debug!(
2250                        parent_trait_ref = ?derived_obligation.parent_trait_pred,
2251                        self_ty.kind = ?ty.kind(),
2252                    );
2253
2254                    match *ty.kind() {
2255                        ty::Coroutine(did, ..) | ty::CoroutineWitness(did, ..) => {
2256                            coroutine = coroutine.or(Some(did));
2257                            outer_coroutine = Some(did);
2258                        }
2259                        ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2260                            // By introducing a tuple of upvar types into the chain of obligations
2261                            // of a coroutine, the first non-coroutine item is now the tuple itself,
2262                            // we shall ignore this.
2263
2264                            seen_upvar_tys_infer_tuple = true;
2265                        }
2266                        _ if coroutine.is_none() => {
2267                            trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
2268                            target_ty = Some(ty);
2269                        }
2270                        _ => {}
2271                    }
2272
2273                    next_code = Some(&derived_obligation.parent_code);
2274                }
2275                _ => break,
2276            }
2277        }
2278
2279        // Only continue if a coroutine was found.
2280        debug!(?coroutine, ?trait_ref, ?target_ty);
2281        let (Some(coroutine_did), Some(trait_ref), Some(target_ty)) =
2282            (coroutine, trait_ref, target_ty)
2283        else {
2284            return false;
2285        };
2286
2287        let span = self.tcx.def_span(coroutine_did);
2288
2289        let coroutine_did_root = self.tcx.typeck_root_def_id(coroutine_did);
2290        debug!(
2291            ?coroutine_did,
2292            ?coroutine_did_root,
2293            typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
2294            ?span,
2295        );
2296
2297        let coroutine_body =
2298            coroutine_did.as_local().and_then(|def_id| self.tcx.hir_maybe_body_owned_by(def_id));
2299        let mut visitor = AwaitsVisitor::default();
2300        if let Some(body) = coroutine_body {
2301            visitor.visit_body(&body);
2302        }
2303        debug!(awaits = ?visitor.awaits);
2304
2305        // Look for a type inside the coroutine interior that matches the target type to get
2306        // a span.
2307        let target_ty_erased = self.tcx.erase_regions(target_ty);
2308        let ty_matches = |ty| -> bool {
2309            // Careful: the regions for types that appear in the
2310            // coroutine interior are not generally known, so we
2311            // want to erase them when comparing (and anyway,
2312            // `Send` and other bounds are generally unaffected by
2313            // the choice of region). When erasing regions, we
2314            // also have to erase late-bound regions. This is
2315            // because the types that appear in the coroutine
2316            // interior generally contain "bound regions" to
2317            // represent regions that are part of the suspended
2318            // coroutine frame. Bound regions are preserved by
2319            // `erase_regions` and so we must also call
2320            // `instantiate_bound_regions_with_erased`.
2321            let ty_erased = self.tcx.instantiate_bound_regions_with_erased(ty);
2322            let ty_erased = self.tcx.erase_regions(ty_erased);
2323            let eq = ty_erased == target_ty_erased;
2324            debug!(?ty_erased, ?target_ty_erased, ?eq);
2325            eq
2326        };
2327
2328        // Get the typeck results from the infcx if the coroutine is the function we are currently
2329        // type-checking; otherwise, get them by performing a query. This is needed to avoid
2330        // cycles. If we can't use resolved types because the coroutine comes from another crate,
2331        // we still provide a targeted error but without all the relevant spans.
2332        let coroutine_data = match &self.typeck_results {
2333            Some(t) if t.hir_owner.to_def_id() == coroutine_did_root => CoroutineData(t),
2334            _ if coroutine_did.is_local() => {
2335                CoroutineData(self.tcx.typeck(coroutine_did.expect_local()))
2336            }
2337            _ => return false,
2338        };
2339
2340        let coroutine_within_in_progress_typeck = match &self.typeck_results {
2341            Some(t) => t.hir_owner.to_def_id() == coroutine_did_root,
2342            _ => false,
2343        };
2344
2345        let mut interior_or_upvar_span = None;
2346
2347        let from_awaited_ty = coroutine_data.get_from_await_ty(visitor, self.tcx, ty_matches);
2348        debug!(?from_awaited_ty);
2349
2350        // Avoid disclosing internal information to downstream crates.
2351        if coroutine_did.is_local()
2352            // Try to avoid cycles.
2353            && !coroutine_within_in_progress_typeck
2354            && let Some(coroutine_info) = self.tcx.mir_coroutine_witnesses(coroutine_did)
2355        {
2356            debug!(?coroutine_info);
2357            'find_source: for (variant, source_info) in
2358                coroutine_info.variant_fields.iter().zip(&coroutine_info.variant_source_info)
2359            {
2360                debug!(?variant);
2361                for &local in variant {
2362                    let decl = &coroutine_info.field_tys[local];
2363                    debug!(?decl);
2364                    if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.ignore_for_traits {
2365                        interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(
2366                            decl.source_info.span,
2367                            Some((source_info.span, from_awaited_ty)),
2368                        ));
2369                        break 'find_source;
2370                    }
2371                }
2372            }
2373        }
2374
2375        if interior_or_upvar_span.is_none() {
2376            interior_or_upvar_span =
2377                coroutine_data.try_get_upvar_span(self, coroutine_did, ty_matches);
2378        }
2379
2380        if interior_or_upvar_span.is_none() && !coroutine_did.is_local() {
2381            interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(span, None));
2382        }
2383
2384        debug!(?interior_or_upvar_span);
2385        if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2386            let is_async = self.tcx.coroutine_is_async(coroutine_did);
2387            self.note_obligation_cause_for_async_await(
2388                err,
2389                interior_or_upvar_span,
2390                is_async,
2391                outer_coroutine,
2392                trait_ref,
2393                target_ty,
2394                obligation,
2395                next_code,
2396            );
2397            true
2398        } else {
2399            false
2400        }
2401    }
2402
2403    /// Unconditionally adds the diagnostic note described in
2404    /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2405    #[instrument(level = "debug", skip_all)]
2406    fn note_obligation_cause_for_async_await<G: EmissionGuarantee>(
2407        &self,
2408        err: &mut Diag<'_, G>,
2409        interior_or_upvar_span: CoroutineInteriorOrUpvar,
2410        is_async: bool,
2411        outer_coroutine: Option<DefId>,
2412        trait_pred: ty::TraitPredicate<'tcx>,
2413        target_ty: Ty<'tcx>,
2414        obligation: &PredicateObligation<'tcx>,
2415        next_code: Option<&ObligationCauseCode<'tcx>>,
2416    ) {
2417        let source_map = self.tcx.sess.source_map();
2418
2419        let (await_or_yield, an_await_or_yield) =
2420            if is_async { ("await", "an await") } else { ("yield", "a yield") };
2421        let future_or_coroutine = if is_async { "future" } else { "coroutine" };
2422
2423        // Special case the primary error message when send or sync is the trait that was
2424        // not implemented.
2425        let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2426            self.tcx.get_diagnostic_name(trait_pred.def_id())
2427        {
2428            let (trait_name, trait_verb) =
2429                if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2430
2431            err.code = None;
2432            err.primary_message(format!(
2433                "{future_or_coroutine} cannot be {trait_verb} between threads safely"
2434            ));
2435
2436            let original_span = err.span.primary_span().unwrap();
2437            let mut span = MultiSpan::from_span(original_span);
2438
2439            let message = outer_coroutine
2440                .and_then(|coroutine_did| {
2441                    Some(match self.tcx.coroutine_kind(coroutine_did).unwrap() {
2442                        CoroutineKind::Coroutine(_) => format!("coroutine is not {trait_name}"),
2443                        CoroutineKind::Desugared(
2444                            CoroutineDesugaring::Async,
2445                            CoroutineSource::Fn,
2446                        ) => self
2447                            .tcx
2448                            .parent(coroutine_did)
2449                            .as_local()
2450                            .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
2451                            .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
2452                            .map(|name| {
2453                                format!("future returned by `{name}` is not {trait_name}")
2454                            })?,
2455                        CoroutineKind::Desugared(
2456                            CoroutineDesugaring::Async,
2457                            CoroutineSource::Block,
2458                        ) => {
2459                            format!("future created by async block is not {trait_name}")
2460                        }
2461                        CoroutineKind::Desugared(
2462                            CoroutineDesugaring::Async,
2463                            CoroutineSource::Closure,
2464                        ) => {
2465                            format!("future created by async closure is not {trait_name}")
2466                        }
2467                        CoroutineKind::Desugared(
2468                            CoroutineDesugaring::AsyncGen,
2469                            CoroutineSource::Fn,
2470                        ) => self
2471                            .tcx
2472                            .parent(coroutine_did)
2473                            .as_local()
2474                            .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
2475                            .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
2476                            .map(|name| {
2477                                format!("async iterator returned by `{name}` is not {trait_name}")
2478                            })?,
2479                        CoroutineKind::Desugared(
2480                            CoroutineDesugaring::AsyncGen,
2481                            CoroutineSource::Block,
2482                        ) => {
2483                            format!("async iterator created by async gen block is not {trait_name}")
2484                        }
2485                        CoroutineKind::Desugared(
2486                            CoroutineDesugaring::AsyncGen,
2487                            CoroutineSource::Closure,
2488                        ) => {
2489                            format!(
2490                                "async iterator created by async gen closure is not {trait_name}"
2491                            )
2492                        }
2493                        CoroutineKind::Desugared(CoroutineDesugaring::Gen, CoroutineSource::Fn) => {
2494                            self.tcx
2495                                .parent(coroutine_did)
2496                                .as_local()
2497                                .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
2498                                .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
2499                                .map(|name| {
2500                                    format!("iterator returned by `{name}` is not {trait_name}")
2501                                })?
2502                        }
2503                        CoroutineKind::Desugared(
2504                            CoroutineDesugaring::Gen,
2505                            CoroutineSource::Block,
2506                        ) => {
2507                            format!("iterator created by gen block is not {trait_name}")
2508                        }
2509                        CoroutineKind::Desugared(
2510                            CoroutineDesugaring::Gen,
2511                            CoroutineSource::Closure,
2512                        ) => {
2513                            format!("iterator created by gen closure is not {trait_name}")
2514                        }
2515                    })
2516                })
2517                .unwrap_or_else(|| format!("{future_or_coroutine} is not {trait_name}"));
2518
2519            span.push_span_label(original_span, message);
2520            err.span(span);
2521
2522            format!("is not {trait_name}")
2523        } else {
2524            format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2525        };
2526
2527        let mut explain_yield = |interior_span: Span, yield_span: Span| {
2528            let mut span = MultiSpan::from_span(yield_span);
2529            let snippet = match source_map.span_to_snippet(interior_span) {
2530                // #70935: If snippet contains newlines, display "the value" instead
2531                // so that we do not emit complex diagnostics.
2532                Ok(snippet) if !snippet.contains('\n') => format!("`{snippet}`"),
2533                _ => "the value".to_string(),
2534            };
2535            // note: future is not `Send` as this value is used across an await
2536            //   --> $DIR/issue-70935-complex-spans.rs:13:9
2537            //    |
2538            // LL |            baz(|| async {
2539            //    |  ______________-
2540            //    | |
2541            //    | |
2542            // LL | |              foo(tx.clone());
2543            // LL | |          }).await;
2544            //    | |          - ^^^^^^ await occurs here, with value maybe used later
2545            //    | |__________|
2546            //    |            has type `closure` which is not `Send`
2547            // note: value is later dropped here
2548            // LL | |          }).await;
2549            //    | |                  ^
2550            //
2551            span.push_span_label(
2552                yield_span,
2553                format!("{await_or_yield} occurs here, with {snippet} maybe used later"),
2554            );
2555            span.push_span_label(
2556                interior_span,
2557                format!("has type `{target_ty}` which {trait_explanation}"),
2558            );
2559            err.span_note(
2560                span,
2561                format!("{future_or_coroutine} {trait_explanation} as this value is used across {an_await_or_yield}"),
2562            );
2563        };
2564        match interior_or_upvar_span {
2565            CoroutineInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2566                if let Some((yield_span, from_awaited_ty)) = interior_extra_info {
2567                    if let Some(await_span) = from_awaited_ty {
2568                        // The type causing this obligation is one being awaited at await_span.
2569                        let mut span = MultiSpan::from_span(await_span);
2570                        span.push_span_label(
2571                            await_span,
2572                            format!(
2573                                "await occurs here on type `{target_ty}`, which {trait_explanation}"
2574                            ),
2575                        );
2576                        err.span_note(
2577                            span,
2578                            format!(
2579                                "future {trait_explanation} as it awaits another future which {trait_explanation}"
2580                            ),
2581                        );
2582                    } else {
2583                        // Look at the last interior type to get a span for the `.await`.
2584                        explain_yield(interior_span, yield_span);
2585                    }
2586                }
2587            }
2588            CoroutineInteriorOrUpvar::Upvar(upvar_span) => {
2589                // `Some((ref_ty, is_mut))` if `target_ty` is `&T` or `&mut T` and fails to impl `Send`
2590                let non_send = match target_ty.kind() {
2591                    ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(obligation) {
2592                        Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
2593                        _ => None,
2594                    },
2595                    _ => None,
2596                };
2597
2598                let (span_label, span_note) = match non_send {
2599                    // if `target_ty` is `&T` or `&mut T` and fails to impl `Send`,
2600                    // include suggestions to make `T: Sync` so that `&T: Send`,
2601                    // or to make `T: Send` so that `&mut T: Send`
2602                    Some((ref_ty, is_mut)) => {
2603                        let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
2604                        let ref_kind = if is_mut { "&mut" } else { "&" };
2605                        (
2606                            format!(
2607                                "has type `{target_ty}` which {trait_explanation}, because `{ref_ty}` is not `{ref_ty_trait}`"
2608                            ),
2609                            format!(
2610                                "captured value {trait_explanation} because `{ref_kind}` references cannot be sent unless their referent is `{ref_ty_trait}`"
2611                            ),
2612                        )
2613                    }
2614                    None => (
2615                        format!("has type `{target_ty}` which {trait_explanation}"),
2616                        format!("captured value {trait_explanation}"),
2617                    ),
2618                };
2619
2620                let mut span = MultiSpan::from_span(upvar_span);
2621                span.push_span_label(upvar_span, span_label);
2622                err.span_note(span, span_note);
2623            }
2624        }
2625
2626        // Add a note for the item obligation that remains - normally a note pointing to the
2627        // bound that introduced the obligation (e.g. `T: Send`).
2628        debug!(?next_code);
2629        self.note_obligation_cause_code(
2630            obligation.cause.body_id,
2631            err,
2632            obligation.predicate,
2633            obligation.param_env,
2634            next_code.unwrap(),
2635            &mut Vec::new(),
2636            &mut Default::default(),
2637        );
2638    }
2639
2640    pub(super) fn note_obligation_cause_code<G: EmissionGuarantee, T>(
2641        &self,
2642        body_id: LocalDefId,
2643        err: &mut Diag<'_, G>,
2644        predicate: T,
2645        param_env: ty::ParamEnv<'tcx>,
2646        cause_code: &ObligationCauseCode<'tcx>,
2647        obligated_types: &mut Vec<Ty<'tcx>>,
2648        seen_requirements: &mut FxHashSet<DefId>,
2649    ) where
2650        T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
2651    {
2652        let tcx = self.tcx;
2653        let predicate = predicate.upcast(tcx);
2654        let suggest_remove_deref = |err: &mut Diag<'_, G>, expr: &hir::Expr<'_>| {
2655            if let Some(pred) = predicate.as_trait_clause()
2656                && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
2657                && let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind
2658            {
2659                err.span_suggestion_verbose(
2660                    expr.span.until(inner.span),
2661                    "references are always `Sized`, even if they point to unsized data; consider \
2662                     not dereferencing the expression",
2663                    String::new(),
2664                    Applicability::MaybeIncorrect,
2665                );
2666            }
2667        };
2668        match *cause_code {
2669            ObligationCauseCode::ExprAssignable
2670            | ObligationCauseCode::MatchExpressionArm { .. }
2671            | ObligationCauseCode::Pattern { .. }
2672            | ObligationCauseCode::IfExpression { .. }
2673            | ObligationCauseCode::IfExpressionWithNoElse
2674            | ObligationCauseCode::MainFunctionType
2675            | ObligationCauseCode::LangFunctionType(_)
2676            | ObligationCauseCode::IntrinsicType
2677            | ObligationCauseCode::MethodReceiver
2678            | ObligationCauseCode::ReturnNoExpression
2679            | ObligationCauseCode::Misc
2680            | ObligationCauseCode::WellFormed(..)
2681            | ObligationCauseCode::MatchImpl(..)
2682            | ObligationCauseCode::ReturnValue(_)
2683            | ObligationCauseCode::BlockTailExpression(..)
2684            | ObligationCauseCode::AwaitableExpr(_)
2685            | ObligationCauseCode::ForLoopIterator
2686            | ObligationCauseCode::QuestionMark
2687            | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2688            | ObligationCauseCode::LetElse
2689            | ObligationCauseCode::BinOp { .. }
2690            | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2691            | ObligationCauseCode::AlwaysApplicableImpl
2692            | ObligationCauseCode::ConstParam(_)
2693            | ObligationCauseCode::ReferenceOutlivesReferent(..)
2694            | ObligationCauseCode::ObjectTypeBound(..) => {}
2695            ObligationCauseCode::RustCall => {
2696                if let Some(pred) = predicate.as_trait_clause()
2697                    && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
2698                {
2699                    err.note("argument required to be sized due to `extern \"rust-call\"` ABI");
2700                }
2701            }
2702            ObligationCauseCode::SliceOrArrayElem => {
2703                err.note("slice and array elements must have `Sized` type");
2704            }
2705            ObligationCauseCode::ArrayLen(array_ty) => {
2706                err.note(format!("the length of array `{array_ty}` must be type `usize`"));
2707            }
2708            ObligationCauseCode::TupleElem => {
2709                err.note("only the last element of a tuple may have a dynamically sized type");
2710            }
2711            ObligationCauseCode::WhereClause(item_def_id, span)
2712            | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)
2713            | ObligationCauseCode::HostEffectInExpr(item_def_id, span, ..)
2714                if !span.is_dummy() =>
2715            {
2716                if let ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, pos) = &cause_code {
2717                    if let Node::Expr(expr) = tcx.parent_hir_node(*hir_id)
2718                        && let hir::ExprKind::Call(_, args) = expr.kind
2719                        && let Some(expr) = args.get(*pos)
2720                    {
2721                        suggest_remove_deref(err, &expr);
2722                    } else if let Node::Expr(expr) = self.tcx.hir_node(*hir_id)
2723                        && let hir::ExprKind::MethodCall(_, _, args, _) = expr.kind
2724                        && let Some(expr) = args.get(*pos)
2725                    {
2726                        suggest_remove_deref(err, &expr);
2727                    }
2728                }
2729                let item_name = tcx.def_path_str(item_def_id);
2730                let short_item_name = with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
2731                let mut multispan = MultiSpan::from(span);
2732                let sm = tcx.sess.source_map();
2733                if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2734                    let same_line =
2735                        match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2736                            (Ok(l), Ok(r)) => l.line == r.line,
2737                            _ => true,
2738                        };
2739                    if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
2740                        multispan.push_span_label(
2741                            ident.span,
2742                            format!(
2743                                "required by a bound in this {}",
2744                                tcx.def_kind(item_def_id).descr(item_def_id)
2745                            ),
2746                        );
2747                    }
2748                }
2749                let mut a = "a";
2750                let mut this = "this bound";
2751                let mut note = None;
2752                let mut help = None;
2753                if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() {
2754                    match clause {
2755                        ty::ClauseKind::Trait(trait_pred) => {
2756                            let def_id = trait_pred.def_id();
2757                            let visible_item = if let Some(local) = def_id.as_local() {
2758                                // Check for local traits being reachable.
2759                                let vis = &tcx.resolutions(()).effective_visibilities;
2760                                // Account for non-`pub` traits in the root of the local crate.
2761                                let is_locally_reachable = tcx.parent(def_id).is_crate_root();
2762                                vis.is_reachable(local) || is_locally_reachable
2763                            } else {
2764                                // Check for foreign traits being reachable.
2765                                tcx.visible_parent_map(()).get(&def_id).is_some()
2766                            };
2767                            if tcx.is_lang_item(def_id, LangItem::Sized) {
2768                                // Check if this is an implicit bound, even in foreign crates.
2769                                if tcx
2770                                    .generics_of(item_def_id)
2771                                    .own_params
2772                                    .iter()
2773                                    .any(|param| tcx.def_span(param.def_id) == span)
2774                                {
2775                                    a = "an implicit `Sized`";
2776                                    this =
2777                                        "the implicit `Sized` requirement on this type parameter";
2778                                }
2779                                if let Some(hir::Node::TraitItem(hir::TraitItem {
2780                                    generics,
2781                                    kind: hir::TraitItemKind::Type(bounds, None),
2782                                    ..
2783                                })) = tcx.hir_get_if_local(item_def_id)
2784                                    // Do not suggest relaxing if there is an explicit `Sized` obligation.
2785                                    && !bounds.iter()
2786                                        .filter_map(|bound| bound.trait_ref())
2787                                        .any(|tr| tr.trait_def_id().is_some_and(|def_id| tcx.is_lang_item(def_id, LangItem::Sized)))
2788                                {
2789                                    let (span, separator) = if let [.., last] = bounds {
2790                                        (last.span().shrink_to_hi(), " +")
2791                                    } else {
2792                                        (generics.span.shrink_to_hi(), ":")
2793                                    };
2794                                    err.span_suggestion_verbose(
2795                                        span,
2796                                        "consider relaxing the implicit `Sized` restriction",
2797                                        format!("{separator} ?Sized"),
2798                                        Applicability::MachineApplicable,
2799                                    );
2800                                }
2801                            }
2802                            if let DefKind::Trait = tcx.def_kind(item_def_id)
2803                                && !visible_item
2804                            {
2805                                note = Some(format!(
2806                                    "`{short_item_name}` is a \"sealed trait\", because to implement it \
2807                                    you also need to implement `{}`, which is not accessible; this is \
2808                                    usually done to force you to use one of the provided types that \
2809                                    already implement it",
2810                                    with_no_trimmed_paths!(tcx.def_path_str(def_id)),
2811                                ));
2812                                let impls_of = tcx.trait_impls_of(def_id);
2813                                let impls = impls_of
2814                                    .non_blanket_impls()
2815                                    .values()
2816                                    .flatten()
2817                                    .chain(impls_of.blanket_impls().iter())
2818                                    .collect::<Vec<_>>();
2819                                if !impls.is_empty() {
2820                                    let len = impls.len();
2821                                    let mut types = impls
2822                                        .iter()
2823                                        .map(|t| {
2824                                            with_no_trimmed_paths!(format!(
2825                                                "  {}",
2826                                                tcx.type_of(*t).instantiate_identity(),
2827                                            ))
2828                                        })
2829                                        .collect::<Vec<_>>();
2830                                    let post = if types.len() > 9 {
2831                                        types.truncate(8);
2832                                        format!("\nand {} others", len - 8)
2833                                    } else {
2834                                        String::new()
2835                                    };
2836                                    help = Some(format!(
2837                                        "the following type{} implement{} the trait:\n{}{post}",
2838                                        pluralize!(len),
2839                                        if len == 1 { "s" } else { "" },
2840                                        types.join("\n"),
2841                                    ));
2842                                }
2843                            }
2844                        }
2845                        ty::ClauseKind::ConstArgHasType(..) => {
2846                            let descr =
2847                                format!("required by a const generic parameter in `{item_name}`");
2848                            if span.is_visible(sm) {
2849                                let msg = format!(
2850                                    "required by this const generic parameter in `{short_item_name}`"
2851                                );
2852                                multispan.push_span_label(span, msg);
2853                                err.span_note(multispan, descr);
2854                            } else {
2855                                err.span_note(tcx.def_span(item_def_id), descr);
2856                            }
2857                            return;
2858                        }
2859                        _ => (),
2860                    }
2861                }
2862                let descr = format!("required by {a} bound in `{item_name}`");
2863                if span.is_visible(sm) {
2864                    let msg = format!("required by {this} in `{short_item_name}`");
2865                    multispan.push_span_label(span, msg);
2866                    err.span_note(multispan, descr);
2867                } else {
2868                    err.span_note(tcx.def_span(item_def_id), descr);
2869                }
2870                if let Some(note) = note {
2871                    err.note(note);
2872                }
2873                if let Some(help) = help {
2874                    err.help(help);
2875                }
2876            }
2877            ObligationCauseCode::WhereClause(..)
2878            | ObligationCauseCode::WhereClauseInExpr(..)
2879            | ObligationCauseCode::HostEffectInExpr(..) => {
2880                // We hold the `DefId` of the item introducing the obligation, but displaying it
2881                // doesn't add user usable information. It always point at an associated item.
2882            }
2883            ObligationCauseCode::OpaqueTypeBound(span, definition_def_id) => {
2884                err.span_note(span, "required by a bound in an opaque type");
2885                if let Some(definition_def_id) = definition_def_id
2886                    // If there are any stalled coroutine obligations, then this
2887                    // error may be due to that, and not because the body has more
2888                    // where-clauses.
2889                    && self.tcx.typeck(definition_def_id).coroutine_stalled_predicates.is_empty()
2890                {
2891                    // FIXME(compiler-errors): We could probably point to something
2892                    // specific here if we tried hard enough...
2893                    err.span_note(
2894                        tcx.def_span(definition_def_id),
2895                        "this definition site has more where clauses than the opaque type",
2896                    );
2897                }
2898            }
2899            ObligationCauseCode::Coercion { source, target } => {
2900                let source =
2901                    tcx.short_string(self.resolve_vars_if_possible(source), err.long_ty_path());
2902                let target =
2903                    tcx.short_string(self.resolve_vars_if_possible(target), err.long_ty_path());
2904                err.note(with_forced_trimmed_paths!(format!(
2905                    "required for the cast from `{source}` to `{target}`",
2906                )));
2907            }
2908            ObligationCauseCode::RepeatElementCopy { is_constable, elt_span } => {
2909                err.note(
2910                    "the `Copy` trait is required because this value will be copied for each element of the array",
2911                );
2912                let sm = tcx.sess.source_map();
2913                if matches!(is_constable, IsConstable::Fn | IsConstable::Ctor)
2914                    && let Ok(snip) = sm.span_to_snippet(elt_span)
2915                {
2916                    err.span_suggestion(
2917                        elt_span,
2918                        "create an inline `const` block",
2919                        format!("const {{ {snip} }}"),
2920                        Applicability::MachineApplicable,
2921                    );
2922                } else {
2923                    // FIXME: we may suggest array::repeat instead
2924                    err.help("consider using `core::array::from_fn` to initialize the array");
2925                    err.help("see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html for more information");
2926                }
2927            }
2928            ObligationCauseCode::VariableType(hir_id) => {
2929                if let Some(typeck_results) = &self.typeck_results
2930                    && let Some(ty) = typeck_results.node_type_opt(hir_id)
2931                    && let ty::Error(_) = ty.kind()
2932                {
2933                    err.note(format!(
2934                        "`{predicate}` isn't satisfied, but the type of this pattern is \
2935                         `{{type error}}`",
2936                    ));
2937                    err.downgrade_to_delayed_bug();
2938                }
2939                let mut local = true;
2940                match tcx.parent_hir_node(hir_id) {
2941                    Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }) => {
2942                        err.span_suggestion_verbose(
2943                            ty.span.shrink_to_lo(),
2944                            "consider borrowing here",
2945                            "&",
2946                            Applicability::MachineApplicable,
2947                        );
2948                    }
2949                    Node::LetStmt(hir::LetStmt {
2950                        init: Some(hir::Expr { kind: hir::ExprKind::Index(..), span, .. }),
2951                        ..
2952                    }) => {
2953                        // When encountering an assignment of an unsized trait, like
2954                        // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2955                        // order to use have a slice instead.
2956                        err.span_suggestion_verbose(
2957                            span.shrink_to_lo(),
2958                            "consider borrowing here",
2959                            "&",
2960                            Applicability::MachineApplicable,
2961                        );
2962                    }
2963                    Node::LetStmt(hir::LetStmt { init: Some(expr), .. }) => {
2964                        // When encountering an assignment of an unsized trait, like `let x = *"";`,
2965                        // we check if the RHS is a deref operation, to suggest removing it.
2966                        suggest_remove_deref(err, &expr);
2967                    }
2968                    Node::Param(param) => {
2969                        err.span_suggestion_verbose(
2970                            param.ty_span.shrink_to_lo(),
2971                            "function arguments must have a statically known size, borrowed types \
2972                            always have a known size",
2973                            "&",
2974                            Applicability::MachineApplicable,
2975                        );
2976                        local = false;
2977                    }
2978                    _ => {}
2979                }
2980                if local {
2981                    err.note("all local variables must have a statically known size");
2982                }
2983                if !tcx.features().unsized_locals() {
2984                    err.help("unsized locals are gated as an unstable feature");
2985                }
2986            }
2987            ObligationCauseCode::SizedArgumentType(hir_id) => {
2988                let mut ty = None;
2989                let borrowed_msg = "function arguments must have a statically known size, borrowed \
2990                                    types always have a known size";
2991                if let Some(hir_id) = hir_id
2992                    && let hir::Node::Param(param) = self.tcx.hir_node(hir_id)
2993                    && let Some(decl) = self.tcx.parent_hir_node(hir_id).fn_decl()
2994                    && let Some(t) = decl.inputs.iter().find(|t| param.ty_span.contains(t.span))
2995                {
2996                    // We use `contains` because the type might be surrounded by parentheses,
2997                    // which makes `ty_span` and `t.span` disagree with each other, but one
2998                    // fully contains the other: `foo: (dyn Foo + Bar)`
2999                    //                                 ^-------------^
3000                    //                                 ||
3001                    //                                 |t.span
3002                    //                                 param._ty_span
3003                    ty = Some(t);
3004                } else if let Some(hir_id) = hir_id
3005                    && let hir::Node::Ty(t) = self.tcx.hir_node(hir_id)
3006                {
3007                    ty = Some(t);
3008                }
3009                if let Some(ty) = ty {
3010                    match ty.kind {
3011                        hir::TyKind::TraitObject(traits, _) => {
3012                            let (span, kw) = match traits {
3013                                [first, ..] if first.span.lo() == ty.span.lo() => {
3014                                    // Missing `dyn` in front of trait object.
3015                                    (ty.span.shrink_to_lo(), "dyn ")
3016                                }
3017                                [first, ..] => (ty.span.until(first.span), ""),
3018                                [] => span_bug!(ty.span, "trait object with no traits: {ty:?}"),
3019                            };
3020                            let needs_parens = traits.len() != 1;
3021                            err.span_suggestion_verbose(
3022                                span,
3023                                "you can use `impl Trait` as the argument type",
3024                                "impl ",
3025                                Applicability::MaybeIncorrect,
3026                            );
3027                            let sugg = if !needs_parens {
3028                                vec![(span.shrink_to_lo(), format!("&{kw}"))]
3029                            } else {
3030                                vec![
3031                                    (span.shrink_to_lo(), format!("&({kw}")),
3032                                    (ty.span.shrink_to_hi(), ")".to_string()),
3033                                ]
3034                            };
3035                            err.multipart_suggestion_verbose(
3036                                borrowed_msg,
3037                                sugg,
3038                                Applicability::MachineApplicable,
3039                            );
3040                        }
3041                        hir::TyKind::Slice(_ty) => {
3042                            err.span_suggestion_verbose(
3043                                ty.span.shrink_to_lo(),
3044                                "function arguments must have a statically known size, borrowed \
3045                                 slices always have a known size",
3046                                "&",
3047                                Applicability::MachineApplicable,
3048                            );
3049                        }
3050                        hir::TyKind::Path(_) => {
3051                            err.span_suggestion_verbose(
3052                                ty.span.shrink_to_lo(),
3053                                borrowed_msg,
3054                                "&",
3055                                Applicability::MachineApplicable,
3056                            );
3057                        }
3058                        _ => {}
3059                    }
3060                } else {
3061                    err.note("all function arguments must have a statically known size");
3062                }
3063                if tcx.sess.opts.unstable_features.is_nightly_build()
3064                    && !tcx.features().unsized_fn_params()
3065                {
3066                    err.help("unsized fn params are gated as an unstable feature");
3067                }
3068            }
3069            ObligationCauseCode::SizedReturnType | ObligationCauseCode::SizedCallReturnType => {
3070                err.note("the return type of a function must have a statically known size");
3071            }
3072            ObligationCauseCode::SizedYieldType => {
3073                err.note("the yield type of a coroutine must have a statically known size");
3074            }
3075            ObligationCauseCode::AssignmentLhsSized => {
3076                err.note("the left-hand-side of an assignment must have a statically known size");
3077            }
3078            ObligationCauseCode::TupleInitializerSized => {
3079                err.note("tuples must have a statically known size to be initialized");
3080            }
3081            ObligationCauseCode::StructInitializerSized => {
3082                err.note("structs must have a statically known size to be initialized");
3083            }
3084            ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
3085                match *item {
3086                    AdtKind::Struct => {
3087                        if last {
3088                            err.note(
3089                                "the last field of a packed struct may only have a \
3090                                dynamically sized type if it does not need drop to be run",
3091                            );
3092                        } else {
3093                            err.note(
3094                                "only the last field of a struct may have a dynamically sized type",
3095                            );
3096                        }
3097                    }
3098                    AdtKind::Union => {
3099                        err.note("no field of a union may have a dynamically sized type");
3100                    }
3101                    AdtKind::Enum => {
3102                        err.note("no field of an enum variant may have a dynamically sized type");
3103                    }
3104                }
3105                err.help("change the field's type to have a statically known size");
3106                err.span_suggestion(
3107                    span.shrink_to_lo(),
3108                    "borrowed types always have a statically known size",
3109                    "&",
3110                    Applicability::MachineApplicable,
3111                );
3112                err.multipart_suggestion(
3113                    "the `Box` type always has a statically known size and allocates its contents \
3114                     in the heap",
3115                    vec![
3116                        (span.shrink_to_lo(), "Box<".to_string()),
3117                        (span.shrink_to_hi(), ">".to_string()),
3118                    ],
3119                    Applicability::MachineApplicable,
3120                );
3121            }
3122            ObligationCauseCode::SizedConstOrStatic => {
3123                err.note("statics and constants must have a statically known size");
3124            }
3125            ObligationCauseCode::InlineAsmSized => {
3126                err.note("all inline asm arguments must have a statically known size");
3127            }
3128            ObligationCauseCode::SizedClosureCapture(closure_def_id) => {
3129                err.note(
3130                    "all values captured by value by a closure must have a statically known size",
3131                );
3132                let hir::ExprKind::Closure(closure) =
3133                    tcx.hir_node_by_def_id(closure_def_id).expect_expr().kind
3134                else {
3135                    bug!("expected closure in SizedClosureCapture obligation");
3136                };
3137                if let hir::CaptureBy::Value { .. } = closure.capture_clause
3138                    && let Some(span) = closure.fn_arg_span
3139                {
3140                    err.span_label(span, "this closure captures all values by move");
3141                }
3142            }
3143            ObligationCauseCode::SizedCoroutineInterior(coroutine_def_id) => {
3144                let what = match tcx.coroutine_kind(coroutine_def_id) {
3145                    None
3146                    | Some(hir::CoroutineKind::Coroutine(_))
3147                    | Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)) => {
3148                        "yield"
3149                    }
3150                    Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
3151                        "await"
3152                    }
3153                    Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => {
3154                        "yield`/`await"
3155                    }
3156                };
3157                err.note(format!(
3158                    "all values live across `{what}` must have a statically known size"
3159                ));
3160            }
3161            ObligationCauseCode::SharedStatic => {
3162                err.note("shared static variables must have a type that implements `Sync`");
3163            }
3164            ObligationCauseCode::BuiltinDerived(ref data) => {
3165                let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3166                let ty = parent_trait_ref.skip_binder().self_ty();
3167                if parent_trait_ref.references_error() {
3168                    // NOTE(eddyb) this was `.cancel()`, but `err`
3169                    // is borrowed, so we can't fully defuse it.
3170                    err.downgrade_to_delayed_bug();
3171                    return;
3172                }
3173
3174                // If the obligation for a tuple is set directly by a Coroutine or Closure,
3175                // then the tuple must be the one containing capture types.
3176                let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
3177                    false
3178                } else if let ObligationCauseCode::BuiltinDerived(data) = &*data.parent_code {
3179                    let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3180                    let nested_ty = parent_trait_ref.skip_binder().self_ty();
3181                    matches!(nested_ty.kind(), ty::Coroutine(..))
3182                        || matches!(nested_ty.kind(), ty::Closure(..))
3183                } else {
3184                    false
3185                };
3186
3187                let is_builtin_async_fn_trait =
3188                    tcx.async_fn_trait_kind_from_def_id(data.parent_trait_pred.def_id()).is_some();
3189
3190                if !is_upvar_tys_infer_tuple && !is_builtin_async_fn_trait {
3191                    let ty_str = tcx.short_string(ty, err.long_ty_path());
3192                    let msg = format!("required because it appears within the type `{ty_str}`");
3193                    match ty.kind() {
3194                        ty::Adt(def, _) => match tcx.opt_item_ident(def.did()) {
3195                            Some(ident) => {
3196                                err.span_note(ident.span, msg);
3197                            }
3198                            None => {
3199                                err.note(msg);
3200                            }
3201                        },
3202                        ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
3203                            // If the previous type is async fn, this is the future generated by the body of an async function.
3204                            // Avoid printing it twice (it was already printed in the `ty::Coroutine` arm below).
3205                            let is_future = tcx.ty_is_opaque_future(ty);
3206                            debug!(
3207                                ?obligated_types,
3208                                ?is_future,
3209                                "note_obligation_cause_code: check for async fn"
3210                            );
3211                            if is_future
3212                                && obligated_types.last().is_some_and(|ty| match ty.kind() {
3213                                    ty::Coroutine(last_def_id, ..) => {
3214                                        tcx.coroutine_is_async(*last_def_id)
3215                                    }
3216                                    _ => false,
3217                                })
3218                            {
3219                                // See comment above; skip printing twice.
3220                            } else {
3221                                err.span_note(tcx.def_span(def_id), msg);
3222                            }
3223                        }
3224                        ty::Coroutine(def_id, _) => {
3225                            let sp = tcx.def_span(def_id);
3226
3227                            // Special-case this to say "async block" instead of `[static coroutine]`.
3228                            let kind = tcx.coroutine_kind(def_id).unwrap();
3229                            err.span_note(
3230                                sp,
3231                                with_forced_trimmed_paths!(format!(
3232                                    "required because it's used within this {kind:#}",
3233                                )),
3234                            );
3235                        }
3236                        ty::CoroutineWitness(..) => {
3237                            // Skip printing coroutine-witnesses, since we'll drill into
3238                            // the bad field in another derived obligation cause.
3239                        }
3240                        ty::Closure(def_id, _) | ty::CoroutineClosure(def_id, _) => {
3241                            err.span_note(
3242                                tcx.def_span(def_id),
3243                                "required because it's used within this closure",
3244                            );
3245                        }
3246                        ty::Str => {
3247                            err.note("`str` is considered to contain a `[u8]` slice for auto trait purposes");
3248                        }
3249                        _ => {
3250                            err.note(msg);
3251                        }
3252                    };
3253                }
3254
3255                obligated_types.push(ty);
3256
3257                let parent_predicate = parent_trait_ref;
3258                if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
3259                    // #74711: avoid a stack overflow
3260                    ensure_sufficient_stack(|| {
3261                        self.note_obligation_cause_code(
3262                            body_id,
3263                            err,
3264                            parent_predicate,
3265                            param_env,
3266                            &data.parent_code,
3267                            obligated_types,
3268                            seen_requirements,
3269                        )
3270                    });
3271                } else {
3272                    ensure_sufficient_stack(|| {
3273                        self.note_obligation_cause_code(
3274                            body_id,
3275                            err,
3276                            parent_predicate,
3277                            param_env,
3278                            cause_code.peel_derives(),
3279                            obligated_types,
3280                            seen_requirements,
3281                        )
3282                    });
3283                }
3284            }
3285            ObligationCauseCode::ImplDerived(ref data) => {
3286                let mut parent_trait_pred =
3287                    self.resolve_vars_if_possible(data.derived.parent_trait_pred);
3288                let parent_def_id = parent_trait_pred.def_id();
3289                if tcx.is_diagnostic_item(sym::FromResidual, parent_def_id)
3290                    && !tcx.features().enabled(sym::try_trait_v2)
3291                {
3292                    // If `#![feature(try_trait_v2)]` is not enabled, then there's no point on
3293                    // talking about `FromResidual<Result<A, B>>`, as the end user has nothing they
3294                    // can do about it. As far as they are concerned, `?` is compiler magic.
3295                    return;
3296                }
3297                let self_ty_str =
3298                    tcx.short_string(parent_trait_pred.skip_binder().self_ty(), err.long_ty_path());
3299                let trait_name = parent_trait_pred.print_modifiers_and_trait_path().to_string();
3300                let msg = format!("required for `{self_ty_str}` to implement `{trait_name}`");
3301                let mut is_auto_trait = false;
3302                match tcx.hir_get_if_local(data.impl_or_alias_def_id) {
3303                    Some(Node::Item(hir::Item {
3304                        kind: hir::ItemKind::Trait(is_auto, _, ident, ..),
3305                        ..
3306                    })) => {
3307                        // FIXME: we should do something else so that it works even on crate foreign
3308                        // auto traits.
3309                        is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
3310                        err.span_note(ident.span, msg);
3311                    }
3312                    Some(Node::Item(hir::Item {
3313                        kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, generics, .. }),
3314                        ..
3315                    })) => {
3316                        let mut spans = Vec::with_capacity(2);
3317                        if let Some(trait_ref) = of_trait {
3318                            spans.push(trait_ref.path.span);
3319                        }
3320                        spans.push(self_ty.span);
3321                        let mut spans: MultiSpan = spans.into();
3322                        if matches!(
3323                            self_ty.span.ctxt().outer_expn_data().kind,
3324                            ExpnKind::Macro(MacroKind::Derive, _)
3325                        ) || matches!(
3326                            of_trait.as_ref().map(|t| t.path.span.ctxt().outer_expn_data().kind),
3327                            Some(ExpnKind::Macro(MacroKind::Derive, _))
3328                        ) {
3329                            spans.push_span_label(
3330                                data.span,
3331                                "unsatisfied trait bound introduced in this `derive` macro",
3332                            );
3333                        } else if !data.span.is_dummy() && !data.span.overlaps(self_ty.span) {
3334                            spans.push_span_label(
3335                                data.span,
3336                                "unsatisfied trait bound introduced here",
3337                            );
3338                        }
3339                        err.span_note(spans, msg);
3340                        point_at_assoc_type_restriction(
3341                            tcx,
3342                            err,
3343                            &self_ty_str,
3344                            &trait_name,
3345                            predicate,
3346                            &generics,
3347                            &data,
3348                        );
3349                    }
3350                    _ => {
3351                        err.note(msg);
3352                    }
3353                };
3354
3355                let mut parent_predicate = parent_trait_pred;
3356                let mut data = &data.derived;
3357                let mut count = 0;
3358                seen_requirements.insert(parent_def_id);
3359                if is_auto_trait {
3360                    // We don't want to point at the ADT saying "required because it appears within
3361                    // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
3362                    while let ObligationCauseCode::BuiltinDerived(derived) = &*data.parent_code {
3363                        let child_trait_ref =
3364                            self.resolve_vars_if_possible(derived.parent_trait_pred);
3365                        let child_def_id = child_trait_ref.def_id();
3366                        if seen_requirements.insert(child_def_id) {
3367                            break;
3368                        }
3369                        data = derived;
3370                        parent_predicate = child_trait_ref.upcast(tcx);
3371                        parent_trait_pred = child_trait_ref;
3372                    }
3373                }
3374                while let ObligationCauseCode::ImplDerived(child) = &*data.parent_code {
3375                    // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
3376                    let child_trait_pred =
3377                        self.resolve_vars_if_possible(child.derived.parent_trait_pred);
3378                    let child_def_id = child_trait_pred.def_id();
3379                    if seen_requirements.insert(child_def_id) {
3380                        break;
3381                    }
3382                    count += 1;
3383                    data = &child.derived;
3384                    parent_predicate = child_trait_pred.upcast(tcx);
3385                    parent_trait_pred = child_trait_pred;
3386                }
3387                if count > 0 {
3388                    err.note(format!(
3389                        "{} redundant requirement{} hidden",
3390                        count,
3391                        pluralize!(count)
3392                    ));
3393                    let self_ty = tcx.short_string(
3394                        parent_trait_pred.skip_binder().self_ty(),
3395                        err.long_ty_path(),
3396                    );
3397                    err.note(format!(
3398                        "required for `{self_ty}` to implement `{}`",
3399                        parent_trait_pred.print_modifiers_and_trait_path()
3400                    ));
3401                }
3402                // #74711: avoid a stack overflow
3403                ensure_sufficient_stack(|| {
3404                    self.note_obligation_cause_code(
3405                        body_id,
3406                        err,
3407                        parent_predicate,
3408                        param_env,
3409                        &data.parent_code,
3410                        obligated_types,
3411                        seen_requirements,
3412                    )
3413                });
3414            }
3415            ObligationCauseCode::ImplDerivedHost(ref data) => {
3416                let self_ty =
3417                    self.resolve_vars_if_possible(data.derived.parent_host_pred.self_ty());
3418                let msg = format!(
3419                    "required for `{self_ty}` to implement `{} {}`",
3420                    data.derived.parent_host_pred.skip_binder().constness,
3421                    data.derived
3422                        .parent_host_pred
3423                        .map_bound(|pred| pred.trait_ref)
3424                        .print_only_trait_path(),
3425                );
3426                match tcx.hir_get_if_local(data.impl_def_id) {
3427                    Some(Node::Item(hir::Item {
3428                        kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
3429                        ..
3430                    })) => {
3431                        let mut spans = vec![self_ty.span];
3432                        spans.extend(of_trait.as_ref().map(|t| t.path.span));
3433                        let mut spans: MultiSpan = spans.into();
3434                        spans.push_span_label(data.span, "unsatisfied trait bound introduced here");
3435                        err.span_note(spans, msg);
3436                    }
3437                    _ => {
3438                        err.note(msg);
3439                    }
3440                }
3441                ensure_sufficient_stack(|| {
3442                    self.note_obligation_cause_code(
3443                        body_id,
3444                        err,
3445                        data.derived.parent_host_pred,
3446                        param_env,
3447                        &data.derived.parent_code,
3448                        obligated_types,
3449                        seen_requirements,
3450                    )
3451                });
3452            }
3453            ObligationCauseCode::BuiltinDerivedHost(ref data) => {
3454                ensure_sufficient_stack(|| {
3455                    self.note_obligation_cause_code(
3456                        body_id,
3457                        err,
3458                        data.parent_host_pred,
3459                        param_env,
3460                        &data.parent_code,
3461                        obligated_types,
3462                        seen_requirements,
3463                    )
3464                });
3465            }
3466            ObligationCauseCode::WellFormedDerived(ref data) => {
3467                let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3468                let parent_predicate = parent_trait_ref;
3469                // #74711: avoid a stack overflow
3470                ensure_sufficient_stack(|| {
3471                    self.note_obligation_cause_code(
3472                        body_id,
3473                        err,
3474                        parent_predicate,
3475                        param_env,
3476                        &data.parent_code,
3477                        obligated_types,
3478                        seen_requirements,
3479                    )
3480                });
3481            }
3482            ObligationCauseCode::TypeAlias(ref nested, span, def_id) => {
3483                // #74711: avoid a stack overflow
3484                ensure_sufficient_stack(|| {
3485                    self.note_obligation_cause_code(
3486                        body_id,
3487                        err,
3488                        predicate,
3489                        param_env,
3490                        nested,
3491                        obligated_types,
3492                        seen_requirements,
3493                    )
3494                });
3495                let mut multispan = MultiSpan::from(span);
3496                multispan.push_span_label(span, "required by this bound");
3497                err.span_note(
3498                    multispan,
3499                    format!("required by a bound on the type alias `{}`", tcx.item_name(def_id)),
3500                );
3501            }
3502            ObligationCauseCode::FunctionArg {
3503                arg_hir_id, call_hir_id, ref parent_code, ..
3504            } => {
3505                self.note_function_argument_obligation(
3506                    body_id,
3507                    err,
3508                    arg_hir_id,
3509                    parent_code,
3510                    param_env,
3511                    predicate,
3512                    call_hir_id,
3513                );
3514                ensure_sufficient_stack(|| {
3515                    self.note_obligation_cause_code(
3516                        body_id,
3517                        err,
3518                        predicate,
3519                        param_env,
3520                        parent_code,
3521                        obligated_types,
3522                        seen_requirements,
3523                    )
3524                });
3525            }
3526            // Suppress `compare_type_predicate_entailment` errors for RPITITs, since they
3527            // should be implied by the parent method.
3528            ObligationCauseCode::CompareImplItem { trait_item_def_id, .. }
3529                if tcx.is_impl_trait_in_trait(trait_item_def_id) => {}
3530            ObligationCauseCode::CompareImplItem { trait_item_def_id, kind, .. } => {
3531                let item_name = tcx.item_name(trait_item_def_id);
3532                let msg = format!(
3533                    "the requirement `{predicate}` appears on the `impl`'s {kind} \
3534                     `{item_name}` but not on the corresponding trait's {kind}",
3535                );
3536                let sp = tcx
3537                    .opt_item_ident(trait_item_def_id)
3538                    .map(|i| i.span)
3539                    .unwrap_or_else(|| tcx.def_span(trait_item_def_id));
3540                let mut assoc_span: MultiSpan = sp.into();
3541                assoc_span.push_span_label(
3542                    sp,
3543                    format!("this trait's {kind} doesn't have the requirement `{predicate}`"),
3544                );
3545                if let Some(ident) = tcx
3546                    .opt_associated_item(trait_item_def_id)
3547                    .and_then(|i| tcx.opt_item_ident(i.container_id(tcx)))
3548                {
3549                    assoc_span.push_span_label(ident.span, "in this trait");
3550                }
3551                err.span_note(assoc_span, msg);
3552            }
3553            ObligationCauseCode::TrivialBound => {
3554                err.help("see issue #48214");
3555                tcx.disabled_nightly_features(
3556                    err,
3557                    Some(tcx.local_def_id_to_hir_id(body_id)),
3558                    [(String::new(), sym::trivial_bounds)],
3559                );
3560            }
3561            ObligationCauseCode::OpaqueReturnType(expr_info) => {
3562                let (expr_ty, expr) = if let Some((expr_ty, hir_id)) = expr_info {
3563                    let expr_ty = tcx.short_string(expr_ty, err.long_ty_path());
3564                    let expr = tcx.hir_expect_expr(hir_id);
3565                    (expr_ty, expr)
3566                } else if let Some(body_id) = tcx.hir_node_by_def_id(body_id).body_id()
3567                    && let body = tcx.hir_body(body_id)
3568                    && let hir::ExprKind::Block(block, _) = body.value.kind
3569                    && let Some(expr) = block.expr
3570                    && let Some(expr_ty) = self
3571                        .typeck_results
3572                        .as_ref()
3573                        .and_then(|typeck| typeck.node_type_opt(expr.hir_id))
3574                    && let Some(pred) = predicate.as_clause()
3575                    && let ty::ClauseKind::Trait(pred) = pred.kind().skip_binder()
3576                    && self.can_eq(param_env, pred.self_ty(), expr_ty)
3577                {
3578                    let expr_ty = tcx.short_string(expr_ty, err.long_ty_path());
3579                    (expr_ty, expr)
3580                } else {
3581                    return;
3582                };
3583                err.span_label(
3584                    expr.span,
3585                    with_forced_trimmed_paths!(format!(
3586                        "return type was inferred to be `{expr_ty}` here",
3587                    )),
3588                );
3589                suggest_remove_deref(err, &expr);
3590            }
3591        }
3592    }
3593
3594    #[instrument(
3595        level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
3596    )]
3597    pub(super) fn suggest_await_before_try(
3598        &self,
3599        err: &mut Diag<'_>,
3600        obligation: &PredicateObligation<'tcx>,
3601        trait_pred: ty::PolyTraitPredicate<'tcx>,
3602        span: Span,
3603    ) {
3604        let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
3605
3606        let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
3607        let impls_future = self.type_implements_trait(
3608            future_trait,
3609            [self.tcx.instantiate_bound_regions_with_erased(self_ty)],
3610            obligation.param_env,
3611        );
3612        if !impls_future.must_apply_modulo_regions() {
3613            return;
3614        }
3615
3616        let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
3617        // `<T as Future>::Output`
3618        let projection_ty = trait_pred.map_bound(|trait_pred| {
3619            Ty::new_projection(
3620                self.tcx,
3621                item_def_id,
3622                // Future::Output has no args
3623                [trait_pred.self_ty()],
3624            )
3625        });
3626        let InferOk { value: projection_ty, .. } =
3627            self.at(&obligation.cause, obligation.param_env).normalize(projection_ty);
3628
3629        debug!(
3630            normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
3631        );
3632        let try_obligation = self.mk_trait_obligation_with_new_self_ty(
3633            obligation.param_env,
3634            trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
3635        );
3636        debug!(try_trait_obligation = ?try_obligation);
3637        if self.predicate_may_hold(&try_obligation)
3638            && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
3639            && snippet.ends_with('?')
3640        {
3641            match self.tcx.coroutine_kind(obligation.cause.body_id) {
3642                Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
3643                    err.span_suggestion_verbose(
3644                        span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
3645                        "consider `await`ing on the `Future`",
3646                        ".await",
3647                        Applicability::MaybeIncorrect,
3648                    );
3649                }
3650                _ => {
3651                    let mut span: MultiSpan = span.with_lo(span.hi() - BytePos(1)).into();
3652                    span.push_span_label(
3653                        self.tcx.def_span(obligation.cause.body_id),
3654                        "this is not `async`",
3655                    );
3656                    err.span_note(
3657                        span,
3658                        "this implements `Future` and its output type supports \
3659                        `?`, but the future cannot be awaited in a synchronous function",
3660                    );
3661                }
3662            }
3663        }
3664    }
3665
3666    pub(super) fn suggest_floating_point_literal(
3667        &self,
3668        obligation: &PredicateObligation<'tcx>,
3669        err: &mut Diag<'_>,
3670        trait_pred: ty::PolyTraitPredicate<'tcx>,
3671    ) {
3672        let rhs_span = match obligation.cause.code() {
3673            ObligationCauseCode::BinOp { rhs_span: Some(span), rhs_is_lit, .. } if *rhs_is_lit => {
3674                span
3675            }
3676            _ => return,
3677        };
3678        if let ty::Float(_) = trait_pred.skip_binder().self_ty().kind()
3679            && let ty::Infer(InferTy::IntVar(_)) =
3680                trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
3681        {
3682            err.span_suggestion_verbose(
3683                rhs_span.shrink_to_hi(),
3684                "consider using a floating-point literal by writing it with `.0`",
3685                ".0",
3686                Applicability::MaybeIncorrect,
3687            );
3688        }
3689    }
3690
3691    pub fn suggest_derive(
3692        &self,
3693        obligation: &PredicateObligation<'tcx>,
3694        err: &mut Diag<'_>,
3695        trait_pred: ty::PolyTraitPredicate<'tcx>,
3696    ) {
3697        if trait_pred.polarity() == ty::PredicatePolarity::Negative {
3698            return;
3699        }
3700        let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3701            return;
3702        };
3703        let (adt, args) = match trait_pred.skip_binder().self_ty().kind() {
3704            ty::Adt(adt, args) if adt.did().is_local() => (adt, args),
3705            _ => return,
3706        };
3707        let can_derive = {
3708            let is_derivable_trait = match diagnostic_name {
3709                sym::Default => !adt.is_enum(),
3710                sym::PartialEq | sym::PartialOrd => {
3711                    let rhs_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
3712                    trait_pred.skip_binder().self_ty() == rhs_ty
3713                }
3714                sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3715                _ => false,
3716            };
3717            is_derivable_trait &&
3718                // Ensure all fields impl the trait.
3719                adt.all_fields().all(|field| {
3720                    let field_ty = ty::GenericArg::from(field.ty(self.tcx, args));
3721                    let trait_args = match diagnostic_name {
3722                        sym::PartialEq | sym::PartialOrd => {
3723                            Some(field_ty)
3724                        }
3725                        _ => None,
3726                    };
3727                    let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3728                        trait_ref: ty::TraitRef::new(self.tcx,
3729                            trait_pred.def_id(),
3730                            [field_ty].into_iter().chain(trait_args),
3731                        ),
3732                        ..*tr
3733                    });
3734                    let field_obl = Obligation::new(
3735                        self.tcx,
3736                        obligation.cause.clone(),
3737                        obligation.param_env,
3738                        trait_pred,
3739                    );
3740                    self.predicate_must_hold_modulo_regions(&field_obl)
3741                })
3742        };
3743        if can_derive {
3744            err.span_suggestion_verbose(
3745                self.tcx.def_span(adt.did()).shrink_to_lo(),
3746                format!(
3747                    "consider annotating `{}` with `#[derive({})]`",
3748                    trait_pred.skip_binder().self_ty(),
3749                    diagnostic_name,
3750                ),
3751                // FIXME(const_trait_impl) derive_const as suggestion?
3752                format!("#[derive({diagnostic_name})]\n"),
3753                Applicability::MaybeIncorrect,
3754            );
3755        }
3756    }
3757
3758    pub(super) fn suggest_dereferencing_index(
3759        &self,
3760        obligation: &PredicateObligation<'tcx>,
3761        err: &mut Diag<'_>,
3762        trait_pred: ty::PolyTraitPredicate<'tcx>,
3763    ) {
3764        if let ObligationCauseCode::ImplDerived(_) = obligation.cause.code()
3765            && self
3766                .tcx
3767                .is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3768            && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
3769            && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3770            && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3771        {
3772            err.span_suggestion_verbose(
3773                obligation.cause.span.shrink_to_lo(),
3774                "dereference this index",
3775                '*',
3776                Applicability::MachineApplicable,
3777            );
3778        }
3779    }
3780
3781    fn note_function_argument_obligation<G: EmissionGuarantee>(
3782        &self,
3783        body_id: LocalDefId,
3784        err: &mut Diag<'_, G>,
3785        arg_hir_id: HirId,
3786        parent_code: &ObligationCauseCode<'tcx>,
3787        param_env: ty::ParamEnv<'tcx>,
3788        failed_pred: ty::Predicate<'tcx>,
3789        call_hir_id: HirId,
3790    ) {
3791        let tcx = self.tcx;
3792        if let Node::Expr(expr) = tcx.hir_node(arg_hir_id)
3793            && let Some(typeck_results) = &self.typeck_results
3794        {
3795            if let hir::Expr { kind: hir::ExprKind::MethodCall(_, rcvr, _, _), .. } = expr
3796                && let Some(ty) = typeck_results.node_type_opt(rcvr.hir_id)
3797                && let Some(failed_pred) = failed_pred.as_trait_clause()
3798                && let pred = failed_pred.map_bound(|pred| pred.with_self_ty(tcx, ty))
3799                && self.predicate_must_hold_modulo_regions(&Obligation::misc(
3800                    tcx, expr.span, body_id, param_env, pred,
3801                ))
3802                && expr.span.hi() != rcvr.span.hi()
3803            {
3804                err.span_suggestion_verbose(
3805                    expr.span.with_lo(rcvr.span.hi()),
3806                    format!(
3807                        "consider removing this method call, as the receiver has type `{ty}` and \
3808                         `{pred}` trivially holds",
3809                    ),
3810                    "",
3811                    Applicability::MaybeIncorrect,
3812                );
3813            }
3814            if let hir::Expr { kind: hir::ExprKind::Block(block, _), .. } = expr {
3815                let inner_expr = expr.peel_blocks();
3816                let ty = typeck_results
3817                    .expr_ty_adjusted_opt(inner_expr)
3818                    .unwrap_or(Ty::new_misc_error(tcx));
3819                let span = inner_expr.span;
3820                if Some(span) != err.span.primary_span() {
3821                    err.span_label(
3822                        span,
3823                        if ty.references_error() {
3824                            String::new()
3825                        } else {
3826                            let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3827                            format!("this tail expression is of type `{ty}`")
3828                        },
3829                    );
3830                    if let ty::PredicateKind::Clause(clause) = failed_pred.kind().skip_binder()
3831                        && let ty::ClauseKind::Trait(pred) = clause
3832                        && [
3833                            tcx.lang_items().fn_once_trait(),
3834                            tcx.lang_items().fn_mut_trait(),
3835                            tcx.lang_items().fn_trait(),
3836                        ]
3837                        .contains(&Some(pred.def_id()))
3838                    {
3839                        if let [stmt, ..] = block.stmts
3840                            && let hir::StmtKind::Semi(value) = stmt.kind
3841                            && let hir::ExprKind::Closure(hir::Closure {
3842                                body, fn_decl_span, ..
3843                            }) = value.kind
3844                            && let body = tcx.hir_body(*body)
3845                            && !matches!(body.value.kind, hir::ExprKind::Block(..))
3846                        {
3847                            // Check if the failed predicate was an expectation of a closure type
3848                            // and if there might have been a `{ |args|` typo instead of `|args| {`.
3849                            err.multipart_suggestion(
3850                                "you might have meant to open the closure body instead of placing \
3851                                 a closure within a block",
3852                                vec![
3853                                    (expr.span.with_hi(value.span.lo()), String::new()),
3854                                    (fn_decl_span.shrink_to_hi(), " {".to_string()),
3855                                ],
3856                                Applicability::MaybeIncorrect,
3857                            );
3858                        } else {
3859                            // Maybe the bare block was meant to be a closure.
3860                            err.span_suggestion_verbose(
3861                                expr.span.shrink_to_lo(),
3862                                "you might have meant to create the closure instead of a block",
3863                                format!(
3864                                    "|{}| ",
3865                                    (0..pred.trait_ref.args.len() - 1)
3866                                        .map(|_| "_")
3867                                        .collect::<Vec<_>>()
3868                                        .join(", ")
3869                                ),
3870                                Applicability::MaybeIncorrect,
3871                            );
3872                        }
3873                    }
3874                }
3875            }
3876
3877            // FIXME: visit the ty to see if there's any closure involved, and if there is,
3878            // check whether its evaluated return type is the same as the one corresponding
3879            // to an associated type (as seen from `trait_pred`) in the predicate. Like in
3880            // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
3881            let mut type_diffs = vec![];
3882            if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = parent_code
3883                && let Some(node_args) = typeck_results.node_args_opt(call_hir_id)
3884                && let where_clauses =
3885                    self.tcx.predicates_of(def_id).instantiate(self.tcx, node_args)
3886                && let Some(where_pred) = where_clauses.predicates.get(*idx)
3887            {
3888                if let Some(where_pred) = where_pred.as_trait_clause()
3889                    && let Some(failed_pred) = failed_pred.as_trait_clause()
3890                    && where_pred.def_id() == failed_pred.def_id()
3891                {
3892                    self.enter_forall(where_pred, |where_pred| {
3893                        let failed_pred = self.instantiate_binder_with_fresh_vars(
3894                            expr.span,
3895                            BoundRegionConversionTime::FnCall,
3896                            failed_pred,
3897                        );
3898
3899                        let zipped =
3900                            iter::zip(where_pred.trait_ref.args, failed_pred.trait_ref.args);
3901                        for (expected, actual) in zipped {
3902                            self.probe(|_| {
3903                                match self
3904                                    .at(&ObligationCause::misc(expr.span, body_id), param_env)
3905                                    // Doesn't actually matter if we define opaque types here, this is just used for
3906                                    // diagnostics, and the result is never kept around.
3907                                    .eq(DefineOpaqueTypes::Yes, expected, actual)
3908                                {
3909                                    Ok(_) => (), // We ignore nested obligations here for now.
3910                                    Err(err) => type_diffs.push(err),
3911                                }
3912                            })
3913                        }
3914                    })
3915                } else if let Some(where_pred) = where_pred.as_projection_clause()
3916                    && let Some(failed_pred) = failed_pred.as_projection_clause()
3917                    && let Some(found) = failed_pred.skip_binder().term.as_type()
3918                {
3919                    type_diffs = vec![TypeError::Sorts(ty::error::ExpectedFound {
3920                        expected: where_pred
3921                            .skip_binder()
3922                            .projection_term
3923                            .expect_ty(self.tcx)
3924                            .to_ty(self.tcx),
3925                        found,
3926                    })];
3927                }
3928            }
3929            if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3930                && let hir::Path { res: Res::Local(hir_id), .. } = path
3931                && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
3932                && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(binding.hir_id)
3933                && let Some(binding_expr) = local.init
3934            {
3935                // If the expression we're calling on is a binding, we want to point at the
3936                // `let` when talking about the type. Otherwise we'll point at every part
3937                // of the method chain with the type.
3938                self.point_at_chain(binding_expr, typeck_results, type_diffs, param_env, err);
3939            } else {
3940                self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
3941            }
3942        }
3943        let call_node = tcx.hir_node(call_hir_id);
3944        if let Node::Expr(hir::Expr { kind: hir::ExprKind::MethodCall(path, rcvr, ..), .. }) =
3945            call_node
3946        {
3947            if Some(rcvr.span) == err.span.primary_span() {
3948                err.replace_span_with(path.ident.span, true);
3949            }
3950        }
3951
3952        if let Node::Expr(expr) = call_node {
3953            if let hir::ExprKind::Call(hir::Expr { span, .. }, _)
3954            | hir::ExprKind::MethodCall(
3955                hir::PathSegment { ident: Ident { span, .. }, .. },
3956                ..,
3957            ) = expr.kind
3958            {
3959                if Some(*span) != err.span.primary_span() {
3960                    err.span_label(*span, "required by a bound introduced by this call");
3961                }
3962            }
3963
3964            if let hir::ExprKind::MethodCall(_, expr, ..) = expr.kind {
3965                self.suggest_option_method_if_applicable(failed_pred, param_env, err, expr);
3966            }
3967        }
3968    }
3969
3970    fn suggest_option_method_if_applicable<G: EmissionGuarantee>(
3971        &self,
3972        failed_pred: ty::Predicate<'tcx>,
3973        param_env: ty::ParamEnv<'tcx>,
3974        err: &mut Diag<'_, G>,
3975        expr: &hir::Expr<'_>,
3976    ) {
3977        let tcx = self.tcx;
3978        let infcx = self.infcx;
3979        let Some(typeck_results) = self.typeck_results.as_ref() else { return };
3980
3981        // Make sure we're dealing with the `Option` type.
3982        let Some(option_ty_adt) = typeck_results.expr_ty_adjusted(expr).ty_adt_def() else {
3983            return;
3984        };
3985        if !tcx.is_diagnostic_item(sym::Option, option_ty_adt.did()) {
3986            return;
3987        }
3988
3989        // Given the predicate `fn(&T): FnOnce<(U,)>`, extract `fn(&T)` and `(U,)`,
3990        // then suggest `Option::as_deref(_mut)` if `U` can deref to `T`
3991        if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, .. }))
3992            = failed_pred.kind().skip_binder()
3993            && tcx.is_fn_trait(trait_ref.def_id)
3994            && let [self_ty, found_ty] = trait_ref.args.as_slice()
3995            && let Some(fn_ty) = self_ty.as_type().filter(|ty| ty.is_fn())
3996            && let fn_sig @ ty::FnSig {
3997                abi: ExternAbi::Rust,
3998                c_variadic: false,
3999                safety: hir::Safety::Safe,
4000                ..
4001            } = fn_ty.fn_sig(tcx).skip_binder()
4002
4003            // Extract first param of fn sig with peeled refs, e.g. `fn(&T)` -> `T`
4004            && let Some(&ty::Ref(_, target_ty, needs_mut)) = fn_sig.inputs().first().map(|t| t.kind())
4005            && !target_ty.has_escaping_bound_vars()
4006
4007            // Extract first tuple element out of fn trait, e.g. `FnOnce<(U,)>` -> `U`
4008            && let Some(ty::Tuple(tys)) = found_ty.as_type().map(Ty::kind)
4009            && let &[found_ty] = tys.as_slice()
4010            && !found_ty.has_escaping_bound_vars()
4011
4012            // Extract `<U as Deref>::Target` assoc type and check that it is `T`
4013            && let Some(deref_target_did) = tcx.lang_items().deref_target()
4014            && let projection = Ty::new_projection_from_args(tcx,deref_target_did, tcx.mk_args(&[ty::GenericArg::from(found_ty)]))
4015            && let InferOk { value: deref_target, obligations } = infcx.at(&ObligationCause::dummy(), param_env).normalize(projection)
4016            && obligations.iter().all(|obligation| infcx.predicate_must_hold_modulo_regions(obligation))
4017            && infcx.can_eq(param_env, deref_target, target_ty)
4018        {
4019            let help = if let hir::Mutability::Mut = needs_mut
4020                && let Some(deref_mut_did) = tcx.lang_items().deref_mut_trait()
4021                && infcx
4022                    .type_implements_trait(deref_mut_did, iter::once(found_ty), param_env)
4023                    .must_apply_modulo_regions()
4024            {
4025                Some(("call `Option::as_deref_mut()` first", ".as_deref_mut()"))
4026            } else if let hir::Mutability::Not = needs_mut {
4027                Some(("call `Option::as_deref()` first", ".as_deref()"))
4028            } else {
4029                None
4030            };
4031
4032            if let Some((msg, sugg)) = help {
4033                err.span_suggestion_with_style(
4034                    expr.span.shrink_to_hi(),
4035                    msg,
4036                    sugg,
4037                    Applicability::MaybeIncorrect,
4038                    SuggestionStyle::ShowAlways,
4039                );
4040            }
4041        }
4042    }
4043
4044    fn look_for_iterator_item_mistakes<G: EmissionGuarantee>(
4045        &self,
4046        assocs_in_this_method: &[Option<(Span, (DefId, Ty<'tcx>))>],
4047        typeck_results: &TypeckResults<'tcx>,
4048        type_diffs: &[TypeError<'tcx>],
4049        param_env: ty::ParamEnv<'tcx>,
4050        path_segment: &hir::PathSegment<'_>,
4051        args: &[hir::Expr<'_>],
4052        err: &mut Diag<'_, G>,
4053    ) {
4054        let tcx = self.tcx;
4055        // Special case for iterator chains, we look at potential failures of `Iterator::Item`
4056        // not being `: Clone` and `Iterator::map` calls with spurious trailing `;`.
4057        for entry in assocs_in_this_method {
4058            let Some((_span, (def_id, ty))) = entry else {
4059                continue;
4060            };
4061            for diff in type_diffs {
4062                let TypeError::Sorts(expected_found) = diff else {
4063                    continue;
4064                };
4065                if tcx.is_diagnostic_item(sym::IteratorItem, *def_id)
4066                    && path_segment.ident.name == sym::map
4067                    && self.can_eq(param_env, expected_found.found, *ty)
4068                    && let [arg] = args
4069                    && let hir::ExprKind::Closure(closure) = arg.kind
4070                {
4071                    let body = tcx.hir_body(closure.body);
4072                    if let hir::ExprKind::Block(block, None) = body.value.kind
4073                        && let None = block.expr
4074                        && let [.., stmt] = block.stmts
4075                        && let hir::StmtKind::Semi(expr) = stmt.kind
4076                        // FIXME: actually check the expected vs found types, but right now
4077                        // the expected is a projection that we need to resolve.
4078                        // && let Some(tail_ty) = typeck_results.expr_ty_opt(expr)
4079                        && expected_found.found.is_unit()
4080                        // FIXME: this happens with macro calls. Need to figure out why the stmt
4081                        // `println!();` doesn't include the `;` in its `Span`. (#133845)
4082                        // We filter these out to avoid ICEs with debug assertions on caused by
4083                        // empty suggestions.
4084                        && expr.span.hi() != stmt.span.hi()
4085                    {
4086                        err.span_suggestion_verbose(
4087                            expr.span.shrink_to_hi().with_hi(stmt.span.hi()),
4088                            "consider removing this semicolon",
4089                            String::new(),
4090                            Applicability::MachineApplicable,
4091                        );
4092                    }
4093                    let expr = if let hir::ExprKind::Block(block, None) = body.value.kind
4094                        && let Some(expr) = block.expr
4095                    {
4096                        expr
4097                    } else {
4098                        body.value
4099                    };
4100                    if let hir::ExprKind::MethodCall(path_segment, rcvr, [], span) = expr.kind
4101                        && path_segment.ident.name == sym::clone
4102                        && let Some(expr_ty) = typeck_results.expr_ty_opt(expr)
4103                        && let Some(rcvr_ty) = typeck_results.expr_ty_opt(rcvr)
4104                        && self.can_eq(param_env, expr_ty, rcvr_ty)
4105                        && let ty::Ref(_, ty, _) = expr_ty.kind()
4106                    {
4107                        err.span_label(
4108                            span,
4109                            format!(
4110                                "this method call is cloning the reference `{expr_ty}`, not \
4111                                 `{ty}` which doesn't implement `Clone`",
4112                            ),
4113                        );
4114                        let ty::Param(..) = ty.kind() else {
4115                            continue;
4116                        };
4117                        let node =
4118                            tcx.hir_node_by_def_id(tcx.hir_get_parent_item(expr.hir_id).def_id);
4119
4120                        let pred = ty::Binder::dummy(ty::TraitPredicate {
4121                            trait_ref: ty::TraitRef::new(
4122                                tcx,
4123                                tcx.require_lang_item(LangItem::Clone, Some(span)),
4124                                [*ty],
4125                            ),
4126                            polarity: ty::PredicatePolarity::Positive,
4127                        });
4128                        let Some(generics) = node.generics() else {
4129                            continue;
4130                        };
4131                        let Some(body_id) = node.body_id() else {
4132                            continue;
4133                        };
4134                        suggest_restriction(
4135                            tcx,
4136                            tcx.hir_body_owner_def_id(body_id),
4137                            generics,
4138                            &format!("type parameter `{ty}`"),
4139                            err,
4140                            node.fn_sig(),
4141                            None,
4142                            pred,
4143                            None,
4144                        );
4145                    }
4146                }
4147            }
4148        }
4149    }
4150
4151    fn point_at_chain<G: EmissionGuarantee>(
4152        &self,
4153        expr: &hir::Expr<'_>,
4154        typeck_results: &TypeckResults<'tcx>,
4155        type_diffs: Vec<TypeError<'tcx>>,
4156        param_env: ty::ParamEnv<'tcx>,
4157        err: &mut Diag<'_, G>,
4158    ) {
4159        let mut primary_spans = vec![];
4160        let mut span_labels = vec![];
4161
4162        let tcx = self.tcx;
4163
4164        let mut print_root_expr = true;
4165        let mut assocs = vec![];
4166        let mut expr = expr;
4167        let mut prev_ty = self.resolve_vars_if_possible(
4168            typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
4169        );
4170        while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
4171            // Point at every method call in the chain with the resulting type.
4172            // vec![1, 2, 3].iter().map(mapper).sum<i32>()
4173            //               ^^^^^^ ^^^^^^^^^^^
4174            expr = rcvr_expr;
4175            let assocs_in_this_method =
4176                self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
4177            self.look_for_iterator_item_mistakes(
4178                &assocs_in_this_method,
4179                typeck_results,
4180                &type_diffs,
4181                param_env,
4182                path_segment,
4183                args,
4184                err,
4185            );
4186            assocs.push(assocs_in_this_method);
4187            prev_ty = self.resolve_vars_if_possible(
4188                typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
4189            );
4190
4191            if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
4192                && let hir::Path { res: Res::Local(hir_id), .. } = path
4193                && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
4194            {
4195                let parent = self.tcx.parent_hir_node(binding.hir_id);
4196                // We've reached the root of the method call chain...
4197                if let hir::Node::LetStmt(local) = parent
4198                    && let Some(binding_expr) = local.init
4199                {
4200                    // ...and it is a binding. Get the binding creation and continue the chain.
4201                    expr = binding_expr;
4202                }
4203                if let hir::Node::Param(param) = parent {
4204                    // ...and it is an fn argument.
4205                    let prev_ty = self.resolve_vars_if_possible(
4206                        typeck_results
4207                            .node_type_opt(param.hir_id)
4208                            .unwrap_or(Ty::new_misc_error(tcx)),
4209                    );
4210                    let assocs_in_this_method = self.probe_assoc_types_at_expr(
4211                        &type_diffs,
4212                        param.ty_span,
4213                        prev_ty,
4214                        param.hir_id,
4215                        param_env,
4216                    );
4217                    if assocs_in_this_method.iter().any(|a| a.is_some()) {
4218                        assocs.push(assocs_in_this_method);
4219                        print_root_expr = false;
4220                    }
4221                    break;
4222                }
4223            }
4224        }
4225        // We want the type before deref coercions, otherwise we talk about `&[_]`
4226        // instead of `Vec<_>`.
4227        if let Some(ty) = typeck_results.expr_ty_opt(expr)
4228            && print_root_expr
4229        {
4230            let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
4231            // Point at the root expression
4232            // vec![1, 2, 3].iter().map(mapper).sum<i32>()
4233            // ^^^^^^^^^^^^^
4234            span_labels.push((expr.span, format!("this expression has type `{ty}`")));
4235        };
4236        // Only show this if it is not a "trivial" expression (not a method
4237        // chain) and there are associated types to talk about.
4238        let mut assocs = assocs.into_iter().peekable();
4239        while let Some(assocs_in_method) = assocs.next() {
4240            let Some(prev_assoc_in_method) = assocs.peek() else {
4241                for entry in assocs_in_method {
4242                    let Some((span, (assoc, ty))) = entry else {
4243                        continue;
4244                    };
4245                    if primary_spans.is_empty()
4246                        || type_diffs.iter().any(|diff| {
4247                            let TypeError::Sorts(expected_found) = diff else {
4248                                return false;
4249                            };
4250                            self.can_eq(param_env, expected_found.found, ty)
4251                        })
4252                    {
4253                        // FIXME: this doesn't quite work for `Iterator::collect`
4254                        // because we have `Vec<i32>` and `()`, but we'd want `i32`
4255                        // to point at the `.into_iter()` call, but as long as we
4256                        // still point at the other method calls that might have
4257                        // introduced the issue, this is fine for now.
4258                        primary_spans.push(span);
4259                    }
4260                    span_labels.push((
4261                        span,
4262                        with_forced_trimmed_paths!(format!(
4263                            "`{}` is `{ty}` here",
4264                            self.tcx.def_path_str(assoc),
4265                        )),
4266                    ));
4267                }
4268                break;
4269            };
4270            for (entry, prev_entry) in
4271                assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
4272            {
4273                match (entry, prev_entry) {
4274                    (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
4275                        let ty_str = with_forced_trimmed_paths!(self.ty_to_string(ty));
4276
4277                        let assoc = with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
4278                        if !self.can_eq(param_env, ty, *prev_ty) {
4279                            if type_diffs.iter().any(|diff| {
4280                                let TypeError::Sorts(expected_found) = diff else {
4281                                    return false;
4282                                };
4283                                self.can_eq(param_env, expected_found.found, ty)
4284                            }) {
4285                                primary_spans.push(span);
4286                            }
4287                            span_labels
4288                                .push((span, format!("`{assoc}` changed to `{ty_str}` here")));
4289                        } else {
4290                            span_labels.push((span, format!("`{assoc}` remains `{ty_str}` here")));
4291                        }
4292                    }
4293                    (Some((span, (assoc, ty))), None) => {
4294                        span_labels.push((
4295                            span,
4296                            with_forced_trimmed_paths!(format!(
4297                                "`{}` is `{}` here",
4298                                self.tcx.def_path_str(assoc),
4299                                self.ty_to_string(ty),
4300                            )),
4301                        ));
4302                    }
4303                    (None, Some(_)) | (None, None) => {}
4304                }
4305            }
4306        }
4307        if !primary_spans.is_empty() {
4308            let mut multi_span: MultiSpan = primary_spans.into();
4309            for (span, label) in span_labels {
4310                multi_span.push_span_label(span, label);
4311            }
4312            err.span_note(
4313                multi_span,
4314                "the method call chain might not have had the expected associated types",
4315            );
4316        }
4317    }
4318
4319    fn probe_assoc_types_at_expr(
4320        &self,
4321        type_diffs: &[TypeError<'tcx>],
4322        span: Span,
4323        prev_ty: Ty<'tcx>,
4324        body_id: HirId,
4325        param_env: ty::ParamEnv<'tcx>,
4326    ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
4327        let ocx = ObligationCtxt::new(self.infcx);
4328        let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
4329        for diff in type_diffs {
4330            let TypeError::Sorts(expected_found) = diff else {
4331                continue;
4332            };
4333            let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else {
4334                continue;
4335            };
4336
4337            // Make `Self` be equivalent to the type of the call chain
4338            // expression we're looking at now, so that we can tell what
4339            // for example `Iterator::Item` is at this point in the chain.
4340            let args = GenericArgs::for_item(self.tcx, proj.def_id, |param, _| {
4341                if param.index == 0 {
4342                    debug_assert_matches!(param.kind, ty::GenericParamDefKind::Type { .. });
4343                    return prev_ty.into();
4344                }
4345                self.var_for_def(span, param)
4346            });
4347            // This will hold the resolved type of the associated type, if the
4348            // current expression implements the trait that associated type is
4349            // in. For example, this would be what `Iterator::Item` is here.
4350            let ty = self.infcx.next_ty_var(span);
4351            // This corresponds to `<ExprTy as Iterator>::Item = _`.
4352            let projection = ty::Binder::dummy(ty::PredicateKind::Clause(
4353                ty::ClauseKind::Projection(ty::ProjectionPredicate {
4354                    projection_term: ty::AliasTerm::new_from_args(self.tcx, proj.def_id, args),
4355                    term: ty.into(),
4356                }),
4357            ));
4358            let body_def_id = self.tcx.hir_enclosing_body_owner(body_id);
4359            // Add `<ExprTy as Iterator>::Item = _` obligation.
4360            ocx.register_obligation(Obligation::misc(
4361                self.tcx,
4362                span,
4363                body_def_id,
4364                param_env,
4365                projection,
4366            ));
4367            if ocx.select_where_possible().is_empty()
4368                && let ty = self.resolve_vars_if_possible(ty)
4369                && !ty.is_ty_var()
4370            {
4371                assocs_in_this_method.push(Some((span, (proj.def_id, ty))));
4372            } else {
4373                // `<ExprTy as Iterator>` didn't select, so likely we've
4374                // reached the end of the iterator chain, like the originating
4375                // `Vec<_>` or the `ty` couldn't be determined.
4376                // Keep the space consistent for later zipping.
4377                assocs_in_this_method.push(None);
4378            }
4379        }
4380        assocs_in_this_method
4381    }
4382
4383    /// If the type that failed selection is an array or a reference to an array,
4384    /// but the trait is implemented for slices, suggest that the user converts
4385    /// the array into a slice.
4386    pub(super) fn suggest_convert_to_slice(
4387        &self,
4388        err: &mut Diag<'_>,
4389        obligation: &PredicateObligation<'tcx>,
4390        trait_pred: ty::PolyTraitPredicate<'tcx>,
4391        candidate_impls: &[ImplCandidate<'tcx>],
4392        span: Span,
4393    ) {
4394        // We can only suggest the slice coersion for function and binary operation arguments,
4395        // since the suggestion would make no sense in turbofish or call
4396        let (ObligationCauseCode::BinOp { .. } | ObligationCauseCode::FunctionArg { .. }) =
4397            obligation.cause.code()
4398        else {
4399            return;
4400        };
4401
4402        // Three cases where we can make a suggestion:
4403        // 1. `[T; _]` (array of T)
4404        // 2. `&[T; _]` (reference to array of T)
4405        // 3. `&mut [T; _]` (mutable reference to array of T)
4406        let (element_ty, mut mutability) = match *trait_pred.skip_binder().self_ty().kind() {
4407            ty::Array(element_ty, _) => (element_ty, None),
4408
4409            ty::Ref(_, pointee_ty, mutability) => match *pointee_ty.kind() {
4410                ty::Array(element_ty, _) => (element_ty, Some(mutability)),
4411                _ => return,
4412            },
4413
4414            _ => return,
4415        };
4416
4417        // Go through all the candidate impls to see if any of them is for
4418        // slices of `element_ty` with `mutability`.
4419        let mut is_slice = |candidate: Ty<'tcx>| match *candidate.kind() {
4420            ty::RawPtr(t, m) | ty::Ref(_, t, m) => {
4421                if matches!(*t.kind(), ty::Slice(e) if e == element_ty)
4422                    && m == mutability.unwrap_or(m)
4423                {
4424                    // Use the candidate's mutability going forward.
4425                    mutability = Some(m);
4426                    true
4427                } else {
4428                    false
4429                }
4430            }
4431            _ => false,
4432        };
4433
4434        // Grab the first candidate that matches, if any, and make a suggestion.
4435        if let Some(slice_ty) = candidate_impls
4436            .iter()
4437            .map(|trait_ref| trait_ref.trait_ref.self_ty())
4438            .find(|t| is_slice(*t))
4439        {
4440            let msg = format!("convert the array to a `{slice_ty}` slice instead");
4441
4442            if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
4443                let mut suggestions = vec![];
4444                if snippet.starts_with('&') {
4445                } else if let Some(hir::Mutability::Mut) = mutability {
4446                    suggestions.push((span.shrink_to_lo(), "&mut ".into()));
4447                } else {
4448                    suggestions.push((span.shrink_to_lo(), "&".into()));
4449                }
4450                suggestions.push((span.shrink_to_hi(), "[..]".into()));
4451                err.multipart_suggestion_verbose(msg, suggestions, Applicability::MaybeIncorrect);
4452            } else {
4453                err.span_help(span, msg);
4454            }
4455        }
4456    }
4457
4458    /// If the type failed selection but the trait is implemented for `(T,)`, suggest that the user
4459    /// creates a unary tuple
4460    ///
4461    /// This is a common gotcha when using libraries that emulate variadic functions with traits for tuples.
4462    pub(super) fn suggest_tuple_wrapping(
4463        &self,
4464        err: &mut Diag<'_>,
4465        root_obligation: &PredicateObligation<'tcx>,
4466        obligation: &PredicateObligation<'tcx>,
4467    ) {
4468        let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code() else {
4469            return;
4470        };
4471
4472        let Some(root_pred) = root_obligation.predicate.as_trait_clause() else { return };
4473
4474        let trait_ref = root_pred.map_bound(|root_pred| {
4475            root_pred
4476                .trait_ref
4477                .with_self_ty(self.tcx, Ty::new_tup(self.tcx, &[root_pred.trait_ref.self_ty()]))
4478        });
4479
4480        let obligation =
4481            Obligation::new(self.tcx, obligation.cause.clone(), obligation.param_env, trait_ref);
4482
4483        if self.predicate_must_hold_modulo_regions(&obligation) {
4484            let arg_span = self.tcx.hir().span(*arg_hir_id);
4485            err.multipart_suggestion_verbose(
4486                format!("use a unary tuple instead"),
4487                vec![(arg_span.shrink_to_lo(), "(".into()), (arg_span.shrink_to_hi(), ",)".into())],
4488                Applicability::MaybeIncorrect,
4489            );
4490        }
4491    }
4492
4493    pub(super) fn explain_hrtb_projection(
4494        &self,
4495        diag: &mut Diag<'_>,
4496        pred: ty::PolyTraitPredicate<'tcx>,
4497        param_env: ty::ParamEnv<'tcx>,
4498        cause: &ObligationCause<'tcx>,
4499    ) {
4500        if pred.skip_binder().has_escaping_bound_vars() && pred.skip_binder().has_non_region_infer()
4501        {
4502            self.probe(|_| {
4503                let ocx = ObligationCtxt::new(self);
4504                self.enter_forall(pred, |pred| {
4505                    let pred = ocx.normalize(&ObligationCause::dummy(), param_env, pred);
4506                    ocx.register_obligation(Obligation::new(
4507                        self.tcx,
4508                        ObligationCause::dummy(),
4509                        param_env,
4510                        pred,
4511                    ));
4512                });
4513                if !ocx.select_where_possible().is_empty() {
4514                    // encountered errors.
4515                    return;
4516                }
4517
4518                if let ObligationCauseCode::FunctionArg {
4519                    call_hir_id,
4520                    arg_hir_id,
4521                    parent_code: _,
4522                } = cause.code()
4523                {
4524                    let arg_span = self.tcx.hir().span(*arg_hir_id);
4525                    let mut sp: MultiSpan = arg_span.into();
4526
4527                    sp.push_span_label(
4528                        arg_span,
4529                        "the trait solver is unable to infer the \
4530                        generic types that should be inferred from this argument",
4531                    );
4532                    sp.push_span_label(
4533                        self.tcx.hir().span(*call_hir_id),
4534                        "add turbofish arguments to this call to \
4535                        specify the types manually, even if it's redundant",
4536                    );
4537                    diag.span_note(
4538                        sp,
4539                        "this is a known limitation of the trait solver that \
4540                        will be lifted in the future",
4541                    );
4542                } else {
4543                    let mut sp: MultiSpan = cause.span.into();
4544                    sp.push_span_label(
4545                        cause.span,
4546                        "try adding turbofish arguments to this expression to \
4547                        specify the types manually, even if it's redundant",
4548                    );
4549                    diag.span_note(
4550                        sp,
4551                        "this is a known limitation of the trait solver that \
4552                        will be lifted in the future",
4553                    );
4554                }
4555            });
4556        }
4557    }
4558
4559    pub(super) fn suggest_desugaring_async_fn_in_trait(
4560        &self,
4561        err: &mut Diag<'_>,
4562        trait_pred: ty::PolyTraitPredicate<'tcx>,
4563    ) {
4564        // Don't suggest if RTN is active -- we should prefer a where-clause bound instead.
4565        if self.tcx.features().return_type_notation() {
4566            return;
4567        }
4568
4569        let trait_def_id = trait_pred.def_id();
4570
4571        // Only suggest specifying auto traits
4572        if !self.tcx.trait_is_auto(trait_def_id) {
4573            return;
4574        }
4575
4576        // Look for an RPITIT
4577        let ty::Alias(ty::Projection, alias_ty) = trait_pred.self_ty().skip_binder().kind() else {
4578            return;
4579        };
4580        let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, opaque_def_id }) =
4581            self.tcx.opt_rpitit_info(alias_ty.def_id)
4582        else {
4583            return;
4584        };
4585
4586        let auto_trait = self.tcx.def_path_str(trait_def_id);
4587        // ... which is a local function
4588        let Some(fn_def_id) = fn_def_id.as_local() else {
4589            // If it's not local, we can at least mention that the method is async, if it is.
4590            if self.tcx.asyncness(fn_def_id).is_async() {
4591                err.span_note(
4592                    self.tcx.def_span(fn_def_id),
4593                    format!(
4594                        "`{}::{}` is an `async fn` in trait, which does not \
4595                    automatically imply that its future is `{auto_trait}`",
4596                        alias_ty.trait_ref(self.tcx),
4597                        self.tcx.item_name(fn_def_id)
4598                    ),
4599                );
4600            }
4601            return;
4602        };
4603        let hir::Node::TraitItem(item) = self.tcx.hir_node_by_def_id(fn_def_id) else {
4604            return;
4605        };
4606
4607        // ... whose signature is `async` (i.e. this is an AFIT)
4608        let (sig, body) = item.expect_fn();
4609        let hir::FnRetTy::Return(hir::Ty { kind: hir::TyKind::OpaqueDef(opaq_def, ..), .. }) =
4610            sig.decl.output
4611        else {
4612            // This should never happen, but let's not ICE.
4613            return;
4614        };
4615
4616        // Check that this is *not* a nested `impl Future` RPIT in an async fn
4617        // (i.e. `async fn foo() -> impl Future`)
4618        if opaq_def.def_id.to_def_id() != opaque_def_id {
4619            return;
4620        }
4621
4622        let Some(sugg) = suggest_desugaring_async_fn_to_impl_future_in_trait(
4623            self.tcx,
4624            *sig,
4625            *body,
4626            opaque_def_id.expect_local(),
4627            &format!(" + {auto_trait}"),
4628        ) else {
4629            return;
4630        };
4631
4632        let function_name = self.tcx.def_path_str(fn_def_id);
4633        err.multipart_suggestion(
4634            format!(
4635                "`{auto_trait}` can be made part of the associated future's \
4636                guarantees for all implementations of `{function_name}`"
4637            ),
4638            sugg,
4639            Applicability::MachineApplicable,
4640        );
4641    }
4642
4643    pub fn ty_kind_suggestion(
4644        &self,
4645        param_env: ty::ParamEnv<'tcx>,
4646        ty: Ty<'tcx>,
4647    ) -> Option<String> {
4648        let tcx = self.infcx.tcx;
4649        let implements_default = |ty| {
4650            let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
4651                return false;
4652            };
4653            self.type_implements_trait(default_trait, [ty], param_env).must_apply_modulo_regions()
4654        };
4655
4656        Some(match *ty.kind() {
4657            ty::Never | ty::Error(_) => return None,
4658            ty::Bool => "false".to_string(),
4659            ty::Char => "\'x\'".to_string(),
4660            ty::Int(_) | ty::Uint(_) => "42".into(),
4661            ty::Float(_) => "3.14159".into(),
4662            ty::Slice(_) => "[]".to_string(),
4663            ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => {
4664                "vec![]".to_string()
4665            }
4666            ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::String) => {
4667                "String::new()".to_string()
4668            }
4669            ty::Adt(def, args) if def.is_box() => {
4670                format!("Box::new({})", self.ty_kind_suggestion(param_env, args[0].expect_ty())?)
4671            }
4672            ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Option) => {
4673                "None".to_string()
4674            }
4675            ty::Adt(def, args) if Some(def.did()) == tcx.get_diagnostic_item(sym::Result) => {
4676                format!("Ok({})", self.ty_kind_suggestion(param_env, args[0].expect_ty())?)
4677            }
4678            ty::Adt(_, _) if implements_default(ty) => "Default::default()".to_string(),
4679            ty::Ref(_, ty, mutability) => {
4680                if let (ty::Str, hir::Mutability::Not) = (ty.kind(), mutability) {
4681                    "\"\"".to_string()
4682                } else {
4683                    let ty = self.ty_kind_suggestion(param_env, ty)?;
4684                    format!("&{}{ty}", mutability.prefix_str())
4685                }
4686            }
4687            ty::Array(ty, len) if let Some(len) = len.try_to_target_usize(tcx) => {
4688                if len == 0 {
4689                    "[]".to_string()
4690                } else if self.type_is_copy_modulo_regions(param_env, ty) || len == 1 {
4691                    // Can only suggest `[ty; 0]` if sz == 1 or copy
4692                    format!("[{}; {}]", self.ty_kind_suggestion(param_env, ty)?, len)
4693                } else {
4694                    "/* value */".to_string()
4695                }
4696            }
4697            ty::Tuple(tys) => format!(
4698                "({}{})",
4699                tys.iter()
4700                    .map(|ty| self.ty_kind_suggestion(param_env, ty))
4701                    .collect::<Option<Vec<String>>>()?
4702                    .join(", "),
4703                if tys.len() == 1 { "," } else { "" }
4704            ),
4705            _ => "/* value */".to_string(),
4706        })
4707    }
4708
4709    // For E0277 when use `?` operator, suggest adding
4710    // a suitable return type in `FnSig`, and a default
4711    // return value at the end of the function's body.
4712    pub(super) fn suggest_add_result_as_return_type(
4713        &self,
4714        obligation: &PredicateObligation<'tcx>,
4715        err: &mut Diag<'_>,
4716        trait_pred: ty::PolyTraitPredicate<'tcx>,
4717    ) {
4718        if ObligationCauseCode::QuestionMark != *obligation.cause.code().peel_derives() {
4719            return;
4720        }
4721
4722        // Only suggest for local function and associated method,
4723        // because this suggest adding both return type in
4724        // the `FnSig` and a default return value in the body, so it
4725        // is not suitable for foreign function without a local body,
4726        // and neither for trait method which may be also implemented
4727        // in other place, so shouldn't change it's FnSig.
4728        fn choose_suggest_items<'tcx, 'hir>(
4729            tcx: TyCtxt<'tcx>,
4730            node: hir::Node<'hir>,
4731        ) -> Option<(&'hir hir::FnDecl<'hir>, hir::BodyId)> {
4732            match node {
4733                hir::Node::Item(item)
4734                    if let hir::ItemKind::Fn { sig, body: body_id, .. } = item.kind =>
4735                {
4736                    Some((sig.decl, body_id))
4737                }
4738                hir::Node::ImplItem(item)
4739                    if let hir::ImplItemKind::Fn(sig, body_id) = item.kind =>
4740                {
4741                    let parent = tcx.parent_hir_node(item.hir_id());
4742                    if let hir::Node::Item(item) = parent
4743                        && let hir::ItemKind::Impl(imp) = item.kind
4744                        && imp.of_trait.is_none()
4745                    {
4746                        return Some((sig.decl, body_id));
4747                    }
4748                    None
4749                }
4750                _ => None,
4751            }
4752        }
4753
4754        let node = self.tcx.hir_node_by_def_id(obligation.cause.body_id);
4755        if let Some((fn_decl, body_id)) = choose_suggest_items(self.tcx, node)
4756            && let hir::FnRetTy::DefaultReturn(ret_span) = fn_decl.output
4757            && self.tcx.is_diagnostic_item(sym::FromResidual, trait_pred.def_id())
4758            && trait_pred.skip_binder().trait_ref.args.type_at(0).is_unit()
4759            && let ty::Adt(def, _) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
4760            && self.tcx.is_diagnostic_item(sym::Result, def.did())
4761        {
4762            let mut sugg_spans =
4763                vec![(ret_span, " -> Result<(), Box<dyn std::error::Error>>".to_string())];
4764            let body = self.tcx.hir_body(body_id);
4765            if let hir::ExprKind::Block(b, _) = body.value.kind
4766                && b.expr.is_none()
4767            {
4768                // The span of '}' in the end of block.
4769                let span = self.tcx.sess.source_map().end_point(b.span);
4770                sugg_spans.push((
4771                    span.shrink_to_lo(),
4772                    format!(
4773                        "{}{}",
4774                        "    Ok(())\n",
4775                        self.tcx.sess.source_map().indentation_before(span).unwrap_or_default(),
4776                    ),
4777                ));
4778            }
4779            err.multipart_suggestion_verbose(
4780                format!("consider adding return type"),
4781                sugg_spans,
4782                Applicability::MaybeIncorrect,
4783            );
4784        }
4785    }
4786
4787    #[instrument(level = "debug", skip_all)]
4788    pub(super) fn suggest_unsized_bound_if_applicable(
4789        &self,
4790        err: &mut Diag<'_>,
4791        obligation: &PredicateObligation<'tcx>,
4792    ) {
4793        let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
4794            obligation.predicate.kind().skip_binder()
4795        else {
4796            return;
4797        };
4798        let (ObligationCauseCode::WhereClause(item_def_id, span)
4799        | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)) =
4800            *obligation.cause.code().peel_derives()
4801        else {
4802            return;
4803        };
4804        if span.is_dummy() {
4805            return;
4806        }
4807        debug!(?pred, ?item_def_id, ?span);
4808
4809        let (Some(node), true) = (
4810            self.tcx.hir_get_if_local(item_def_id),
4811            self.tcx.is_lang_item(pred.def_id(), LangItem::Sized),
4812        ) else {
4813            return;
4814        };
4815
4816        let Some(generics) = node.generics() else {
4817            return;
4818        };
4819        let sized_trait = self.tcx.lang_items().sized_trait();
4820        debug!(?generics.params);
4821        debug!(?generics.predicates);
4822        let Some(param) = generics.params.iter().find(|param| param.span == span) else {
4823            return;
4824        };
4825        // Check that none of the explicit trait bounds is `Sized`. Assume that an explicit
4826        // `Sized` bound is there intentionally and we don't need to suggest relaxing it.
4827        let explicitly_sized = generics
4828            .bounds_for_param(param.def_id)
4829            .flat_map(|bp| bp.bounds)
4830            .any(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) == sized_trait);
4831        if explicitly_sized {
4832            return;
4833        }
4834        debug!(?param);
4835        match node {
4836            hir::Node::Item(
4837                item @ hir::Item {
4838                    // Only suggest indirection for uses of type parameters in ADTs.
4839                    kind:
4840                        hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..),
4841                    ..
4842                },
4843            ) => {
4844                if self.suggest_indirection_for_unsized(err, item, param) {
4845                    return;
4846                }
4847            }
4848            _ => {}
4849        };
4850
4851        // Didn't add an indirection suggestion, so add a general suggestion to relax `Sized`.
4852        let (span, separator, open_paren_sp) =
4853            if let Some((s, open_paren_sp)) = generics.bounds_span_for_suggestions(param.def_id) {
4854                (s, " +", open_paren_sp)
4855            } else {
4856                (param.name.ident().span.shrink_to_hi(), ":", None)
4857            };
4858
4859        let mut suggs = vec![];
4860        let suggestion = format!("{separator} ?Sized");
4861
4862        if let Some(open_paren_sp) = open_paren_sp {
4863            suggs.push((open_paren_sp, "(".to_string()));
4864            suggs.push((span, format!("){suggestion}")));
4865        } else {
4866            suggs.push((span, suggestion));
4867        }
4868
4869        err.multipart_suggestion_verbose(
4870            "consider relaxing the implicit `Sized` restriction",
4871            suggs,
4872            Applicability::MachineApplicable,
4873        );
4874    }
4875
4876    fn suggest_indirection_for_unsized(
4877        &self,
4878        err: &mut Diag<'_>,
4879        item: &hir::Item<'tcx>,
4880        param: &hir::GenericParam<'tcx>,
4881    ) -> bool {
4882        // Suggesting `T: ?Sized` is only valid in an ADT if `T` is only used in a
4883        // borrow. `struct S<'a, T: ?Sized>(&'a T);` is valid, `struct S<T: ?Sized>(T);`
4884        // is not. Look for invalid "bare" parameter uses, and suggest using indirection.
4885        let mut visitor =
4886            FindTypeParam { param: param.name.ident().name, invalid_spans: vec![], nested: false };
4887        visitor.visit_item(item);
4888        if visitor.invalid_spans.is_empty() {
4889            return false;
4890        }
4891        let mut multispan: MultiSpan = param.span.into();
4892        multispan.push_span_label(
4893            param.span,
4894            format!("this could be changed to `{}: ?Sized`...", param.name.ident()),
4895        );
4896        for sp in visitor.invalid_spans {
4897            multispan.push_span_label(
4898                sp,
4899                format!("...if indirection were used here: `Box<{}>`", param.name.ident()),
4900            );
4901        }
4902        err.span_help(
4903            multispan,
4904            format!(
4905                "you could relax the implicit `Sized` bound on `{T}` if it were \
4906                used through indirection like `&{T}` or `Box<{T}>`",
4907                T = param.name.ident(),
4908            ),
4909        );
4910        true
4911    }
4912    pub(crate) fn suggest_swapping_lhs_and_rhs<T>(
4913        &self,
4914        err: &mut Diag<'_>,
4915        predicate: T,
4916        param_env: ty::ParamEnv<'tcx>,
4917        cause_code: &ObligationCauseCode<'tcx>,
4918    ) where
4919        T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
4920    {
4921        let tcx = self.tcx;
4922        let predicate = predicate.upcast(tcx);
4923        match *cause_code {
4924            ObligationCauseCode::BinOp {
4925                lhs_hir_id,
4926                rhs_hir_id: Some(rhs_hir_id),
4927                rhs_span: Some(rhs_span),
4928                ..
4929            } if let Some(typeck_results) = &self.typeck_results
4930                && let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
4931                && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
4932                && let Some(lhs_ty) = typeck_results.expr_ty_opt(lhs)
4933                && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs) =>
4934            {
4935                if let Some(pred) = predicate.as_trait_clause()
4936                    && tcx.is_lang_item(pred.def_id(), LangItem::PartialEq)
4937                    && self
4938                        .infcx
4939                        .type_implements_trait(pred.def_id(), [rhs_ty, lhs_ty], param_env)
4940                        .must_apply_modulo_regions()
4941                {
4942                    let lhs_span = tcx.hir().span(lhs_hir_id);
4943                    let sm = tcx.sess.source_map();
4944                    if let Ok(rhs_snippet) = sm.span_to_snippet(rhs_span)
4945                        && let Ok(lhs_snippet) = sm.span_to_snippet(lhs_span)
4946                    {
4947                        err.note(format!("`{rhs_ty}` implements `PartialEq<{lhs_ty}>`"));
4948                        err.multipart_suggestion(
4949                            "consider swapping the equality",
4950                            vec![(lhs_span, rhs_snippet), (rhs_span, lhs_snippet)],
4951                            Applicability::MaybeIncorrect,
4952                        );
4953                    }
4954                }
4955            }
4956            _ => {}
4957        }
4958    }
4959}
4960
4961/// Add a hint to add a missing borrow or remove an unnecessary one.
4962fn hint_missing_borrow<'tcx>(
4963    infcx: &InferCtxt<'tcx>,
4964    param_env: ty::ParamEnv<'tcx>,
4965    span: Span,
4966    found: Ty<'tcx>,
4967    expected: Ty<'tcx>,
4968    found_node: Node<'_>,
4969    err: &mut Diag<'_>,
4970) {
4971    if matches!(found_node, Node::TraitItem(..)) {
4972        return;
4973    }
4974
4975    let found_args = match found.kind() {
4976        ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
4977        kind => {
4978            span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
4979        }
4980    };
4981    let expected_args = match expected.kind() {
4982        ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
4983        kind => {
4984            span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
4985        }
4986    };
4987
4988    // This could be a variant constructor, for example.
4989    let Some(fn_decl) = found_node.fn_decl() else {
4990        return;
4991    };
4992
4993    let args = fn_decl.inputs.iter();
4994
4995    let mut to_borrow = Vec::new();
4996    let mut remove_borrow = Vec::new();
4997
4998    for ((found_arg, expected_arg), arg) in found_args.zip(expected_args).zip(args) {
4999        let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
5000        let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
5001
5002        if infcx.can_eq(param_env, found_ty, expected_ty) {
5003            // FIXME: This could handle more exotic cases like mutability mismatches too!
5004            if found_refs.len() < expected_refs.len()
5005                && found_refs[..] == expected_refs[expected_refs.len() - found_refs.len()..]
5006            {
5007                to_borrow.push((
5008                    arg.span.shrink_to_lo(),
5009                    expected_refs[..expected_refs.len() - found_refs.len()]
5010                        .iter()
5011                        .map(|mutbl| format!("&{}", mutbl.prefix_str()))
5012                        .collect::<Vec<_>>()
5013                        .join(""),
5014                ));
5015            } else if found_refs.len() > expected_refs.len() {
5016                let mut span = arg.span.shrink_to_lo();
5017                let mut left = found_refs.len() - expected_refs.len();
5018                let mut ty = arg;
5019                while let hir::TyKind::Ref(_, mut_ty) = &ty.kind
5020                    && left > 0
5021                {
5022                    span = span.with_hi(mut_ty.ty.span.lo());
5023                    ty = mut_ty.ty;
5024                    left -= 1;
5025                }
5026                let sugg = if left == 0 {
5027                    (span, String::new())
5028                } else {
5029                    (arg.span, expected_arg.to_string())
5030                };
5031                remove_borrow.push(sugg);
5032            }
5033        }
5034    }
5035
5036    if !to_borrow.is_empty() {
5037        err.subdiagnostic(errors::AdjustSignatureBorrow::Borrow { to_borrow });
5038    }
5039
5040    if !remove_borrow.is_empty() {
5041        err.subdiagnostic(errors::AdjustSignatureBorrow::RemoveBorrow { remove_borrow });
5042    }
5043}
5044
5045/// Collect all the paths that reference `Self`.
5046/// Used to suggest replacing associated types with an explicit type in `where` clauses.
5047#[derive(Debug)]
5048pub struct SelfVisitor<'v> {
5049    pub paths: Vec<&'v hir::Ty<'v>>,
5050    pub name: Option<Symbol>,
5051}
5052
5053impl<'v> Visitor<'v> for SelfVisitor<'v> {
5054    fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
5055        if let hir::TyKind::Path(path) = ty.kind
5056            && let hir::QPath::TypeRelative(inner_ty, segment) = path
5057            && (Some(segment.ident.name) == self.name || self.name.is_none())
5058            && let hir::TyKind::Path(inner_path) = inner_ty.kind
5059            && let hir::QPath::Resolved(None, inner_path) = inner_path
5060            && let Res::SelfTyAlias { .. } = inner_path.res
5061        {
5062            self.paths.push(ty.as_unambig_ty());
5063        }
5064        hir::intravisit::walk_ty(self, ty);
5065    }
5066}
5067
5068/// Collect all the returned expressions within the input expression.
5069/// Used to point at the return spans when we want to suggest some change to them.
5070#[derive(Default)]
5071pub struct ReturnsVisitor<'v> {
5072    pub returns: Vec<&'v hir::Expr<'v>>,
5073    in_block_tail: bool,
5074}
5075
5076impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
5077    fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
5078        // Visit every expression to detect `return` paths, either through the function's tail
5079        // expression or `return` statements. We walk all nodes to find `return` statements, but
5080        // we only care about tail expressions when `in_block_tail` is `true`, which means that
5081        // they're in the return path of the function body.
5082        match ex.kind {
5083            hir::ExprKind::Ret(Some(ex)) => {
5084                self.returns.push(ex);
5085            }
5086            hir::ExprKind::Block(block, _) if self.in_block_tail => {
5087                self.in_block_tail = false;
5088                for stmt in block.stmts {
5089                    hir::intravisit::walk_stmt(self, stmt);
5090                }
5091                self.in_block_tail = true;
5092                if let Some(expr) = block.expr {
5093                    self.visit_expr(expr);
5094                }
5095            }
5096            hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
5097                self.visit_expr(then);
5098                if let Some(el) = else_opt {
5099                    self.visit_expr(el);
5100                }
5101            }
5102            hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
5103                for arm in arms {
5104                    self.visit_expr(arm.body);
5105                }
5106            }
5107            // We need to walk to find `return`s in the entire body.
5108            _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
5109            _ => self.returns.push(ex),
5110        }
5111    }
5112
5113    fn visit_body(&mut self, body: &hir::Body<'v>) {
5114        assert!(!self.in_block_tail);
5115        self.in_block_tail = true;
5116        hir::intravisit::walk_body(self, body);
5117    }
5118}
5119
5120/// Collect all the awaited expressions within the input expression.
5121#[derive(Default)]
5122struct AwaitsVisitor {
5123    awaits: Vec<HirId>,
5124}
5125
5126impl<'v> Visitor<'v> for AwaitsVisitor {
5127    fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
5128        if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
5129            self.awaits.push(id)
5130        }
5131        hir::intravisit::walk_expr(self, ex)
5132    }
5133}
5134
5135/// Suggest a new type parameter name for diagnostic purposes.
5136///
5137/// `name` is the preferred name you'd like to suggest if it's not in use already.
5138pub trait NextTypeParamName {
5139    fn next_type_param_name(&self, name: Option<&str>) -> String;
5140}
5141
5142impl NextTypeParamName for &[hir::GenericParam<'_>] {
5143    fn next_type_param_name(&self, name: Option<&str>) -> String {
5144        // Type names are usually single letters in uppercase. So convert the first letter of input string to uppercase.
5145        let name = name.and_then(|n| n.chars().next()).map(|c| c.to_uppercase().to_string());
5146        let name = name.as_deref();
5147
5148        // This is the list of possible parameter names that we might suggest.
5149        let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
5150
5151        // Filter out used names based on `filter_fn`.
5152        let used_names: Vec<Symbol> = self
5153            .iter()
5154            .filter_map(|param| match param.name {
5155                hir::ParamName::Plain(ident) => Some(ident.name),
5156                _ => None,
5157            })
5158            .collect();
5159
5160        // Find a name from `possible_names` that is not in `used_names`.
5161        possible_names
5162            .iter()
5163            .find(|n| !used_names.contains(&Symbol::intern(n)))
5164            .unwrap_or(&"ParamName")
5165            .to_string()
5166    }
5167}
5168
5169/// Collect the spans that we see the generic param `param_did`
5170struct ReplaceImplTraitVisitor<'a> {
5171    ty_spans: &'a mut Vec<Span>,
5172    param_did: DefId,
5173}
5174
5175impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
5176    fn visit_ty(&mut self, t: &'hir hir::Ty<'hir, AmbigArg>) {
5177        if let hir::TyKind::Path(hir::QPath::Resolved(
5178            None,
5179            hir::Path { res: Res::Def(_, segment_did), .. },
5180        )) = t.kind
5181        {
5182            if self.param_did == *segment_did {
5183                // `fn foo(t: impl Trait)`
5184                //            ^^^^^^^^^^ get this to suggest `T` instead
5185
5186                // There might be more than one `impl Trait`.
5187                self.ty_spans.push(t.span);
5188                return;
5189            }
5190        }
5191
5192        hir::intravisit::walk_ty(self, t);
5193    }
5194}
5195
5196pub(super) fn get_explanation_based_on_obligation<'tcx>(
5197    tcx: TyCtxt<'tcx>,
5198    obligation: &PredicateObligation<'tcx>,
5199    trait_predicate: ty::PolyTraitPredicate<'tcx>,
5200    pre_message: String,
5201) -> String {
5202    if let ObligationCauseCode::MainFunctionType = obligation.cause.code() {
5203        "consider using `()`, or a `Result`".to_owned()
5204    } else {
5205        let ty_desc = match trait_predicate.self_ty().skip_binder().kind() {
5206            ty::FnDef(_, _) => Some("fn item"),
5207            ty::Closure(_, _) => Some("closure"),
5208            _ => None,
5209        };
5210
5211        let desc = match ty_desc {
5212            Some(desc) => format!(" {desc}"),
5213            None => String::new(),
5214        };
5215        if let ty::PredicatePolarity::Positive = trait_predicate.polarity() {
5216            format!(
5217                "{pre_message}the trait `{}` is not implemented for{desc} `{}`",
5218                trait_predicate.print_modifiers_and_trait_path(),
5219                tcx.short_string(trait_predicate.self_ty().skip_binder(), &mut None),
5220            )
5221        } else {
5222            // "the trait bound `T: !Send` is not satisfied" reads better than "`!Send` is
5223            // not implemented for `T`".
5224            // FIXME: add note explaining explicit negative trait bounds.
5225            format!("{pre_message}the trait bound `{trait_predicate}` is not satisfied")
5226        }
5227    }
5228}
5229
5230// Replace `param` with `replace_ty`
5231struct ReplaceImplTraitFolder<'tcx> {
5232    tcx: TyCtxt<'tcx>,
5233    param: &'tcx ty::GenericParamDef,
5234    replace_ty: Ty<'tcx>,
5235}
5236
5237impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceImplTraitFolder<'tcx> {
5238    fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
5239        if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
5240            if self.param.index == *index {
5241                return self.replace_ty;
5242            }
5243        }
5244        t.super_fold_with(self)
5245    }
5246
5247    fn cx(&self) -> TyCtxt<'tcx> {
5248        self.tcx
5249    }
5250}
5251
5252pub fn suggest_desugaring_async_fn_to_impl_future_in_trait<'tcx>(
5253    tcx: TyCtxt<'tcx>,
5254    sig: hir::FnSig<'tcx>,
5255    body: hir::TraitFn<'tcx>,
5256    opaque_def_id: LocalDefId,
5257    add_bounds: &str,
5258) -> Option<Vec<(Span, String)>> {
5259    let hir::IsAsync::Async(async_span) = sig.header.asyncness else {
5260        return None;
5261    };
5262    let async_span = tcx.sess.source_map().span_extend_while_whitespace(async_span);
5263
5264    let future = tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
5265    let [hir::GenericBound::Trait(trait_ref)] = future.bounds else {
5266        // `async fn` should always lower to a single bound... but don't ICE.
5267        return None;
5268    };
5269    let Some(hir::PathSegment { args: Some(args), .. }) = trait_ref.trait_ref.path.segments.last()
5270    else {
5271        // desugaring to a single path segment for `Future<...>`.
5272        return None;
5273    };
5274    let Some(future_output_ty) = args.constraints.first().and_then(|constraint| constraint.ty())
5275    else {
5276        // Also should never happen.
5277        return None;
5278    };
5279
5280    let mut sugg = if future_output_ty.span.is_empty() {
5281        vec![
5282            (async_span, String::new()),
5283            (
5284                future_output_ty.span,
5285                format!(" -> impl std::future::Future<Output = ()>{add_bounds}"),
5286            ),
5287        ]
5288    } else {
5289        vec![
5290            (future_output_ty.span.shrink_to_lo(), "impl std::future::Future<Output = ".to_owned()),
5291            (future_output_ty.span.shrink_to_hi(), format!(">{add_bounds}")),
5292            (async_span, String::new()),
5293        ]
5294    };
5295
5296    // If there's a body, we also need to wrap it in `async {}`
5297    if let hir::TraitFn::Provided(body) = body {
5298        let body = tcx.hir_body(body);
5299        let body_span = body.value.span;
5300        let body_span_without_braces =
5301            body_span.with_lo(body_span.lo() + BytePos(1)).with_hi(body_span.hi() - BytePos(1));
5302        if body_span_without_braces.is_empty() {
5303            sugg.push((body_span_without_braces, " async {} ".to_owned()));
5304        } else {
5305            sugg.extend([
5306                (body_span_without_braces.shrink_to_lo(), "async {".to_owned()),
5307                (body_span_without_braces.shrink_to_hi(), "} ".to_owned()),
5308            ]);
5309        }
5310    }
5311
5312    Some(sugg)
5313}
5314
5315/// On `impl` evaluation cycles, look for `Self::AssocTy` restrictions in `where` clauses, explain
5316/// they are not allowed and if possible suggest alternatives.
5317fn point_at_assoc_type_restriction<G: EmissionGuarantee>(
5318    tcx: TyCtxt<'_>,
5319    err: &mut Diag<'_, G>,
5320    self_ty_str: &str,
5321    trait_name: &str,
5322    predicate: ty::Predicate<'_>,
5323    generics: &hir::Generics<'_>,
5324    data: &ImplDerivedCause<'_>,
5325) {
5326    let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() else {
5327        return;
5328    };
5329    let ty::ClauseKind::Projection(proj) = clause else {
5330        return;
5331    };
5332    let name = tcx.item_name(proj.projection_term.def_id);
5333    let mut predicates = generics.predicates.iter().peekable();
5334    let mut prev: Option<(&hir::WhereBoundPredicate<'_>, Span)> = None;
5335    while let Some(pred) = predicates.next() {
5336        let curr_span = pred.span;
5337        let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind else {
5338            continue;
5339        };
5340        let mut bounds = pred.bounds.iter();
5341        while let Some(bound) = bounds.next() {
5342            let Some(trait_ref) = bound.trait_ref() else {
5343                continue;
5344            };
5345            if bound.span() != data.span {
5346                continue;
5347            }
5348            if let hir::TyKind::Path(path) = pred.bounded_ty.kind
5349                && let hir::QPath::TypeRelative(ty, segment) = path
5350                && segment.ident.name == name
5351                && let hir::TyKind::Path(inner_path) = ty.kind
5352                && let hir::QPath::Resolved(None, inner_path) = inner_path
5353                && let Res::SelfTyAlias { .. } = inner_path.res
5354            {
5355                // The following block is to determine the right span to delete for this bound
5356                // that will leave valid code after the suggestion is applied.
5357                let span = if pred.origin == hir::PredicateOrigin::WhereClause
5358                    && generics
5359                        .predicates
5360                        .iter()
5361                        .filter(|p| {
5362                            matches!(
5363                                p.kind,
5364                                hir::WherePredicateKind::BoundPredicate(p)
5365                                if hir::PredicateOrigin::WhereClause == p.origin
5366                            )
5367                        })
5368                        .count()
5369                        == 1
5370                {
5371                    // There's only one `where` bound, that needs to be removed. Remove the whole
5372                    // `where` clause.
5373                    generics.where_clause_span
5374                } else if let Some(next_pred) = predicates.peek()
5375                    && let hir::WherePredicateKind::BoundPredicate(next) = next_pred.kind
5376                    && pred.origin == next.origin
5377                {
5378                    // There's another bound, include the comma for the current one.
5379                    curr_span.until(next_pred.span)
5380                } else if let Some((prev, prev_span)) = prev
5381                    && pred.origin == prev.origin
5382                {
5383                    // Last bound, try to remove the previous comma.
5384                    prev_span.shrink_to_hi().to(curr_span)
5385                } else if pred.origin == hir::PredicateOrigin::WhereClause {
5386                    curr_span.with_hi(generics.where_clause_span.hi())
5387                } else {
5388                    curr_span
5389                };
5390
5391                err.span_suggestion_verbose(
5392                    span,
5393                    "associated type for the current `impl` cannot be restricted in `where` \
5394                     clauses, remove this bound",
5395                    "",
5396                    Applicability::MaybeIncorrect,
5397                );
5398            }
5399            if let Some(new) =
5400                tcx.associated_items(data.impl_or_alias_def_id).find_by_name_and_kind(
5401                    tcx,
5402                    Ident::with_dummy_span(name),
5403                    ty::AssocKind::Type,
5404                    data.impl_or_alias_def_id,
5405                )
5406            {
5407                // The associated type is specified in the `impl` we're
5408                // looking at. Point at it.
5409                let span = tcx.def_span(new.def_id);
5410                err.span_label(
5411                    span,
5412                    format!(
5413                        "associated type `<{self_ty_str} as {trait_name}>::{name}` is specified \
5414                         here",
5415                    ),
5416                );
5417                // Search for the associated type `Self::{name}`, get
5418                // its type and suggest replacing the bound with it.
5419                let mut visitor = SelfVisitor { paths: vec![], name: Some(name) };
5420                visitor.visit_trait_ref(trait_ref);
5421                for path in visitor.paths {
5422                    err.span_suggestion_verbose(
5423                        path.span,
5424                        "replace the associated type with the type specified in this `impl`",
5425                        tcx.type_of(new.def_id).skip_binder(),
5426                        Applicability::MachineApplicable,
5427                    );
5428                }
5429            } else {
5430                let mut visitor = SelfVisitor { paths: vec![], name: None };
5431                visitor.visit_trait_ref(trait_ref);
5432                let span: MultiSpan =
5433                    visitor.paths.iter().map(|p| p.span).collect::<Vec<Span>>().into();
5434                err.span_note(
5435                    span,
5436                    "associated types for the current `impl` cannot be restricted in `where` \
5437                     clauses",
5438                );
5439            }
5440        }
5441        prev = Some((pred, curr_span));
5442    }
5443}
5444
5445fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec<hir::Mutability>) {
5446    let mut refs = vec![];
5447
5448    while let ty::Ref(_, new_ty, mutbl) = ty.kind() {
5449        ty = *new_ty;
5450        refs.push(*mutbl);
5451    }
5452
5453    (ty, refs)
5454}
5455
5456/// Look for type `param` in an ADT being used only through a reference to confirm that suggesting
5457/// `param: ?Sized` would be a valid constraint.
5458struct FindTypeParam {
5459    param: rustc_span::Symbol,
5460    invalid_spans: Vec<Span>,
5461    nested: bool,
5462}
5463
5464impl<'v> Visitor<'v> for FindTypeParam {
5465    fn visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>) {
5466        // Skip where-clauses, to avoid suggesting indirection for type parameters found there.
5467    }
5468
5469    fn visit_ty(&mut self, ty: &hir::Ty<'_, AmbigArg>) {
5470        // We collect the spans of all uses of the "bare" type param, like in `field: T` or
5471        // `field: (T, T)` where we could make `T: ?Sized` while skipping cases that are known to be
5472        // valid like `field: &'a T` or `field: *mut T` and cases that *might* have further `Sized`
5473        // obligations like `Box<T>` and `Vec<T>`, but we perform no extra analysis for those cases
5474        // and suggest `T: ?Sized` regardless of their obligations. This is fine because the errors
5475        // in that case should make what happened clear enough.
5476        match ty.kind {
5477            hir::TyKind::Ptr(_) | hir::TyKind::Ref(..) | hir::TyKind::TraitObject(..) => {}
5478            hir::TyKind::Path(hir::QPath::Resolved(None, path))
5479                if let [segment] = path.segments
5480                    && segment.ident.name == self.param =>
5481            {
5482                if !self.nested {
5483                    debug!(?ty, "FindTypeParam::visit_ty");
5484                    self.invalid_spans.push(ty.span);
5485                }
5486            }
5487            hir::TyKind::Path(_) => {
5488                let prev = self.nested;
5489                self.nested = true;
5490                hir::intravisit::walk_ty(self, ty);
5491                self.nested = prev;
5492            }
5493            _ => {
5494                hir::intravisit::walk_ty(self, ty);
5495            }
5496        }
5497    }
5498}