Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,11 @@ class Single(Enum):
VALUE = 1

static_assert(is_equivalent_to(P | Q | Single, Literal[Single.VALUE] | Q | P))

static_assert(is_equivalent_to(Any, Any | Intersection[Any, str]))
static_assert(is_equivalent_to(Any, Intersection[str, Any] | Any))
static_assert(is_equivalent_to(Any, Any | Intersection[Any, Not[None]]))
static_assert(is_equivalent_to(Any, Intersection[Not[None], Any] | Any))
```

## Tuples
Expand Down
7 changes: 7 additions & 0 deletions crates/ty_python_semantic/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1050,6 +1050,13 @@ impl<'db> Type<'db> {
}
}

pub(crate) const fn into_intersection(self) -> Option<IntersectionType<'db>> {
match self {
Type::Intersection(intersection_type) => Some(intersection_type),
_ => None,
}
}

#[cfg(test)]
#[track_caller]
pub(crate) fn expect_union(self) -> UnionType<'db> {
Expand Down
9 changes: 8 additions & 1 deletion crates/ty_python_semantic/src/types/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -504,9 +504,16 @@ impl<'db> UnionBuilder<'db> {
if should_simplify_full && !matches!(element_type, Type::TypeAlias(_)) {
if ty.is_equivalent_to(self.db, element_type)
|| ty.is_subtype_of(self.db, element_type)
|| ty.into_intersection().is_some_and(|intersection| {
intersection.positive(self.db).contains(&element_type)
})
Comment on lines 505 to +509
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A more generalised solution here (that would also allow us to get rid of the separate is_equivalent_to call -- so might be quite a bit faster?) would be to add a third type relation, UnionSimplification (not sure what the best name would be really), which would sit in between TypeRelation::Subtyping and TypeRelation::Assignability. It would mostly behave the same way as subtyping (Any | int would not be considered simplifiable to Any), but Any <: Any, (Any | int) <: (int | Any) and (Any & str) <: Any would all be considered true under this type relation.

{
return;
} else if element_type.is_subtype_of(self.db, ty) {
} else if element_type.is_subtype_of(self.db, ty)
|| element_type
.into_intersection()
.is_some_and(|intersection| intersection.positive(self.db).contains(&ty))
{
to_remove.push(index);
} else if ty_negated.is_subtype_of(self.db, element_type) {
// We add `ty` to the union. We just checked that `~ty` is a subtype of an
Expand Down
Loading