Skip to content

Commit d23826c

Browse files
carljmMichaReiserAlexWaygood
authored
[ty] cache Type::is_redundant_with (#20477)
Co-authored-by: Micha Reiser <micha@reiser.io> Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
1 parent 5fb1423 commit d23826c

2 files changed

Lines changed: 31 additions & 0 deletions

File tree

crates/ty_python_semantic/resources/mdtest/pep695_type_aliases.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,3 +360,14 @@ type X = tuple[X, int]
360360
def _(x: X):
361361
reveal_type(x is x) # revealed: bool
362362
```
363+
364+
### Recursive invariant
365+
366+
```py
367+
type X = dict[str, X]
368+
type Y = X | str | dict[str, Y]
369+
370+
def _(y: Y):
371+
if isinstance(y, dict):
372+
reveal_type(y) # revealed: dict[str, X] | dict[str, Y]
373+
```

crates/ty_python_semantic/src/types.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1543,6 +1543,7 @@ impl<'db> Type<'db> {
15431543
/// Return `true` if it would be redundant to add `self` to a union that already contains `other`.
15441544
///
15451545
/// See [`TypeRelation::Redundancy`] for more details.
1546+
#[salsa::tracked(cycle_fn=is_redundant_with_cycle_recover, cycle_initial=is_redundant_with_cycle_initial, heap_size=ruff_memory_usage::heap_size)]
15461547
pub(crate) fn is_redundant_with(self, db: &'db dyn Db, other: Type<'db>) -> bool {
15471548
self.has_relation_to(db, other, InferableTypeVars::None, TypeRelation::Redundancy)
15481549
.is_always_satisfied()
@@ -7326,6 +7327,25 @@ impl<'db> VarianceInferable<'db> for Type<'db> {
73267327
}
73277328
}
73287329

7330+
#[allow(clippy::trivially_copy_pass_by_ref)]
7331+
fn is_redundant_with_cycle_recover<'db>(
7332+
_db: &'db dyn Db,
7333+
_value: &bool,
7334+
_count: u32,
7335+
_subtype: Type<'db>,
7336+
_supertype: Type<'db>,
7337+
) -> salsa::CycleRecoveryAction<bool> {
7338+
salsa::CycleRecoveryAction::Iterate
7339+
}
7340+
7341+
fn is_redundant_with_cycle_initial<'db>(
7342+
_db: &'db dyn Db,
7343+
_subtype: Type<'db>,
7344+
_supertype: Type<'db>,
7345+
) -> bool {
7346+
true
7347+
}
7348+
73297349
fn apply_specialization_cycle_recover<'db>(
73307350
_db: &'db dyn Db,
73317351
_value: &Type<'db>,

0 commit comments

Comments
 (0)