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                            let mut alias_def_id = opaque_ty.def_id;
399                            while let DefKind::OpaqueTy = tcx.def_kind(alias_def_id) {
400                                alias_def_id = tcx.parent(alias_def_id);
401                            }
402                            let opaque_path = tcx.def_path_str(alias_def_id);
403                            // FIXME(type_alias_impl_trait): make this a structured suggestion
404                            match tcx.opaque_ty_origin(opaque_ty.def_id) {
405                                rustc_hir::OpaqueTyOrigin::FnReturn { .. } => {}
406                                rustc_hir::OpaqueTyOrigin::AsyncFn { .. } => {}
407                                rustc_hir::OpaqueTyOrigin::TyAlias {
408                                    in_assoc_ty: false, ..
409                                } => {
410                                    diag.span_note(
411                                        sp,
412                                        format!("this item must have a `#[define_opaque({opaque_path})]` \
413                                        attribute to be able to define hidden types"),
414                                    );
415                                }
416                                rustc_hir::OpaqueTyOrigin::TyAlias {
417                                    in_assoc_ty: true, ..
418                                } => {}
419                            }
420                        }
421                        // If two if arms can be coerced to a trait object, provide a structured
422                        // suggestion.
423                        let ObligationCauseCode::IfExpression(cause) = cause.code() else {
424                            return;
425                        };
426                        let hir::Node::Block(blk) = self.tcx.hir_node(cause.then_id) else {
427                            return;
428                        };
429                        let Some(then) = blk.expr else {
430                            return;
431                        };
432                        let hir::Node::Block(blk) = self.tcx.hir_node(cause.else_id) else {
433                            return;
434                        };
435                        let Some(else_) = blk.expr else {
436                            return;
437                        };
438                        let expected = match values.found.kind() {
439                            ty::Alias(..) => values.expected,
440                            _ => values.found,
441                        };
442                        let preds = tcx.explicit_item_self_bounds(opaque_ty.def_id);
443                        for (pred, _span) in preds.skip_binder() {
444                            let ty::ClauseKind::Trait(trait_predicate) = pred.kind().skip_binder()
445                            else {
446                                continue;
447                            };
448                            if trait_predicate.polarity != ty::PredicatePolarity::Positive {
449                                continue;
450                            }
451                            let def_id = trait_predicate.def_id();
452                            let mut impl_def_ids = vec![];
453                            tcx.for_each_relevant_impl(def_id, expected, |did| {
454                                impl_def_ids.push(did)
455                            });
456                            if let [_] = &impl_def_ids[..] {
457                                let trait_name = tcx.item_name(def_id);
458                                diag.multipart_suggestion(
459                                    format!(
460                                        "`{expected}` implements `{trait_name}` so you can box \
461                                         both arms and coerce to the trait object \
462                                         `Box<dyn {trait_name}>`",
463                                    ),
464                                    vec![
465                                        (then.span.shrink_to_lo(), "Box::new(".to_string()),
466                                        (
467                                            then.span.shrink_to_hi(),
468                                            format!(") as Box<dyn {}>", tcx.def_path_str(def_id)),
469                                        ),
470                                        (else_.span.shrink_to_lo(), "Box::new(".to_string()),
471                                        (else_.span.shrink_to_hi(), ")".to_string()),
472                                    ],
473                                    MachineApplicable,
474                                );
475                            }
476                        }
477                    }
478                    (ty::FnPtr(_, hdr), ty::FnDef(def_id, _))
479                    | (ty::FnDef(def_id, _), ty::FnPtr(_, hdr)) => {
480                        if tcx.fn_sig(def_id).skip_binder().safety() < hdr.safety {
481                            if !tcx.codegen_fn_attrs(def_id).safe_target_features {
482                                diag.note(
483                                "unsafe functions cannot be coerced into safe function pointers",
484                                );
485                            }
486                        }
487                    }
488                    (ty::Adt(_, _), ty::Adt(def, args))
489                        if let ObligationCauseCode::IfExpression(cause) = cause.code()
490                            && let hir::Node::Block(blk) = self.tcx.hir_node(cause.then_id)
491                            && let Some(then) = blk.expr
492                            && def.is_box()
493                            && let boxed_ty = args.type_at(0)
494                            && let ty::Dynamic(t, _, _) = boxed_ty.kind()
495                            && let Some(def_id) = t.principal_def_id()
496                            && let mut impl_def_ids = vec![]
497                            && let _ =
498                                tcx.for_each_relevant_impl(def_id, values.expected, |did| {
499                                    impl_def_ids.push(did)
500                                })
501                            && let [_] = &impl_def_ids[..] =>
502                    {
503                        // We have divergent if/else arms where the expected value is a type that
504                        // implements the trait of the found boxed trait object.
505                        diag.multipart_suggestion(
506                            format!(
507                                "`{}` implements `{}` so you can box it to coerce to the trait \
508                                 object `{}`",
509                                values.expected,
510                                tcx.item_name(def_id),
511                                values.found,
512                            ),
513                            vec![
514                                (then.span.shrink_to_lo(), "Box::new(".to_string()),
515                                (then.span.shrink_to_hi(), ")".to_string()),
516                            ],
517                            MachineApplicable,
518                        );
519                    }
520                    _ => {}
521                }
522                debug!(
523                    "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
524                    values.expected,
525                    values.expected.kind(),
526                    values.found,
527                    values.found.kind(),
528                );
529            }
530            TypeError::CyclicTy(ty) => {
531                // Watch out for various cases of cyclic types and try to explain.
532                if ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure() {
533                    diag.note(
534                        "closures cannot capture themselves or take themselves as argument;\n\
535                         this error may be the result of a recent compiler bug-fix,\n\
536                         see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
537                         for more information",
538                    );
539                }
540            }
541            TypeError::TargetFeatureCast(def_id) => {
542                let target_spans =
543                    tcx.get_attrs(def_id, sym::target_feature).map(|attr| attr.span());
544                diag.note(
545                    "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
546                );
547                diag.span_labels(target_spans, "`#[target_feature]` added here");
548            }
549            _ => {}
550        }
551    }
552
553    fn suggest_constraint(
554        &self,
555        diag: &mut Diag<'_>,
556        msg: impl Fn() -> String,
557        body_owner_def_id: DefId,
558        proj_ty: ty::AliasTy<'tcx>,
559        ty: Ty<'tcx>,
560    ) -> bool {
561        let tcx = self.tcx;
562        let assoc = tcx.associated_item(proj_ty.def_id);
563        let (trait_ref, assoc_args) = proj_ty.trait_ref_and_own_args(tcx);
564        let Some(item) = tcx.hir_get_if_local(body_owner_def_id) else {
565            return false;
566        };
567        let Some(hir_generics) = item.generics() else {
568            return false;
569        };
570        // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
571        // This will also work for `impl Trait`.
572        let ty::Param(param_ty) = *proj_ty.self_ty().kind() else {
573            return false;
574        };
575        let generics = tcx.generics_of(body_owner_def_id);
576        let def_id = generics.type_param(param_ty, tcx).def_id;
577        let Some(def_id) = def_id.as_local() else {
578            return false;
579        };
580
581        // First look in the `where` clause, as this might be
582        // `fn foo<T>(x: T) where T: Trait`.
583        for pred in hir_generics.bounds_for_param(def_id) {
584            if self.constrain_generic_bound_associated_type_structured_suggestion(
585                diag,
586                trait_ref,
587                pred.bounds,
588                assoc,
589                assoc_args,
590                ty,
591                &msg,
592                false,
593            ) {
594                return true;
595            }
596        }
597        if (param_ty.index as usize) >= generics.parent_count {
598            // The param comes from the current item, do not look at the parent. (#117209)
599            return false;
600        }
601        // If associated item, look to constrain the params of the trait/impl.
602        let hir_id = match item {
603            hir::Node::ImplItem(item) => item.hir_id(),
604            hir::Node::TraitItem(item) => item.hir_id(),
605            _ => return false,
606        };
607        let parent = tcx.hir_get_parent_item(hir_id).def_id;
608        self.suggest_constraint(diag, msg, parent.into(), proj_ty, ty)
609    }
610
611    /// An associated type was expected and a different type was found.
612    ///
613    /// We perform a few different checks to see what we can suggest:
614    ///
615    ///  - In the current item, look for associated functions that return the expected type and
616    ///    suggest calling them. (Not a structured suggestion.)
617    ///  - If any of the item's generic bounds can be constrained, we suggest constraining the
618    ///    associated type to the found type.
619    ///  - If the associated type has a default type and was expected inside of a `trait`, we
620    ///    mention that this is disallowed.
621    ///  - If all other things fail, and the error is not because of a mismatch between the `trait`
622    ///    and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
623    ///    fn that returns the type.
624    fn expected_projection(
625        &self,
626        diag: &mut Diag<'_>,
627        proj_ty: ty::AliasTy<'tcx>,
628        values: ExpectedFound<Ty<'tcx>>,
629        body_owner_def_id: DefId,
630        cause_code: &ObligationCauseCode<'_>,
631    ) {
632        let tcx = self.tcx;
633
634        // Don't suggest constraining a projection to something containing itself
635        if self.tcx.erase_regions(values.found).contains(self.tcx.erase_regions(values.expected)) {
636            return;
637        }
638
639        let msg = || {
640            format!(
641                "consider constraining the associated type `{}` to `{}`",
642                values.expected, values.found
643            )
644        };
645
646        let body_owner = tcx.hir_get_if_local(body_owner_def_id);
647        let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
648
649        // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
650        let callable_scope = matches!(
651            body_owner,
652            Some(
653                hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { .. }, .. })
654                    | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
655                    | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
656            )
657        );
658        let impl_comparison = matches!(cause_code, ObligationCauseCode::CompareImplItem { .. });
659        let assoc = tcx.associated_item(proj_ty.def_id);
660        if impl_comparison {
661            // We do not want to suggest calling functions when the reason of the
662            // type error is a comparison of an `impl` with its `trait`.
663        } else {
664            let point_at_assoc_fn = if callable_scope
665                && self.point_at_methods_that_satisfy_associated_type(
666                    diag,
667                    assoc.container_id(tcx),
668                    current_method_ident,
669                    proj_ty.def_id,
670                    values.expected,
671                ) {
672                // If we find a suitable associated function that returns the expected type, we
673                // don't want the more general suggestion later in this method about "consider
674                // constraining the associated type or calling a method that returns the associated
675                // type".
676                true
677            } else {
678                false
679            };
680            // Possibly suggest constraining the associated type to conform to the
681            // found type.
682            if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found)
683                || point_at_assoc_fn
684            {
685                return;
686            }
687        }
688
689        self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found);
690
691        if self.point_at_associated_type(diag, body_owner_def_id, values.found) {
692            return;
693        }
694
695        if !impl_comparison {
696            // Generic suggestion when we can't be more specific.
697            if callable_scope {
698                diag.help(format!(
699                    "{} or calling a method that returns `{}`",
700                    msg(),
701                    values.expected
702                ));
703            } else {
704                diag.help(msg());
705            }
706            diag.note(
707                "for more information, visit \
708                 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
709            );
710        }
711        if diag.code.is_some_and(|code| tcx.sess.teach(code)) {
712            diag.help(
713                "given an associated type `T` and a method `foo`:
714```
715trait Trait {
716type T;
717fn foo(&self) -> Self::T;
718}
719```
720the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
721```
722impl Trait for X {
723type T = String;
724fn foo(&self) -> Self::T { String::new() }
725}
726```",
727            );
728        }
729    }
730
731    /// When the expected `impl Trait` is not defined in the current item, it will come from
732    /// a return type. This can occur when dealing with `TryStream` (#71035).
733    fn suggest_constraining_opaque_associated_type(
734        &self,
735        diag: &mut Diag<'_>,
736        msg: impl Fn() -> String,
737        proj_ty: ty::AliasTy<'tcx>,
738        ty: Ty<'tcx>,
739    ) -> bool {
740        let tcx = self.tcx;
741
742        let assoc = tcx.associated_item(proj_ty.def_id);
743        if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *proj_ty.self_ty().kind() {
744            let opaque_local_def_id = def_id.as_local();
745            let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
746                tcx.hir_expect_opaque_ty(opaque_local_def_id)
747            } else {
748                return false;
749            };
750
751            let (trait_ref, assoc_args) = proj_ty.trait_ref_and_own_args(tcx);
752
753            self.constrain_generic_bound_associated_type_structured_suggestion(
754                diag,
755                trait_ref,
756                opaque_hir_ty.bounds,
757                assoc,
758                assoc_args,
759                ty,
760                msg,
761                true,
762            )
763        } else {
764            false
765        }
766    }
767
768    fn point_at_methods_that_satisfy_associated_type(
769        &self,
770        diag: &mut Diag<'_>,
771        assoc_container_id: DefId,
772        current_method_ident: Option<Symbol>,
773        proj_ty_item_def_id: DefId,
774        expected: Ty<'tcx>,
775    ) -> bool {
776        let tcx = self.tcx;
777
778        let items = tcx.associated_items(assoc_container_id);
779        // Find all the methods in the trait that could be called to construct the
780        // expected associated type.
781        // FIXME: consider suggesting the use of associated `const`s.
782        let methods: Vec<(Span, String)> = items
783            .in_definition_order()
784            .filter(|item| {
785                ty::AssocKind::Fn == item.kind
786                    && Some(item.name) != current_method_ident
787                    && !tcx.is_doc_hidden(item.def_id)
788            })
789            .filter_map(|item| {
790                let method = tcx.fn_sig(item.def_id).instantiate_identity();
791                match *method.output().skip_binder().kind() {
792                    ty::Alias(ty::Projection, ty::AliasTy { def_id: item_def_id, .. })
793                        if item_def_id == proj_ty_item_def_id =>
794                    {
795                        Some((
796                            tcx.def_span(item.def_id),
797                            format!("consider calling `{}`", tcx.def_path_str(item.def_id)),
798                        ))
799                    }
800                    _ => None,
801                }
802            })
803            .collect();
804        if !methods.is_empty() {
805            // Use a single `help:` to show all the methods in the trait that can
806            // be used to construct the expected associated type.
807            let mut span: MultiSpan =
808                methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
809            let msg = format!(
810                "{some} method{s} {are} available that return{r} `{ty}`",
811                some = if methods.len() == 1 { "a" } else { "some" },
812                s = pluralize!(methods.len()),
813                are = pluralize!("is", methods.len()),
814                r = if methods.len() == 1 { "s" } else { "" },
815                ty = expected
816            );
817            for (sp, label) in methods.into_iter() {
818                span.push_span_label(sp, label);
819            }
820            diag.span_help(span, msg);
821            return true;
822        }
823        false
824    }
825
826    fn point_at_associated_type(
827        &self,
828        diag: &mut Diag<'_>,
829        body_owner_def_id: DefId,
830        found: Ty<'tcx>,
831    ) -> bool {
832        let tcx = self.tcx;
833
834        let Some(def_id) = body_owner_def_id.as_local() else {
835            return false;
836        };
837
838        // When `body_owner` is an `impl` or `trait` item, look in its associated types for
839        // `expected` and point at it.
840        let hir_id = tcx.local_def_id_to_hir_id(def_id);
841        let parent_id = tcx.hir_get_parent_item(hir_id);
842        let item = tcx.hir_node_by_def_id(parent_id.def_id);
843
844        debug!("expected_projection parent item {:?}", item);
845
846        let param_env = tcx.param_env(body_owner_def_id);
847
848        match item {
849            hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. }) => {
850                // FIXME: account for `#![feature(specialization)]`
851                for item in &items[..] {
852                    match item.kind {
853                        hir::AssocItemKind::Type => {
854                            // FIXME: account for returning some type in a trait fn impl that has
855                            // an assoc type as a return type (#72076).
856                            if let hir::Defaultness::Default { has_value: true } =
857                                tcx.defaultness(item.id.owner_id)
858                            {
859                                let assoc_ty = tcx.type_of(item.id.owner_id).instantiate_identity();
860                                if self.infcx.can_eq(param_env, assoc_ty, found) {
861                                    diag.span_label(
862                                        item.span,
863                                        "associated type defaults can't be assumed inside the \
864                                            trait defining them",
865                                    );
866                                    return true;
867                                }
868                            }
869                        }
870                        _ => {}
871                    }
872                }
873            }
874            hir::Node::Item(hir::Item {
875                kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
876                ..
877            }) => {
878                for item in &items[..] {
879                    if let hir::AssocItemKind::Type = item.kind {
880                        let assoc_ty = tcx.type_of(item.id.owner_id).instantiate_identity();
881                        if let hir::Defaultness::Default { has_value: true } =
882                            tcx.defaultness(item.id.owner_id)
883                            && self.infcx.can_eq(param_env, assoc_ty, found)
884                        {
885                            diag.span_label(
886                                item.span,
887                                "associated type is `default` and may be overridden",
888                            );
889                            return true;
890                        }
891                    }
892                }
893            }
894            _ => {}
895        }
896        false
897    }
898
899    /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
900    /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
901    ///
902    /// `is_bound_surely_present` indicates whether we know the bound we're looking for is
903    /// inside `bounds`. If that's the case then we can consider `bounds` containing only one
904    /// trait bound as the one we're looking for. This can help in cases where the associated
905    /// type is defined on a supertrait of the one present in the bounds.
906    fn constrain_generic_bound_associated_type_structured_suggestion(
907        &self,
908        diag: &mut Diag<'_>,
909        trait_ref: ty::TraitRef<'tcx>,
910        bounds: hir::GenericBounds<'_>,
911        assoc: ty::AssocItem,
912        assoc_args: &[ty::GenericArg<'tcx>],
913        ty: Ty<'tcx>,
914        msg: impl Fn() -> String,
915        is_bound_surely_present: bool,
916    ) -> bool {
917        // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
918
919        let trait_bounds = bounds.iter().filter_map(|bound| match bound {
920            hir::GenericBound::Trait(ptr) if ptr.modifiers == hir::TraitBoundModifiers::NONE => {
921                Some(ptr)
922            }
923            _ => None,
924        });
925
926        let matching_trait_bounds = trait_bounds
927            .clone()
928            .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
929            .collect::<Vec<_>>();
930
931        let span = match &matching_trait_bounds[..] {
932            &[ptr] => ptr.span,
933            &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
934                &[ptr] => ptr.span,
935                _ => return false,
936            },
937            _ => return false,
938        };
939
940        self.constrain_associated_type_structured_suggestion(diag, span, assoc, assoc_args, ty, msg)
941    }
942
943    /// Given a span corresponding to a bound, provide a structured suggestion to set an
944    /// associated type to a given type `ty`.
945    fn constrain_associated_type_structured_suggestion(
946        &self,
947        diag: &mut Diag<'_>,
948        span: Span,
949        assoc: ty::AssocItem,
950        assoc_args: &[ty::GenericArg<'tcx>],
951        ty: Ty<'tcx>,
952        msg: impl Fn() -> String,
953    ) -> bool {
954        let tcx = self.tcx;
955
956        if let Ok(has_params) =
957            tcx.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
958        {
959            let (span, sugg) = if has_params {
960                let pos = span.hi() - BytePos(1);
961                let span = Span::new(pos, pos, span.ctxt(), span.parent());
962                (span, format!(", {} = {}", assoc.ident(tcx), ty))
963            } else {
964                let item_args = self.format_generic_args(assoc_args);
965                (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(tcx), item_args, ty))
966            };
967            diag.span_suggestion_verbose(span, msg(), sugg, MaybeIncorrect);
968            return true;
969        }
970        false
971    }
972
973    pub fn format_generic_args(&self, args: &[ty::GenericArg<'tcx>]) -> String {
974        FmtPrinter::print_string(self.tcx, hir::def::Namespace::TypeNS, |cx| {
975            cx.path_generic_args(|_| Ok(()), args)
976        })
977        .expect("could not write to `String`.")
978    }
979}