Skip to content

Commit 06256af

Browse files
authored
[ty] Simplify an intersection of N & ~T to Never if B & ~T would simplify to Never, where B is the concrete base type of a NewType N (#24086)
## Summary Fixes astral-sh/ty#2941 Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com> ## Test Plan added an mdtest
1 parent f32b9bb commit 06256af

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

crates/ty_python_semantic/resources/mdtest/annotations/new_types.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,17 @@ def _(x: Foo | float, y: Bar | complex):
429429
reveal_type(not y) # revealed: bool
430430
```
431431

432+
Intersections with `NewType`s solve to `Never` if the intersection with the `NewType`'s concrete
433+
base type would also solve to `Never`:
434+
435+
```py
436+
TFloat = NewType("TFloat", float)
437+
438+
def f(x: TFloat) -> None:
439+
if not isinstance(x, float | int):
440+
reveal_type(x) # revealed: Never
441+
```
442+
432443
## A `NewType` definition must be a simple variable assignment
433444

434445
```py

crates/ty_python_semantic/src/types/set_theoretic/builder.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1516,7 +1516,11 @@ impl<'db> InnerIntersectionBuilder<'db> {
15161516
// to their upper bound and all constrained type variables to the union of their constraints.
15171517
// If that speculative intersection simplifies to `Never`, this intersection must also simplify
15181518
// to `Never`.
1519-
if self.positive.iter().any(|ty| ty.is_type_var()) {
1519+
if self
1520+
.positive
1521+
.iter()
1522+
.any(|ty| matches!(ty, Type::TypeVar(_) | Type::NewTypeInstance(_)))
1523+
{
15201524
let mut speculative = IntersectionBuilder::new(db);
15211525
for pos in &self.positive {
15221526
match pos {
@@ -1533,6 +1537,9 @@ impl<'db> InnerIntersectionBuilder<'db> {
15331537
None => {}
15341538
}
15351539
}
1540+
Type::NewTypeInstance(newtype) => {
1541+
speculative = speculative.add_positive(newtype.concrete_base_type(db));
1542+
}
15361543
_ => speculative = speculative.add_positive(*pos),
15371544
}
15381545
}

0 commit comments

Comments
 (0)