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