Skip to main content

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