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