mirror of
https://github.com/astral-sh/ruff.git
synced 2026-12-04 00:22:00 +08:00
[ty] Read specialization fields through a single Salsa getter
Intern the fields as one record so recursive type mapping can borrow them all at once. Use Salsa’s public lookup traits to compare borrowed arguments with the stored slice and allocate only when interning a new specialization.
This commit is contained in:
@@ -1193,12 +1193,18 @@ impl<'db> GenericContext<'db> {
|
||||
///
|
||||
/// TODO: Handle nested specializations better, with actual parent links to the specialization of
|
||||
/// the lexically containing context.
|
||||
#[salsa::interned(debug, heap_size=ruff_memory_usage::heap_size)]
|
||||
#[salsa::interned(debug, constructor=intern, heap_size=ruff_memory_usage::heap_size)]
|
||||
pub struct Specialization<'db> {
|
||||
#[returns(copy)]
|
||||
pub(crate) generic_context: GenericContext<'db>,
|
||||
#[returns(deref)]
|
||||
pub(crate) types: Box<[Type<'db>]>,
|
||||
#[returns(ref)]
|
||||
fields: SpecializationFields<'db>,
|
||||
}
|
||||
|
||||
/// Store the fields together so mapping nested arguments only needs one Salsa lookup
|
||||
/// per specialization. The interner owns the arguments, but a lookup can borrow them.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, get_size2::GetSize, salsa::SalsaValue)]
|
||||
pub struct SpecializationFields<'db, T = Box<[Type<'db>]>> {
|
||||
generic_context: GenericContext<'db>,
|
||||
types: T,
|
||||
/// The materialization kind of the specialization. For example, given an invariant
|
||||
/// generic type `A`, `Top[A[Any]]` is a supertype of all materializations of `A[Any]`,
|
||||
/// and is represented here with `Some(MaterializationKind::Top)`. Similarly,
|
||||
@@ -1206,27 +1212,108 @@ pub struct Specialization<'db> {
|
||||
/// with `Some(MaterializationKind::Bottom)`.
|
||||
/// The `materialization_kind` field may be non-`None` only if the specialization contains
|
||||
/// dynamic types in invariant positions or positions with constrained type variables.
|
||||
#[returns(copy)]
|
||||
pub(crate) materialization_kind: Option<MaterializationKind>,
|
||||
materialization_kind: Option<MaterializationKind>,
|
||||
|
||||
/// For specializations of `tuple`, we also store more detailed information about the tuple's
|
||||
/// elements, above what the class's (single) typevar can represent.
|
||||
#[returns(copy)]
|
||||
tuple_inner: Option<TupleType<'db>>,
|
||||
}
|
||||
|
||||
/// Use the same fields and hash for lookups as for stored specializations.
|
||||
/// The wrapper keeps our lookup implementation disjoint from Salsa's blanket
|
||||
/// implementation of `Lookup<T> for T` when the caller already owns a boxed slice.
|
||||
#[derive(Hash)]
|
||||
struct SpecializationKey<'db, T>(SpecializationFields<'db, T>);
|
||||
|
||||
impl<'db, T: salsa::Lookup<Box<[Type<'db>]>>> salsa::Lookup<SpecializationFields<'db>>
|
||||
for SpecializationKey<'db, T>
|
||||
{
|
||||
fn into_owned(self) -> SpecializationFields<'db> {
|
||||
SpecializationFields {
|
||||
generic_context: self.0.generic_context,
|
||||
types: self.0.types.into_owned(),
|
||||
materialization_kind: self.0.materialization_kind,
|
||||
tuple_inner: self.0.tuple_inner,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'db, T> salsa::HashEqLike<SpecializationKey<'db, T>> for SpecializationFields<'db>
|
||||
where
|
||||
Box<[Type<'db>]>: salsa::HashEqLike<T>,
|
||||
{
|
||||
fn eq(&self, key: &SpecializationKey<'db, T>) -> bool {
|
||||
self.generic_context == key.0.generic_context
|
||||
&& salsa::HashEqLike::eq(&self.types, &key.0.types)
|
||||
&& self.materialization_kind == key.0.materialization_kind
|
||||
&& self.tuple_inner == key.0.tuple_inner
|
||||
}
|
||||
}
|
||||
|
||||
// The Salsa heap is tracked separately.
|
||||
impl get_size2::GetSize for Specialization<'_> {}
|
||||
|
||||
/// A changed unary argument can be passed to the interner as a borrowed slice. Keep
|
||||
/// it inline here, so only a cache miss needs a new allocation. This is temporary
|
||||
/// storage and does not change the layout of an interned specialization.
|
||||
/// Keep a single replacement on the stack so we can pass a borrowed slice to
|
||||
/// Salsa. Only a new specialization needs to allocate storage for that argument.
|
||||
enum MappedArguments<'db> {
|
||||
Unchanged,
|
||||
One(Type<'db>),
|
||||
Many(Vec<Type<'db>>),
|
||||
}
|
||||
|
||||
impl<'db> SpecializationFields<'db> {
|
||||
fn map_arguments(
|
||||
&self,
|
||||
db: &'db dyn Db,
|
||||
mut map: impl FnMut(usize, GenericParameter<'db>, Type<'db>) -> Type<'db>,
|
||||
) -> MappedArguments<'db> {
|
||||
let types = &self.types;
|
||||
let mut changed = Vec::new();
|
||||
let mut parameters = self.generic_context.variables_inner(db).values().copied();
|
||||
for (index, &ty) in types.iter().enumerate() {
|
||||
let Some(parameter) = parameters.next() else {
|
||||
break;
|
||||
};
|
||||
let mapped = map(index, parameter, ty);
|
||||
if changed.is_empty() {
|
||||
if mapped == ty {
|
||||
continue;
|
||||
}
|
||||
if types.len() == 1 {
|
||||
return MappedArguments::One(mapped);
|
||||
}
|
||||
changed.reserve_exact(types.len());
|
||||
changed.extend_from_slice(&types[..index]);
|
||||
}
|
||||
changed.push(mapped);
|
||||
}
|
||||
|
||||
if changed.is_empty() {
|
||||
MappedArguments::Unchanged
|
||||
} else {
|
||||
MappedArguments::Many(changed)
|
||||
}
|
||||
}
|
||||
|
||||
// Only changed specializations need an interner key. Keep those temporaries off
|
||||
// the stack during recursive mapping of deeply nested type arguments.
|
||||
#[inline(never)]
|
||||
fn intern_mapped(
|
||||
&self,
|
||||
db: &'db dyn Db,
|
||||
mapped: MappedArguments<'db>,
|
||||
kind: Option<MaterializationKind>,
|
||||
tuple_inner: Option<TupleType<'db>>,
|
||||
) -> Specialization<'db> {
|
||||
let types = match mapped {
|
||||
MappedArguments::Unchanged => Cow::Borrowed(self.types.as_ref()),
|
||||
MappedArguments::One(ref ty) => Cow::Borrowed(std::slice::from_ref(ty)),
|
||||
MappedArguments::Many(types) => Cow::Owned(types),
|
||||
};
|
||||
Specialization::new(db, self.generic_context, types, kind, tuple_inner)
|
||||
}
|
||||
}
|
||||
|
||||
/// Visit specialization arguments and the generic declaration.
|
||||
pub(super) fn walk_specialization<'db, V: TypeVisitor<'db> + ?Sized>(
|
||||
db: &'db dyn Db,
|
||||
@@ -1252,6 +1339,44 @@ pub(super) fn walk_specialization_types<'db, V: TypeVisitor<'db> + ?Sized>(
|
||||
}
|
||||
|
||||
impl<'db> Specialization<'db> {
|
||||
pub(crate) fn new<T>(
|
||||
db: &'db dyn Db,
|
||||
generic_context: GenericContext<'db>,
|
||||
types: T,
|
||||
materialization_kind: Option<MaterializationKind>,
|
||||
tuple_inner: Option<TupleType<'db>>,
|
||||
) -> Self
|
||||
where
|
||||
T: salsa::Lookup<Box<[Type<'db>]>> + std::hash::Hash,
|
||||
Box<[Type<'db>]>: salsa::HashEqLike<T>,
|
||||
{
|
||||
Self::intern(
|
||||
db,
|
||||
SpecializationKey(SpecializationFields {
|
||||
generic_context,
|
||||
types,
|
||||
materialization_kind,
|
||||
tuple_inner,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn generic_context(self, db: &'db dyn Db) -> GenericContext<'db> {
|
||||
self.fields(db).generic_context
|
||||
}
|
||||
|
||||
pub(crate) fn types(self, db: &'db dyn Db) -> &'db [Type<'db>] {
|
||||
&self.fields(db).types
|
||||
}
|
||||
|
||||
pub(crate) fn materialization_kind(self, db: &'db dyn Db) -> Option<MaterializationKind> {
|
||||
self.fields(db).materialization_kind
|
||||
}
|
||||
|
||||
fn tuple_inner(self, db: &'db dyn Db) -> Option<TupleType<'db>> {
|
||||
self.fields(db).tuple_inner
|
||||
}
|
||||
|
||||
/// Merge cycle iterations that differ only by gradual `Unknown` type arguments.
|
||||
///
|
||||
/// Known argument mismatches are not merged because doing so would be unsound for invariant
|
||||
@@ -1295,47 +1420,14 @@ impl<'db> Specialization<'db> {
|
||||
db: &'db dyn Db,
|
||||
map: impl FnMut(usize, GenericParameter<'db>, Type<'db>) -> Type<'db>,
|
||||
) -> Cow<'db, [Type<'db>]> {
|
||||
let types = self.types(db);
|
||||
match Self::map_arguments(db, self.generic_context(db), types, map) {
|
||||
MappedArguments::Unchanged => Cow::Borrowed(types),
|
||||
let original = self.fields(db);
|
||||
match original.map_arguments(db, map) {
|
||||
MappedArguments::Unchanged => Cow::Borrowed(&original.types),
|
||||
MappedArguments::One(ty) => Cow::Owned(vec![ty]),
|
||||
MappedArguments::Many(mapped) => Cow::Owned(mapped),
|
||||
}
|
||||
}
|
||||
|
||||
fn map_arguments(
|
||||
db: &'db dyn Db,
|
||||
context: GenericContext<'db>,
|
||||
types: &[Type<'db>],
|
||||
mut map: impl FnMut(usize, GenericParameter<'db>, Type<'db>) -> Type<'db>,
|
||||
) -> MappedArguments<'db> {
|
||||
let mut changed = Vec::new();
|
||||
let mut parameters = context.variables_inner(db).values().copied();
|
||||
for (index, &ty) in types.iter().enumerate() {
|
||||
let Some(parameter) = parameters.next() else {
|
||||
break;
|
||||
};
|
||||
let mapped = map(index, parameter, ty);
|
||||
if changed.is_empty() {
|
||||
if mapped == ty {
|
||||
continue;
|
||||
}
|
||||
if types.len() == 1 {
|
||||
return MappedArguments::One(mapped);
|
||||
}
|
||||
changed.reserve_exact(types.len());
|
||||
changed.extend_from_slice(&types[..index]);
|
||||
}
|
||||
changed.push(mapped);
|
||||
}
|
||||
|
||||
if changed.is_empty() {
|
||||
MappedArguments::Unchanged
|
||||
} else {
|
||||
MappedArguments::Many(changed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Intersects gradual type arguments with their type parameters' upper bounds.
|
||||
///
|
||||
/// For example, in a protocol `P[T: str]`, a member typed as `T` remains bounded by
|
||||
@@ -1505,13 +1597,9 @@ impl<'db> Specialization<'db> {
|
||||
return self.materialize_impl(db, *materialization_kind, visitor);
|
||||
}
|
||||
|
||||
// Each getter on an interned struct looks up the same record. Read it once
|
||||
// per level, even when mapping nested arguments leaves everything unchanged.
|
||||
let zalsa = db.zalsa();
|
||||
let &(context, ref arguments, original_kind, original_tuple_inner) =
|
||||
Specialization::ingredient(zalsa).fields(zalsa, self);
|
||||
let mut new_materialization_kind = original_kind;
|
||||
let mapped = Self::map_arguments(db, context, arguments, |i, parameter, ty| {
|
||||
let original = self.fields(db);
|
||||
let mut new_materialization_kind = original.materialization_kind;
|
||||
let mapped = original.map_arguments(db, |i, parameter, ty| {
|
||||
let tcx = TypeContext::preference(tcx.get(i).copied());
|
||||
if type_mapping.is_structural() {
|
||||
return ty.apply_type_mapping_impl(db, type_mapping, tcx, visitor);
|
||||
@@ -1559,45 +1647,19 @@ impl<'db> Specialization<'db> {
|
||||
}
|
||||
});
|
||||
|
||||
let tuple_inner = original_tuple_inner.map(|tuple| {
|
||||
let tuple_inner = original.tuple_inner.map(|tuple| {
|
||||
tuple.apply_type_mapping_impl(db, type_mapping, TypeContext::default(), visitor)
|
||||
});
|
||||
|
||||
// Tuple shape and materialization can change independently of the arguments.
|
||||
if matches!(mapped, MappedArguments::Unchanged)
|
||||
&& tuple_inner == original_tuple_inner
|
||||
&& new_materialization_kind == original_kind
|
||||
&& tuple_inner == original.tuple_inner
|
||||
&& new_materialization_kind == original.materialization_kind
|
||||
{
|
||||
return self;
|
||||
}
|
||||
|
||||
Self::intern_mapped(
|
||||
db,
|
||||
context,
|
||||
arguments,
|
||||
mapped,
|
||||
new_materialization_kind,
|
||||
tuple_inner,
|
||||
)
|
||||
}
|
||||
|
||||
// Only changed specializations need an interner key. Keep those temporaries off
|
||||
// the stack during recursive mapping of deeply nested type arguments.
|
||||
#[inline(never)]
|
||||
fn intern_mapped(
|
||||
db: &'db dyn Db,
|
||||
context: GenericContext<'db>,
|
||||
original: &[Type<'db>],
|
||||
mapped: MappedArguments<'db>,
|
||||
kind: Option<MaterializationKind>,
|
||||
tuple_inner: Option<TupleType<'db>>,
|
||||
) -> Self {
|
||||
let types = match mapped {
|
||||
MappedArguments::Unchanged => Cow::Borrowed(original),
|
||||
MappedArguments::One(ref ty) => Cow::Borrowed(std::slice::from_ref(ty)),
|
||||
MappedArguments::Many(types) => Cow::Owned(types),
|
||||
};
|
||||
Self::new(db, context, types, kind, tuple_inner)
|
||||
original.intern_mapped(db, mapped, new_materialization_kind, tuple_inner)
|
||||
}
|
||||
|
||||
/// Applies an optional specialization to this specialization.
|
||||
@@ -5405,6 +5467,20 @@ mod tests {
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn borrowed_and_owned_arguments_intern_the_same_specialization() {
|
||||
let db = setup_db();
|
||||
let db = &db;
|
||||
let env = db.program_environment();
|
||||
let context = GenericContext::from_typevar_instances(db, &env, create_typevars(db, ["T"]));
|
||||
let types = [Type::object()];
|
||||
|
||||
let borrowed = Specialization::new(db, context, types.as_slice(), None, None);
|
||||
let owned = Specialization::new(db, context, Box::<[_]>::from(types), None, None);
|
||||
assert_eq!(borrowed, owned);
|
||||
assert_eq!(borrowed, context.specialize(db, types.to_vec()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recursive_specialization_uses_concrete_peers_before_cycle_recovery() {
|
||||
let db = setup_db();
|
||||
|
||||
Reference in New Issue
Block a user