Skip to main content

rustc_hir_analysis/hir_ty_lowering/
errors.rs

1use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
2use rustc_data_structures::sorted_map::SortedMap;
3use rustc_data_structures::thin_vec::ThinVec;
4use rustc_data_structures::unord::UnordMap;
5use rustc_errors::codes::*;
6use rustc_errors::{
7    Applicability, Diag, ErrorGuaranteed, MultiSpan, SuggestionStyle, listify, msg, pluralize,
8    struct_span_code_err,
9};
10use rustc_hir::def::{CtorOf, DefKind, Res};
11use rustc_hir::def_id::DefId;
12use rustc_hir::{self as hir, HirId};
13use rustc_middle::bug;
14use rustc_middle::ty::fast_reject::{TreatParams, simplify_type};
15use rustc_middle::ty::print::{PrintPolyTraitRefExt as _, PrintTraitRefExt as _};
16use rustc_middle::ty::{
17    self, AdtDef, GenericParamDefKind, Ty, TyCtxt, TypeVisitableExt,
18    suggest_constraining_type_param,
19};
20use rustc_session::diagnostics::feature_err;
21use rustc_span::edit_distance::find_best_match_for_name;
22use rustc_span::{BytePos, DUMMY_SP, Ident, Span, Symbol, kw, sym};
23use rustc_trait_selection::error_reporting::traits::report_dyn_incompatibility;
24use rustc_trait_selection::traits::{
25    FulfillmentError, dyn_compatibility_violations_for_assoc_item,
26};
27use smallvec::SmallVec;
28use tracing::debug;
29
30use super::InherentAssocCandidate;
31use crate::diagnostics::{
32    self, AssocItemConstraintsNotAllowedHere, ManualImplementation, ParenthesizedFnTraitExpansion,
33    TraitObjectDeclaredWithNoTraits,
34};
35use crate::hir_ty_lowering::{AssocItemQSelf, HirTyLowerer};
36
37impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
38    pub(crate) fn report_missing_generic_params(
39        &self,
40        missing_generic_params: Vec<(Symbol, ty::GenericParamDefKind)>,
41        def_id: DefId,
42        span: Span,
43        empty_generic_args: bool,
44    ) {
45        if missing_generic_params.is_empty() {
46            return;
47        }
48
49        self.dcx().emit_err(diagnostics::MissingGenericParams {
50            span,
51            def_span: self.tcx().def_span(def_id),
52            span_snippet: self.tcx().sess.source_map().span_to_snippet(span).ok(),
53            missing_generic_params,
54            empty_generic_args,
55        });
56    }
57
58    /// When the code is using the `Fn` traits directly, instead of the `Fn(A) -> B` syntax, emit
59    /// an error and attempt to build a reasonable structured suggestion.
60    pub(crate) fn report_internal_fn_trait(
61        &self,
62        span: Span,
63        trait_def_id: DefId,
64        trait_segment: &'_ hir::PathSegment<'_>,
65        is_impl: bool,
66    ) {
67        if self.tcx().features().unboxed_closures() {
68            return;
69        }
70
71        let trait_def = self.tcx().trait_def(trait_def_id);
72        if !trait_def.paren_sugar {
73            if trait_segment.args().parenthesized == hir::GenericArgsParentheses::ParenSugar {
74                // For now, require that parenthetical notation be used only with `Fn()` etc.
75                feature_err(
76                    &self.tcx().sess,
77                    sym::unboxed_closures,
78                    span,
79                    "parenthetical notation is only stable when used with `Fn`-family traits",
80                )
81                .emit();
82            }
83
84            return;
85        }
86
87        let sess = self.tcx().sess;
88
89        if trait_segment.args().parenthesized != hir::GenericArgsParentheses::ParenSugar {
90            // For now, require that parenthetical notation be used only with `Fn()` etc.
91            let mut err = feature_err(
92                sess,
93                sym::unboxed_closures,
94                span,
95                "the precise format of `Fn`-family traits' type parameters is subject to change",
96            );
97            // Do not suggest the other syntax if we are in trait impl:
98            // the desugaring would contain an associated type constraint.
99            if !is_impl {
100                err.span_suggestion(
101                    span,
102                    "use parenthetical notation instead",
103                    fn_trait_to_string(self.tcx(), trait_segment, true),
104                    Applicability::MaybeIncorrect,
105                );
106            }
107            err.emit();
108        }
109
110        if is_impl {
111            let trait_name = self.tcx().def_path_str(trait_def_id);
112            self.dcx().emit_err(ManualImplementation { span, trait_name });
113        }
114    }
115
116    pub(super) fn report_unresolved_assoc_item<I>(
117        &self,
118        all_candidates: impl Fn() -> I,
119        qself: AssocItemQSelf,
120        assoc_tag: ty::AssocTag,
121        assoc_ident: Ident,
122        span: Span,
123        constraint: Option<&hir::AssocItemConstraint<'tcx>>,
124    ) -> ErrorGuaranteed
125    where
126        I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
127    {
128        let tcx = self.tcx();
129
130        // First and foremost, provide a more user-friendly & “intuitive” error on kind mismatches.
131        if let Some(assoc_item) = all_candidates().find_map(|r| {
132            tcx.associated_items(r.def_id())
133                .filter_by_name_unhygienic(assoc_ident.name)
134                .find(|item| tcx.hygienic_eq(assoc_ident, item.ident(tcx), r.def_id()))
135        }) {
136            return self.report_assoc_kind_mismatch(
137                assoc_item,
138                assoc_tag,
139                assoc_ident,
140                span,
141                constraint,
142            );
143        }
144
145        let assoc_kind = assoc_tag_str(assoc_tag);
146        let qself_str = qself.to_string(tcx);
147
148        // The fallback span is needed because `assoc_name` might be an `Fn()`'s `Output` without a
149        // valid span, so we point at the whole path segment instead.
150        let is_dummy = assoc_ident.span == DUMMY_SP;
151
152        let mut err = diagnostics::AssocItemNotFound {
153            span: if is_dummy { span } else { assoc_ident.span },
154            assoc_ident,
155            assoc_kind,
156            qself: &qself_str,
157            label: None,
158            sugg: None,
159            // Try to get the span of the identifier within the path's syntax context
160            // (if that's different).
161            within_macro_span: assoc_ident.span.within_macro(span, tcx.sess.source_map()),
162        };
163
164        if is_dummy {
165            err.label = Some(diagnostics::AssocItemNotFoundLabel::NotFound {
166                span,
167                assoc_ident,
168                assoc_kind,
169            });
170            return self.dcx().emit_err(err);
171        }
172
173        let all_candidate_names: Vec<_> = all_candidates()
174            .flat_map(|r| tcx.associated_items(r.def_id()).in_definition_order())
175            .filter_map(|item| {
176                if !item.is_impl_trait_in_trait() && item.tag() == assoc_tag {
177                    item.opt_name()
178                } else {
179                    None
180                }
181            })
182            .collect();
183
184        if let Some(suggested_name) =
185            find_best_match_for_name(&all_candidate_names, assoc_ident.name, None)
186        {
187            err.sugg = Some(diagnostics::AssocItemNotFoundSugg::Similar {
188                span: assoc_ident.span,
189                assoc_kind,
190                suggested_name,
191            });
192            return self.dcx().emit_err(err);
193        }
194
195        // If we didn't find a good item in the supertraits (or couldn't get
196        // the supertraits), like in ItemCtxt, then look more generally from
197        // all visible traits. If there's one clear winner, just suggest that.
198
199        let visible_traits: Vec<_> = tcx
200            .visible_traits()
201            .filter(|trait_def_id| {
202                let viz = tcx.visibility(*trait_def_id);
203                let def_id = self.item_def_id();
204                viz.is_accessible_from(def_id, tcx)
205            })
206            .collect();
207
208        let wider_candidate_names: Vec<_> = visible_traits
209            .iter()
210            .flat_map(|trait_def_id| tcx.associated_items(*trait_def_id).in_definition_order())
211            .filter_map(|item| {
212                (!item.is_impl_trait_in_trait() && item.tag() == assoc_tag).then(|| item.name())
213            })
214            .collect();
215
216        if let Some(suggested_name) =
217            find_best_match_for_name(&wider_candidate_names, assoc_ident.name, None)
218        {
219            if let [best_trait] = visible_traits
220                .iter()
221                .copied()
222                .filter(|&trait_def_id| {
223                    tcx.associated_items(trait_def_id)
224                        .filter_by_name_unhygienic(suggested_name)
225                        .any(|item| item.tag() == assoc_tag)
226                })
227                .collect::<Vec<_>>()[..]
228            {
229                let trait_name = tcx.def_path_str(best_trait);
230                err.label = Some(diagnostics::AssocItemNotFoundLabel::FoundInOtherTrait {
231                    span: assoc_ident.span,
232                    assoc_kind,
233                    trait_name: &trait_name,
234                    suggested_name,
235                    identically_named: suggested_name == assoc_ident.name,
236                });
237                if let AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span) = qself
238                    // Not using `self.item_def_id()` here as that would yield the opaque type itself if we're
239                    // inside an opaque type while we're interested in the overarching type alias (TAIT).
240                    // FIXME: However, for trait aliases, this incorrectly returns the enclosing module...
241                    && let item_def_id =
242                        tcx.hir_get_parent_item(tcx.local_def_id_to_hir_id(ty_param_def_id))
243                    // FIXME: ...which obviously won't have any generics.
244                    && let Some(generics) = tcx.hir_get_generics(item_def_id.def_id)
245                {
246                    // FIXME: Suggest adding supertrait bounds if we have a `Self` type param.
247                    // FIXME(trait_alias): Suggest adding `Self: Trait` to
248                    // `trait Alias = where Self::Proj:;` with `trait Trait { type Proj; }`.
249                    if generics
250                        .bounds_for_param(ty_param_def_id)
251                        .flat_map(|pred| pred.bounds.iter())
252                        .any(|b| match b {
253                            hir::GenericBound::Trait(t, ..) => {
254                                t.trait_ref.trait_def_id() == Some(best_trait)
255                            }
256                            _ => false,
257                        })
258                    {
259                        // The type param already has a bound for `trait_name`, we just need to
260                        // change the associated item.
261                        err.sugg = Some(diagnostics::AssocItemNotFoundSugg::SimilarInOtherTrait {
262                            span: assoc_ident.span,
263                            trait_name: &trait_name,
264                            assoc_kind,
265                            suggested_name,
266                        });
267                        return self.dcx().emit_err(err);
268                    }
269
270                    let trait_args = &ty::GenericArgs::identity_for_item(tcx, best_trait)[1..];
271                    let mut trait_ref = trait_name.clone();
272                    let applicability = if let [arg, args @ ..] = trait_args {
273                        use std::fmt::Write;
274                        trait_ref.write_fmt(format_args!("</* {0}", arg))write!(trait_ref, "</* {arg}").unwrap();
275                        args.iter().try_for_each(|arg| trait_ref.write_fmt(format_args!(", {0}", arg))write!(trait_ref, ", {arg}")).unwrap();
276                        trait_ref += " */>";
277                        Applicability::HasPlaceholders
278                    } else {
279                        Applicability::MaybeIncorrect
280                    };
281
282                    let identically_named = suggested_name == assoc_ident.name;
283
284                    if let DefKind::TyAlias = tcx.def_kind(item_def_id)
285                        && !tcx.type_alias_is_checked(item_def_id)
286                    {
287                        err.sugg =
288                            Some(diagnostics::AssocItemNotFoundSugg::SimilarInOtherTraitQPath {
289                                lo: ty_param_span.shrink_to_lo(),
290                                mi: ty_param_span.shrink_to_hi(),
291                                hi: (!identically_named).then_some(assoc_ident.span),
292                                trait_ref,
293                                identically_named,
294                                suggested_name,
295                                assoc_kind,
296                                applicability,
297                            });
298                    } else {
299                        let mut err = self.dcx().create_err(err);
300                        if suggest_constraining_type_param(
301                            tcx,
302                            generics,
303                            &mut err,
304                            &qself_str,
305                            &trait_ref,
306                            Some(best_trait),
307                            None,
308                        ) && !identically_named
309                        {
310                            // We suggested constraining a type parameter, but the associated item on it
311                            // was also not an exact match, so we also suggest changing it.
312                            err.span_suggestion_verbose(
313                                assoc_ident.span,
314                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...and changing the associated {$assoc_kind} name"))msg!("...and changing the associated {$assoc_kind} name"),
315                                suggested_name,
316                                Applicability::MaybeIncorrect,
317                            );
318                        }
319                        return err.emit();
320                    }
321                }
322                return self.dcx().emit_err(err);
323            }
324        }
325
326        // If we still couldn't find any associated item, and only one associated item exists,
327        // suggest using it.
328        if let [candidate_name] = all_candidate_names.as_slice() {
329            err.sugg = Some(diagnostics::AssocItemNotFoundSugg::Other {
330                span: assoc_ident.span,
331                qself: &qself_str,
332                assoc_kind,
333                suggested_name: *candidate_name,
334            });
335        } else {
336            err.label = Some(diagnostics::AssocItemNotFoundLabel::NotFound {
337                span: assoc_ident.span,
338                assoc_ident,
339                assoc_kind,
340            });
341        }
342
343        self.dcx().emit_err(err)
344    }
345
346    fn report_assoc_kind_mismatch(
347        &self,
348        assoc_item: &ty::AssocItem,
349        assoc_tag: ty::AssocTag,
350        ident: Ident,
351        span: Span,
352        constraint: Option<&hir::AssocItemConstraint<'tcx>>,
353    ) -> ErrorGuaranteed {
354        let tcx = self.tcx();
355
356        let bound_on_assoc_const_label = if let ty::AssocKind::Const { .. } = assoc_item.kind
357            && let Some(constraint) = constraint
358            && let hir::AssocItemConstraintKind::Bound { .. } = constraint.kind
359        {
360            let lo = if constraint.gen_args.span_ext.is_dummy() {
361                ident.span
362            } else {
363                constraint.gen_args.span_ext
364            };
365            Some(lo.between(span.shrink_to_hi()))
366        } else {
367            None
368        };
369
370        // FIXME(mgca): This has quite a few false positives and negatives.
371        let wrap_in_braces_sugg = if let Some(constraint) = constraint
372            && let Some(hir_ty) = constraint.ty()
373            && let ty = self.lower_ty(hir_ty)
374            && (ty.is_enum() || ty.references_error())
375            && tcx.features().min_generic_const_args()
376        {
377            Some(diagnostics::AssocKindMismatchWrapInBracesSugg {
378                lo: hir_ty.span.shrink_to_lo(),
379                hi: hir_ty.span.shrink_to_hi(),
380            })
381        } else {
382            None
383        };
384
385        // For equality constraints, we want to blame the term (RHS) instead of the item (LHS) since
386        // one can argue that that's more “intuitive” to the user.
387        let (span, expected_because_label, expected, got) = if let Some(constraint) = constraint
388            && let hir::AssocItemConstraintKind::Equality { term } = constraint.kind
389        {
390            let span = match term {
391                hir::Term::Ty(ty) => ty.span,
392                hir::Term::Const(ct) => ct.span,
393            };
394            (span, Some(ident.span), assoc_item.tag(), assoc_tag)
395        } else {
396            (ident.span, None, assoc_tag, assoc_item.tag())
397        };
398
399        self.dcx().emit_err(diagnostics::AssocKindMismatch {
400            span,
401            expected: assoc_tag_str(expected),
402            got: assoc_tag_str(got),
403            expected_because_label,
404            assoc_kind: assoc_tag_str(assoc_item.tag()),
405            def_span: tcx.def_span(assoc_item.def_id),
406            bound_on_assoc_const_label,
407            wrap_in_braces_sugg,
408        })
409    }
410
411    pub(super) fn report_ambiguous_assoc_item(
412        &self,
413        matching_candidates: &[ty::PolyTraitRef<'tcx>],
414        qself: AssocItemQSelf,
415        assoc_tag: ty::AssocTag,
416        assoc_ident: Ident,
417        span: Span,
418        constraint: Option<&hir::AssocItemConstraint<'tcx>>,
419    ) -> ErrorGuaranteed {
420        let tcx = self.tcx();
421
422        let assoc_kind_str = assoc_tag_str(assoc_tag);
423        let qself_str = qself.to_string(tcx);
424        let mut err = self.dcx().create_err(crate::diagnostics::AmbiguousAssocItem {
425            span,
426            assoc_kind: assoc_kind_str,
427            assoc_ident,
428            qself: &qself_str,
429        });
430        // Provide a more specific error code index entry for equality bindings.
431        err.code(
432            if let Some(constraint) = constraint
433                && let hir::AssocItemConstraintKind::Equality { .. } = constraint.kind
434            {
435                E0222
436            } else {
437                E0221
438            },
439        );
440
441        // FIXME(#97583): Print associated item bindings properly (i.e., not as equality
442        // predicates!).
443        // FIXME: Turn this into a structured, translatable & more actionable suggestion.
444        let mut where_bounds = ::alloc::vec::Vec::new()vec![];
445        for &bound in matching_candidates {
446            let bound_id = bound.def_id();
447            let assoc_item = tcx.associated_items(bound_id).find_by_ident_and_kind(
448                tcx,
449                assoc_ident,
450                assoc_tag,
451                bound_id,
452            );
453            let bound_span = assoc_item.and_then(|item| tcx.hir_span_if_local(item.def_id));
454
455            if let Some(bound_span) = bound_span {
456                err.span_label(
457                    bound_span,
458                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("ambiguous `{1}` from `{0}`",
                bound.print_trait_sugared(), assoc_ident))
    })format!("ambiguous `{assoc_ident}` from `{}`", bound.print_trait_sugared(),),
459                );
460                if let Some(constraint) = constraint {
461                    match constraint.kind {
462                        hir::AssocItemConstraintKind::Equality { term } => {
463                            let term: ty::Term<'_> = match term {
464                                hir::Term::Ty(ty) => self.lower_ty(ty).into(),
465                                hir::Term::Const(ct) => {
466                                    let assoc_item =
467                                        assoc_item.expect("assoc_item should be present");
468                                    let projection_term = bound.map_bound(|trait_ref| {
469                                        let item_segment = hir::PathSegment {
470                                            ident: constraint.ident,
471                                            hir_id: constraint.hir_id,
472                                            res: Res::Err,
473                                            args: Some(constraint.gen_args),
474                                            infer_args: false,
475                                            delegation_child_segment: false,
476                                        };
477
478                                        let alias_args = self.lower_generic_args_of_assoc_item(
479                                            constraint.ident.span,
480                                            assoc_item.def_id,
481                                            &item_segment,
482                                            trait_ref.args,
483                                        );
484                                        ty::AliasTerm::new_from_def_id(
485                                            tcx,
486                                            assoc_item.def_id,
487                                            alias_args,
488                                        )
489                                    });
490
491                                    // FIXME(mgca): code duplication with other places we lower
492                                    // the rhs' of associated const bindings
493                                    let ty = projection_term.map_bound(|alias| {
494                                        alias.expect_ct().type_of(tcx).skip_norm_wip()
495                                    });
496                                    let ty = super::bounds::check_assoc_const_binding_type(
497                                        self,
498                                        constraint.ident,
499                                        ty,
500                                        constraint.hir_id,
501                                    );
502
503                                    self.lower_const_arg(ct, ty).into()
504                                }
505                            };
506                            if term.references_error() {
507                                continue;
508                            }
509                            // FIXME(#97583): This isn't syntactically well-formed!
510                            where_bounds.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("        T: {0}::{1} = {2}",
                bound.print_only_trait_path(), assoc_ident, term))
    })format!(
511                                "        T: {trait}::{assoc_ident} = {term}",
512                                trait = bound.print_only_trait_path(),
513                            ));
514                        }
515                        // FIXME: Provide a suggestion.
516                        hir::AssocItemConstraintKind::Bound { bounds: _ } => {}
517                    }
518                } else {
519                    err.span_suggestion_verbose(
520                        span.with_hi(assoc_ident.span.lo()),
521                        "use fully-qualified syntax to disambiguate",
522                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{1} as {0}>::",
                bound.print_only_trait_path(), qself_str))
    })format!("<{qself_str} as {}>::", bound.print_only_trait_path()),
523                        Applicability::MaybeIncorrect,
524                    );
525                }
526            } else {
527                let trait_ = tcx.short_string(bound.print_only_trait_path(), err.long_ty_path());
528                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("associated {0} `{1}` could derive from `{2}`",
                assoc_kind_str, assoc_ident, trait_))
    })format!(
529                    "associated {assoc_kind_str} `{assoc_ident}` could derive from `{trait_}`",
530                ));
531            }
532        }
533        if !where_bounds.is_empty() {
534            err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider introducing a new type parameter `T` and adding `where` constraints:\n    where\n        T: {1},\n{0}",
                where_bounds.join(",\n"), qself_str))
    })format!(
535                "consider introducing a new type parameter `T` and adding `where` constraints:\
536                     \n    where\n        T: {qself_str},\n{}",
537                where_bounds.join(",\n"),
538            ));
539        }
540        err.emit()
541    }
542
543    pub(crate) fn report_missing_self_ty_for_resolved_path(
544        &self,
545        trait_def_id: DefId,
546        span: Span,
547        item_segment: &hir::PathSegment<'tcx>,
548        assoc_tag: ty::AssocTag,
549    ) -> ErrorGuaranteed {
550        let tcx = self.tcx();
551        let path_str = tcx.def_path_str(trait_def_id);
552
553        let def_id = self.item_def_id();
554        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs:554",
                        "rustc_hir_analysis::hir_ty_lowering::errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(554u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::errors"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("item_def_id")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("item_def_id");
                                            NAME.as_str()
                                        }], ::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(&::tracing::field::debug(&def_id)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(item_def_id = ?def_id);
555
556        // FIXME: document why/how this is different from `tcx.local_parent(def_id)`
557        let parent_def_id = tcx.hir_get_parent_item(tcx.local_def_id_to_hir_id(def_id)).to_def_id();
558        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs:558",
                        "rustc_hir_analysis::hir_ty_lowering::errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(558u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::errors"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("parent_def_id")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("parent_def_id");
                                            NAME.as_str()
                                        }], ::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(&::tracing::field::debug(&parent_def_id)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?parent_def_id);
559
560        // If the trait in segment is the same as the trait defining the item,
561        // use the `<Self as ..>` syntax in the error.
562        let is_part_of_self_trait_constraints = def_id.to_def_id() == trait_def_id;
563        let is_part_of_fn_in_self_trait = parent_def_id == trait_def_id;
564
565        let type_names = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
566            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        ["Self".to_string()]))vec!["Self".to_string()]
567        } else {
568            // Find all the types that have an `impl` for the trait.
569            tcx.all_impls(trait_def_id)
570                .map(|impl_def_id| tcx.impl_trait_header(impl_def_id))
571                .filter(|header| {
572                    // Consider only accessible traits
573                    tcx.visibility(trait_def_id).is_accessible_from(self.item_def_id(), tcx)
574                        && header.polarity != ty::ImplPolarity::Negative
575                })
576                .map(|header| header.trait_ref.instantiate_identity().skip_norm_wip().self_ty())
577                // We don't care about blanket impls.
578                .filter(|self_ty| !self_ty.has_non_region_param())
579                .map(|self_ty| tcx.erase_and_anonymize_regions(self_ty).to_string())
580                .collect()
581        };
582        // FIXME: also look at `tcx.generics_of(self.item_def_id()).params` any that
583        // references the trait. Relevant for the first case in
584        // `src/test/ui/associated-types/associated-types-in-ambiguous-context.rs`
585        self.report_ambiguous_assoc_item_path(
586            span,
587            &type_names,
588            &[path_str],
589            item_segment.ident,
590            assoc_tag,
591        )
592    }
593
594    pub(super) fn report_unresolved_type_relative_path(
595        &self,
596        self_ty: Ty<'tcx>,
597        hir_self_ty: &hir::Ty<'_>,
598        assoc_tag: ty::AssocTag,
599        ident: Ident,
600        qpath_hir_id: HirId,
601        span: Span,
602        variant_def_id: Option<DefId>,
603    ) -> ErrorGuaranteed {
604        let tcx = self.tcx();
605        let kind_str = assoc_tag_str(assoc_tag);
606        if variant_def_id.is_some() {
607            // Variant in type position
608            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, found variant `{1}`",
                kind_str, ident))
    })format!("expected {kind_str}, found variant `{ident}`");
609            self.dcx().span_err(span, msg)
610        } else if self_ty.is_enum() {
611            let mut err = self.dcx().create_err(diagnostics::NoVariantNamed {
612                span: ident.span,
613                ident,
614                ty: self_ty,
615            });
616
617            let adt_def = self_ty.ty_adt_def().expect("enum is not an ADT");
618            if let Some(variant_name) = find_best_match_for_name(
619                &adt_def.variants().iter().map(|variant| variant.name).collect::<Vec<Symbol>>(),
620                ident.name,
621                None,
622            ) && let Some(variant) = adt_def.variants().iter().find(|s| s.name == variant_name)
623            {
624                let mut suggestion = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(ident.span, variant_name.to_string())]))vec![(ident.span, variant_name.to_string())];
625                if let hir::Node::Stmt(&hir::Stmt { kind: hir::StmtKind::Semi(expr), .. })
626                | hir::Node::Expr(expr) = tcx.parent_hir_node(qpath_hir_id)
627                    && let hir::ExprKind::Struct(..) = expr.kind
628                {
629                    match variant.ctor {
630                        None => {
631                            // struct
632                            suggestion = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(ident.span.with_hi(expr.span.hi()),
                    if variant.fields.is_empty() {
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("{0} {{}}", variant_name))
                            })
                    } else {
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("{1} {{ {0} }}",
                                        variant.fields.iter().map(|f|
                                                        ::alloc::__export::must_use({
                                                                ::alloc::fmt::format(format_args!("{0}: /* value */",
                                                                        f.name))
                                                            })).collect::<Vec<_>>().join(", "), variant_name))
                            })
                    })]))vec![(
633                                ident.span.with_hi(expr.span.hi()),
634                                if variant.fields.is_empty() {
635                                    format!("{variant_name} {{}}")
636                                } else {
637                                    format!(
638                                        "{variant_name} {{ {} }}",
639                                        variant
640                                            .fields
641                                            .iter()
642                                            .map(|f| format!("{}: /* value */", f.name))
643                                            .collect::<Vec<_>>()
644                                            .join(", ")
645                                    )
646                                },
647                            )];
648                        }
649                        Some((hir::def::CtorKind::Fn, def_id)) => {
650                            // tuple
651                            let fn_sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
652                            let inputs = fn_sig.inputs().skip_binder();
653                            suggestion = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(ident.span.with_hi(expr.span.hi()),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{1}({0})",
                                    inputs.iter().map(|i|
                                                    ::alloc::__export::must_use({
                                                            ::alloc::fmt::format(format_args!("/* {0} */", i))
                                                        })).collect::<Vec<_>>().join(", "), variant_name))
                        }))]))vec![(
654                                ident.span.with_hi(expr.span.hi()),
655                                format!(
656                                    "{variant_name}({})",
657                                    inputs
658                                        .iter()
659                                        .map(|i| format!("/* {i} */"))
660                                        .collect::<Vec<_>>()
661                                        .join(", ")
662                                ),
663                            )];
664                        }
665                        Some((hir::def::CtorKind::Const, _)) => {
666                            // unit
667                            suggestion = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(ident.span.with_hi(expr.span.hi()), variant_name.to_string())]))vec![(
668                                ident.span.with_hi(expr.span.hi()),
669                                variant_name.to_string(),
670                            )];
671                        }
672                    }
673                }
674                err.multipart_suggestion(
675                    "there is a variant with a similar name",
676                    suggestion,
677                    Applicability::HasPlaceholders,
678                );
679            } else {
680                err.span_label(ident.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("variant not found in `{0}`",
                self_ty))
    })format!("variant not found in `{self_ty}`"));
681            }
682
683            if let Some(sp) = tcx.hir_span_if_local(adt_def.did()) {
684                err.span_label(sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("variant `{0}` not found here",
                ident))
    })format!("variant `{ident}` not found here"));
685            }
686
687            err.emit()
688        } else if let Err(reported) = self_ty.error_reported() {
689            reported
690        } else {
691            match self.maybe_report_similar_assoc_fn(span, self_ty, hir_self_ty) {
692                Ok(()) => {}
693                Err(reported) => return reported,
694            }
695
696            let traits: Vec<_> = self.probe_traits_that_match_assoc_ty(self_ty, ident);
697
698            self.report_ambiguous_assoc_item_path(
699                span,
700                &[self_ty.to_string()],
701                &traits,
702                ident,
703                assoc_tag,
704            )
705        }
706    }
707
708    fn report_ambiguous_assoc_item_path(
709        &self,
710        span: Span,
711        types: &[String],
712        traits: &[String],
713        ident: Ident,
714        assoc_tag: ty::AssocTag,
715    ) -> ErrorGuaranteed {
716        let kind_str = assoc_tag_str(assoc_tag);
717        let mut err =
718            {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("ambiguous associated {0}",
                            kind_str))
                })).with_code(E0223)
}struct_span_code_err!(self.dcx(), span, E0223, "ambiguous associated {kind_str}");
719        if self
720            .tcx()
721            .resolutions(())
722            .confused_type_with_std_module
723            .keys()
724            .any(|full_span| full_span.contains(span))
725        {
726            err.span_suggestion_verbose(
727                span.shrink_to_lo(),
728                "you are looking for the module in `std`, not the primitive type",
729                "std::",
730                Applicability::MachineApplicable,
731            );
732        } else {
733            let sugg_sp = span.until(ident.span);
734
735            let mut types = types.to_vec();
736            types.sort();
737            let mut traits = traits.to_vec();
738            traits.sort();
739            match (&types[..], &traits[..]) {
740                ([], []) => {
741                    err.span_suggestion_verbose(
742                        sugg_sp,
743                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if there were a type named `Type` that implements a trait named `Trait` with associated {0} `{1}`, you could use the fully-qualified path",
                kind_str, ident))
    })format!(
744                            "if there were a type named `Type` that implements a trait named \
745                             `Trait` with associated {kind_str} `{ident}`, you could use the \
746                             fully-qualified path",
747                        ),
748                        "<Type as Trait>::",
749                        Applicability::HasPlaceholders,
750                    );
751                }
752                ([], [trait_str]) => {
753                    err.span_suggestion_verbose(
754                        sugg_sp,
755                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if there were a type named `Example` that implemented `{0}`, you could use the fully-qualified path",
                trait_str))
    })format!(
756                            "if there were a type named `Example` that implemented `{trait_str}`, \
757                             you could use the fully-qualified path",
758                        ),
759                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<Example as {0}>::", trait_str))
    })format!("<Example as {trait_str}>::"),
760                        Applicability::HasPlaceholders,
761                    );
762                }
763                ([], traits) => {
764                    err.span_suggestions_with_style(
765                        sugg_sp,
766                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if there were a type named `Example` that implemented one of the traits with associated {0} `{1}`, you could use the fully-qualified path",
                kind_str, ident))
    })format!(
767                            "if there were a type named `Example` that implemented one of the \
768                             traits with associated {kind_str} `{ident}`, you could use the \
769                             fully-qualified path",
770                        ),
771                        traits.iter().map(|trait_str| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<Example as {0}>::", trait_str))
    })format!("<Example as {trait_str}>::")),
772                        Applicability::HasPlaceholders,
773                        SuggestionStyle::ShowAlways,
774                    );
775                }
776                ([type_str], []) => {
777                    err.span_suggestion_verbose(
778                        sugg_sp,
779                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if there were a trait named `Example` with associated {0} `{1}` implemented for `{2}`, you could use the fully-qualified path",
                kind_str, ident, type_str))
    })format!(
780                            "if there were a trait named `Example` with associated {kind_str} `{ident}` \
781                             implemented for `{type_str}`, you could use the fully-qualified path",
782                        ),
783                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0} as Example>::", type_str))
    })format!("<{type_str} as Example>::"),
784                        Applicability::HasPlaceholders,
785                    );
786                }
787                (types, []) => {
788                    err.span_suggestions_with_style(
789                        sugg_sp,
790                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if there were a trait named `Example` with associated {0} `{1}` implemented for one of the types, you could use the fully-qualified path",
                kind_str, ident))
    })format!(
791                            "if there were a trait named `Example` with associated {kind_str} `{ident}` \
792                             implemented for one of the types, you could use the fully-qualified \
793                             path",
794                        ),
795                        types
796                            .into_iter()
797                            .map(|type_str| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0} as Example>::", type_str))
    })format!("<{type_str} as Example>::")),
798                        Applicability::HasPlaceholders,
799                        SuggestionStyle::ShowAlways,
800                    );
801                }
802                (types, traits) => {
803                    let mut suggestions = ::alloc::vec::Vec::new()vec![];
804                    for type_str in types {
805                        for trait_str in traits {
806                            suggestions.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0} as {1}>::", type_str,
                trait_str))
    })format!("<{type_str} as {trait_str}>::"));
807                        }
808                    }
809                    err.span_suggestions_with_style(
810                        sugg_sp,
811                        "use fully-qualified syntax",
812                        suggestions,
813                        Applicability::MachineApplicable,
814                        SuggestionStyle::ShowAlways,
815                    );
816                }
817            }
818        }
819        err.emit()
820    }
821
822    pub(crate) fn report_ambiguous_inherent_assoc_item(
823        &self,
824        name: Ident,
825        candidates: Vec<DefId>,
826        span: Span,
827    ) -> ErrorGuaranteed {
828        let mut err = {
    self.dcx().struct_span_err(name.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("multiple applicable items in scope"))
                })).with_code(E0034)
}struct_span_code_err!(
829            self.dcx(),
830            name.span,
831            E0034,
832            "multiple applicable items in scope"
833        );
834        err.span_label(name.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("multiple `{0}` found", name))
    })format!("multiple `{name}` found"));
835        self.note_ambiguous_inherent_assoc_item(&mut err, candidates, span);
836        err.emit()
837    }
838
839    // FIXME(fmease): Heavily adapted from `rustc_hir_typeck::method::suggest`. Deduplicate.
840    fn note_ambiguous_inherent_assoc_item(
841        &self,
842        err: &mut Diag<'_>,
843        candidates: Vec<DefId>,
844        span: Span,
845    ) {
846        let tcx = self.tcx();
847
848        // Dynamic limit to avoid hiding just one candidate, which is silly.
849        let limit = if candidates.len() == 5 { 5 } else { 4 };
850
851        for (index, &item) in candidates.iter().take(limit).enumerate() {
852            let impl_ = tcx.parent(item);
853
854            let note_span = if item.is_local() {
855                Some(tcx.def_span(item))
856            } else if impl_.is_local() {
857                Some(tcx.def_span(impl_))
858            } else {
859                None
860            };
861
862            let title = if candidates.len() > 1 {
863                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("candidate #{0}", index + 1))
    })format!("candidate #{}", index + 1)
864            } else {
865                "the candidate".into()
866            };
867
868            let impl_ty = tcx.at(span).type_of(impl_).instantiate_identity().skip_norm_wip();
869            let note = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} is defined in an impl for the type `{1}`",
                title, impl_ty))
    })format!("{title} is defined in an impl for the type `{impl_ty}`");
870
871            if let Some(span) = note_span {
872                err.span_note(span, note);
873            } else {
874                err.note(note);
875            }
876        }
877        if candidates.len() > limit {
878            err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("and {0} others",
                candidates.len() - limit))
    })format!("and {} others", candidates.len() - limit));
879        }
880    }
881
882    // FIXME(inherent_associated_types): Find similarly named associated types and suggest them.
883    pub(crate) fn report_unresolved_inherent_assoc_item(
884        &self,
885        name: Ident,
886        self_ty: Ty<'tcx>,
887        candidates: Vec<InherentAssocCandidate>,
888        fulfillment_errors: ThinVec<FulfillmentError<'tcx>>,
889        span: Span,
890        assoc_tag: ty::AssocTag,
891    ) -> ErrorGuaranteed {
892        // FIXME(fmease): This was copied in parts from an old version of `rustc_hir_typeck::method::suggest`.
893        // Either
894        // * update this code by applying changes similar to #106702 or by taking a
895        //   Vec<(DefId, (DefId, DefId), Option<Vec<FulfillmentError<'tcx>>>)> or
896        // * deduplicate this code across the two crates.
897
898        let tcx = self.tcx();
899
900        let assoc_tag_str = assoc_tag_str(assoc_tag);
901        let adt_did = self_ty.ty_adt_def().map(|def| def.did());
902        let add_def_label = |err: &mut Diag<'_>| {
903            if let Some(did) = adt_did {
904                err.span_label(
905                    tcx.def_span(did),
906                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("associated {1} `{2}` not found for this {0}",
                tcx.def_descr(did), assoc_tag_str, name))
    })format!(
907                        "associated {assoc_tag_str} `{name}` not found for this {}",
908                        tcx.def_descr(did)
909                    ),
910                );
911            }
912        };
913
914        if fulfillment_errors.is_empty() {
915            // FIXME(fmease): Copied from `rustc_hir_typeck::method::probe`. Deduplicate.
916
917            let limit = if candidates.len() == 5 { 5 } else { 4 };
918            let type_candidates = candidates
919                .iter()
920                .take(limit)
921                .map(|cand| {
922                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("- `{0}`",
                tcx.at(span).type_of(cand.impl_).instantiate_identity().skip_norm_wip()))
    })format!(
923                        "- `{}`",
924                        tcx.at(span).type_of(cand.impl_).instantiate_identity().skip_norm_wip()
925                    )
926                })
927                .collect::<Vec<_>>()
928                .join("\n");
929            let additional_types = if candidates.len() > limit {
930                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\nand {0} more types",
                candidates.len() - limit))
    })format!("\nand {} more types", candidates.len() - limit)
931            } else {
932                String::new()
933            };
934
935            let mut err = {
    self.dcx().struct_span_err(name.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("associated {0} `{1}` not found for `{2}` in the current scope",
                            assoc_tag_str, name, self_ty))
                })).with_code(E0220)
}struct_span_code_err!(
936                self.dcx(),
937                name.span,
938                E0220,
939                "associated {assoc_tag_str} `{name}` not found for `{self_ty}` in the current scope"
940            );
941            err.span_label(name.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("associated item not found in `{0}`",
                self_ty))
    })format!("associated item not found in `{self_ty}`"));
942            err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the associated {0} was found for\n{1}{2}",
                assoc_tag_str, type_candidates, additional_types))
    })format!(
943                "the associated {assoc_tag_str} was found for\n{type_candidates}{additional_types}",
944            ));
945            add_def_label(&mut err);
946            return err.emit();
947        }
948
949        let mut bound_spans: SortedMap<Span, Vec<String>> = Default::default();
950
951        let mut bound_span_label = |self_ty: Ty<'_>, obligation: &str, quiet: &str| {
952            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`",
                if obligation.len() > 50 { quiet } else { obligation }))
    })format!("`{}`", if obligation.len() > 50 { quiet } else { obligation });
953            match self_ty.kind() {
954                // Point at the type that couldn't satisfy the bound.
955                ty::Adt(def, _) => {
956                    bound_spans.get_mut_or_insert_default(tcx.def_span(def.did())).push(msg)
957                }
958                // Point at the trait object that couldn't satisfy the bound.
959                ty::Dynamic(preds, _) => {
960                    for pred in preds.iter() {
961                        match pred.skip_binder() {
962                            ty::ExistentialPredicate::Trait(tr) => {
963                                bound_spans
964                                    .get_mut_or_insert_default(tcx.def_span(tr.def_id))
965                                    .push(msg.clone());
966                            }
967                            ty::ExistentialPredicate::Projection(_)
968                            | ty::ExistentialPredicate::AutoTrait(_) => {}
969                        }
970                    }
971                }
972                // Point at the closure that couldn't satisfy the bound.
973                ty::Closure(def_id, _) => {
974                    bound_spans
975                        .get_mut_or_insert_default(tcx.def_span(*def_id))
976                        .push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", quiet))
    })format!("`{quiet}`"));
977                }
978                _ => {}
979            }
980        };
981
982        let format_pred = |pred: ty::Predicate<'tcx>| {
983            let bound_predicate = pred.kind();
984            match bound_predicate.skip_binder() {
985                ty::PredicateKind::Clause(ty::ClauseKind::Projection(pred)) => {
986                    // `<Foo as Iterator>::Item = String`.
987                    let projection_term = pred.projection_term;
988                    let term = pred.term;
989                    let self_ty = projection_term.args.get(0).and_then(|arg| arg.as_type())?;
990
991                    let obligation = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} = {1}", projection_term, term))
    })format!("{projection_term} = {term}");
992                    let quiet_projection_term = projection_term
993                        .with_replaced_self_ty(tcx, Ty::new_var(tcx, ty::TyVid::ZERO));
994                    let quiet = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} = {1}", quiet_projection_term,
                term))
    })format!("{quiet_projection_term} = {term}");
995
996                    bound_span_label(self_ty, &obligation, &quiet);
997
998                    Some(obligation)
999                }
1000                ty::PredicateKind::Clause(ty::ClauseKind::Trait(poly_trait_ref)) => {
1001                    let p = poly_trait_ref.trait_ref;
1002                    let self_ty = p.self_ty();
1003                    let path = p.print_only_trait_path();
1004                    let obligation = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", self_ty, path))
    })format!("{self_ty}: {path}");
1005                    let quiet = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("_: {0}", path))
    })format!("_: {path}");
1006                    bound_span_label(self_ty, &obligation, &quiet);
1007                    Some(obligation)
1008                }
1009                _ => None,
1010            }
1011        };
1012
1013        // FIXME(fmease): `rustc_hir_typeck::method::suggest` uses a `skip_list` to filter out some bounds.
1014        // I would do the same here if it didn't mean more code duplication.
1015        let mut bounds: Vec<_> = fulfillment_errors
1016            .into_iter()
1017            .map(|error| error.root_obligation.predicate)
1018            .filter_map(format_pred)
1019            .map(|p| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", p))
    })format!("`{p}`"))
1020            .collect();
1021        bounds.sort();
1022        bounds.dedup();
1023
1024        let mut err = self.dcx().struct_span_err(
1025            name.span,
1026            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the associated {0} `{1}` exists for `{2}`, but its trait bounds were not satisfied",
                assoc_tag_str, name, self_ty))
    })format!("the associated {assoc_tag_str} `{name}` exists for `{self_ty}`, but its trait bounds were not satisfied")
1027        );
1028        if !bounds.is_empty() {
1029            err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the following trait bounds were not satisfied:\n{0}",
                bounds.join("\n")))
    })format!(
1030                "the following trait bounds were not satisfied:\n{}",
1031                bounds.join("\n")
1032            ));
1033        }
1034        err.span_label(
1035            name.span,
1036            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("associated {0} cannot be referenced on `{1}` due to unsatisfied trait bounds",
                assoc_tag_str, self_ty))
    })format!("associated {assoc_tag_str} cannot be referenced on `{self_ty}` due to unsatisfied trait bounds")
1037        );
1038
1039        for (span, mut bounds) in bound_spans {
1040            if !tcx.sess.source_map().is_span_accessible(span) {
1041                continue;
1042            }
1043            bounds.sort();
1044            bounds.dedup();
1045            let msg = match &bounds[..] {
1046                [bound] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("doesn\'t satisfy {0}", bound))
    })format!("doesn't satisfy {bound}"),
1047                bounds if bounds.len() > 4 => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("doesn\'t satisfy {0} bounds",
                bounds.len()))
    })format!("doesn't satisfy {} bounds", bounds.len()),
1048                [bounds @ .., last] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("doesn\'t satisfy {0} or {1}",
                bounds.join(", "), last))
    })format!("doesn't satisfy {} or {last}", bounds.join(", ")),
1049                [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1050            };
1051            err.span_label(span, msg);
1052        }
1053        add_def_label(&mut err);
1054        err.emit()
1055    }
1056
1057    /// If there are any missing associated items, emit an error instructing the user to provide
1058    /// them unless that's impossible due to shadowing. Moreover, if any corresponding trait refs
1059    /// are dyn incompatible due to associated items we emit an dyn incompatibility error instead.
1060    pub(crate) fn check_for_required_assoc_items(
1061        &self,
1062        spans: SmallVec<[Span; 1]>,
1063        missing_assoc_items: FxIndexSet<(DefId, ty::PolyTraitRef<'tcx>)>,
1064        potential_assoc_items: Vec<usize>,
1065        trait_bounds: &[hir::PolyTraitRef<'_>],
1066    ) -> Result<(), ErrorGuaranteed> {
1067        if missing_assoc_items.is_empty() {
1068            return Ok(());
1069        }
1070
1071        let tcx = self.tcx();
1072        let principal_span = *spans.first().unwrap();
1073
1074        // FIXME: This logic needs some more care w.r.t handling of conflicts
1075        let missing_assoc_items: Vec<_> = missing_assoc_items
1076            .into_iter()
1077            .map(|(def_id, trait_ref)| (tcx.associated_item(def_id), trait_ref))
1078            .collect();
1079        let mut names: FxIndexMap<_, Vec<_>> = Default::default();
1080        let mut names_len = 0;
1081        let mut descr = None;
1082
1083        enum Descr {
1084            Item,
1085            Tag(ty::AssocTag),
1086        }
1087
1088        for &(assoc_item, trait_ref) in &missing_assoc_items {
1089            // We don't want to suggest specifying associated items if there's something wrong with
1090            // any of them that renders the trait dyn incompatible; providing them certainly won't
1091            // fix the issue and we could also risk suggesting invalid code.
1092            //
1093            // Note that this check is only truly necessary in item ctxts where we merely perform
1094            // *minimal* dyn compatibility checks. In fn ctxts we would've already bailed out with
1095            // an error by this point if the trait was dyn incompatible.
1096            let violations =
1097                dyn_compatibility_violations_for_assoc_item(tcx, trait_ref.def_id(), assoc_item);
1098            if !violations.is_empty() {
1099                return Err(report_dyn_incompatibility(
1100                    tcx,
1101                    principal_span,
1102                    None,
1103                    trait_ref.def_id(),
1104                    &violations,
1105                )
1106                .emit());
1107            }
1108
1109            names.entry(trait_ref).or_default().push(assoc_item.name());
1110            names_len += 1;
1111
1112            descr = match descr {
1113                None => Some(Descr::Tag(assoc_item.tag())),
1114                Some(Descr::Tag(tag)) if tag != assoc_item.tag() => Some(Descr::Item),
1115                _ => continue,
1116            };
1117        }
1118
1119        // related to issue #91997, turbofishes added only when in an expr or pat
1120        let mut in_expr_or_pat = false;
1121        if let ([], [bound]) = (&potential_assoc_items[..], &trait_bounds) {
1122            let grandparent = tcx.parent_hir_node(tcx.parent_hir_id(bound.trait_ref.hir_ref_id));
1123            in_expr_or_pat = match grandparent {
1124                hir::Node::Expr(_) | hir::Node::Pat(_) => true,
1125                _ => false,
1126            };
1127        }
1128
1129        // We get all the associated items that *are* set, so that we can check if any of
1130        // their names match one of the ones we are missing.
1131        // This would mean that they are shadowing the associated item we are missing, and
1132        // we can then use their span to indicate this to the user.
1133        //
1134        // FIXME: This does not account for trait aliases. I think we should just make
1135        //        `lower_trait_object_ty` compute the list of all specified items or give us the
1136        //        necessary ingredients if it's too expensive to compute in the happy path.
1137        let bound_names: UnordMap<_, _> =
1138            trait_bounds
1139                .iter()
1140                .filter_map(|poly_trait_ref| {
1141                    let path = poly_trait_ref.trait_ref.path.segments.last()?;
1142                    let args = path.args?;
1143                    let Res::Def(DefKind::Trait, trait_def_id) = path.res else { return None };
1144
1145                    Some(args.constraints.iter().filter_map(move |constraint| {
1146                        let hir::AssocItemConstraintKind::Equality { term } = constraint.kind
1147                        else {
1148                            return None;
1149                        };
1150                        let tag = match term {
1151                            hir::Term::Ty(_) => ty::AssocTag::Type,
1152                            hir::Term::Const(_) => ty::AssocTag::Const,
1153                        };
1154                        let assoc_item = tcx
1155                            .associated_items(trait_def_id)
1156                            .find_by_ident_and_kind(tcx, constraint.ident, tag, trait_def_id)?;
1157                        Some(((constraint.ident.name, tag), assoc_item.def_id))
1158                    }))
1159                })
1160                .flatten()
1161                .collect();
1162
1163        let mut names: Vec<_> = names
1164            .into_iter()
1165            .map(|(trait_, mut assocs)| {
1166                assocs.sort();
1167                let trait_ = trait_.print_trait_sugared();
1168                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} in `{1}`",
                listify(&assocs[..],
                        |a|
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("`{0}`", a))
                                })).unwrap_or_default(), trait_))
    })format!(
1169                    "{} in `{trait_}`",
1170                    listify(&assocs[..], |a| format!("`{a}`")).unwrap_or_default()
1171                )
1172            })
1173            .collect();
1174        names.sort();
1175        let names = names.join(", ");
1176
1177        let descr = match descr.unwrap() {
1178            Descr::Item => "associated item",
1179            Descr::Tag(tag) => tag.descr(),
1180        };
1181        let mut err = {
    self.dcx().struct_span_err(principal_span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("the value of the {1}{0} {2} must be specified",
                            if names_len == 1 { "" } else { "s" }, descr, names))
                })).with_code(E0191)
}struct_span_code_err!(
1182            self.dcx(),
1183            principal_span,
1184            E0191,
1185            "the value of the {descr}{s} {names} must be specified",
1186            s = pluralize!(names_len),
1187        );
1188        let mut suggestions = ::alloc::vec::Vec::new()vec![];
1189        let mut items_count = 0;
1190        let mut where_constraints = ::alloc::vec::Vec::new()vec![];
1191        let mut already_has_generics_args_suggestion = false;
1192
1193        let mut names: UnordMap<_, usize> = Default::default();
1194        for (item, _) in &missing_assoc_items {
1195            items_count += 1;
1196            *names.entry((item.name(), item.tag())).or_insert(0) += 1;
1197        }
1198        let mut dupes = false;
1199        let mut shadows = false;
1200        for (item, trait_ref) in &missing_assoc_items {
1201            let name = item.name();
1202            let key = (name, item.tag());
1203
1204            if names[&key] > 1 {
1205                dupes = true;
1206            } else if bound_names.get(&key).is_some_and(|&def_id| def_id != item.def_id) {
1207                shadows = true;
1208            }
1209
1210            let prefix = if dupes || shadows {
1211                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::",
                tcx.def_path_str(trait_ref.def_id())))
    })format!("{}::", tcx.def_path_str(trait_ref.def_id()))
1212            } else {
1213                String::new()
1214            };
1215            let mut is_shadowed = false;
1216
1217            if let Some(&def_id) = bound_names.get(&key)
1218                && def_id != item.def_id
1219            {
1220                is_shadowed = true;
1221
1222                let rename_message = if def_id.is_local() { ", consider renaming it" } else { "" };
1223                err.span_label(
1224                    tcx.def_span(def_id),
1225                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}{1}` shadowed here{2}", prefix,
                name, rename_message))
    })format!("`{prefix}{name}` shadowed here{rename_message}"),
1226                );
1227            }
1228
1229            let rename_message = if is_shadowed { ", consider renaming it" } else { "" };
1230
1231            if let Some(sp) = tcx.hir_span_if_local(item.def_id) {
1232                err.span_label(sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}{1}` defined here{2}", prefix,
                name, rename_message))
    })format!("`{prefix}{name}` defined here{rename_message}"));
1233            }
1234        }
1235        if potential_assoc_items.len() == missing_assoc_items.len() {
1236            // When the amount of missing associated types equals the number of
1237            // extra type arguments present. A suggesting to replace the generic args with
1238            // associated types is already emitted.
1239            already_has_generics_args_suggestion = true;
1240        } else if let (Ok(snippet), false, false) =
1241            (tcx.sess.source_map().span_to_snippet(principal_span), dupes, shadows)
1242        {
1243            let bindings: Vec<_> = missing_assoc_items
1244                .iter()
1245                .map(|(item, _)| {
1246                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} = /* {1} */", item.name(),
                match item.kind {
                    ty::AssocKind::Const { .. } => "CONST",
                    ty::AssocKind::Type { .. } => "Type",
                    ty::AssocKind::Fn { .. } =>
                        ::core::panicking::panic("internal error: entered unreachable code"),
                }))
    })format!(
1247                        "{} = /* {} */",
1248                        item.name(),
1249                        match item.kind {
1250                            ty::AssocKind::Const { .. } => "CONST",
1251                            ty::AssocKind::Type { .. } => "Type",
1252                            ty::AssocKind::Fn { .. } => unreachable!(),
1253                        }
1254                    )
1255                })
1256                .collect();
1257            let code = if let Some(snippet) = snippet.strip_suffix("<>") {
1258                // Empty generics
1259                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}<{0}>", bindings.join(", "),
                snippet))
    })format!("{snippet}<{}>", bindings.join(", "))
1260            } else if let Some(snippet) = snippet.strip_suffix('>') {
1261                // Non-empty generics
1262                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}, {0}>", bindings.join(", "),
                snippet))
    })format!("{snippet}, {}>", bindings.join(", "))
1263            } else if in_expr_or_pat {
1264                // The user wrote `Trait`, so we don't have a term we can suggest, but at least we
1265                // can clue them to the correct syntax `Trait::<Item = /* ... */>`.
1266                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::<{1}>", snippet,
                bindings.join(", ")))
    })format!("{}::<{}>", snippet, bindings.join(", "))
1267            } else {
1268                // The user wrote `Trait`, so we don't have a term we can suggest, but at least we
1269                // can clue them to the correct syntax `Trait<Item = /* ... */>`.
1270                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}<{1}>", snippet,
                bindings.join(", ")))
    })format!("{}<{}>", snippet, bindings.join(", "))
1271            };
1272            suggestions.push((principal_span, code));
1273        } else if dupes {
1274            where_constraints.push(principal_span);
1275        }
1276
1277        // FIXME: This note doesn't make sense, get rid of this outright.
1278        //        I don't see how adding a type param (to the trait?) would help.
1279        //        If the user can modify the trait, they should just rename one of the assoc tys.
1280        //        What does it mean with the rest of the message?
1281        //        Does it suggest adding equality predicates (unimplemented) to the trait object
1282        //        type? (pseudo) "dyn B + <Self as B>::X = T + <Self as A>::X = U"?
1283        //        Instead, maybe mention shadowing if applicable (yes, even when no "relevant"
1284        //        bindings were provided).
1285        let where_msg = "consider introducing a new type parameter, adding `where` constraints \
1286                         using the fully-qualified path to the associated types";
1287        if !where_constraints.is_empty() && suggestions.is_empty() {
1288            // If there are duplicates associated type names and a single trait bound do not
1289            // use structured suggestion, it means that there are multiple supertraits with
1290            // the same associated type name.
1291            err.help(where_msg);
1292        }
1293        if suggestions.len() != 1 || already_has_generics_args_suggestion {
1294            // We don't need this label if there's an inline suggestion, show otherwise.
1295            let mut names: FxIndexMap<_, usize> = FxIndexMap::default();
1296            for (item, _) in &missing_assoc_items {
1297                items_count += 1;
1298                *names.entry(item.name()).or_insert(0) += 1;
1299            }
1300            let mut label = ::alloc::vec::Vec::new()vec![];
1301            for (item, trait_ref) in &missing_assoc_items {
1302                let name = item.name();
1303                let postfix = if names[&name] > 1 {
1304                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" (from trait `{0}`)",
                trait_ref.print_trait_sugared()))
    })format!(" (from trait `{}`)", trait_ref.print_trait_sugared())
1305                } else {
1306                    String::new()
1307                };
1308                label.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`{1}", name, postfix))
    })format!("`{}`{}", name, postfix));
1309            }
1310            if !label.is_empty() {
1311                err.span_label(
1312                    principal_span,
1313                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{2}{0} {1} must be specified",
                if label.len() == 1 { "" } else { "s" }, label.join(", "),
                descr))
    })format!(
1314                        "{descr}{s} {names} must be specified",
1315                        s = pluralize!(label.len()),
1316                        names = label.join(", "),
1317                    ),
1318                );
1319            }
1320        }
1321        suggestions.sort_by_key(|&(span, _)| span);
1322        // There are cases where one bound points to a span within another bound's span, like when
1323        // you have code like the following (#115019), so we skip providing a suggestion in those
1324        // cases to avoid having a malformed suggestion.
1325        //
1326        // pub struct Flatten<I> {
1327        //     inner: <IntoIterator<Item: IntoIterator<Item: >>::IntoIterator as Item>::core,
1328        //             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1329        //             |                  ^^^^^^^^^^^^^^^^^^^^^
1330        //             |                  |
1331        //             |                  associated types `Item`, `IntoIter` must be specified
1332        //             associated types `Item`, `IntoIter` must be specified
1333        // }
1334        let overlaps = suggestions.windows(2).any(|pair| pair[0].0.overlaps(pair[1].0));
1335        if !suggestions.is_empty() && !overlaps {
1336            err.multipart_suggestion(
1337                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("specify the {1}{0}",
                if items_count == 1 { "" } else { "s" }, descr))
    })format!("specify the {descr}{s}", s = pluralize!(items_count)),
1338                suggestions,
1339                Applicability::HasPlaceholders,
1340            );
1341            if !where_constraints.is_empty() {
1342                err.span_help(where_constraints, where_msg);
1343            }
1344        }
1345
1346        Err(err.emit())
1347    }
1348
1349    /// On ambiguous associated type, look for an associated function whose name matches the
1350    /// extended path and, if found, emit an E0223 error with a structured suggestion.
1351    /// e.g. for `String::from::utf8`, suggest `String::from_utf8` (#109195)
1352    pub(crate) fn maybe_report_similar_assoc_fn(
1353        &self,
1354        span: Span,
1355        qself_ty: Ty<'tcx>,
1356        qself: &hir::Ty<'_>,
1357    ) -> Result<(), ErrorGuaranteed> {
1358        let tcx = self.tcx();
1359        if let Some((_, node)) = tcx.hir_parent_iter(qself.hir_id).skip(1).next()
1360            && let hir::Node::Expr(hir::Expr {
1361                kind:
1362                    hir::ExprKind::Path(hir::QPath::TypeRelative(
1363                        hir::Ty {
1364                            kind:
1365                                hir::TyKind::Path(hir::QPath::TypeRelative(
1366                                    _,
1367                                    hir::PathSegment { ident: ident2, .. },
1368                                )),
1369                            ..
1370                        },
1371                        hir::PathSegment { ident: ident3, .. },
1372                    )),
1373                ..
1374            }) = node
1375            && let Some(inherent_impls) = qself_ty
1376                .ty_adt_def()
1377                .map(|adt_def| tcx.inherent_impls(adt_def.did()))
1378                .or_else(|| {
1379                    simplify_type(tcx, qself_ty, TreatParams::InstantiateWithInfer)
1380                        .map(|simple_ty| tcx.incoherent_impls(simple_ty))
1381                })
1382            && let name = Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}_{1}", ident2, ident3))
    })format!("{ident2}_{ident3}"))
1383            && let Some(item) = inherent_impls
1384                .iter()
1385                .flat_map(|&inherent_impl| {
1386                    tcx.associated_items(inherent_impl).filter_by_name_unhygienic(name)
1387                })
1388                .next()
1389            && item.is_fn()
1390        {
1391            Err({
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("ambiguous associated type"))
                })).with_code(E0223)
}struct_span_code_err!(self.dcx(), span, E0223, "ambiguous associated type")
1392                .with_span_suggestion_verbose(
1393                    ident2.span.to(ident3.span),
1394                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("there is an associated function with a similar name: `{0}`",
                name))
    })format!("there is an associated function with a similar name: `{name}`"),
1395                    name,
1396                    Applicability::MaybeIncorrect,
1397                )
1398                .emit())
1399        } else {
1400            Ok(())
1401        }
1402    }
1403
1404    pub fn report_prohibited_generic_args<'a>(
1405        &self,
1406        segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
1407        args_visitors: impl Iterator<Item = &'a hir::GenericArg<'a>> + Clone,
1408        err_extend: GenericsArgsErrExtend<'a>,
1409    ) -> ErrorGuaranteed {
1410        #[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for ProhibitGenericsArg {
    #[inline]
    fn eq(&self, other: &ProhibitGenericsArg) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ProhibitGenericsArg {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for ProhibitGenericsArg {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state)
    }
}Hash)]
1411        enum ProhibitGenericsArg {
1412            Lifetime,
1413            Type,
1414            Const,
1415            Infer,
1416        }
1417
1418        let mut prohibit_args = FxIndexSet::default();
1419        args_visitors.for_each(|arg| {
1420            match arg {
1421                hir::GenericArg::Lifetime(_) => prohibit_args.insert(ProhibitGenericsArg::Lifetime),
1422                hir::GenericArg::Type(_) => prohibit_args.insert(ProhibitGenericsArg::Type),
1423                hir::GenericArg::Const(_) => prohibit_args.insert(ProhibitGenericsArg::Const),
1424                hir::GenericArg::Infer(_) => prohibit_args.insert(ProhibitGenericsArg::Infer),
1425            };
1426        });
1427
1428        let segments: Vec<_> = segments.collect();
1429        let types_and_spans: Vec<_> = segments
1430            .iter()
1431            .flat_map(|segment| {
1432                if segment.args().args.is_empty() {
1433                    None
1434                } else {
1435                    Some((
1436                        match segment.res {
1437                            Res::PrimTy(ty) => {
1438                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `{1}`", segment.res.descr(),
                ty.name()))
    })format!("{} `{}`", segment.res.descr(), ty.name())
1439                            }
1440                            Res::Def(_, def_id)
1441                                if let Some(name) = self.tcx().opt_item_name(def_id) =>
1442                            {
1443                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `{1}`", segment.res.descr(),
                name))
    })format!("{} `{name}`", segment.res.descr())
1444                            }
1445                            Res::Err => "this type".to_string(),
1446                            _ => segment.res.descr().to_string(),
1447                        },
1448                        segment.ident.span,
1449                    ))
1450                }
1451            })
1452            .collect();
1453        let this_type = listify(&types_and_spans, |(t, _)| t.to_string())
1454            .expect("expected one segment to deny");
1455
1456        let arg_spans: Vec<Span> =
1457            segments.iter().flat_map(|segment| segment.args().args).map(|arg| arg.span()).collect();
1458
1459        let mut kinds = Vec::with_capacity(4);
1460        prohibit_args.iter().for_each(|arg| match arg {
1461            ProhibitGenericsArg::Lifetime => kinds.push("lifetime"),
1462            ProhibitGenericsArg::Type => kinds.push("type"),
1463            ProhibitGenericsArg::Const => kinds.push("const"),
1464            ProhibitGenericsArg::Infer => kinds.push("generic"),
1465        });
1466
1467        let s = if kinds.len() == 1 { "" } else { "s" }pluralize!(kinds.len());
1468        let kind =
1469            listify(&kinds, |k| k.to_string()).expect("expected at least one generic to prohibit");
1470        let last_span = *arg_spans.last().unwrap();
1471        let span: MultiSpan = arg_spans.into();
1472        let mut err = {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0} arguments are not allowed on {1}",
                            kind, this_type))
                })).with_code(E0109)
}struct_span_code_err!(
1473            self.dcx(),
1474            span,
1475            E0109,
1476            "{kind} arguments are not allowed on {this_type}",
1477        );
1478        err.span_label(last_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} argument{1} not allowed", kind,
                s))
    })format!("{kind} argument{s} not allowed"));
1479        for (what, span) in types_and_spans {
1480            err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not allowed on {0}", what))
    })format!("not allowed on {what}"));
1481        }
1482        generics_args_err_extend(self.tcx(), segments.into_iter(), &mut err, err_extend);
1483        err.emit()
1484    }
1485
1486    pub fn report_trait_object_addition_traits(
1487        &self,
1488        regular_traits: &Vec<(ty::PolyTraitPredicate<'tcx>, SmallVec<[Span; 1]>)>,
1489    ) -> ErrorGuaranteed {
1490        // we use the last span to point at the traits themselves,
1491        // and all other preceding spans are trait alias expansions.
1492        let (&first_span, first_alias_spans) = regular_traits[0].1.split_last().unwrap();
1493        let (&second_span, second_alias_spans) = regular_traits[1].1.split_last().unwrap();
1494        let mut err = {
    self.dcx().struct_span_err(*regular_traits[1].1.first().unwrap(),
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("only auto traits can be used as additional traits in a trait object"))
                })).with_code(E0225)
}struct_span_code_err!(
1495            self.dcx(),
1496            *regular_traits[1].1.first().unwrap(),
1497            E0225,
1498            "only auto traits can be used as additional traits in a trait object"
1499        );
1500        err.span_label(first_span, "first non-auto trait");
1501        for &alias_span in first_alias_spans {
1502            err.span_label(alias_span, "first non-auto trait comes from this alias");
1503        }
1504        err.span_label(second_span, "additional non-auto trait");
1505        for &alias_span in second_alias_spans {
1506            err.span_label(alias_span, "second non-auto trait comes from this alias");
1507        }
1508        err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider creating a new trait with all of these as supertraits and using that trait here instead: `trait NewTrait: {0} {{}}`",
                regular_traits.iter().map(|(pred, _)|
                                pred.map_bound(|pred|
                                                pred.trait_ref).print_only_trait_path().to_string()).collect::<Vec<_>>().join(" + ")))
    })format!(
1509            "consider creating a new trait with all of these as supertraits and using that \
1510             trait here instead: `trait NewTrait: {} {{}}`",
1511            regular_traits
1512                .iter()
1513                // FIXME: This should `print_sugared`, but also needs to integrate projection bounds...
1514                .map(|(pred, _)| pred
1515                    .map_bound(|pred| pred.trait_ref)
1516                    .print_only_trait_path()
1517                    .to_string())
1518                .collect::<Vec<_>>()
1519                .join(" + "),
1520        ));
1521        err.note(
1522            "auto-traits like `Send` and `Sync` are traits that have special properties; \
1523             for more information on them, visit \
1524             <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>",
1525        );
1526        err.emit()
1527    }
1528
1529    pub fn report_trait_object_with_no_traits(
1530        &self,
1531        span: Span,
1532        user_written_clauses: impl IntoIterator<Item = (ty::Clause<'tcx>, Span)>,
1533    ) -> ErrorGuaranteed {
1534        let tcx = self.tcx();
1535        let trait_alias_span = user_written_clauses
1536            .into_iter()
1537            .filter_map(|(clause, _)| clause.as_trait_clause())
1538            .find(|trait_ref| tcx.is_trait_alias(trait_ref.def_id()))
1539            .map(|trait_ref| tcx.def_span(trait_ref.def_id()));
1540
1541        self.dcx().emit_err(TraitObjectDeclaredWithNoTraits { span, trait_alias_span })
1542    }
1543}
1544
1545/// Emit an error for the given associated item constraint.
1546pub fn prohibit_assoc_item_constraint(
1547    cx: &dyn HirTyLowerer<'_>,
1548    constraint: &hir::AssocItemConstraint<'_>,
1549    segment: Option<(DefId, &hir::PathSegment<'_>, Span)>,
1550) -> ErrorGuaranteed {
1551    let tcx = cx.tcx();
1552    let mut err = cx.dcx().create_err(AssocItemConstraintsNotAllowedHere {
1553        span: constraint.span,
1554        fn_trait_expansion: if let Some((_, segment, span)) = segment
1555            && segment.args().parenthesized == hir::GenericArgsParentheses::ParenSugar
1556        {
1557            Some(ParenthesizedFnTraitExpansion {
1558                span,
1559                expanded_type: fn_trait_to_string(tcx, segment, false),
1560            })
1561        } else {
1562            None
1563        },
1564    });
1565
1566    // Emit a suggestion to turn the assoc item binding into a generic arg
1567    // if the relevant item has a generic param whose name matches the binding name;
1568    // otherwise suggest the removal of the binding.
1569    if let Some((def_id, segment, _)) = segment
1570        && segment.args().parenthesized == hir::GenericArgsParentheses::No
1571    {
1572        // Suggests removal of the offending binding
1573        let suggest_removal = |e: &mut Diag<'_>| {
1574            let constraints = segment.args().constraints;
1575            let args = segment.args().args;
1576
1577            // Compute the span to remove based on the position
1578            // of the binding. We do that as follows:
1579            //  1. Find the index of the binding in the list of bindings
1580            //  2. Locate the spans preceding and following the binding.
1581            //     If it's the first binding the preceding span would be
1582            //     that of the last arg
1583            //  3. Using this information work out whether the span
1584            //     to remove will start from the end of the preceding span,
1585            //     the start of the next span or will simply be the
1586            //     span encomassing everything within the generics brackets
1587
1588            let Some(index) = constraints.iter().position(|b| b.hir_id == constraint.hir_id) else {
1589                ::rustc_middle::util::bug::bug_fmt(format_args!("a type binding exists but its HIR ID not found in generics"));bug!("a type binding exists but its HIR ID not found in generics");
1590            };
1591
1592            let preceding_span = if index > 0 {
1593                Some(constraints[index - 1].span)
1594            } else {
1595                args.last().map(|a| a.span())
1596            };
1597
1598            let next_span = constraints.get(index + 1).map(|constraint| constraint.span);
1599
1600            let removal_span = match (preceding_span, next_span) {
1601                (Some(prec), _) => constraint.span.with_lo(prec.hi()),
1602                (None, Some(next)) => constraint.span.with_hi(next.lo()),
1603                (None, None) => {
1604                    let Some(generics_span) = segment.args().span_ext() else {
1605                        ::rustc_middle::util::bug::bug_fmt(format_args!("a type binding exists but generic span is empty"));bug!("a type binding exists but generic span is empty");
1606                    };
1607
1608                    generics_span
1609                }
1610            };
1611
1612            // Now emit the suggestion
1613            e.span_suggestion_verbose(
1614                removal_span,
1615                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider removing this associated item {0}",
                constraint.kind.descr()))
    })format!("consider removing this associated item {}", constraint.kind.descr()),
1616                "",
1617                Applicability::MaybeIncorrect,
1618            );
1619        };
1620
1621        // Suggest replacing the associated item binding with a generic argument.
1622        // i.e., replacing `<..., T = A, ...>` with `<..., A, ...>`.
1623        let suggest_direct_use = |e: &mut Diag<'_>, sp: Span| {
1624            if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(sp) {
1625                e.span_suggestion_verbose(
1626                    constraint.span,
1627                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("to use `{0}` as a generic argument specify it directly",
                snippet))
    })format!("to use `{snippet}` as a generic argument specify it directly"),
1628                    snippet,
1629                    Applicability::MaybeIncorrect,
1630                );
1631            }
1632        };
1633
1634        // Check if the type has a generic param with the same name
1635        // as the assoc type name in the associated item binding.
1636        let generics = tcx.generics_of(def_id);
1637        let matching_param = generics.own_params.iter().find(|p| p.name == constraint.ident.name);
1638
1639        // Now emit the appropriate suggestion
1640        if let Some(matching_param) = matching_param {
1641            match (constraint.kind, &matching_param.kind) {
1642                (
1643                    hir::AssocItemConstraintKind::Equality { term: hir::Term::Ty(ty) },
1644                    GenericParamDefKind::Type { .. },
1645                ) => suggest_direct_use(&mut err, ty.span),
1646                (
1647                    hir::AssocItemConstraintKind::Equality { term: hir::Term::Const(c) },
1648                    GenericParamDefKind::Const { .. },
1649                ) => {
1650                    suggest_direct_use(&mut err, c.span);
1651                }
1652                (hir::AssocItemConstraintKind::Bound { bounds }, _) => {
1653                    // Suggest `impl<T: Bound> Trait<T> for Foo` when finding
1654                    // `impl Trait<T: Bound> for Foo`
1655
1656                    // Get the parent impl block based on the binding we have
1657                    // and the trait DefId
1658                    let impl_block = tcx
1659                        .hir_parent_iter(constraint.hir_id)
1660                        .find_map(|(_, node)| node.impl_block_of_trait(def_id));
1661
1662                    let type_with_constraints =
1663                        tcx.sess.source_map().span_to_snippet(constraint.span);
1664
1665                    if let Some(impl_block) = impl_block
1666                        && let Ok(type_with_constraints) = type_with_constraints
1667                    {
1668                        // Filter out the lifetime parameters because
1669                        // they should be declared before the type parameter
1670                        let lifetimes: String = bounds
1671                            .iter()
1672                            .filter_map(|bound| {
1673                                if let hir::GenericBound::Outlives(lifetime) = bound {
1674                                    Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, ", lifetime))
    })format!("{lifetime}, "))
1675                                } else {
1676                                    None
1677                                }
1678                            })
1679                            .collect();
1680                        // Figure out a span and suggestion string based on
1681                        // whether there are any existing parameters
1682                        let param_decl = if let Some(param_span) =
1683                            impl_block.generics.span_for_param_suggestion()
1684                        {
1685                            (param_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", {0}{1}", lifetimes,
                type_with_constraints))
    })format!(", {lifetimes}{type_with_constraints}"))
1686                        } else {
1687                            (
1688                                impl_block.generics.span.shrink_to_lo(),
1689                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}{1}>", lifetimes,
                type_with_constraints))
    })format!("<{lifetimes}{type_with_constraints}>"),
1690                            )
1691                        };
1692                        let suggestions = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [param_decl,
                (constraint.span.with_lo(constraint.ident.span.hi()),
                    String::new())]))vec![
1693                            param_decl,
1694                            (constraint.span.with_lo(constraint.ident.span.hi()), String::new()),
1695                        ];
1696
1697                        err.multipart_suggestion(
1698                            "declare the type parameter right after the `impl` keyword",
1699                            suggestions,
1700                            Applicability::MaybeIncorrect,
1701                        );
1702                    }
1703                }
1704                _ => suggest_removal(&mut err),
1705            }
1706        } else {
1707            suggest_removal(&mut err);
1708        }
1709    }
1710
1711    err.emit()
1712}
1713
1714pub(crate) fn fn_trait_to_string(
1715    tcx: TyCtxt<'_>,
1716    trait_segment: &hir::PathSegment<'_>,
1717    parenthesized: bool,
1718) -> String {
1719    let args = trait_segment
1720        .args
1721        .and_then(|args| args.args.first())
1722        .and_then(|arg| match arg {
1723            hir::GenericArg::Type(ty) => match ty.kind {
1724                hir::TyKind::Tup(t) => t
1725                    .iter()
1726                    .map(|e| tcx.sess.source_map().span_to_snippet(e.span))
1727                    .collect::<Result<Vec<_>, _>>()
1728                    .map(|a| a.join(", ")),
1729                _ => tcx.sess.source_map().span_to_snippet(ty.span),
1730            }
1731            .map(|s| {
1732                // `is_empty()` checks to see if the type is the unit tuple, if so we don't want a comma
1733                if parenthesized || s.is_empty() { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0})", s))
    })format!("({s})") } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0},)", s))
    })format!("({s},)") }
1734            })
1735            .ok(),
1736            _ => None,
1737        })
1738        .unwrap_or_else(|| "()".to_string());
1739
1740    let ret = trait_segment
1741        .args()
1742        .constraints
1743        .iter()
1744        .find_map(|c| {
1745            if c.ident.name == sym::Output
1746                && let Some(ty) = c.ty()
1747                && ty.span != tcx.hir_span(trait_segment.hir_id)
1748            {
1749                tcx.sess.source_map().span_to_snippet(ty.span).ok()
1750            } else {
1751                None
1752            }
1753        })
1754        .unwrap_or_else(|| "()".to_string());
1755
1756    if parenthesized {
1757        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1} -> {2}",
                trait_segment.ident, args, ret))
    })format!("{}{} -> {}", trait_segment.ident, args, ret)
1758    } else {
1759        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}<{1}, Output={2}>",
                trait_segment.ident, args, ret))
    })format!("{}<{}, Output={}>", trait_segment.ident, args, ret)
1760    }
1761}
1762
1763/// Used for generics args error extend.
1764pub enum GenericsArgsErrExtend<'tcx> {
1765    EnumVariant {
1766        qself: &'tcx hir::Ty<'tcx>,
1767        assoc_segment: &'tcx hir::PathSegment<'tcx>,
1768        adt_def: AdtDef<'tcx>,
1769    },
1770    OpaqueTy,
1771    PrimTy(hir::PrimTy),
1772    SelfTyAlias {
1773        def_id: DefId,
1774        span: Span,
1775    },
1776    SelfTyParam(Span),
1777    Param(DefId),
1778    DefVariant(&'tcx [hir::PathSegment<'tcx>]),
1779    None,
1780}
1781
1782fn generics_args_err_extend<'a>(
1783    tcx: TyCtxt<'_>,
1784    segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
1785    err: &mut Diag<'_>,
1786    err_extend: GenericsArgsErrExtend<'a>,
1787) {
1788    match err_extend {
1789        GenericsArgsErrExtend::EnumVariant { qself, assoc_segment, adt_def } => {
1790            err.note("enum variants can't have type parameters");
1791            let type_name = tcx.item_name(adt_def.did());
1792            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might have meant to specify type parameters on enum `{0}`",
                type_name))
    })format!(
1793                "you might have meant to specify type parameters on enum \
1794                `{type_name}`"
1795            );
1796            let Some(args) = assoc_segment.args else {
1797                return;
1798            };
1799            // Get the span of the generics args *including* the leading `::`.
1800            // We do so by stretching args.span_ext to the left by 2. Earlier
1801            // it was done based on the end of assoc segment but that sometimes
1802            // led to impossible spans and caused issues like #116473
1803            let args_span = args.span_ext.with_lo(args.span_ext.lo() - BytePos(2));
1804            if tcx.generics_of(adt_def.did()).is_empty() {
1805                // FIXME(estebank): we could also verify that the arguments being
1806                // work for the `enum`, instead of just looking if it takes *any*.
1807                err.span_suggestion_verbose(
1808                    args_span,
1809                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} doesn\'t have generic parameters",
                type_name))
    })format!("{type_name} doesn't have generic parameters"),
1810                    "",
1811                    Applicability::MachineApplicable,
1812                );
1813                return;
1814            }
1815            let Ok(snippet) = tcx.sess.source_map().span_to_snippet(args_span) else {
1816                err.note(msg);
1817                return;
1818            };
1819            let (qself_sugg_span, is_self) =
1820                if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &qself.kind {
1821                    // If the path segment already has type params, we want to overwrite
1822                    // them.
1823                    match &path.segments {
1824                        // `segment` is the previous to last element on the path,
1825                        // which would normally be the `enum` itself, while the last
1826                        // `_` `PathSegment` corresponds to the variant.
1827                        [
1828                            ..,
1829                            hir::PathSegment {
1830                                ident, args, res: Res::Def(DefKind::Enum, _), ..
1831                            },
1832                            _,
1833                        ] => (
1834                            // We need to include the `::` in `Type::Variant::<Args>`
1835                            // to point the span to `::<Args>`, not just `<Args>`.
1836                            ident
1837                                .span
1838                                .shrink_to_hi()
1839                                .to(args.map_or(ident.span.shrink_to_hi(), |a| a.span_ext)),
1840                            false,
1841                        ),
1842                        [segment] => {
1843                            (
1844                                // We need to include the `::` in `Type::Variant::<Args>`
1845                                // to point the span to `::<Args>`, not just `<Args>`.
1846                                segment.ident.span.shrink_to_hi().to(segment
1847                                    .args
1848                                    .map_or(segment.ident.span.shrink_to_hi(), |a| a.span_ext)),
1849                                kw::SelfUpper == segment.ident.name,
1850                            )
1851                        }
1852                        _ => {
1853                            err.note(msg);
1854                            return;
1855                        }
1856                    }
1857                } else {
1858                    err.note(msg);
1859                    return;
1860                };
1861            let suggestion = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [if is_self {
                    (qself.span,
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("{0}{1}", type_name,
                                        snippet))
                            }))
                } else { (qself_sugg_span, snippet) },
                (args_span, String::new())]))vec![
1862                if is_self {
1863                    // Account for people writing `Self::Variant::<Args>`, where
1864                    // `Self` is the enum, and suggest replacing `Self` with the
1865                    // appropriate type: `Type::<Args>::Variant`.
1866                    (qself.span, format!("{type_name}{snippet}"))
1867                } else {
1868                    (qself_sugg_span, snippet)
1869                },
1870                (args_span, String::new()),
1871            ];
1872            err.multipart_suggestion(msg, suggestion, Applicability::MaybeIncorrect);
1873        }
1874        GenericsArgsErrExtend::DefVariant(segments) => {
1875            let args: Vec<Span> = segments
1876                .iter()
1877                .filter_map(|segment| match segment.res {
1878                    Res::Def(
1879                        DefKind::Ctor(CtorOf::Variant, _) | DefKind::Variant | DefKind::Enum,
1880                        _,
1881                    ) => segment.args().span_ext().map(|s| s.with_lo(segment.ident.span.hi())),
1882                    _ => None,
1883                })
1884                .collect();
1885            if args.len() > 1
1886                && let Some(span) = args.into_iter().next_back()
1887            {
1888                err.note(
1889                    "generic arguments are not allowed on both an enum and its variant's path \
1890                     segments simultaneously; they are only valid in one place or the other",
1891                );
1892                err.span_suggestion_verbose(
1893                    span,
1894                    "remove the generics arguments from one of the path segments",
1895                    String::new(),
1896                    Applicability::MaybeIncorrect,
1897                );
1898            }
1899        }
1900        GenericsArgsErrExtend::PrimTy(prim_ty) => {
1901            let name = prim_ty.name_str();
1902            for segment in segments {
1903                if let Some(args) = segment.args {
1904                    err.span_suggestion_verbose(
1905                        segment.ident.span.shrink_to_hi().to(args.span_ext),
1906                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("primitive type `{0}` doesn\'t have generic parameters",
                name))
    })format!("primitive type `{name}` doesn't have generic parameters"),
1907                        "",
1908                        Applicability::MaybeIncorrect,
1909                    );
1910                }
1911            }
1912        }
1913        GenericsArgsErrExtend::OpaqueTy => {
1914            err.note("`impl Trait` types can't have type parameters");
1915        }
1916        GenericsArgsErrExtend::Param(def_id) => {
1917            let span = tcx.def_ident_span(def_id).unwrap();
1918            let kind = tcx.def_descr(def_id);
1919            let name = tcx.item_name(def_id);
1920            err.span_note(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `{1}` defined here", kind,
                name))
    })format!("{kind} `{name}` defined here"));
1921        }
1922        GenericsArgsErrExtend::SelfTyParam(span) => {
1923            err.span_suggestion_verbose(
1924                span,
1925                "the `Self` type doesn't accept type parameters",
1926                "",
1927                Applicability::MaybeIncorrect,
1928            );
1929        }
1930        GenericsArgsErrExtend::SelfTyAlias { def_id, span } => {
1931            let ty = tcx.at(span).type_of(def_id).instantiate_identity().skip_norm_wip();
1932            let span_of_impl = tcx.span_of_impl(def_id);
1933            let ty::Adt(self_def, _) = *ty.kind() else { return };
1934            let def_id = self_def.did();
1935
1936            let type_name = tcx.item_name(def_id);
1937            let span_of_ty = tcx.def_ident_span(def_id);
1938            let generics = tcx.generics_of(def_id).count();
1939
1940            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`Self` is of type `{0}`", ty))
    })format!("`Self` is of type `{ty}`");
1941            if let (Ok(i_sp), Some(t_sp)) = (span_of_impl, span_of_ty) {
1942                let mut span: MultiSpan = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [t_sp]))vec![t_sp].into();
1943                span.push_span_label(
1944                    i_sp,
1945                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`Self` is on type `{0}` in this `impl`",
                type_name))
    })format!("`Self` is on type `{type_name}` in this `impl`"),
1946                );
1947                let mut postfix = "";
1948                if generics == 0 {
1949                    postfix = ", which doesn't have generic parameters";
1950                }
1951                span.push_span_label(t_sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`Self` corresponds to this type{0}",
                postfix))
    })format!("`Self` corresponds to this type{postfix}"));
1952                err.span_note(span, msg);
1953            } else {
1954                err.note(msg);
1955            }
1956            for segment in segments {
1957                if let Some(args) = segment.args
1958                    && segment.ident.name == kw::SelfUpper
1959                {
1960                    if generics == 0 {
1961                        // FIXME(estebank): we could also verify that the arguments being
1962                        // work for the `enum`, instead of just looking if it takes *any*.
1963                        err.span_suggestion_verbose(
1964                            segment.ident.span.shrink_to_hi().to(args.span_ext),
1965                            "the `Self` type doesn't accept type parameters",
1966                            "",
1967                            Applicability::MachineApplicable,
1968                        );
1969                        return;
1970                    } else {
1971                        err.span_suggestion_verbose(
1972                            segment.ident.span,
1973                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the `Self` type doesn\'t accept type parameters, use the concrete type\'s name `{0}` instead if you want to specify its type parameters",
                type_name))
    })format!(
1974                                "the `Self` type doesn't accept type parameters, use the \
1975                                concrete type's name `{type_name}` instead if you want to \
1976                                specify its type parameters"
1977                            ),
1978                            type_name,
1979                            Applicability::MaybeIncorrect,
1980                        );
1981                    }
1982                }
1983            }
1984        }
1985        _ => {}
1986    }
1987}
1988
1989pub(super) struct AmbiguityBetweenVariantAndAssocItem<'tcx> {
1990    pub(super) variant_def_id: DefId,
1991    pub(super) item_def_id: DefId,
1992    pub(super) span: Span,
1993    pub(super) segment_ident: Ident,
1994    pub(super) bound_def_id: DefId,
1995    pub(super) self_ty: Ty<'tcx>,
1996    pub(super) tcx: TyCtxt<'tcx>,
1997    pub(super) mode: super::LowerTypeRelativePathMode,
1998}
1999
2000impl<'a, 'tcx> rustc_errors::Diagnostic<'a, ()> for AmbiguityBetweenVariantAndAssocItem<'tcx> {
2001    fn into_diag(
2002        self,
2003        dcx: rustc_errors::DiagCtxtHandle<'a>,
2004        level: rustc_errors::Level,
2005    ) -> Diag<'a, ()> {
2006        let Self {
2007            variant_def_id,
2008            item_def_id,
2009            span,
2010            segment_ident,
2011            bound_def_id,
2012            self_ty,
2013            tcx,
2014            mode,
2015        } = self;
2016        let mut lint = Diag::new(dcx, level, "ambiguous associated item");
2017
2018        let mut could_refer_to = |kind: DefKind, def_id, also| {
2019            let note_msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` could{1} refer to the {2} defined here",
                segment_ident, also, tcx.def_kind_descr(kind, def_id)))
    })format!(
2020                "`{}` could{} refer to the {} defined here",
2021                segment_ident,
2022                also,
2023                tcx.def_kind_descr(kind, def_id)
2024            );
2025            lint.span_note(tcx.def_span(def_id), note_msg);
2026        };
2027
2028        could_refer_to(DefKind::Variant, variant_def_id, "");
2029        could_refer_to(mode.def_kind_for_diagnostics(), item_def_id, " also");
2030
2031        lint.span_suggestion(
2032            span,
2033            "use fully-qualified syntax",
2034            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0} as {1}>::{2}", self_ty,
                tcx.item_name(bound_def_id), segment_ident))
    })format!("<{} as {}>::{}", self_ty, tcx.item_name(bound_def_id), segment_ident),
2035            Applicability::MachineApplicable,
2036        );
2037        lint
2038    }
2039}
2040
2041fn assoc_tag_str(assoc_tag: ty::AssocTag) -> &'static str {
2042    match assoc_tag {
2043        ty::AssocTag::Fn => "function",
2044        ty::AssocTag::Const => "constant",
2045        ty::AssocTag::Type => "type",
2046    }
2047}