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