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