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