Rollup merge of #137913 - compiler-errors:struct-field-default-generic, r=BoxyUwU

Allow struct field default values to reference struct's generics

Right now, the default field value feature (https://github.com/rust-lang/rust/issues/132162) lowers anon consts whose types may reference ADT params that the const doesn't inherit.

This PR fixes this, so that these defaults can reference ADTs' generics, and sets the `generics_of` parenting up correctly.

There doesn't seem to be a good reason not to support this, since the anon const has a well-defined type from the field, and the anon const doesn't interact with the type system like generic parameter defaults do.

r? `````@boxyuwu````` or reassign

I could also make this into an error if this seems problematic (https://github.com/rust-lang/rust/compare/master...compiler-errors:rust:default-field-value-implicit-param?expand=1)...... but I'd rather make this work and register an open question on the tracking issue about validating that this is well-vetted.

Fixes #137896
This commit is contained in:
Jubilee 2025-03-04 19:37:01 -08:00 committed by GitHub
commit b3d7c1483d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 112 additions and 19 deletions

View file

@ -78,6 +78,7 @@ struct IsNeverPattern;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum AnonConstKind {
EnumDiscriminant,
FieldDefaultValue,
InlineConst,
ConstArg(IsRepeatExpr),
}
@ -1406,7 +1407,7 @@ impl<'ra: 'ast, 'ast, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'r
visit_opt!(self, visit_ident, ident);
try_visit!(self.visit_ty(ty));
if let Some(v) = &default {
self.resolve_anon_const(v, AnonConstKind::ConstArg(IsRepeatExpr::No));
self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
}
}
}
@ -4659,6 +4660,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
AnonConstKind::EnumDiscriminant => {
ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
}
AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
AnonConstKind::ConstArg(_) => {
if self.r.tcx.features().generic_const_exprs() || is_trivial_const_arg {