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