1use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
2use rustc_data_structures::sorted_map::SortedMap;
3use rustc_data_structures::thin_vec::ThinVec;
4use rustc_data_structures::unord::UnordMap;
5use rustc_errors::codes::*;
6use rustc_errors::{
7 Applicability, Diag, ErrorGuaranteed, MultiSpan, SuggestionStyle, listify, msg, pluralize,
8 struct_span_code_err,
9};
10use rustc_hir::def::{CtorOf, DefKind, Res};
11use rustc_hir::def_id::DefId;
12use rustc_hir::{self as hir, HirId};
13use rustc_middle::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::diagnostics::feature_err;
20use rustc_span::edit_distance::find_best_match_for_name;
21use rustc_span::{BytePos, DUMMY_SP, Ident, OrdSpan, Span, Symbol, bug, 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::diagnostics::{
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(diagnostics::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_verbose(
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<'_>>,
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 = diagnostics::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 = Some(diagnostics::AssocItemNotFoundLabel::NotFound {
165 span,
166 assoc_ident,
167 assoc_kind,
168 });
169 return self.dcx().emit_err(err);
170 }
171
172 let all_candidate_names: Vec<_> = all_candidates()
173 .flat_map(|r| tcx.associated_items(r.def_id()).in_definition_order())
174 .filter_map(|item| {
175 if !item.is_impl_trait_in_trait() && item.tag() == assoc_tag {
176 item.opt_name()
177 } else {
178 None
179 }
180 })
181 .collect();
182
183 if let Some(suggested_name) =
184 find_best_match_for_name(&all_candidate_names, assoc_ident.name, None)
185 {
186 err.sugg = Some(diagnostics::AssocItemNotFoundSugg::Similar {
187 span: assoc_ident.span,
188 assoc_kind,
189 suggested_name,
190 });
191 return self.dcx().emit_err(err);
192 }
193
194 let visible_traits: Vec<_> = tcx
199 .visible_traits()
200 .filter(|trait_def_id| {
201 let viz = tcx.visibility(*trait_def_id);
202 viz.is_accessible_from(self.mod_id(), tcx)
203 })
204 .collect();
205
206 let wider_candidate_names: Vec<_> = visible_traits
207 .iter()
208 .flat_map(|trait_def_id| tcx.associated_items(*trait_def_id).in_definition_order())
209 .filter_map(|item| {
210 (!item.is_impl_trait_in_trait() && item.tag() == assoc_tag).then(|| item.name())
211 })
212 .collect();
213
214 if let Some(suggested_name) =
215 find_best_match_for_name(&wider_candidate_names, assoc_ident.name, None)
216 {
217 if let [best_trait] = visible_traits
218 .iter()
219 .copied()
220 .filter(|&trait_def_id| {
221 tcx.associated_items(trait_def_id)
222 .filter_by_name_unhygienic(suggested_name)
223 .any(|item| item.tag() == assoc_tag)
224 })
225 .collect::<Vec<_>>()[..]
226 {
227 let trait_name = tcx.def_path_str(best_trait);
228 err.label = Some(diagnostics::AssocItemNotFoundLabel::FoundInOtherTrait {
229 span: assoc_ident.span,
230 assoc_kind,
231 trait_name: &trait_name,
232 suggested_name,
233 identically_named: suggested_name == assoc_ident.name,
234 });
235 if let AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span) = qself
236 && let item_def_id =
240 tcx.hir_get_parent_item(tcx.local_def_id_to_hir_id(ty_param_def_id))
241 && let Some(generics) = tcx.hir_get_generics(item_def_id.def_id)
243 {
244 if generics
248 .bounds_for_param(ty_param_def_id)
249 .flat_map(|pred| pred.bounds.iter())
250 .any(|b| match b {
251 hir::GenericBound::Trait(t, ..) => {
252 t.trait_ref.trait_def_id() == Some(best_trait)
253 }
254 _ => false,
255 })
256 {
257 err.sugg = Some(diagnostics::AssocItemNotFoundSugg::SimilarInOtherTrait {
260 span: assoc_ident.span,
261 trait_name: &trait_name,
262 assoc_kind,
263 suggested_name,
264 });
265 return self.dcx().emit_err(err);
266 }
267
268 let trait_args = &ty::GenericArgs::identity_for_item(tcx, best_trait)[1..];
269 let mut trait_ref = trait_name.clone();
270 let applicability = if let [arg, args @ ..] = trait_args {
271 use std::fmt::Write;
272 trait_ref.write_fmt(format_args!("</* {0}", arg))write!(trait_ref, "</* {arg}").unwrap();
273 args.iter().try_for_each(|arg| trait_ref.write_fmt(format_args!(", {0}", arg))write!(trait_ref, ", {arg}")).unwrap();
274 trait_ref += " */>";
275 Applicability::HasPlaceholders
276 } else {
277 Applicability::MaybeIncorrect
278 };
279
280 let identically_named = suggested_name == assoc_ident.name;
281
282 if let DefKind::TyAlias = tcx.def_kind(item_def_id)
283 && !tcx.type_alias_is_checked(item_def_id)
284 {
285 err.sugg =
286 Some(diagnostics::AssocItemNotFoundSugg::SimilarInOtherTraitQPath {
287 lo: ty_param_span.shrink_to_lo(),
288 mi: ty_param_span.shrink_to_hi(),
289 hi: (!identically_named).then_some(assoc_ident.span),
290 trait_ref,
291 identically_named,
292 suggested_name,
293 assoc_kind,
294 applicability,
295 });
296 } else {
297 let mut err = self.dcx().create_err(err);
298 if suggest_constraining_type_param(
299 tcx,
300 generics,
301 &mut err,
302 &qself_str,
303 &trait_ref,
304 Some(best_trait),
305 None,
306 ) && !identically_named
307 {
308 err.span_suggestion_verbose(
311 assoc_ident.span,
312 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...and changing the associated {$assoc_kind} name"))msg!("...and changing the associated {$assoc_kind} name"),
313 suggested_name,
314 Applicability::MaybeIncorrect,
315 );
316 }
317 return err.emit_err();
318 }
319 }
320 return self.dcx().emit_err(err);
321 }
322 }
323
324 if let [candidate_name] = all_candidate_names.as_slice() {
327 err.sugg = Some(diagnostics::AssocItemNotFoundSugg::Other {
328 span: assoc_ident.span,
329 qself: &qself_str,
330 assoc_kind,
331 suggested_name: *candidate_name,
332 });
333 } else {
334 err.label = Some(diagnostics::AssocItemNotFoundLabel::NotFound {
335 span: assoc_ident.span,
336 assoc_ident,
337 assoc_kind,
338 });
339 }
340
341 self.dcx().emit_err(err)
342 }
343
344 fn report_assoc_kind_mismatch(
345 &self,
346 assoc_item: &ty::AssocItem,
347 assoc_tag: ty::AssocTag,
348 ident: Ident,
349 span: Span,
350 constraint: Option<&hir::AssocItemConstraint<'_>>,
351 ) -> ErrorGuaranteed {
352 let tcx = self.tcx();
353
354 let bound_on_assoc_const_label = if let ty::AssocKind::Const { .. } = assoc_item.kind
355 && let Some(constraint) = constraint
356 && let hir::AssocItemConstraintKind::Bound { .. } = constraint.kind
357 {
358 let lo = if constraint.gen_args.span_ext.is_dummy() {
359 ident.span
360 } else {
361 constraint.gen_args.span_ext
362 };
363 Some(lo.between(span.shrink_to_hi()))
364 } else {
365 None
366 };
367
368 let wrap_in_braces_sugg = if let Some(constraint) = constraint
370 && let Some(hir_ty) = constraint.ty()
371 && let ty = self.lower_ty(hir_ty)
372 && (ty.is_enum() || ty.references_error())
373 && tcx.features().gca()
374 {
375 Some(diagnostics::AssocKindMismatchWrapInBracesSugg {
376 lo: hir_ty.span.shrink_to_lo(),
377 hi: hir_ty.span.shrink_to_hi(),
378 })
379 } else {
380 None
381 };
382
383 let (span, expected_because_label, expected, got) = if let Some(constraint) = constraint
386 && let hir::AssocItemConstraintKind::Equality { term } = constraint.kind
387 {
388 let span = match term {
389 hir::Term::Ty(ty) => ty.span,
390 hir::Term::Const(ct) => ct.span,
391 };
392 (span, Some(ident.span), assoc_item.tag(), assoc_tag)
393 } else {
394 (ident.span, None, assoc_tag, assoc_item.tag())
395 };
396
397 let def_kind = tcx.def_kind(self.item_def_id());
398 let item_span = tcx.def_span(self.item_def_id()).shrink_to_lo();
399 let (item_span, enclosing_span) = match def_kind {
400 DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy => (
401 item_span,
402 Some(tcx.def_span(tcx.parent(self.item_def_id().into())).shrink_to_lo()),
403 ),
404 DefKind::OpaqueTy => {
405 let item_span = tcx.def_span(tcx.parent(self.item_def_id().into())).shrink_to_lo();
406 let enclosing_span =
407 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy =
408 tcx.def_kind(tcx.parent(self.item_def_id().into()))
409 {
410 Some(tcx.def_span(tcx.parent(self.item_def_id().into())).shrink_to_lo())
411 } else {
412 None
413 };
414 (item_span, enclosing_span)
415 }
416 _ => (item_span, None),
417 };
418 self.dcx().emit_err(diagnostics::AssocKindMismatch {
419 span,
420 item_span,
421 enclosing_span,
422 expected: assoc_tag_str(expected),
423 got: assoc_tag_str(got),
424 expected_because_label,
425 assoc_kind: assoc_tag_str(assoc_item.tag()),
426 def_span: tcx.def_span(assoc_item.def_id),
427 bound_on_assoc_const_label,
428 wrap_in_braces_sugg,
429 })
430 }
431
432 pub(super) fn report_ambiguous_assoc_item(
433 &self,
434 matching_candidates: &[ty::PolyTraitRef<'tcx>],
435 qself: AssocItemQSelf,
436 assoc_tag: ty::AssocTag,
437 assoc_ident: Ident,
438 span: Span,
439 constraint: Option<&hir::AssocItemConstraint<'_>>,
440 ) -> ErrorGuaranteed {
441 let tcx = self.tcx();
442
443 let assoc_kind_str = assoc_tag_str(assoc_tag);
444 let qself_str = qself.to_string(tcx);
445 let mut err = self.dcx().create_err(crate::diagnostics::AmbiguousAssocItem {
446 span,
447 assoc_kind: assoc_kind_str,
448 assoc_ident,
449 qself: &qself_str,
450 });
451 err.code(
453 if let Some(constraint) = constraint
454 && let hir::AssocItemConstraintKind::Equality { .. } = constraint.kind
455 {
456 E0222
457 } else {
458 E0221
459 },
460 );
461
462 let mut where_bounds = ::alloc::vec::Vec::new()vec![];
466 for &bound in matching_candidates {
467 let bound_id = bound.def_id();
468 let assoc_item = tcx.associated_items(bound_id).find_by_ident_and_kind(
469 tcx,
470 assoc_ident,
471 assoc_tag,
472 bound_id,
473 );
474 let bound_span = assoc_item.and_then(|item| tcx.hir_span_if_local(item.def_id));
475
476 if let Some(bound_span) = bound_span {
477 err.span_label(
478 bound_span,
479 ::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(),),
480 );
481 if let Some(constraint) = constraint {
482 match constraint.kind {
483 hir::AssocItemConstraintKind::Equality { term } => {
484 let term: ty::Term<'_> = match term {
485 hir::Term::Ty(ty) => self.lower_ty(ty).into(),
486 hir::Term::Const(ct) => {
487 let assoc_item =
488 assoc_item.expect("assoc_item should be present");
489 let projection_term = bound.map_bound(|trait_ref| {
490 let item_segment = hir::PathSegment {
491 ident: constraint.ident,
492 hir_id: constraint.hir_id,
493 res: Res::Err,
494 args: Some(constraint.gen_args),
495 infer_args: false,
496 delegation_child_segment: false,
497 };
498
499 let alias_args = self.lower_generic_args_of_assoc_item(
500 constraint.ident.span,
501 assoc_item.def_id,
502 &item_segment,
503 trait_ref.args,
504 );
505 let kind = ty::AliasTermKind::ProjectionConst {
506 def_id: assoc_item.def_id,
507 };
508 ty::AliasTerm::new_from_args(tcx, kind, alias_args)
509 });
510
511 let ty = projection_term.map_bound(|alias| {
514 alias.expect_ct().type_of(tcx).skip_norm_wip()
515 });
516 let ty = super::bounds::check_assoc_const_binding_type(
517 self,
518 constraint.ident,
519 ty,
520 constraint.hir_id,
521 );
522
523 self.lower_const_arg(ct, ty).into()
524 }
525 };
526 if term.references_error() {
527 continue;
528 }
529 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!(
531 " T: {trait}::{assoc_ident} = {term}",
532 trait = bound.print_only_trait_path(),
533 ));
534 }
535 hir::AssocItemConstraintKind::Bound { bounds: _ } => {}
537 }
538 } else {
539 err.span_suggestion_verbose(
540 span.with_hi(assoc_ident.span.lo()),
541 "use fully-qualified syntax to disambiguate",
542 ::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()),
543 Applicability::MaybeIncorrect,
544 );
545 }
546 } else {
547 let trait_ = tcx.short_string(bound.print_only_trait_path(), err.long_ty_path());
548 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!(
549 "associated {assoc_kind_str} `{assoc_ident}` could derive from `{trait_}`",
550 ));
551 }
552 }
553 if !where_bounds.is_empty() {
554 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!(
555 "consider introducing a new type parameter `T` and adding `where` constraints:\
556 \n where\n T: {qself_str},\n{}",
557 where_bounds.join(",\n"),
558 ));
559 }
560 err.emit_err()
561 }
562
563 pub(crate) fn report_missing_self_ty_for_resolved_path(
564 &self,
565 trait_def_id: DefId,
566 span: Span,
567 item_segment: &hir::PathSegment<'_>,
568 assoc_tag: ty::AssocTag,
569 ) -> ErrorGuaranteed {
570 let tcx = self.tcx();
571 let path_str = tcx.def_path_str(trait_def_id);
572
573 let def_id = self.item_def_id();
574 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6f5da406b56c2db6607202b63daee73aa8c61297/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs:574",
"rustc_hir_analysis::hir_ty_lowering::errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6f5da406b56c2db6607202b63daee73aa8c61297/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs"),
::tracing_core::__macro_support::Option::Some(574u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::errors"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item_def_id")
}> =
::tracing::__macro_support::FieldName::new("item_def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(item_def_id = ?def_id);
575
576 let parent_def_id = tcx.hir_get_parent_item(tcx.local_def_id_to_hir_id(def_id)).to_def_id();
578 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6f5da406b56c2db6607202b63daee73aa8c61297/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs:578",
"rustc_hir_analysis::hir_ty_lowering::errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6f5da406b56c2db6607202b63daee73aa8c61297/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs"),
::tracing_core::__macro_support::Option::Some(578u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::errors"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("parent_def_id")
}> =
::tracing::__macro_support::FieldName::new("parent_def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_def_id)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?parent_def_id);
579
580 let is_part_of_self_trait_constraints = def_id.to_def_id() == trait_def_id;
583 let is_part_of_fn_in_self_trait = parent_def_id == trait_def_id;
584
585 let type_names = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
586 ::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()]
587 } else {
588 tcx.all_impls(trait_def_id)
590 .map(|impl_def_id| tcx.impl_trait_header(impl_def_id))
591 .filter(|header| {
592 tcx.visibility(trait_def_id).is_accessible_from(self.mod_id(), tcx)
594 && header.polarity != ty::ImplPolarity::Negative
595 })
596 .map(|header| header.trait_ref.instantiate_identity().skip_norm_wip().self_ty())
597 .filter(|self_ty| !self_ty.has_non_region_param())
599 .map(|self_ty| tcx.erase_and_anonymize_regions(self_ty).to_string())
600 .collect()
601 };
602 self.report_ambiguous_assoc_item_path(
606 span,
607 &type_names,
608 &[path_str],
609 item_segment.ident,
610 assoc_tag,
611 )
612 }
613
614 pub(super) fn report_unresolved_type_relative_path(
615 &self,
616 self_ty: Ty<'tcx>,
617 hir_self_ty: &hir::Ty<'_>,
618 assoc_tag: ty::AssocTag,
619 ident: Ident,
620 qpath_hir_id: HirId,
621 span: Span,
622 variant_def_id: Option<DefId>,
623 ) -> ErrorGuaranteed {
624 let tcx = self.tcx();
625 let kind_str = assoc_tag_str(assoc_tag);
626 if variant_def_id.is_some() {
627 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}`");
629 self.dcx().span_err(span, msg)
630 } else if self_ty.is_enum() {
631 let mut err = self.dcx().create_err(diagnostics::NoVariantNamed {
632 span: ident.span,
633 ident,
634 ty: self_ty,
635 });
636
637 let adt_def = self_ty.ty_adt_def().expect("enum is not an ADT");
638 if let Some(variant_name) = find_best_match_for_name(
639 &adt_def.variants().iter().map(|variant| variant.name).collect::<Vec<Symbol>>(),
640 ident.name,
641 None,
642 ) && let Some(variant) = adt_def.variants().iter().find(|s| s.name == variant_name)
643 {
644 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())];
645 if let hir::Node::Stmt(&hir::Stmt { kind: hir::StmtKind::Semi(expr), .. })
646 | hir::Node::Expr(expr) = tcx.parent_hir_node(qpath_hir_id)
647 && let hir::ExprKind::Struct(..) = expr.kind
648 {
649 match variant.ctor {
650 None => {
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()),
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![(
653 ident.span.with_hi(expr.span.hi()),
654 if variant.fields.is_empty() {
655 format!("{variant_name} {{}}")
656 } else {
657 format!(
658 "{variant_name} {{ {} }}",
659 variant
660 .fields
661 .iter()
662 .map(|f| format!("{}: /* value */", f.name))
663 .collect::<Vec<_>>()
664 .join(", ")
665 )
666 },
667 )];
668 }
669 Some((hir::def::CtorKind::Fn, def_id)) => {
670 let fn_sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
672 let inputs = fn_sig.inputs().skip_binder();
673 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![(
674 ident.span.with_hi(expr.span.hi()),
675 format!(
676 "{variant_name}({})",
677 inputs
678 .iter()
679 .map(|i| format!("/* {i} */"))
680 .collect::<Vec<_>>()
681 .join(", ")
682 ),
683 )];
684 }
685 Some((hir::def::CtorKind::Const, _)) => {
686 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![(
688 ident.span.with_hi(expr.span.hi()),
689 variant_name.to_string(),
690 )];
691 }
692 }
693 }
694 err.multipart_suggestion(
695 "there is a variant with a similar name",
696 suggestion,
697 Applicability::HasPlaceholders,
698 );
699 } else {
700 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}`"));
701 }
702
703 if let Some(sp) = tcx.hir_span_if_local(adt_def.did()) {
704 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"));
705 }
706
707 err.emit_err()
708 } else if let Err(reported) = self_ty.error_reported() {
709 reported
710 } else {
711 match self.maybe_report_similar_assoc_fn(span, self_ty, hir_self_ty) {
712 Ok(()) => {}
713 Err(reported) => return reported,
714 }
715
716 let traits: Vec<_> = self.probe_traits_that_match_assoc_ty(self_ty, ident);
717
718 self.report_ambiguous_assoc_item_path(
719 span,
720 &[self_ty.to_string()],
721 &traits,
722 ident,
723 assoc_tag,
724 )
725 }
726 }
727
728 fn report_ambiguous_assoc_item_path(
729 &self,
730 span: Span,
731 types: &[String],
732 traits: &[String],
733 ident: Ident,
734 assoc_tag: ty::AssocTag,
735 ) -> ErrorGuaranteed {
736 let kind_str = assoc_tag_str(assoc_tag);
737 let mut err =
738 {
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}");
739 if self
740 .tcx()
741 .resolutions(())
742 .confused_type_with_std_module
743 .keys()
744 .any(|full_span| full_span.contains(span))
745 {
746 err.span_suggestion_verbose(
747 span.shrink_to_lo(),
748 "you are looking for the module in `std`, not the primitive type",
749 "std::",
750 Applicability::MachineApplicable,
751 );
752 } else {
753 let sugg_sp = span.until(ident.span);
754
755 let mut types = types.to_vec();
756 types.sort();
757 let mut traits = traits.to_vec();
758 traits.sort();
759 match (&types[..], &traits[..]) {
760 ([], []) => {
761 err.span_suggestion_verbose(
762 sugg_sp,
763 ::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!(
764 "if there were a type named `Type` that implements a trait named \
765 `Trait` with associated {kind_str} `{ident}`, you could use the \
766 fully-qualified path",
767 ),
768 "<Type as Trait>::",
769 Applicability::HasPlaceholders,
770 );
771 }
772 ([], [trait_str]) => {
773 err.span_suggestion_verbose(
774 sugg_sp,
775 ::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!(
776 "if there were a type named `Example` that implemented `{trait_str}`, \
777 you could use the fully-qualified path",
778 ),
779 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<Example as {0}>::", trait_str))
})format!("<Example as {trait_str}>::"),
780 Applicability::HasPlaceholders,
781 );
782 }
783 ([], traits) => {
784 err.span_suggestions_with_style(
785 sugg_sp,
786 ::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!(
787 "if there were a type named `Example` that implemented one of the \
788 traits with associated {kind_str} `{ident}`, you could use the \
789 fully-qualified path",
790 ),
791 traits.iter().map(|trait_str| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<Example as {0}>::", trait_str))
})format!("<Example as {trait_str}>::")),
792 Applicability::HasPlaceholders,
793 SuggestionStyle::ShowAlways,
794 );
795 }
796 ([type_str], []) => {
797 err.span_suggestion_verbose(
798 sugg_sp,
799 ::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!(
800 "if there were a trait named `Example` with associated {kind_str} `{ident}` \
801 implemented for `{type_str}`, you could use the fully-qualified path",
802 ),
803 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0} as Example>::", type_str))
})format!("<{type_str} as Example>::"),
804 Applicability::HasPlaceholders,
805 );
806 }
807 (types, []) => {
808 err.span_suggestions_with_style(
809 sugg_sp,
810 ::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!(
811 "if there were a trait named `Example` with associated {kind_str} `{ident}` \
812 implemented for one of the types, you could use the fully-qualified \
813 path",
814 ),
815 types
816 .into_iter()
817 .map(|type_str| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0} as Example>::", type_str))
})format!("<{type_str} as Example>::")),
818 Applicability::HasPlaceholders,
819 SuggestionStyle::ShowAlways,
820 );
821 }
822 (types, traits) => {
823 let mut suggestions = ::alloc::vec::Vec::new()vec![];
824 for type_str in types {
825 for trait_str in traits {
826 suggestions.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0} as {1}>::", type_str,
trait_str))
})format!("<{type_str} as {trait_str}>::"));
827 }
828 }
829 err.span_suggestions_with_style(
830 sugg_sp,
831 "use fully-qualified syntax",
832 suggestions,
833 Applicability::MachineApplicable,
834 SuggestionStyle::ShowAlways,
835 );
836 }
837 }
838 }
839 err.emit_err()
840 }
841
842 pub(crate) fn report_ambiguous_inherent_assoc_item(
843 &self,
844 name: Ident,
845 candidates: Vec<DefId>,
846 span: Span,
847 ) -> ErrorGuaranteed {
848 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!(
849 self.dcx(),
850 name.span,
851 E0034,
852 "multiple applicable items in scope"
853 );
854 err.span_label(name.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("multiple `{0}` found", name))
})format!("multiple `{name}` found"));
855 self.note_ambiguous_inherent_assoc_item(&mut err, candidates, span);
856 err.emit_err()
857 }
858
859 fn note_ambiguous_inherent_assoc_item(
861 &self,
862 err: &mut Diag<'_>,
863 candidates: Vec<DefId>,
864 span: Span,
865 ) {
866 let tcx = self.tcx();
867
868 let limit = if candidates.len() == 5 { 5 } else { 4 };
870
871 for (index, &item) in candidates.iter().take(limit).enumerate() {
872 let impl_ = tcx.parent(item);
873
874 let note_span = if item.is_local() {
875 Some(tcx.def_span(item))
876 } else if impl_.is_local() {
877 Some(tcx.def_span(impl_))
878 } else {
879 None
880 };
881
882 let title = if candidates.len() > 1 {
883 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("candidate #{0}", index + 1))
})format!("candidate #{}", index + 1)
884 } else {
885 "the candidate".into()
886 };
887
888 let impl_ty = tcx.at(span).type_of(impl_).instantiate_identity().skip_norm_wip();
889 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}`");
890
891 if let Some(span) = note_span {
892 err.span_note(span, note);
893 } else {
894 err.note(note);
895 }
896 }
897 if candidates.len() > limit {
898 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("and {0} others",
candidates.len() - limit))
})format!("and {} others", candidates.len() - limit));
899 }
900 }
901
902 pub(crate) fn report_unresolved_inherent_assoc_item(
904 &self,
905 name: Ident,
906 self_ty: Ty<'tcx>,
907 candidates: Vec<InherentAssocCandidate>,
908 fulfillment_errors: ThinVec<FulfillmentError<'tcx>>,
909 span: Span,
910 assoc_tag: ty::AssocTag,
911 ) -> ErrorGuaranteed {
912 let tcx = self.tcx();
919
920 let assoc_tag_str = assoc_tag_str(assoc_tag);
921 let adt_did = self_ty.ty_adt_def().map(|def| def.did());
922 let add_def_label = |err: &mut Diag<'_>| {
923 if let Some(did) = adt_did {
924 err.span_label(
925 tcx.def_span(did),
926 ::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!(
927 "associated {assoc_tag_str} `{name}` not found for this {}",
928 tcx.def_descr(did)
929 ),
930 );
931 }
932 };
933
934 if fulfillment_errors.is_empty() {
935 let limit = if candidates.len() == 5 { 5 } else { 4 };
938 let type_candidates = candidates
939 .iter()
940 .take(limit)
941 .map(|cand| {
942 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("- `{0}`",
tcx.at(span).type_of(cand.impl_).instantiate_identity().skip_norm_wip()))
})format!(
943 "- `{}`",
944 tcx.at(span).type_of(cand.impl_).instantiate_identity().skip_norm_wip()
945 )
946 })
947 .collect::<Vec<_>>()
948 .join("\n");
949 let additional_types = if candidates.len() > limit {
950 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\nand {0} more types",
candidates.len() - limit))
})format!("\nand {} more types", candidates.len() - limit)
951 } else {
952 String::new()
953 };
954
955 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!(
956 self.dcx(),
957 name.span,
958 E0220,
959 "associated {assoc_tag_str} `{name}` not found for `{self_ty}` in the current scope"
960 );
961 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}`"));
962 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!(
963 "the associated {assoc_tag_str} was found for\n{type_candidates}{additional_types}",
964 ));
965 add_def_label(&mut err);
966 return err.emit_err();
967 }
968
969 let mut bound_spans: SortedMap<OrdSpan, Vec<String>> = Default::default();
970
971 let mut bound_span_label = |self_ty: Ty<'_>, obligation: &str, quiet: &str| {
972 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 });
973 match self_ty.kind() {
974 ty::Adt(def, _) => bound_spans
976 .get_mut_or_insert_default(OrdSpan(tcx.def_span(def.did())))
977 .push(msg),
978 ty::Dynamic(preds, _) => {
980 for pred in preds.iter() {
981 match pred.skip_binder() {
982 ty::ExistentialPredicate::Trait(tr) => {
983 bound_spans
984 .get_mut_or_insert_default(OrdSpan(tcx.def_span(tr.def_id)))
985 .push(msg.clone());
986 }
987 ty::ExistentialPredicate::Projection(_)
988 | ty::ExistentialPredicate::AutoTrait(_) => {}
989 }
990 }
991 }
992 ty::Closure(def_id, _) => {
994 bound_spans
995 .get_mut_or_insert_default(OrdSpan(tcx.def_span(*def_id)))
996 .push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", quiet))
})format!("`{quiet}`"));
997 }
998 _ => {}
999 }
1000 };
1001
1002 let format_pred = |pred: ty::Predicate<'tcx>| {
1003 let bound_predicate = pred.kind();
1004 match bound_predicate.skip_binder() {
1005 ty::PredicateKind::Clause(ty::ClauseKind::Projection(pred)) => {
1006 let projection_term = pred.projection_term;
1008 let term = pred.term;
1009 let self_ty = projection_term.args.get(0).and_then(|arg| arg.as_type())?;
1010
1011 let obligation = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} = {1}", projection_term, term))
})format!("{projection_term} = {term}");
1012 let quiet_projection_term = projection_term
1013 .with_replaced_self_ty(tcx, Ty::new_var(tcx, ty::TyVid::ZERO));
1014 let quiet = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} = {1}", quiet_projection_term,
term))
})format!("{quiet_projection_term} = {term}");
1015
1016 bound_span_label(self_ty, &obligation, &quiet);
1017
1018 Some(obligation)
1019 }
1020 ty::PredicateKind::Clause(ty::ClauseKind::Trait(poly_trait_ref)) => {
1021 let p = poly_trait_ref.trait_ref;
1022 let self_ty = p.self_ty();
1023 let path = p.print_only_trait_path();
1024 let obligation = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", self_ty, path))
})format!("{self_ty}: {path}");
1025 let quiet = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("_: {0}", path))
})format!("_: {path}");
1026 bound_span_label(self_ty, &obligation, &quiet);
1027 Some(obligation)
1028 }
1029 _ => None,
1030 }
1031 };
1032
1033 let mut bounds: Vec<_> = fulfillment_errors
1036 .into_iter()
1037 .map(|error| error.root_obligation.predicate)
1038 .filter_map(format_pred)
1039 .map(|p| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", p))
})format!("`{p}`"))
1040 .collect();
1041 bounds.sort();
1042 bounds.dedup();
1043
1044 let mut err = self.dcx().struct_span_err(
1045 name.span,
1046 ::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")
1047 );
1048 if !bounds.is_empty() {
1049 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the following trait bounds were not satisfied:\n{0}",
bounds.join("\n")))
})format!(
1050 "the following trait bounds were not satisfied:\n{}",
1051 bounds.join("\n")
1052 ));
1053 }
1054 err.span_label(
1055 name.span,
1056 ::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")
1057 );
1058
1059 for (span, mut bounds) in bound_spans {
1060 if !tcx.sess.source_map().is_span_accessible(span.0) {
1061 continue;
1062 }
1063 bounds.sort();
1064 bounds.dedup();
1065 let msg = match &bounds[..] {
1066 [bound] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("doesn\'t satisfy {0}", bound))
})format!("doesn't satisfy {bound}"),
1067 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()),
1068 [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(", ")),
1069 [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1070 };
1071 err.span_label(span.0, msg);
1072 }
1073 add_def_label(&mut err);
1074 err.emit_err()
1075 }
1076
1077 pub(crate) fn check_for_required_assoc_items(
1081 &self,
1082 spans: SmallVec<[Span; 1]>,
1083 missing_assoc_items: FxIndexSet<(DefId, ty::PolyTraitRef<'tcx>)>,
1084 potential_assoc_items: Vec<usize>,
1085 trait_bounds: &[hir::PolyTraitRef<'_>],
1086 ) -> Result<(), ErrorGuaranteed> {
1087 if missing_assoc_items.is_empty() {
1088 return Ok(());
1089 }
1090
1091 let tcx = self.tcx();
1092 let principal_span = *spans.first().unwrap();
1093
1094 let missing_assoc_items: Vec<_> = missing_assoc_items
1096 .into_iter()
1097 .map(|(def_id, trait_ref)| (tcx.associated_item(def_id), trait_ref))
1098 .collect();
1099 let mut names: FxIndexMap<_, Vec<_>> = Default::default();
1100 let mut names_len = 0;
1101 let mut descr = None;
1102
1103 enum Descr {
1104 Item,
1105 Tag(ty::AssocTag),
1106 }
1107
1108 for &(assoc_item, trait_ref) in &missing_assoc_items {
1109 let violations =
1117 dyn_compatibility_violations_for_assoc_item(tcx, trait_ref.def_id(), assoc_item);
1118 if !violations.is_empty() {
1119 return Err(report_dyn_incompatibility(
1120 tcx,
1121 principal_span,
1122 None,
1123 trait_ref.def_id(),
1124 &violations,
1125 )
1126 .emit_err());
1127 }
1128
1129 names.entry(trait_ref).or_default().push(assoc_item.name());
1130 names_len += 1;
1131
1132 descr = match descr {
1133 None => Some(Descr::Tag(assoc_item.tag())),
1134 Some(Descr::Tag(tag)) if tag != assoc_item.tag() => Some(Descr::Item),
1135 _ => continue,
1136 };
1137 }
1138
1139 let mut in_expr_or_pat = false;
1141 if let ([], [bound]) = (&potential_assoc_items[..], &trait_bounds) {
1142 let grandparent = tcx.parent_hir_node(tcx.parent_hir_id(bound.trait_ref.hir_ref_id));
1143 in_expr_or_pat = match grandparent {
1144 hir::Node::Expr(_) | hir::Node::Pat(_) => true,
1145 _ => false,
1146 };
1147 }
1148
1149 let bound_names: UnordMap<_, _> =
1158 trait_bounds
1159 .iter()
1160 .filter_map(|poly_trait_ref| {
1161 let path = poly_trait_ref.trait_ref.path.segments.last()?;
1162 let args = path.args?;
1163 let Res::Def(DefKind::Trait, trait_def_id) = path.res else { return None };
1164
1165 Some(args.constraints.iter().filter_map(move |constraint| {
1166 let hir::AssocItemConstraintKind::Equality { term } = constraint.kind
1167 else {
1168 return None;
1169 };
1170 let tag = match term {
1171 hir::Term::Ty(_) => ty::AssocTag::Type,
1172 hir::Term::Const(_) => ty::AssocTag::Const,
1173 };
1174 let assoc_item = tcx
1175 .associated_items(trait_def_id)
1176 .find_by_ident_and_kind(tcx, constraint.ident, tag, trait_def_id)?;
1177 Some(((constraint.ident.name, tag), assoc_item.def_id))
1178 }))
1179 })
1180 .flatten()
1181 .collect();
1182
1183 let mut names: Vec<_> = names
1184 .into_iter()
1185 .map(|(trait_, mut assocs)| {
1186 assocs.sort();
1187 let trait_ = trait_.print_trait_sugared();
1188 ::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!(
1189 "{} in `{trait_}`",
1190 listify(&assocs[..], |a| format!("`{a}`")).unwrap_or_default()
1191 )
1192 })
1193 .collect();
1194 names.sort();
1195 let names = names.join(", ");
1196
1197 let descr = match descr.unwrap() {
1198 Descr::Item => "associated item",
1199 Descr::Tag(tag) => tag.descr(),
1200 };
1201 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!(
1202 self.dcx(),
1203 principal_span,
1204 E0191,
1205 "the value of the {descr}{s} {names} must be specified",
1206 s = pluralize!(names_len),
1207 );
1208 let mut suggestions = ::alloc::vec::Vec::new()vec![];
1209 let mut items_count = 0;
1210 let mut where_constraints = ::alloc::vec::Vec::new()vec![];
1211 let mut already_has_generics_args_suggestion = false;
1212
1213 let mut names: UnordMap<_, usize> = Default::default();
1214 for (item, _) in &missing_assoc_items {
1215 items_count += 1;
1216 *names.entry((item.name(), item.tag())).or_insert(0) += 1;
1217 }
1218 let mut dupes = false;
1219 let mut shadows = false;
1220 for (item, trait_ref) in &missing_assoc_items {
1221 let name = item.name();
1222 let key = (name, item.tag());
1223
1224 if names[&key] > 1 {
1225 dupes = true;
1226 } else if bound_names.get(&key).is_some_and(|&def_id| def_id != item.def_id) {
1227 shadows = true;
1228 }
1229
1230 let prefix = if dupes || shadows {
1231 ::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()))
1232 } else {
1233 String::new()
1234 };
1235 let mut is_shadowed = false;
1236
1237 if let Some(&def_id) = bound_names.get(&key)
1238 && def_id != item.def_id
1239 {
1240 is_shadowed = true;
1241
1242 let rename_message = if def_id.is_local() { ", consider renaming it" } else { "" };
1243 err.span_label(
1244 tcx.def_span(def_id),
1245 ::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}"),
1246 );
1247 }
1248
1249 let rename_message = if is_shadowed { ", consider renaming it" } else { "" };
1250
1251 if let Some(sp) = tcx.hir_span_if_local(item.def_id) {
1252 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}"));
1253 }
1254 }
1255 if potential_assoc_items.len() == missing_assoc_items.len() {
1256 already_has_generics_args_suggestion = true;
1260 } else if let (Ok(snippet), false, false) =
1261 (tcx.sess.source_map().span_to_snippet(principal_span), dupes, shadows)
1262 {
1263 let bindings: Vec<_> = missing_assoc_items
1264 .iter()
1265 .map(|(item, _)| {
1266 ::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!(
1267 "{} = /* {} */",
1268 item.name(),
1269 match item.kind {
1270 ty::AssocKind::Const { .. } => "CONST",
1271 ty::AssocKind::Type { .. } => "Type",
1272 ty::AssocKind::Fn { .. } => unreachable!(),
1273 }
1274 )
1275 })
1276 .collect();
1277 let code = if let Some(snippet) = snippet.strip_suffix("<>") {
1278 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}<{0}>", bindings.join(", "),
snippet))
})format!("{snippet}<{}>", bindings.join(", "))
1280 } else if let Some(snippet) = snippet.strip_suffix('>') {
1281 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}, {0}>", bindings.join(", "),
snippet))
})format!("{snippet}, {}>", bindings.join(", "))
1283 } else if in_expr_or_pat {
1284 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::<{1}>", snippet,
bindings.join(", ")))
})format!("{}::<{}>", snippet, bindings.join(", "))
1287 } else {
1288 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}<{1}>", snippet,
bindings.join(", ")))
})format!("{}<{}>", snippet, bindings.join(", "))
1291 };
1292 suggestions.push((principal_span, code));
1293 } else if dupes {
1294 where_constraints.push(principal_span);
1295 }
1296
1297 let where_msg = "consider introducing a new type parameter, adding `where` constraints \
1306 using the fully-qualified path to the associated types";
1307 if !where_constraints.is_empty() && suggestions.is_empty() {
1308 err.help(where_msg);
1312 }
1313 if suggestions.len() != 1 || already_has_generics_args_suggestion {
1314 let mut names: FxIndexMap<_, usize> = FxIndexMap::default();
1316 for (item, _) in &missing_assoc_items {
1317 items_count += 1;
1318 *names.entry(item.name()).or_insert(0) += 1;
1319 }
1320 let mut label = ::alloc::vec::Vec::new()vec![];
1321 for (item, trait_ref) in &missing_assoc_items {
1322 let name = item.name();
1323 let postfix = if names[&name] > 1 {
1324 ::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())
1325 } else {
1326 String::new()
1327 };
1328 label.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`{1}", name, postfix))
})format!("`{}`{}", name, postfix));
1329 }
1330 if !label.is_empty() {
1331 err.span_label(
1332 principal_span,
1333 ::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!(
1334 "{descr}{s} {names} must be specified",
1335 s = pluralize!(label.len()),
1336 names = label.join(", "),
1337 ),
1338 );
1339 }
1340 }
1341 suggestions.sort_by_key(|&(span, _)| span.lo_hi());
1342 let overlaps = suggestions.windows(2).any(|pair| pair[0].0.overlaps(pair[1].0));
1355 if !suggestions.is_empty() && !overlaps {
1356 err.multipart_suggestion(
1357 ::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)),
1358 suggestions,
1359 Applicability::HasPlaceholders,
1360 );
1361 if !where_constraints.is_empty() {
1362 err.span_help(where_constraints, where_msg);
1363 }
1364 }
1365
1366 Err(err.emit_err())
1367 }
1368
1369 pub(crate) fn maybe_report_similar_assoc_fn(
1373 &self,
1374 span: Span,
1375 qself_ty: Ty<'tcx>,
1376 qself: &hir::Ty<'_>,
1377 ) -> Result<(), ErrorGuaranteed> {
1378 let tcx = self.tcx();
1379 if let Some((_, node)) = tcx.hir_parent_iter(qself.hir_id).skip(1).next()
1380 && let hir::Node::Expr(hir::Expr {
1381 kind:
1382 hir::ExprKind::Path(hir::QPath::TypeRelative(
1383 hir::Ty {
1384 kind:
1385 hir::TyKind::Path(hir::QPath::TypeRelative(
1386 _,
1387 hir::PathSegment { ident: ident2, .. },
1388 )),
1389 ..
1390 },
1391 hir::PathSegment { ident: ident3, .. },
1392 )),
1393 ..
1394 }) = node
1395 && let Some(inherent_impls) = qself_ty
1396 .ty_adt_def()
1397 .map(|adt_def| tcx.inherent_impls(adt_def.did()))
1398 .or_else(|| {
1399 simplify_type(tcx, qself_ty, TreatParams::InstantiateWithInfer)
1400 .map(|simple_ty| tcx.incoherent_impls(simple_ty))
1401 })
1402 && let name = Symbol::intern(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}_{1}", ident2, ident3))
})format!("{ident2}_{ident3}"))
1403 && let Some(item) = inherent_impls
1404 .iter()
1405 .flat_map(|&inherent_impl| {
1406 tcx.associated_items(inherent_impl).filter_by_name_unhygienic(name)
1407 })
1408 .next()
1409 && item.is_fn()
1410 {
1411 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")
1412 .with_span_suggestion_verbose(
1413 ident2.span.to(ident3.span),
1414 ::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}`"),
1415 name,
1416 Applicability::MaybeIncorrect,
1417 )
1418 .emit_err())
1419 } else {
1420 Ok(())
1421 }
1422 }
1423
1424 pub fn report_prohibited_generic_args<'a>(
1425 &self,
1426 segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
1427 args_visitors: impl Iterator<Item = &'a hir::GenericArg<'a>> + Clone,
1428 err_extend: GenericsArgsErrExtend<'a>,
1429 ) -> ErrorGuaranteed {
1430 #[derive(#[automatically_derived]
impl ::core::marker::StructuralPartialEq for ProhibitGenericsArg { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ProhibitGenericsArg {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ProhibitGenericsArg { }Eq, #[automatically_derived]
impl ::core::hash::Hash for ProhibitGenericsArg {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state)
}
}Hash)]
1431 enum ProhibitGenericsArg {
1432 Lifetime,
1433 Type,
1434 Const,
1435 Infer,
1436 }
1437
1438 let mut prohibit_args = FxIndexSet::default();
1439 args_visitors.for_each(|arg| {
1440 match arg {
1441 hir::GenericArg::Lifetime(_) => prohibit_args.insert(ProhibitGenericsArg::Lifetime),
1442 hir::GenericArg::Type(_) => prohibit_args.insert(ProhibitGenericsArg::Type),
1443 hir::GenericArg::Const(_) => prohibit_args.insert(ProhibitGenericsArg::Const),
1444 hir::GenericArg::Infer(_) => prohibit_args.insert(ProhibitGenericsArg::Infer),
1445 };
1446 });
1447
1448 let segments: Vec<_> = segments.collect();
1449 let types_and_spans: Vec<_> = segments
1450 .iter()
1451 .flat_map(|segment| {
1452 if segment.args().args.is_empty() {
1453 None
1454 } else {
1455 Some((
1456 match segment.res {
1457 Res::PrimTy(ty) => {
1458 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}`", segment.res.descr(),
ty.name()))
})format!("{} `{}`", segment.res.descr(), ty.name())
1459 }
1460 Res::Def(_, def_id)
1461 if let Some(name) = self.tcx().opt_item_name(def_id) =>
1462 {
1463 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}`", segment.res.descr(),
name))
})format!("{} `{name}`", segment.res.descr())
1464 }
1465 Res::Err => "this type".to_string(),
1466 _ => segment.res.descr().to_string(),
1467 },
1468 segment.ident.span,
1469 ))
1470 }
1471 })
1472 .collect();
1473 let this_type = listify(&types_and_spans, |(t, _)| t.to_string())
1474 .expect("expected one segment to deny");
1475
1476 let arg_spans: Vec<Span> =
1477 segments.iter().flat_map(|segment| segment.args().args).map(|arg| arg.span()).collect();
1478
1479 let mut kinds = Vec::with_capacity(4);
1480 prohibit_args.iter().for_each(|arg| match arg {
1481 ProhibitGenericsArg::Lifetime => kinds.push("lifetime"),
1482 ProhibitGenericsArg::Type => kinds.push("type"),
1483 ProhibitGenericsArg::Const => kinds.push("const"),
1484 ProhibitGenericsArg::Infer => kinds.push("generic"),
1485 });
1486
1487 let s = if kinds.len() == 1 { "" } else { "s" }pluralize!(kinds.len());
1488 let kind =
1489 listify(&kinds, |k| k.to_string()).expect("expected at least one generic to prohibit");
1490 let last_span = *arg_spans.last().unwrap();
1491 let span: MultiSpan = arg_spans.into();
1492 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!(
1493 self.dcx(),
1494 span,
1495 E0109,
1496 "{kind} arguments are not allowed on {this_type}",
1497 );
1498 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"));
1499 for (what, span) in types_and_spans {
1500 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not allowed on {0}", what))
})format!("not allowed on {what}"));
1501 }
1502 generics_args_err_extend(self.tcx(), segments.into_iter(), &mut err, err_extend);
1503 err.emit_err()
1504 }
1505
1506 pub fn report_trait_object_addition_traits(
1507 &self,
1508 regular_traits: &Vec<(ty::PolyTraitClause<'tcx>, SmallVec<[Span; 1]>)>,
1509 ) -> ErrorGuaranteed {
1510 let (&first_span, first_alias_spans) = regular_traits[0].1.split_last().unwrap();
1513 let (&second_span, second_alias_spans) = regular_traits[1].1.split_last().unwrap();
1514 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!(
1515 self.dcx(),
1516 *regular_traits[1].1.first().unwrap(),
1517 E0225,
1518 "only auto traits can be used as additional traits in a trait object"
1519 );
1520 err.span_label(first_span, "first non-auto trait");
1521 for &alias_span in first_alias_spans {
1522 err.span_label(alias_span, "first non-auto trait comes from this alias");
1523 }
1524 err.span_label(second_span, "additional non-auto trait");
1525 for &alias_span in second_alias_spans {
1526 err.span_label(alias_span, "second non-auto trait comes from this alias");
1527 }
1528 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!(
1529 "consider creating a new trait with all of these as supertraits and using that \
1530 trait here instead: `trait NewTrait: {} {{}}`",
1531 regular_traits
1532 .iter()
1533 .map(|(pred, _)| pred
1535 .map_bound(|pred| pred.trait_ref)
1536 .print_only_trait_path()
1537 .to_string())
1538 .collect::<Vec<_>>()
1539 .join(" + "),
1540 ));
1541 err.note(
1542 "auto-traits like `Send` and `Sync` are traits that have special properties; \
1543 for more information on them, visit \
1544 <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>",
1545 );
1546 err.emit_err()
1547 }
1548
1549 pub fn report_trait_object_with_no_traits(
1550 &self,
1551 span: Span,
1552 user_written_clauses: impl IntoIterator<Item = (ty::Clause<'tcx>, Span)>,
1553 ) -> ErrorGuaranteed {
1554 let tcx = self.tcx();
1555 let trait_alias_span = user_written_clauses
1556 .into_iter()
1557 .filter_map(|(clause, _)| clause.as_trait_clause())
1558 .find(|trait_ref| tcx.is_trait_alias(trait_ref.def_id()))
1559 .map(|trait_ref| tcx.def_span(trait_ref.def_id()));
1560
1561 self.dcx().emit_err(TraitObjectDeclaredWithNoTraits { span, trait_alias_span })
1562 }
1563}
1564
1565pub fn prohibit_assoc_item_constraint(
1567 cx: &dyn HirTyLowerer<'_>,
1568 constraint: &hir::AssocItemConstraint<'_>,
1569 segment: Option<(DefId, &hir::PathSegment<'_>, Span)>,
1570) -> ErrorGuaranteed {
1571 let tcx = cx.tcx();
1572 let mut err = cx.dcx().create_err(AssocItemConstraintsNotAllowedHere {
1573 span: constraint.span,
1574 fn_trait_expansion: if let Some((_, segment, span)) = segment
1575 && segment.args().parenthesized == hir::GenericArgsParentheses::ParenSugar
1576 {
1577 Some(ParenthesizedFnTraitExpansion {
1578 span,
1579 expanded_type: fn_trait_to_string(tcx, segment, false),
1580 })
1581 } else {
1582 None
1583 },
1584 });
1585
1586 if let hir::AssocItemConstraintKind::Bound {
1587 bounds: [hir::GenericBound::Trait(poly_trait_ref)],
1588 } = constraint.kind
1589 && let Res::Err = poly_trait_ref.trait_ref.path.res
1590 {
1591 err.downgrade_to_delayed_bug();
1594 }
1595
1596 if let Some((def_id, segment, _)) = segment
1600 && segment.args().parenthesized == hir::GenericArgsParentheses::No
1601 {
1602 let suggest_removal = |e: &mut Diag<'_>| {
1604 let constraints = segment.args().constraints;
1605 let args = segment.args().args;
1606
1607 let Some(index) = constraints.iter().position(|b| b.hir_id == constraint.hir_id) else {
1619 ::rustc_span::macros::bug_impl(None,
format_args!("a type binding exists but its HIR ID not found in generics"),
Location::caller());bug!("a type binding exists but its HIR ID not found in generics");
1620 };
1621
1622 let preceding_span = if index > 0 {
1623 Some(constraints[index - 1].span)
1624 } else {
1625 args.last().map(|a| a.span())
1626 };
1627
1628 let next_span = constraints.get(index + 1).map(|constraint| constraint.span);
1629
1630 let removal_span = match (preceding_span, next_span) {
1631 (Some(prec), _) => constraint.span.with_lo(prec.hi()),
1632 (None, Some(next)) => constraint.span.with_hi(next.lo()),
1633 (None, None) => {
1634 let Some(generics_span) = segment.args().span_ext() else {
1635 ::rustc_span::macros::bug_impl(None,
format_args!("a type binding exists but generic span is empty"),
Location::caller());bug!("a type binding exists but generic span is empty");
1636 };
1637
1638 generics_span
1639 }
1640 };
1641
1642 e.span_suggestion_verbose(
1644 removal_span,
1645 ::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()),
1646 "",
1647 Applicability::MaybeIncorrect,
1648 );
1649 };
1650
1651 let suggest_direct_use = |e: &mut Diag<'_>, sp: Span| {
1654 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(sp) {
1655 e.span_suggestion_verbose(
1656 constraint.span,
1657 ::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"),
1658 snippet,
1659 Applicability::MaybeIncorrect,
1660 );
1661 }
1662 };
1663
1664 let generics = tcx.generics_of(def_id);
1667 let matching_param = generics.own_params.iter().find(|p| p.name == constraint.ident.name);
1668
1669 if let Some(matching_param) = matching_param {
1671 match (constraint.kind, &matching_param.kind) {
1672 (
1673 hir::AssocItemConstraintKind::Equality { term: hir::Term::Ty(ty) },
1674 GenericParamDefKind::Type { .. },
1675 ) => suggest_direct_use(&mut err, ty.span),
1676 (
1677 hir::AssocItemConstraintKind::Equality { term: hir::Term::Const(c) },
1678 GenericParamDefKind::Const { .. },
1679 ) => {
1680 suggest_direct_use(&mut err, c.span);
1681 }
1682 (hir::AssocItemConstraintKind::Bound { bounds }, _) => {
1683 let impl_block = tcx
1689 .hir_parent_iter(constraint.hir_id)
1690 .find_map(|(_, node)| node.impl_block_of_trait(def_id));
1691
1692 let type_with_constraints =
1693 tcx.sess.source_map().span_to_snippet(constraint.span);
1694
1695 if let Some(impl_block) = impl_block
1696 && let Ok(type_with_constraints) = type_with_constraints
1697 {
1698 let lifetimes: String = bounds
1701 .iter()
1702 .filter_map(|bound| {
1703 if let hir::GenericBound::Outlives(lifetime) = bound {
1704 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ", lifetime))
})format!("{lifetime}, "))
1705 } else {
1706 None
1707 }
1708 })
1709 .collect();
1710 let param_decl = if let Some(param_span) =
1713 impl_block.generics.span_for_param_suggestion()
1714 {
1715 (param_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}{1}", lifetimes,
type_with_constraints))
})format!(", {lifetimes}{type_with_constraints}"))
1716 } else {
1717 (
1718 impl_block.generics.span.shrink_to_lo(),
1719 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}{1}>", lifetimes,
type_with_constraints))
})format!("<{lifetimes}{type_with_constraints}>"),
1720 )
1721 };
1722 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![
1723 param_decl,
1724 (constraint.span.with_lo(constraint.ident.span.hi()), String::new()),
1725 ];
1726
1727 err.multipart_suggestion(
1728 "declare the type parameter right after the `impl` keyword",
1729 suggestions,
1730 Applicability::MaybeIncorrect,
1731 );
1732 }
1733 }
1734 _ => suggest_removal(&mut err),
1735 }
1736 } else {
1737 suggest_removal(&mut err);
1738 }
1739 }
1740
1741 err.emit_err()
1742}
1743
1744pub(crate) fn fn_trait_to_string(
1745 tcx: TyCtxt<'_>,
1746 trait_segment: &hir::PathSegment<'_>,
1747 parenthesized: bool,
1748) -> String {
1749 let args = trait_segment
1750 .args
1751 .and_then(|args| args.args.first())
1752 .and_then(|arg| match arg {
1753 hir::GenericArg::Type(ty) => match ty.kind {
1754 hir::TyKind::Tup(t) => t
1755 .iter()
1756 .map(|e| tcx.sess.source_map().span_to_snippet(e.span))
1757 .collect::<Result<Vec<_>, _>>()
1758 .map(|a| a.join(", ")),
1759 _ => tcx.sess.source_map().span_to_snippet(ty.span),
1760 }
1761 .map(|s| {
1762 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},)") }
1764 })
1765 .ok(),
1766 _ => None,
1767 })
1768 .unwrap_or_else(|| "()".to_string());
1769
1770 let ret = trait_segment
1771 .args()
1772 .constraints
1773 .iter()
1774 .find_map(|c| {
1775 if c.ident.name == sym::Output
1776 && let Some(ty) = c.ty()
1777 && ty.span != tcx.hir_span(trait_segment.hir_id)
1778 {
1779 tcx.sess.source_map().span_to_snippet(ty.span).ok()
1780 } else {
1781 None
1782 }
1783 })
1784 .unwrap_or_else(|| "()".to_string());
1785
1786 if parenthesized {
1787 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1} -> {2}",
trait_segment.ident, args, ret))
})format!("{}{} -> {}", trait_segment.ident, args, ret)
1788 } else {
1789 ::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)
1790 }
1791}
1792
1793pub enum GenericsArgsErrExtend<'tcx> {
1795 EnumVariant {
1796 qself: &'tcx hir::Ty<'tcx>,
1797 assoc_segment: &'tcx hir::PathSegment<'tcx>,
1798 adt_def: AdtDef<'tcx>,
1799 },
1800 OpaqueTy,
1801 PrimTy(hir::PrimTy),
1802 SelfTyAlias {
1803 def_id: DefId,
1804 span: Span,
1805 },
1806 SelfTyParam(Span),
1807 Param(DefId),
1808 DefVariant(&'tcx [hir::PathSegment<'tcx>]),
1809 None,
1810}
1811
1812fn generics_args_err_extend<'a>(
1813 tcx: TyCtxt<'_>,
1814 segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
1815 err: &mut Diag<'_>,
1816 err_extend: GenericsArgsErrExtend<'a>,
1817) {
1818 match err_extend {
1819 GenericsArgsErrExtend::EnumVariant { qself, assoc_segment, adt_def } => {
1820 err.note("enum variants can't have type parameters");
1821 let type_name = tcx.item_name(adt_def.did());
1822 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!(
1823 "you might have meant to specify type parameters on enum \
1824 `{type_name}`"
1825 );
1826 let Some(args) = assoc_segment.args else {
1827 return;
1828 };
1829 let args_span = args.span_ext.with_lo(args.span_ext.lo() - BytePos(2));
1834 if tcx.generics_of(adt_def.did()).is_empty() {
1835 err.span_suggestion_verbose(
1838 args_span,
1839 ::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"),
1840 "",
1841 Applicability::MachineApplicable,
1842 );
1843 return;
1844 }
1845 let Ok(snippet) = tcx.sess.source_map().span_to_snippet(args_span) else {
1846 err.note(msg);
1847 return;
1848 };
1849 let (qself_sugg_span, is_self) =
1850 if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &qself.kind {
1851 match &path.segments {
1854 [
1858 ..,
1859 hir::PathSegment {
1860 ident, args, res: Res::Def(DefKind::Enum, _), ..
1861 },
1862 _,
1863 ] => (
1864 ident
1867 .span
1868 .shrink_to_hi()
1869 .to(args.map_or(ident.span.shrink_to_hi(), |a| a.span_ext)),
1870 false,
1871 ),
1872 [segment] => {
1873 (
1874 segment.ident.span.shrink_to_hi().to(segment
1877 .args
1878 .map_or(segment.ident.span.shrink_to_hi(), |a| a.span_ext)),
1879 kw::SelfUpper == segment.ident.name,
1880 )
1881 }
1882 _ => {
1883 err.note(msg);
1884 return;
1885 }
1886 }
1887 } else {
1888 err.note(msg);
1889 return;
1890 };
1891 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![
1892 if is_self {
1893 (qself.span, format!("{type_name}{snippet}"))
1897 } else {
1898 (qself_sugg_span, snippet)
1899 },
1900 (args_span, String::new()),
1901 ];
1902 err.multipart_suggestion(msg, suggestion, Applicability::MaybeIncorrect);
1903 }
1904 GenericsArgsErrExtend::DefVariant(segments) => {
1905 let args: Vec<Span> = segments
1906 .iter()
1907 .filter_map(|segment| match segment.res {
1908 Res::Def(
1909 DefKind::Ctor(CtorOf::Variant, _) | DefKind::Variant | DefKind::Enum,
1910 _,
1911 ) => segment.args().span_ext().map(|s| s.with_lo(segment.ident.span.hi())),
1912 _ => None,
1913 })
1914 .collect();
1915 if args.len() > 1
1916 && let Some(span) = args.into_iter().next_back()
1917 {
1918 err.note(
1919 "generic arguments are not allowed on both an enum and its variant's path \
1920 segments simultaneously; they are only valid in one place or the other",
1921 );
1922 err.span_suggestion_verbose(
1923 span,
1924 "remove the generics arguments from one of the path segments",
1925 String::new(),
1926 Applicability::MaybeIncorrect,
1927 );
1928 }
1929 }
1930 GenericsArgsErrExtend::PrimTy(prim_ty) => {
1931 let name = prim_ty.name_str();
1932 for segment in segments {
1933 if let Some(args) = segment.args {
1934 err.span_suggestion_verbose(
1935 segment.ident.span.shrink_to_hi().to(args.span_ext),
1936 ::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"),
1937 "",
1938 Applicability::MaybeIncorrect,
1939 );
1940 }
1941 }
1942 }
1943 GenericsArgsErrExtend::OpaqueTy => {
1944 err.note("`impl Trait` types can't have type parameters");
1945 }
1946 GenericsArgsErrExtend::Param(def_id) => {
1947 let span = tcx.def_ident_span(def_id).unwrap();
1948 let kind = tcx.def_descr(def_id);
1949 let name = tcx.item_name(def_id);
1950 err.span_note(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` defined here", kind,
name))
})format!("{kind} `{name}` defined here"));
1951 }
1952 GenericsArgsErrExtend::SelfTyParam(span) => {
1953 err.span_suggestion_verbose(
1954 span,
1955 "the `Self` type doesn't accept type parameters",
1956 "",
1957 Applicability::MaybeIncorrect,
1958 );
1959 }
1960 GenericsArgsErrExtend::SelfTyAlias { def_id, span } => {
1961 let ty = tcx.at(span).type_of(def_id).instantiate_identity().skip_norm_wip();
1962 let span_of_impl = tcx.span_of_impl(def_id);
1963 let ty::Adt(self_def, _) = *ty.kind() else { return };
1964 let def_id = self_def.did();
1965
1966 let type_name = tcx.item_name(def_id);
1967 let span_of_ty = tcx.def_ident_span(def_id);
1968 let generics = tcx.generics_of(def_id).count();
1969
1970 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`Self` is of type `{0}`", ty))
})format!("`Self` is of type `{ty}`");
1971 if let (Ok(i_sp), Some(t_sp)) = (span_of_impl, span_of_ty) {
1972 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();
1973 span.push_span_label(
1974 i_sp,
1975 ::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`"),
1976 );
1977 let mut postfix = "";
1978 if generics == 0 {
1979 postfix = ", which doesn't have generic parameters";
1980 }
1981 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}"));
1982 err.span_note(span, msg);
1983 } else {
1984 err.note(msg);
1985 }
1986 for segment in segments {
1987 if let Some(args) = segment.args
1988 && segment.ident.name == kw::SelfUpper
1989 {
1990 if generics == 0 {
1991 err.span_suggestion_verbose(
1994 segment.ident.span.shrink_to_hi().to(args.span_ext),
1995 "the `Self` type doesn't accept type parameters",
1996 "",
1997 Applicability::MachineApplicable,
1998 );
1999 return;
2000 } else {
2001 err.span_suggestion_verbose(
2002 segment.ident.span,
2003 ::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!(
2004 "the `Self` type doesn't accept type parameters, use the \
2005 concrete type's name `{type_name}` instead if you want to \
2006 specify its type parameters"
2007 ),
2008 type_name,
2009 Applicability::MaybeIncorrect,
2010 );
2011 }
2012 }
2013 }
2014 }
2015 _ => {}
2016 }
2017}
2018
2019pub(super) struct AmbiguityBetweenVariantAndAssocItem<'tcx> {
2020 pub(super) variant_def_id: DefId,
2021 pub(super) item_def_id: DefId,
2022 pub(super) span: Span,
2023 pub(super) segment_ident: Ident,
2024 pub(super) bound_def_id: DefId,
2025 pub(super) self_ty: Ty<'tcx>,
2026 pub(super) tcx: TyCtxt<'tcx>,
2027 pub(super) mode: super::LowerTypeRelativePathMode,
2028}
2029
2030impl<'a, 'tcx> rustc_errors::Diagnostic<'a> for AmbiguityBetweenVariantAndAssocItem<'tcx> {
2031 fn into_diag(
2032 self,
2033 dcx: rustc_errors::DiagCtxtHandle<'a>,
2034 level: rustc_errors::Level,
2035 ) -> Diag<'a> {
2036 let Self {
2037 variant_def_id,
2038 item_def_id,
2039 span,
2040 segment_ident,
2041 bound_def_id,
2042 self_ty,
2043 tcx,
2044 mode,
2045 } = self;
2046 let mut lint = Diag::new(dcx, level, "ambiguous associated item");
2047
2048 let mut could_refer_to = |kind: DefKind, def_id, also| {
2049 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!(
2050 "`{}` could{} refer to the {} defined here",
2051 segment_ident,
2052 also,
2053 tcx.def_kind_descr(kind, def_id)
2054 );
2055 lint.span_note(tcx.def_span(def_id), note_msg);
2056 };
2057
2058 could_refer_to(DefKind::Variant, variant_def_id, "");
2059 could_refer_to(mode.def_kind_for_diagnostics(), item_def_id, " also");
2060
2061 lint.span_suggestion_verbose(
2062 span,
2063 "use fully-qualified syntax",
2064 ::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),
2065 Applicability::MachineApplicable,
2066 );
2067 lint
2068 }
2069}
2070
2071fn assoc_tag_str(assoc_tag: ty::AssocTag) -> &'static str {
2072 match assoc_tag {
2073 ty::AssocTag::Fn => "function",
2074 ty::AssocTag::Const => "constant",
2075 ty::AssocTag::Type => "type",
2076 }
2077}
2078
2079pub(crate) fn eq_ctxt_suggestion_span(pat: Span, ty: Span) -> Option<Span> {
2084 if let Some(ty2) = ty.find_ancestor_in_same_ctxt(pat)
2085 && pat.hi() <= ty2.lo()
2086 {
2087 return Some(pat.between(ty2));
2088 }
2089 if let Some(pat2) = pat.find_ancestor_in_same_ctxt(ty)
2090 && pat2.hi() <= ty.lo()
2091 {
2092 return Some(pat2.between(ty));
2093 }
2094 None
2095}