Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[red-knot] Ensure that bool | AlwaysFalsy is considered equivalent to Literal[True] | AlwaysFalsy #15784

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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 @@ -455,9 +455,9 @@ else:
reveal_type(x) # revealed: slice
finally:
# TODO: should be `Literal[1] | str | bytes | bool | memoryview | float | range | slice`
reveal_type(x) # revealed: bool | float | slice
reveal_type(x) # revealed: bool | slice | float

reveal_type(x) # revealed: bool | float | slice
reveal_type(x) # revealed: bool | slice | float
```

## Nested `try`/`except` blocks
Expand Down Expand Up @@ -534,7 +534,7 @@ try:
reveal_type(x) # revealed: slice
finally:
# TODO: should be `Literal[1] | str | bytes | bool | memoryview | float | range | slice`
reveal_type(x) # revealed: bool | float | slice
reveal_type(x) # revealed: bool | slice | float
x = 2
reveal_type(x) # revealed: Literal[2]
reveal_type(x) # revealed: Literal[2]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,37 +11,37 @@ x = foo()
if x:
reveal_type(x) # revealed: Literal[-1, True, "foo", b"bar"]
else:
reveal_type(x) # revealed: Literal[0, False, "", b""] | None | tuple[()]
reveal_type(x) # revealed: Literal[0, False, "", b""] | tuple[()] | None

if not x:
reveal_type(x) # revealed: Literal[0, False, "", b""] | None | tuple[()]
reveal_type(x) # revealed: Literal[0, False, "", b""] | tuple[()] | None
else:
reveal_type(x) # revealed: Literal[-1, True, "foo", b"bar"]

if x and not x:
reveal_type(x) # revealed: Never
else:
reveal_type(x) # revealed: Literal[0, -1, "", "foo", b"", b"bar"] | bool | None | tuple[()]
reveal_type(x) # revealed: Literal[0, -1, b"bar", "", "foo", b""] | bool | tuple[()] | None

if not (x and not x):
reveal_type(x) # revealed: Literal[0, -1, "", "foo", b"", b"bar"] | bool | None | tuple[()]
reveal_type(x) # revealed: Literal[0, -1, b"bar", "", "foo", b""] | bool | tuple[()] | None
else:
reveal_type(x) # revealed: Never

if x or not x:
reveal_type(x) # revealed: Literal[0, -1, "", "foo", b"", b"bar"] | bool | None | tuple[()]
reveal_type(x) # revealed: Literal[0, -1, b"bar", "", "foo", b""] | bool | tuple[()] | None
else:
reveal_type(x) # revealed: Never

if not (x or not x):
reveal_type(x) # revealed: Never
else:
reveal_type(x) # revealed: Literal[0, -1, "", "foo", b"", b"bar"] | bool | None | tuple[()]
reveal_type(x) # revealed: Literal[0, -1, b"bar", "", "foo", b""] | bool | tuple[()] | None

if (isinstance(x, int) or isinstance(x, str)) and x:
reveal_type(x) # revealed: Literal[-1, True, "foo"]
else:
reveal_type(x) # revealed: Literal[b"", b"bar", 0, False, ""] | None | tuple[()]
reveal_type(x) # revealed: tuple[()] | None | Literal[b"", b"bar", 0, False, ""]
```

## Function Literals
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -346,4 +346,24 @@ static_assert(is_assignable_to(Never, type[str]))
static_assert(is_assignable_to(Never, type[Any]))
```

### `bool` is assignable to unions that include `bool`

Since we decompose `bool` to `Literal[True, False]` in unions, it would be surprisingly easy to get
this wrong if we forgot to normalize `bool` to `Literal[True, False]` when it appeared on the
left-hand side in `Type::is_assignable_to()`.

```py
from knot_extensions import is_assignable_to, static_assert

static_assert(is_assignable_to(bool, str | bool))
```

### `bool` is assignable to `AlwaysTruthy | AlwaysFalsy`

```py
from knot_extensions import static_assert, is_assignable_to, AlwaysTruthy, AlwaysFalsy

static_assert(is_assignable_to(bool, AlwaysTruthy | AlwaysFalsy))
```

[typing documentation]: https://typing.readthedocs.io/en/latest/spec/concepts.html#the-assignable-to-or-consistent-subtyping-relation
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,48 @@ class R: ...
static_assert(is_equivalent_to(Intersection[tuple[P | Q], R], Intersection[tuple[Q | P], R]))
```

## Unions containing tuples containing `bool`

```py
from knot_extensions import is_equivalent_to, static_assert
from typing_extensions import Literal

class P: ...

static_assert(is_equivalent_to(tuple[Literal[True, False]] | P, tuple[bool] | P))
static_assert(is_equivalent_to(P | tuple[bool], P | tuple[Literal[True, False]]))
```

## Unions and intersections involving `AlwaysTruthy`, `bool` and `AlwaysFalsy`

```py
from knot_extensions import AlwaysTruthy, AlwaysFalsy, static_assert, is_equivalent_to, Not
from typing_extensions import Literal

static_assert(is_equivalent_to(AlwaysTruthy | bool, Literal[False] | AlwaysTruthy))
static_assert(is_equivalent_to(AlwaysFalsy | bool, Literal[True] | AlwaysFalsy))
static_assert(is_equivalent_to(Not[AlwaysTruthy] | bool, Not[AlwaysTruthy] | Literal[True]))
static_assert(is_equivalent_to(Not[AlwaysFalsy] | bool, Literal[False] | Not[AlwaysFalsy]))
```

## Unions and intersections involving `AlwaysTruthy`, `LiteralString` and `AlwaysFalsy`

```py
from knot_extensions import AlwaysTruthy, AlwaysFalsy, static_assert, is_equivalent_to, Not, Intersection
from typing_extensions import Literal, LiteralString

# TODO: these should all pass!

# error: [static-assert-error]
static_assert(is_equivalent_to(AlwaysTruthy | LiteralString, Literal[""] | AlwaysTruthy))
# error: [static-assert-error]
static_assert(is_equivalent_to(AlwaysFalsy | LiteralString, Intersection[LiteralString, Not[Literal[""]]] | AlwaysFalsy))
# error: [static-assert-error]
static_assert(is_equivalent_to(Not[AlwaysFalsy] | LiteralString, Literal[""] | Not[AlwaysFalsy]))
# error: [static-assert-error]
static_assert(
is_equivalent_to(Not[AlwaysTruthy] | LiteralString, Not[AlwaysTruthy] | Intersection[LiteralString, Not[Literal[""]]])
)
```

[the equivalence relation]: https://typing.readthedocs.io/en/latest/spec/glossary.html#term-equivalent
Original file line number Diff line number Diff line change
Expand Up @@ -449,5 +449,31 @@ static_assert(not is_subtype_of(Intersection[Unknown, int], int))
static_assert(not is_subtype_of(tuple[int, int], tuple[int, Unknown]))
```

## `bool` is a subtype of `AlwaysTruthy | AlwaysFalsy`

`bool` is equivalent to `Literal[True] | Literal[False]`. `Literal[True]` is a subtype of
`AlwaysTruthy` and `Literal[False]` is a subtype of `AlwaysFalsy`; it therefore stands to reason
that `bool` is a subtype of `AlwaysTruthy | AlwaysFalsy`.

```py
from knot_extensions import AlwaysTruthy, AlwaysFalsy, is_subtype_of, static_assert, Not, is_disjoint_from
from typing_extensions import Literal

static_assert(is_subtype_of(bool, AlwaysTruthy | AlwaysFalsy))

# the inverse also applies -- TODO: this should pass!
# See the TODO comments in the `Type::Intersection` branch of `Type::is_disjoint_from()`.
static_assert(is_disjoint_from(bool, Not[AlwaysTruthy | AlwaysFalsy])) # error: [static-assert-error]

# `Type::is_subtype_of` delegates many questions of `bool` subtyping to `int`,
# but set-theoretic types like intersections and unions are still handled differently to `int`
static_assert(is_subtype_of(Literal[True], Not[Literal[2]]))
static_assert(is_subtype_of(bool, Not[Literal[2]]))
static_assert(is_subtype_of(Literal[True], bool | None))
static_assert(is_subtype_of(bool, bool | None))

static_assert(not is_subtype_of(int, Not[Literal[2]]))
```

[special case for float and complex]: https://typing.readthedocs.io/en/latest/spec/special-types.html#special-cases-for-float-and-complex
[typing documentation]: https://typing.readthedocs.io/en/latest/spec/concepts.html#subtype-supertype-and-type-equivalence
21 changes: 20 additions & 1 deletion crates/red_knot_python_semantic/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -881,6 +881,15 @@ impl<'db> Type<'db> {
(Type::Never, _) => true,
(_, Type::Never) => false,

(Type::Instance(InstanceType { class }), _) if class.is_known(db, KnownClass::Bool) => {
Type::BooleanLiteral(true).is_subtype_of(db, target)
&& Type::BooleanLiteral(false).is_subtype_of(db, target)
}
(_, Type::Instance(InstanceType { class })) if class.is_known(db, KnownClass::Bool) => {
self.is_subtype_of(db, Type::BooleanLiteral(true))
|| self.is_subtype_of(db, Type::BooleanLiteral(false))
}

(Type::Union(union), _) => union
.elements(db)
.iter()
Expand Down Expand Up @@ -961,7 +970,7 @@ impl<'db> Type<'db> {
KnownClass::Str.to_instance(db).is_subtype_of(db, target)
}
(Type::BooleanLiteral(_), _) => {
KnownClass::Bool.to_instance(db).is_subtype_of(db, target)
KnownClass::Int.to_instance(db).is_subtype_of(db, target)
}
(Type::IntLiteral(_), _) => KnownClass::Int.to_instance(db).is_subtype_of(db, target),
(Type::BytesLiteral(_), _) => {
Expand Down Expand Up @@ -1077,6 +1086,7 @@ impl<'db> Type<'db> {
if self.is_gradual_equivalent_to(db, target) {
return true;
}

match (self, target) {
// Never can be assigned to any type.
(Type::Never, _) => true,
Expand All @@ -1093,6 +1103,15 @@ impl<'db> Type<'db> {
true
}

(Type::Instance(InstanceType { class }), _) if class.is_known(db, KnownClass::Bool) => {
Type::BooleanLiteral(true).is_assignable_to(db, target)
&& Type::BooleanLiteral(false).is_assignable_to(db, target)
}
(_, Type::Instance(InstanceType { class })) if class.is_known(db, KnownClass::Bool) => {
self.is_assignable_to(db, Type::BooleanLiteral(false))
|| self.is_assignable_to(db, Type::BooleanLiteral(true))
}

// A union is assignable to a type T iff every element of the union is assignable to T.
(Type::Union(union), ty) => union
.elements(db)
Expand Down
Loading
Loading