rustc_trait_selection/error_reporting/traits/
suggestions.rs

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