Rollup merge of #139669 - nnethercote:overhaul-AssocItem, r=oli-obk

Overhaul `AssocItem`

`AssocItem` has multiple fields that only make sense some of the time. E.g. the `name` can be empty if it's an RPITIT associated type. It's clearer and less error prone if these fields are moved to the relevant `kind` variants.

r? ``@fee1-dead``
This commit is contained in:
Stuart Cook 2025-04-15 15:47:27 +10:00 committed by GitHub
commit 13cd5256ac
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
86 changed files with 609 additions and 546 deletions

View file

@ -2334,13 +2334,13 @@ impl<'tcx> ObligationCause<'tcx> {
subdiags: Vec<TypeErrorAdditionalDiags>,
) -> ObligationCauseFailureCode {
match self.code() {
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn, .. } => {
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn { .. }, .. } => {
ObligationCauseFailureCode::MethodCompat { span, subdiags }
}
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type, .. } => {
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type { .. }, .. } => {
ObligationCauseFailureCode::TypeCompat { span, subdiags }
}
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const, .. } => {
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const { .. }, .. } => {
ObligationCauseFailureCode::ConstCompat { span, subdiags }
}
ObligationCauseCode::BlockTailExpression(.., hir::MatchSource::TryDesugar(_)) => {
@ -2398,13 +2398,13 @@ impl<'tcx> ObligationCause<'tcx> {
fn as_requirement_str(&self) -> &'static str {
match self.code() {
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn, .. } => {
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn { .. }, .. } => {
"method type is compatible with trait"
}
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type, .. } => {
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type { .. }, .. } => {
"associated type is compatible with trait"
}
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const, .. } => {
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const { .. }, .. } => {
"const is compatible with trait"
}
ObligationCauseCode::MainFunctionType => "`main` function has the correct type",
@ -2422,9 +2422,13 @@ pub struct ObligationCauseAsDiagArg<'tcx>(pub ObligationCause<'tcx>);
impl IntoDiagArg for ObligationCauseAsDiagArg<'_> {
fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
let kind = match self.0.code() {
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn, .. } => "method_compat",
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type, .. } => "type_compat",
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const, .. } => {
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn { .. }, .. } => {
"method_compat"
}
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type { .. }, .. } => {
"type_compat"
}
ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const { .. }, .. } => {
"const_compat"
}
ObligationCauseCode::MainFunctionType => "fn_main_correct_type",

View file

@ -98,7 +98,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
let assoc_item = self.tcx().associated_item(trait_item_def_id);
let mut visitor = TypeParamSpanVisitor { tcx: self.tcx(), types: vec![] };
match assoc_item.kind {
ty::AssocKind::Fn => {
ty::AssocKind::Fn { .. } => {
if let Some(hir_id) =
assoc_item.def_id.as_local().map(|id| self.tcx().local_def_id_to_hir_id(id))
{

View file

@ -158,6 +158,6 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
&& self
.tcx()
.opt_associated_item(scope_def_id.to_def_id())
.is_some_and(|i| i.fn_has_self_parameter)
.is_some_and(|i| i.is_method())
}
}

View file

@ -782,8 +782,8 @@ fn foo(&self) -> Self::T { String::new() }
let methods: Vec<(Span, String)> = items
.in_definition_order()
.filter(|item| {
ty::AssocKind::Fn == item.kind
&& Some(item.name) != current_method_ident
item.is_fn()
&& Some(item.name()) != current_method_ident
&& !tcx.is_doc_hidden(item.def_id)
})
.filter_map(|item| {

View file

@ -1017,7 +1017,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
infer::BoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
" for lifetime parameter {}in trait containing associated type `{}`",
br_string(br),
self.tcx.associated_item(def_id).name
self.tcx.associated_item(def_id).name()
),
infer::RegionParameterDefinition(_, name) => {
format!(" for lifetime parameter `{name}`")

View file

@ -348,11 +348,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
&& let None = self.tainted_by_errors()
{
let (verb, noun) = match self.tcx.associated_item(item_id).kind {
ty::AssocKind::Const => ("refer to the", "constant"),
ty::AssocKind::Fn => ("call", "function"),
ty::AssocKind::Const { .. } => ("refer to the", "constant"),
ty::AssocKind::Fn { .. } => ("call", "function"),
// This is already covered by E0223, but this following single match
// arm doesn't hurt here.
ty::AssocKind::Type => ("refer to the", "type"),
ty::AssocKind::Type { .. } => ("refer to the", "type"),
};
// Replace the more general E0283 with a more specific error

View file

@ -2112,16 +2112,20 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
trait_ref: DefId,
) {
if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
if let ty::AssocKind::Const { .. } | ty::AssocKind::Type { .. } = assoc_item.kind {
err.note(format!(
"{}s cannot be accessed directly on a `trait`, they can only be \
accessed through a specific `impl`",
self.tcx.def_kind_descr(assoc_item.kind.as_def_kind(), item_def_id)
self.tcx.def_kind_descr(assoc_item.as_def_kind(), item_def_id)
));
err.span_suggestion(
span,
"use the fully qualified path to an implementation",
format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
format!(
"<Type as {}>::{}",
self.tcx.def_path_str(trait_ref),
assoc_item.name()
),
Applicability::HasPlaceholders,
);
}
@ -5411,7 +5415,7 @@ fn point_at_assoc_type_restriction<G: EmissionGuarantee>(
tcx.associated_items(data.impl_or_alias_def_id).find_by_ident_and_kind(
tcx,
Ident::with_dummy_span(name),
ty::AssocKind::Type,
ty::AssocTag::Type,
data.impl_or_alias_def_id,
)
{

View file

@ -188,7 +188,7 @@ fn bounds_reference_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span
tcx.associated_items(trait_def_id)
.in_definition_order()
// We're only looking at associated type bounds
.filter(|item| item.kind == ty::AssocKind::Type)
.filter(|item| item.is_type())
// Ignore GATs with `Self: Sized`
.filter(|item| !tcx.generics_require_sized_self(item.def_id))
.flat_map(|item| tcx.explicit_item_bounds(item.def_id).iter_identity_copied())
@ -298,31 +298,33 @@ pub fn dyn_compatibility_violations_for_assoc_item(
match item.kind {
// Associated consts are never dyn-compatible, as they can't have `where` bounds yet at all,
// and associated const bounds in trait objects aren't a thing yet either.
ty::AssocKind::Const => {
vec![DynCompatibilityViolation::AssocConst(item.name, item.ident(tcx).span)]
ty::AssocKind::Const { name } => {
vec![DynCompatibilityViolation::AssocConst(name, item.ident(tcx).span)]
}
ty::AssocKind::Fn => virtual_call_violations_for_method(tcx, trait_def_id, item)
.into_iter()
.map(|v| {
let node = tcx.hir_get_if_local(item.def_id);
// Get an accurate span depending on the violation.
let span = match (&v, node) {
(MethodViolationCode::ReferencesSelfInput(Some(span)), _) => *span,
(MethodViolationCode::UndispatchableReceiver(Some(span)), _) => *span,
(MethodViolationCode::ReferencesImplTraitInTrait(span), _) => *span,
(MethodViolationCode::ReferencesSelfOutput, Some(node)) => {
node.fn_decl().map_or(item.ident(tcx).span, |decl| decl.output.span())
}
_ => item.ident(tcx).span,
};
ty::AssocKind::Fn { name, .. } => {
virtual_call_violations_for_method(tcx, trait_def_id, item)
.into_iter()
.map(|v| {
let node = tcx.hir_get_if_local(item.def_id);
// Get an accurate span depending on the violation.
let span = match (&v, node) {
(MethodViolationCode::ReferencesSelfInput(Some(span)), _) => *span,
(MethodViolationCode::UndispatchableReceiver(Some(span)), _) => *span,
(MethodViolationCode::ReferencesImplTraitInTrait(span), _) => *span,
(MethodViolationCode::ReferencesSelfOutput, Some(node)) => {
node.fn_decl().map_or(item.ident(tcx).span, |decl| decl.output.span())
}
_ => item.ident(tcx).span,
};
DynCompatibilityViolation::Method(item.name, v, span)
})
.collect(),
DynCompatibilityViolation::Method(name, v, span)
})
.collect()
}
// Associated types can only be dyn-compatible if they have `Self: Sized` bounds.
ty::AssocKind::Type => {
ty::AssocKind::Type { .. } => {
if !tcx.generics_of(item.def_id).is_own_empty() && !item.is_impl_trait_in_trait() {
vec![DynCompatibilityViolation::GAT(item.name, item.ident(tcx).span)]
vec![DynCompatibilityViolation::GAT(item.name(), item.ident(tcx).span)]
} else {
// We will permit associated types if they are explicitly mentioned in the trait object.
// We can't check this here, as here we only check if it is guaranteed to not be possible.
@ -344,7 +346,7 @@ fn virtual_call_violations_for_method<'tcx>(
let sig = tcx.fn_sig(method.def_id).instantiate_identity();
// The method's first parameter must be named `self`
if !method.fn_has_self_parameter {
if !method.is_method() {
let sugg = if let Some(hir::Node::TraitItem(hir::TraitItem {
generics,
kind: hir::TraitItemKind::Fn(sig, _),

View file

@ -1393,7 +1393,7 @@ fn confirm_future_candidate<'cx, 'tcx>(
coroutine_sig,
);
debug_assert_eq!(tcx.associated_item(obligation.predicate.def_id).name, sym::Output);
debug_assert_eq!(tcx.associated_item(obligation.predicate.def_id).name(), sym::Output);
let predicate = ty::ProjectionPredicate {
projection_term: ty::AliasTerm::new_from_args(
@ -1439,7 +1439,7 @@ fn confirm_iterator_candidate<'cx, 'tcx>(
gen_sig,
);
debug_assert_eq!(tcx.associated_item(obligation.predicate.def_id).name, sym::Item);
debug_assert_eq!(tcx.associated_item(obligation.predicate.def_id).name(), sym::Item);
let predicate = ty::ProjectionPredicate {
projection_term: ty::AliasTerm::new_from_args(
@ -1485,7 +1485,7 @@ fn confirm_async_iterator_candidate<'cx, 'tcx>(
gen_sig,
);
debug_assert_eq!(tcx.associated_item(obligation.predicate.def_id).name, sym::Item);
debug_assert_eq!(tcx.associated_item(obligation.predicate.def_id).name(), sym::Item);
let ty::Adt(_poll_adt, args) = *yield_ty.kind() else {
bug!();
@ -2005,7 +2005,8 @@ fn confirm_impl_candidate<'cx, 'tcx>(
if !assoc_ty.item.defaultness(tcx).has_value() {
debug!(
"confirm_impl_candidate: no associated type {:?} for {:?}",
assoc_ty.item.name, obligation.predicate
assoc_ty.item.name(),
obligation.predicate
);
if tcx.impl_self_is_guaranteed_unsized(impl_def_id) {
// We treat this projection as rigid here, which is represented via

View file

@ -594,9 +594,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
// Associated types that require `Self: Sized` do not show up in the built-in
// implementation of `Trait for dyn Trait`, and can be dropped here.
.filter(|item| !tcx.generics_require_sized_self(item.def_id))
.filter_map(
|item| if item.kind == ty::AssocKind::Type { Some(item.def_id) } else { None },
)
.filter_map(|item| if item.is_type() { Some(item.def_id) } else { None })
.collect();
for assoc_type in assoc_types {

View file

@ -197,10 +197,8 @@ fn own_existential_vtable_entries_iter(
tcx: TyCtxt<'_>,
trait_def_id: DefId,
) -> impl Iterator<Item = DefId> {
let trait_methods = tcx
.associated_items(trait_def_id)
.in_definition_order()
.filter(|item| item.kind == ty::AssocKind::Fn);
let trait_methods =
tcx.associated_items(trait_def_id).in_definition_order().filter(|item| item.is_fn());
// Now list each method's DefId (for within its trait).
let own_entries = trait_methods.filter_map(move |&trait_method| {