[ty] Optimize and simplify some object-related code (#22366)

## Summary

I wondered if this might improve performance a little. It doesn't seem
to, but it's a net reduction in LOC and I think the changes make sense.
I think it's worth it anyway just in terms of simplifying the code.

## Test Plan

Our existing tests all pass and the primer report is clean (aside from
our usual flakes).
This commit is contained in:
Alex Waygood
2026-01-07 08:35:26 +00:00
committed by GitHub
parent 2190fcebe0
commit 5933cc0101
5 changed files with 15 additions and 17 deletions

View File

@@ -32,6 +32,7 @@ typeshed = "/typeshed"
`/typeshed/stdlib/builtins.pyi`:
```pyi
class object: ...
class Custom: ...
custom_builtin: Custom

View File

@@ -980,16 +980,17 @@ impl<'db> InnerIntersectionBuilder<'db> {
}
_ => {
let known_instance = new_positive
.as_nominal_instance()
.and_then(|instance| instance.known_class(db));
let positive_as_instance = new_positive.as_nominal_instance();
if known_instance == Some(KnownClass::Object) {
if let Some(instance) = positive_as_instance
&& instance.is_object()
{
// `object & T` -> `T`; it is always redundant to add `object` to an intersection
return;
}
let addition_is_bool_instance = known_instance == Some(KnownClass::Bool);
let addition_is_bool_instance = positive_as_instance
.is_some_and(|instance| instance.has_known_class(db, KnownClass::Bool));
for (index, existing_positive) in self.positive.iter().enumerate() {
match existing_positive {

View File

@@ -428,10 +428,12 @@ pub enum ClassType<'db> {
impl<'db> ClassType<'db> {
/// Return a `ClassType` representing the class `builtins.object`
pub(super) fn object(db: &'db dyn Db) -> Self {
KnownClass::Object
.to_class_literal(db)
.to_class_type(db)
.unwrap()
ClassType::NonGeneric(
KnownClass::Object
.to_class_literal(db)
.as_class_literal()
.expect("`object` should always be a non-generic class in typeshed"),
)
}
pub(super) const fn is_generic(self) -> bool {

View File

@@ -75,10 +75,7 @@ impl<'db> ClassBase<'db> {
/// Return a `ClassBase` representing the class `builtins.object`
pub(super) fn object(db: &'db dyn Db) -> Self {
KnownClass::Object
.to_class_literal(db)
.to_class_type(db)
.map_or(Self::unknown(), Self::Class)
Self::Class(ClassType::object(db))
}
pub(super) const fn is_typed_dict(self) -> bool {

View File

@@ -221,10 +221,7 @@ impl<'db> NominalInstanceType<'db> {
match self.0 {
NominalInstanceInner::ExactTuple(tuple) => tuple.to_class_type(db),
NominalInstanceInner::NonTuple(class) => class,
NominalInstanceInner::Object => KnownClass::Object
.try_to_class_literal(db)
.expect("Typeshed should always have a `object` class in `builtins.pyi`")
.default_specialization(db),
NominalInstanceInner::Object => ClassType::object(db),
}
}