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