rustc_trait_selection/error_reporting/infer/
note_and_explain.rs

1use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect};
2use rustc_errors::{Diag, MultiSpan, pluralize};
3use rustc_hir as hir;
4use rustc_hir::def::DefKind;
5use rustc_middle::traits::{ObligationCause, ObligationCauseCode};
6use rustc_middle::ty::error::{ExpectedFound, TypeError};
7use rustc_middle::ty::fast_reject::DeepRejectCtxt;
8use rustc_middle::ty::print::{FmtPrinter, Printer};
9use rustc_middle::ty::{self, Ty, suggest_constraining_type_param};
10use rustc_span::def_id::DefId;
11use rustc_span::{BytePos, Span, Symbol, sym};
12use tracing::debug;
13
14use crate::error_reporting::TypeErrCtxt;
15use crate::infer::InferCtxtExt;
16
17impl<'tcx> TypeErrCtxt<'_, 'tcx> {
18    pub fn note_and_explain_type_err(
19        &self,
20        diag: &mut Diag<'_>,
21        err: TypeError<'tcx>,
22        cause: &ObligationCause<'tcx>,
23        sp: Span,
24        body_owner_def_id: DefId,
25    ) {
26        debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
27
28        let tcx = self.tcx;
29
30        match err {
31            TypeError::ArgumentSorts(values, _) | TypeError::Sorts(values) => {
32                match (*values.expected.kind(), *values.found.kind()) {
33                    (ty::Closure(..), ty::Closure(..)) => {
34                        diag.note("no two closures, even if identical, have the same type");
35                        diag.help("consider boxing your closure and/or using it as a trait object");
36                    }
37                    (ty::Coroutine(def_id1, ..), ty::Coroutine(def_id2, ..))
38                        if self.tcx.coroutine_is_async(def_id1)
39                            && self.tcx.coroutine_is_async(def_id2) =>
40                    {
41                        diag.note("no two async blocks, even if identical, have the same type");
42                        diag.help(
43                            "consider pinning your async block and casting it to a trait object",
44                        );
45                    }
46                    (ty::Alias(ty::Opaque, ..), ty::Alias(ty::Opaque, ..)) => {
47                        // Issue #63167
48                        diag.note("distinct uses of `impl Trait` result in different opaque types");
49                    }
50                    (ty::Float(_), ty::Infer(ty::IntVar(_)))
51                        if let Ok(
52                            // Issue #53280
53                            snippet,
54                        ) = tcx.sess.source_map().span_to_snippet(sp) =>
55                    {
56                        if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
57                            diag.span_suggestion_verbose(
58                                sp.shrink_to_hi(),
59                                "use a float literal",
60                                ".0",
61                                MachineApplicable,
62                            );
63                        }
64                    }
65                    (ty::Param(expected), ty::Param(found)) => {
66                        let generics = tcx.generics_of(body_owner_def_id);
67                        let e_span = tcx.def_span(generics.type_param(expected, tcx).def_id);
68                        if !sp.contains(e_span) {
69                            diag.span_label(e_span, "expected type parameter");
70                        }
71                        let f_span = tcx.def_span(generics.type_param(found, tcx).def_id);
72                        if !sp.contains(f_span) {
73                            diag.span_label(f_span, "found type parameter");
74                        }
75                        diag.note(
76                            "a type parameter was expected, but a different one was found; \
77                             you might be missing a type parameter or trait bound",
78                        );
79                        diag.note(
80                            "for more information, visit \
81                             https://doc.rust-lang.org/book/ch10-02-traits.html\
82                             #traits-as-parameters",
83                        );
84                    }
85                    (
86                        ty::Alias(ty::Projection | ty::Inherent, _),
87                        ty::Alias(ty::Projection | ty::Inherent, _),
88                    ) => {
89                        diag.note("an associated type was expected, but a different one was found");
90                    }
91                    // FIXME(inherent_associated_types): Extend this to support `ty::Inherent`, too.
92                    (ty::Param(p), ty::Alias(ty::Projection, proj))
93                    | (ty::Alias(ty::Projection, proj), ty::Param(p))
94                        if !tcx.is_impl_trait_in_trait(proj.def_id) =>
95                    {
96                        let param = tcx.generics_of(body_owner_def_id).type_param(p, tcx);
97                        let p_def_id = param.def_id;
98                        let p_span = tcx.def_span(p_def_id);
99                        let expected = match (values.expected.kind(), values.found.kind()) {
100                            (ty::Param(_), _) => "expected ",
101                            (_, ty::Param(_)) => "found ",
102                            _ => "",
103                        };
104                        if !sp.contains(p_span) {
105                            diag.span_label(p_span, format!("{expected}this type parameter"));
106                        }
107                        let parent = p_def_id.as_local().and_then(|id| {
108                            let local_id = tcx.local_def_id_to_hir_id(id);
109                            let generics = tcx.parent_hir_node(local_id).generics()?;
110                            Some((id, generics))
111                        });
112                        let mut note = true;
113                        if let Some((local_id, generics)) = parent {
114                            // Synthesize the associated type restriction `Add<Output = Expected>`.
115                            // FIXME: extract this logic for use in other diagnostics.
116                            let (trait_ref, assoc_args) = proj.trait_ref_and_own_args(tcx);
117                            let item_name = tcx.item_name(proj.def_id);
118                            let item_args = self.format_generic_args(assoc_args);
119
120                            // Here, we try to see if there's an existing
121                            // trait implementation that matches the one that
122                            // we're suggesting to restrict. If so, find the
123                            // "end", whether it be at the end of the trait
124                            // or the end of the generic arguments.
125                            let mut matching_span = None;
126                            let mut matched_end_of_args = false;
127                            for bound in generics.bounds_for_param(local_id) {
128                                let potential_spans = bound.bounds.iter().find_map(|bound| {
129                                    let bound_trait_path = bound.trait_ref()?.path;
130                                    let def_id = bound_trait_path.res.opt_def_id()?;
131                                    let generic_args = bound_trait_path
132                                        .segments
133                                        .iter()
134                                        .last()
135                                        .map(|path| path.args());
136                                    (def_id == trait_ref.def_id)
137                                        .then_some((bound_trait_path.span, generic_args))
138                                });
139
140                                if let Some((end_of_trait, end_of_args)) = potential_spans {
141                                    let args_span = end_of_args.and_then(|args| args.span());
142                                    matched_end_of_args = args_span.is_some();
143                                    matching_span = args_span
144                                        .or_else(|| Some(end_of_trait))
145                                        .map(|span| span.shrink_to_hi());
146                                    break;
147                                }
148                            }
149
150                            if matched_end_of_args {
151                                // Append suggestion to the end of our args
152                                let path = format!(", {item_name}{item_args} = {p}");
153                                note = !suggest_constraining_type_param(
154                                    tcx,
155                                    generics,
156                                    diag,
157                                    &proj.self_ty().to_string(),
158                                    &path,
159                                    None,
160                                    matching_span,
161                                );
162                            } else {
163                                // Suggest adding a bound to an existing trait
164                                // or if the trait doesn't exist, add the trait
165                                // and the suggested bounds.
166                                let path = format!("<{item_name}{item_args} = {p}>");
167                                note = !suggest_constraining_type_param(
168                                    tcx,
169                                    generics,
170                                    diag,
171                                    &proj.self_ty().to_string(),
172                                    &path,
173                                    None,
174                                    matching_span,
175                                );
176                            }
177                        }
178                        if note {
179                            diag.note("you might be missing a type parameter or trait bound");
180                        }
181                    }
182                    (ty::Param(p), ty::Dynamic(..) | ty::Alias(ty::Opaque, ..))
183                    | (ty::Dynamic(..) | ty::Alias(ty::Opaque, ..), ty::Param(p)) => {
184                        let generics = tcx.generics_of(body_owner_def_id);
185                        let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
186                        let expected = match (values.expected.kind(), values.found.kind()) {
187                            (ty::Param(_), _) => "expected ",
188                            (_, ty::Param(_)) => "found ",
189                            _ => "",
190                        };
191                        if !sp.contains(p_span) {
192                            diag.span_label(p_span, format!("{expected}this type parameter"));
193                        }
194                        diag.help("type parameters must be constrained to match other types");
195                        if diag.code.is_some_and(|code| tcx.sess.teach(code)) {
196                            diag.help(
197                                "given a type parameter `T` and a method `foo`:
198```
199trait Trait<T> { fn foo(&self) -> T; }
200```
201the only ways to implement method `foo` are:
202- constrain `T` with an explicit type:
203```
204impl Trait<String> for X {
205    fn foo(&self) -> String { String::new() }
206}
207```
208- add a trait bound to `T` and call a method on that trait that returns `Self`:
209```
210impl<T: std::default::Default> Trait<T> for X {
211    fn foo(&self) -> T { <T as std::default::Default>::default() }
212}
213```
214- change `foo` to return an argument of type `T`:
215```
216impl<T> Trait<T> for X {
217    fn foo(&self, x: T) -> T { x }
218}
219```",
220                            );
221                        }
222                        diag.note(
223                            "for more information, visit \
224                             https://doc.rust-lang.org/book/ch10-02-traits.html\
225                             #traits-as-parameters",
226                        );
227                    }
228                    (
229                        ty::Param(p),
230                        ty::Closure(..) | ty::CoroutineClosure(..) | ty::Coroutine(..),
231                    ) => {
232                        let generics = tcx.generics_of(body_owner_def_id);
233                        let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
234                        if !sp.contains(p_span) {
235                            diag.span_label(p_span, "expected this type parameter");
236                        }
237                        diag.help(format!(
238                            "every closure has a distinct type and so could not always match the \
239                             caller-chosen type of parameter `{p}`"
240                        ));
241                    }
242                    (ty::Param(p), _) | (_, ty::Param(p)) => {
243                        let generics = tcx.generics_of(body_owner_def_id);
244                        let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
245                        let expected = match (values.expected.kind(), values.found.kind()) {
246                            (ty::Param(_), _) => "expected ",
247                            (_, ty::Param(_)) => "found ",
248                            _ => "",
249                        };
250                        if !sp.contains(p_span) {
251                            diag.span_label(p_span, format!("{expected}this type parameter"));
252                        }
253                    }
254                    (ty::Alias(ty::Projection | ty::Inherent, proj_ty), _)
255                        if !tcx.is_impl_trait_in_trait(proj_ty.def_id) =>
256                    {
257                        self.expected_projection(
258                            diag,
259                            proj_ty,
260                            values,
261                            body_owner_def_id,
262                            cause.code(),
263                        );
264                    }
265                    (_, ty::Alias(ty::Projection | ty::Inherent, proj_ty))
266                        if !tcx.is_impl_trait_in_trait(proj_ty.def_id) =>
267                    {
268                        let msg = || {
269                            format!(
270                                "consider constraining the associated type `{}` to `{}`",
271                                values.found, values.expected,
272                            )
273                        };
274                        if !(self.suggest_constraining_opaque_associated_type(
275                            diag,
276                            msg,
277                            proj_ty,
278                            values.expected,
279                        ) || self.suggest_constraint(
280                            diag,
281                            &msg,
282                            body_owner_def_id,
283                            proj_ty,
284                            values.expected,
285                        )) {
286                            diag.help(msg());
287                            diag.note(
288                                "for more information, visit \
289                                https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
290                            );
291                        }
292                    }
293                    (ty::Dynamic(t, _, ty::DynKind::Dyn), ty::Alias(ty::Opaque, alias))
294                        if let Some(def_id) = t.principal_def_id()
295                            && tcx
296                                .explicit_item_self_bounds(alias.def_id)
297                                .skip_binder()
298                                .iter()
299                                .any(|(pred, _span)| match pred.kind().skip_binder() {
300                                    ty::ClauseKind::Trait(trait_predicate)
301                                        if trait_predicate.polarity
302                                            == ty::PredicatePolarity::Positive =>
303                                    {
304                                        trait_predicate.def_id() == def_id
305                                    }
306                                    _ => false,
307                                }) =>
308                    {
309                        diag.help(format!(
310                            "you can box the `{}` to coerce it to `Box<{}>`, but you'll have to \
311                             change the expected type as well",
312                            values.found, values.expected,
313                        ));
314                    }
315                    (ty::Dynamic(t, _, ty::DynKind::Dyn), _)
316                        if let Some(def_id) = t.principal_def_id() =>
317                    {
318                        let mut has_matching_impl = false;
319                        tcx.for_each_relevant_impl(def_id, values.found, |did| {
320                            if DeepRejectCtxt::relate_rigid_infer(tcx)
321                                .types_may_unify(values.found, tcx.type_of(did).skip_binder())
322                            {
323                                has_matching_impl = true;
324                            }
325                        });
326                        if has_matching_impl {
327                            let trait_name = tcx.item_name(def_id);
328                            diag.help(format!(
329                                "`{}` implements `{trait_name}` so you could box the found value \
330                                 and coerce it to the trait object `Box<dyn {trait_name}>`, you \
331                                 will have to change the expected type as well",
332                                values.found,
333                            ));
334                        }
335                    }
336                    (_, ty::Dynamic(t, _, ty::DynKind::Dyn))
337                        if let Some(def_id) = t.principal_def_id() =>
338                    {
339                        let mut has_matching_impl = false;
340                        tcx.for_each_relevant_impl(def_id, values.expected, |did| {
341                            if DeepRejectCtxt::relate_rigid_infer(tcx)
342                                .types_may_unify(values.expected, tcx.type_of(did).skip_binder())
343                            {
344                                has_matching_impl = true;
345                            }
346                        });
347                        if has_matching_impl {
348                            let trait_name = tcx.item_name(def_id);
349                            diag.help(format!(
350                                "`{}` implements `{trait_name}` so you could change the expected \
351                                 type to `Box<dyn {trait_name}>`",
352                                values.expected,
353                            ));
354                        }
355                    }
356                    (ty::Dynamic(t, _, ty::DynKind::DynStar), _)
357                        if let Some(def_id) = t.principal_def_id() =>
358                    {
359                        let mut has_matching_impl = false;
360                        tcx.for_each_relevant_impl(def_id, values.found, |did| {
361                            if DeepRejectCtxt::relate_rigid_infer(tcx)
362                                .types_may_unify(values.found, tcx.type_of(did).skip_binder())
363                            {
364                                has_matching_impl = true;
365                            }
366                        });
367                        if has_matching_impl {
368                            let trait_name = tcx.item_name(def_id);
369                            diag.help(format!(
370                                "`{}` implements `{trait_name}`, `#[feature(dyn_star)]` is likely \
371                                 not enabled; that feature it is currently incomplete",
372                                values.found,
373                            ));
374                        }
375                    }
376                    (_, ty::Alias(ty::Opaque, opaque_ty))
377                    | (ty::Alias(ty::Opaque, opaque_ty), _) => {
378                        if opaque_ty.def_id.is_local()
379                            && matches!(
380                                tcx.def_kind(body_owner_def_id),
381                                DefKind::Fn
382                                    | DefKind::Static { .. }
383                                    | DefKind::Const
384                                    | DefKind::AssocFn
385                                    | DefKind::AssocConst
386                            )
387                            && matches!(
388                                tcx.opaque_ty_origin(opaque_ty.def_id),
389                                hir::OpaqueTyOrigin::TyAlias { .. }
390                            )
391                            && !tcx
392                                .opaque_types_defined_by(body_owner_def_id.expect_local())
393                                .contains(&opaque_ty.def_id.expect_local())
394                        {
395                            let sp = tcx
396                                .def_ident_span(body_owner_def_id)
397                                .unwrap_or_else(|| tcx.def_span(body_owner_def_id));
398                            diag.span_note(
399                                sp,
400                                "this item must have the opaque type in its signature in order to \
401                                 be able to register hidden types",
402                            );
403                        }
404                        // If two if arms can be coerced to a trait object, provide a structured
405                        // suggestion.
406                        let ObligationCauseCode::IfExpression(cause) = cause.code() else {
407                            return;
408                        };
409                        let hir::Node::Block(blk) = self.tcx.hir_node(cause.then_id) else {
410                            return;
411                        };
412                        let Some(then) = blk.expr else {
413                            return;
414                        };
415                        let hir::Node::Block(blk) = self.tcx.hir_node(cause.else_id) else {
416                            return;
417                        };
418                        let Some(else_) = blk.expr else {
419                            return;
420                        };
421                        let expected = match values.found.kind() {
422                            ty::Alias(..) => values.expected,
423                            _ => values.found,
424                        };
425                        let preds = tcx.explicit_item_self_bounds(opaque_ty.def_id);
426                        for (pred, _span) in preds.skip_binder() {
427                            let ty::ClauseKind::Trait(trait_predicate) = pred.kind().skip_binder()
428                            else {
429                                continue;
430                            };
431                            if trait_predicate.polarity != ty::PredicatePolarity::Positive {
432                                continue;
433                            }
434                            let def_id = trait_predicate.def_id();
435                            let mut impl_def_ids = vec![];
436                            tcx.for_each_relevant_impl(def_id, expected, |did| {
437                                impl_def_ids.push(did)
438                            });
439                            if let [_] = &impl_def_ids[..] {
440                                let trait_name = tcx.item_name(def_id);
441                                diag.multipart_suggestion(
442                                    format!(
443                                        "`{expected}` implements `{trait_name}` so you can box \
444                                         both arms and coerce to the trait object \
445                                         `Box<dyn {trait_name}>`",
446                                    ),
447                                    vec![
448                                        (then.span.shrink_to_lo(), "Box::new(".to_string()),
449                                        (
450                                            then.span.shrink_to_hi(),
451                                            format!(") as Box<dyn {}>", tcx.def_path_str(def_id)),
452                                        ),
453                                        (else_.span.shrink_to_lo(), "Box::new(".to_string()),
454                                        (else_.span.shrink_to_hi(), ")".to_string()),
455                                    ],
456                                    MachineApplicable,
457                                );
458                            }
459                        }
460                    }
461                    (ty::FnPtr(_, hdr), ty::FnDef(def_id, _))
462                    | (ty::FnDef(def_id, _), ty::FnPtr(_, hdr)) => {
463                        if tcx.fn_sig(def_id).skip_binder().safety() < hdr.safety {
464                            if !tcx.codegen_fn_attrs(def_id).safe_target_features {
465                                diag.note(
466                                "unsafe functions cannot be coerced into safe function pointers",
467                                );
468                            }
469                        }
470                    }
471                    (ty::Adt(_, _), ty::Adt(def, args))
472                        if let ObligationCauseCode::IfExpression(cause) = cause.code()
473                            && let hir::Node::Block(blk) = self.tcx.hir_node(cause.then_id)
474                            && let Some(then) = blk.expr
475                            && def.is_box()
476                            && let boxed_ty = args.type_at(0)
477                            && let ty::Dynamic(t, _, _) = boxed_ty.kind()
478                            && let Some(def_id) = t.principal_def_id()
479                            && let mut impl_def_ids = vec![]
480                            && let _ =
481                                tcx.for_each_relevant_impl(def_id, values.expected, |did| {
482                                    impl_def_ids.push(did)
483                                })
484                            && let [_] = &impl_def_ids[..] =>
485                    {
486                        // We have divergent if/else arms where the expected value is a type that
487                        // implements the trait of the found boxed trait object.
488                        diag.multipart_suggestion(
489                            format!(
490                                "`{}` implements `{}` so you can box it to coerce to the trait \
491                                 object `{}`",
492                                values.expected,
493                                tcx.item_name(def_id),
494                                values.found,
495                            ),
496                            vec![
497                                (then.span.shrink_to_lo(), "Box::new(".to_string()),
498                                (then.span.shrink_to_hi(), ")".to_string()),
499                            ],
500                            MachineApplicable,
501                        );
502                    }
503                    _ => {}
504                }
505                debug!(
506                    "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
507                    values.expected,
508                    values.expected.kind(),
509                    values.found,
510                    values.found.kind(),
511                );
512            }
513            TypeError::CyclicTy(ty) => {
514                // Watch out for various cases of cyclic types and try to explain.
515                if ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure() {
516                    diag.note(
517                        "closures cannot capture themselves or take themselves as argument;\n\
518                         this error may be the result of a recent compiler bug-fix,\n\
519                         see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
520                         for more information",
521                    );
522                }
523            }
524            TypeError::TargetFeatureCast(def_id) => {
525                let target_spans = tcx.get_attrs(def_id, sym::target_feature).map(|attr| attr.span);
526                diag.note(
527                    "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
528                );
529                diag.span_labels(target_spans, "`#[target_feature]` added here");
530            }
531            _ => {}
532        }
533    }
534
535    fn suggest_constraint(
536        &self,
537        diag: &mut Diag<'_>,
538        msg: impl Fn() -> String,
539        body_owner_def_id: DefId,
540        proj_ty: ty::AliasTy<'tcx>,
541        ty: Ty<'tcx>,
542    ) -> bool {
543        let tcx = self.tcx;
544        let assoc = tcx.associated_item(proj_ty.def_id);
545        let (trait_ref, assoc_args) = proj_ty.trait_ref_and_own_args(tcx);
546        let Some(item) = tcx.hir().get_if_local(body_owner_def_id) else {
547            return false;
548        };
549        let Some(hir_generics) = item.generics() else {
550            return false;
551        };
552        // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
553        // This will also work for `impl Trait`.
554        let ty::Param(param_ty) = *proj_ty.self_ty().kind() else {
555            return false;
556        };
557        let generics = tcx.generics_of(body_owner_def_id);
558        let def_id = generics.type_param(param_ty, tcx).def_id;
559        let Some(def_id) = def_id.as_local() else {
560            return false;
561        };
562
563        // First look in the `where` clause, as this might be
564        // `fn foo<T>(x: T) where T: Trait`.
565        for pred in hir_generics.bounds_for_param(def_id) {
566            if self.constrain_generic_bound_associated_type_structured_suggestion(
567                diag,
568                trait_ref,
569                pred.bounds,
570                assoc,
571                assoc_args,
572                ty,
573                &msg,
574                false,
575            ) {
576                return true;
577            }
578        }
579        if (param_ty.index as usize) >= generics.parent_count {
580            // The param comes from the current item, do not look at the parent. (#117209)
581            return false;
582        }
583        // If associated item, look to constrain the params of the trait/impl.
584        let hir_id = match item {
585            hir::Node::ImplItem(item) => item.hir_id(),
586            hir::Node::TraitItem(item) => item.hir_id(),
587            _ => return false,
588        };
589        let parent = tcx.hir().get_parent_item(hir_id).def_id;
590        self.suggest_constraint(diag, msg, parent.into(), proj_ty, ty)
591    }
592
593    /// An associated type was expected and a different type was found.
594    ///
595    /// We perform a few different checks to see what we can suggest:
596    ///
597    ///  - In the current item, look for associated functions that return the expected type and
598    ///    suggest calling them. (Not a structured suggestion.)
599    ///  - If any of the item's generic bounds can be constrained, we suggest constraining the
600    ///    associated type to the found type.
601    ///  - If the associated type has a default type and was expected inside of a `trait`, we
602    ///    mention that this is disallowed.
603    ///  - If all other things fail, and the error is not because of a mismatch between the `trait`
604    ///    and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
605    ///    fn that returns the type.
606    fn expected_projection(
607        &self,
608        diag: &mut Diag<'_>,
609        proj_ty: ty::AliasTy<'tcx>,
610        values: ExpectedFound<Ty<'tcx>>,
611        body_owner_def_id: DefId,
612        cause_code: &ObligationCauseCode<'_>,
613    ) {
614        let tcx = self.tcx;
615
616        // Don't suggest constraining a projection to something containing itself
617        if self.tcx.erase_regions(values.found).contains(self.tcx.erase_regions(values.expected)) {
618            return;
619        }
620
621        let msg = || {
622            format!(
623                "consider constraining the associated type `{}` to `{}`",
624                values.expected, values.found
625            )
626        };
627
628        let body_owner = tcx.hir().get_if_local(body_owner_def_id);
629        let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
630
631        // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
632        let callable_scope = matches!(
633            body_owner,
634            Some(
635                hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { .. }, .. })
636                    | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
637                    | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
638            )
639        );
640        let impl_comparison = matches!(cause_code, ObligationCauseCode::CompareImplItem { .. });
641        let assoc = tcx.associated_item(proj_ty.def_id);
642        if impl_comparison {
643            // We do not want to suggest calling functions when the reason of the
644            // type error is a comparison of an `impl` with its `trait`.
645        } else {
646            let point_at_assoc_fn = if callable_scope
647                && self.point_at_methods_that_satisfy_associated_type(
648                    diag,
649                    assoc.container_id(tcx),
650                    current_method_ident,
651                    proj_ty.def_id,
652                    values.expected,
653                ) {
654                // If we find a suitable associated function that returns the expected type, we
655                // don't want the more general suggestion later in this method about "consider
656                // constraining the associated type or calling a method that returns the associated
657                // type".
658                true
659            } else {
660                false
661            };
662            // Possibly suggest constraining the associated type to conform to the
663            // found type.
664            if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found)
665                || point_at_assoc_fn
666            {
667                return;
668            }
669        }
670
671        self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found);
672
673        if self.point_at_associated_type(diag, body_owner_def_id, values.found) {
674            return;
675        }
676
677        if !impl_comparison {
678            // Generic suggestion when we can't be more specific.
679            if callable_scope {
680                diag.help(format!(
681                    "{} or calling a method that returns `{}`",
682                    msg(),
683                    values.expected
684                ));
685            } else {
686                diag.help(msg());
687            }
688            diag.note(
689                "for more information, visit \
690                 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
691            );
692        }
693        if diag.code.is_some_and(|code| tcx.sess.teach(code)) {
694            diag.help(
695                "given an associated type `T` and a method `foo`:
696```
697trait Trait {
698type T;
699fn foo(&self) -> Self::T;
700}
701```
702the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
703```
704impl Trait for X {
705type T = String;
706fn foo(&self) -> Self::T { String::new() }
707}
708```",
709            );
710        }
711    }
712
713    /// When the expected `impl Trait` is not defined in the current item, it will come from
714    /// a return type. This can occur when dealing with `TryStream` (#71035).
715    fn suggest_constraining_opaque_associated_type(
716        &self,
717        diag: &mut Diag<'_>,
718        msg: impl Fn() -> String,
719        proj_ty: ty::AliasTy<'tcx>,
720        ty: Ty<'tcx>,
721    ) -> bool {
722        let tcx = self.tcx;
723
724        let assoc = tcx.associated_item(proj_ty.def_id);
725        if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *proj_ty.self_ty().kind() {
726            let opaque_local_def_id = def_id.as_local();
727            let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
728                tcx.hir().expect_opaque_ty(opaque_local_def_id)
729            } else {
730                return false;
731            };
732
733            let (trait_ref, assoc_args) = proj_ty.trait_ref_and_own_args(tcx);
734
735            self.constrain_generic_bound_associated_type_structured_suggestion(
736                diag,
737                trait_ref,
738                opaque_hir_ty.bounds,
739                assoc,
740                assoc_args,
741                ty,
742                msg,
743                true,
744            )
745        } else {
746            false
747        }
748    }
749
750    fn point_at_methods_that_satisfy_associated_type(
751        &self,
752        diag: &mut Diag<'_>,
753        assoc_container_id: DefId,
754        current_method_ident: Option<Symbol>,
755        proj_ty_item_def_id: DefId,
756        expected: Ty<'tcx>,
757    ) -> bool {
758        let tcx = self.tcx;
759
760        let items = tcx.associated_items(assoc_container_id);
761        // Find all the methods in the trait that could be called to construct the
762        // expected associated type.
763        // FIXME: consider suggesting the use of associated `const`s.
764        let methods: Vec<(Span, String)> = items
765            .in_definition_order()
766            .filter(|item| {
767                ty::AssocKind::Fn == item.kind
768                    && Some(item.name) != current_method_ident
769                    && !tcx.is_doc_hidden(item.def_id)
770            })
771            .filter_map(|item| {
772                let method = tcx.fn_sig(item.def_id).instantiate_identity();
773                match *method.output().skip_binder().kind() {
774                    ty::Alias(ty::Projection, ty::AliasTy { def_id: item_def_id, .. })
775                        if item_def_id == proj_ty_item_def_id =>
776                    {
777                        Some((
778                            tcx.def_span(item.def_id),
779                            format!("consider calling `{}`", tcx.def_path_str(item.def_id)),
780                        ))
781                    }
782                    _ => None,
783                }
784            })
785            .collect();
786        if !methods.is_empty() {
787            // Use a single `help:` to show all the methods in the trait that can
788            // be used to construct the expected associated type.
789            let mut span: MultiSpan =
790                methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
791            let msg = format!(
792                "{some} method{s} {are} available that return{r} `{ty}`",
793                some = if methods.len() == 1 { "a" } else { "some" },
794                s = pluralize!(methods.len()),
795                are = pluralize!("is", methods.len()),
796                r = if methods.len() == 1 { "s" } else { "" },
797                ty = expected
798            );
799            for (sp, label) in methods.into_iter() {
800                span.push_span_label(sp, label);
801            }
802            diag.span_help(span, msg);
803            return true;
804        }
805        false
806    }
807
808    fn point_at_associated_type(
809        &self,
810        diag: &mut Diag<'_>,
811        body_owner_def_id: DefId,
812        found: Ty<'tcx>,
813    ) -> bool {
814        let tcx = self.tcx;
815
816        let Some(def_id) = body_owner_def_id.as_local() else {
817            return false;
818        };
819
820        // When `body_owner` is an `impl` or `trait` item, look in its associated types for
821        // `expected` and point at it.
822        let hir_id = tcx.local_def_id_to_hir_id(def_id);
823        let parent_id = tcx.hir().get_parent_item(hir_id);
824        let item = tcx.hir_node_by_def_id(parent_id.def_id);
825
826        debug!("expected_projection parent item {:?}", item);
827
828        let param_env = tcx.param_env(body_owner_def_id);
829
830        match item {
831            hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. }) => {
832                // FIXME: account for `#![feature(specialization)]`
833                for item in &items[..] {
834                    match item.kind {
835                        hir::AssocItemKind::Type => {
836                            // FIXME: account for returning some type in a trait fn impl that has
837                            // an assoc type as a return type (#72076).
838                            if let hir::Defaultness::Default { has_value: true } =
839                                tcx.defaultness(item.id.owner_id)
840                            {
841                                let assoc_ty = tcx.type_of(item.id.owner_id).instantiate_identity();
842                                if self.infcx.can_eq(param_env, assoc_ty, found) {
843                                    diag.span_label(
844                                        item.span,
845                                        "associated type defaults can't be assumed inside the \
846                                            trait defining them",
847                                    );
848                                    return true;
849                                }
850                            }
851                        }
852                        _ => {}
853                    }
854                }
855            }
856            hir::Node::Item(hir::Item {
857                kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
858                ..
859            }) => {
860                for item in &items[..] {
861                    if let hir::AssocItemKind::Type = item.kind {
862                        let assoc_ty = tcx.type_of(item.id.owner_id).instantiate_identity();
863                        if let hir::Defaultness::Default { has_value: true } =
864                            tcx.defaultness(item.id.owner_id)
865                            && self.infcx.can_eq(param_env, assoc_ty, found)
866                        {
867                            diag.span_label(
868                                item.span,
869                                "associated type is `default` and may be overridden",
870                            );
871                            return true;
872                        }
873                    }
874                }
875            }
876            _ => {}
877        }
878        false
879    }
880
881    /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
882    /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
883    ///
884    /// `is_bound_surely_present` indicates whether we know the bound we're looking for is
885    /// inside `bounds`. If that's the case then we can consider `bounds` containing only one
886    /// trait bound as the one we're looking for. This can help in cases where the associated
887    /// type is defined on a supertrait of the one present in the bounds.
888    fn constrain_generic_bound_associated_type_structured_suggestion(
889        &self,
890        diag: &mut Diag<'_>,
891        trait_ref: ty::TraitRef<'tcx>,
892        bounds: hir::GenericBounds<'_>,
893        assoc: ty::AssocItem,
894        assoc_args: &[ty::GenericArg<'tcx>],
895        ty: Ty<'tcx>,
896        msg: impl Fn() -> String,
897        is_bound_surely_present: bool,
898    ) -> bool {
899        // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
900
901        let trait_bounds = bounds.iter().filter_map(|bound| match bound {
902            hir::GenericBound::Trait(ptr) if ptr.modifiers == hir::TraitBoundModifiers::NONE => {
903                Some(ptr)
904            }
905            _ => None,
906        });
907
908        let matching_trait_bounds = trait_bounds
909            .clone()
910            .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
911            .collect::<Vec<_>>();
912
913        let span = match &matching_trait_bounds[..] {
914            &[ptr] => ptr.span,
915            &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
916                &[ptr] => ptr.span,
917                _ => return false,
918            },
919            _ => return false,
920        };
921
922        self.constrain_associated_type_structured_suggestion(diag, span, assoc, assoc_args, ty, msg)
923    }
924
925    /// Given a span corresponding to a bound, provide a structured suggestion to set an
926    /// associated type to a given type `ty`.
927    fn constrain_associated_type_structured_suggestion(
928        &self,
929        diag: &mut Diag<'_>,
930        span: Span,
931        assoc: ty::AssocItem,
932        assoc_args: &[ty::GenericArg<'tcx>],
933        ty: Ty<'tcx>,
934        msg: impl Fn() -> String,
935    ) -> bool {
936        let tcx = self.tcx;
937
938        if let Ok(has_params) =
939            tcx.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
940        {
941            let (span, sugg) = if has_params {
942                let pos = span.hi() - BytePos(1);
943                let span = Span::new(pos, pos, span.ctxt(), span.parent());
944                (span, format!(", {} = {}", assoc.ident(tcx), ty))
945            } else {
946                let item_args = self.format_generic_args(assoc_args);
947                (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(tcx), item_args, ty))
948            };
949            diag.span_suggestion_verbose(span, msg(), sugg, MaybeIncorrect);
950            return true;
951        }
952        false
953    }
954
955    pub fn format_generic_args(&self, args: &[ty::GenericArg<'tcx>]) -> String {
956        FmtPrinter::print_string(self.tcx, hir::def::Namespace::TypeNS, |cx| {
957            cx.path_generic_args(|_| Ok(()), args)
958        })
959        .expect("could not write to `String`.")
960    }
961}