-
Notifications
You must be signed in to change notification settings - Fork 1.6k
[ty] bidirectional type inference using function return type annotations #20528
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
Merged
Merged
Changes from all commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
5844c01
[ty] propagate the annotated return type of functions to the inferenc…
mtshiba c6f798c
don't wrap the raw return types of async functions in `CoroutineType`
mtshiba d14dcc8
improve `SpecializationBuilder::infer` behavior when `formal` is a un…
mtshiba 238ebf5
Merge branch 'main' into bidi-return-type
mtshiba 69e8582
Merge branch 'main' into bidi-return-type
mtshiba d33ee55
fix `nearest_enclosing_function` returning incorrect types for decora…
mtshiba 9622841
Update bidirectional.md
mtshiba ef75f0a
prevent incorrect specializations in `SpecializationBuilder::infer`
mtshiba 6c5625b
Update crates/ty_python_semantic/src/types/infer/builder.rs
mtshiba 1565280
Update crates/ty_python_semantic/resources/mdtest/bidirectional.md
mtshiba 7e8595a
Update crates/ty_python_semantic/resources/mdtest/bidirectional.md
mtshiba d666494
refactor according to the review
mtshiba 40daa3f
Update bidirectional.md
mtshiba 32bd211
Merge branch 'main' into bidi-return-type
mtshiba b0a62f1
Update signatures.rs
mtshiba 4211ac9
Update bidirectional.md
mtshiba 2212cc7
Update bidirectional.md
mtshiba f99d03f
Merge branch 'main' into bidi-return-type
mtshiba 819a415
Update generics.rs
mtshiba 1b6a505
Apply suggestion from @ibraheemdev
mtshiba b27c1ed
Apply suggestions from code review
mtshiba 0249ba2
improve bidirectional inference in `infer_collection_literal`
mtshiba 9507d72
don't set `generic_context` on the `Signature` returned by `OverloadL…
mtshiba bd5a465
Revert "don't set `generic_context` on the `Signature` returned by `O…
mtshiba 8834fec
Update function.rs
mtshiba d1e9455
improve specialization between unions
mtshiba b5fddbc
Revert "improve specialization between unions"
mtshiba 1b42e05
Merge branch 'main' into bidi-return-type
mtshiba 97c065d
add `TypeDict` test cases
mtshiba 7898360
Merge branch 'main' into bidi-return-type
mtshiba 9cea903
update mdtest
mtshiba db90cda
Merge branch 'main' into bidi-return-type
ibraheemdev e7b5c14
update tests
ibraheemdev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
147 changes: 147 additions & 0 deletions
147
crates/ty_python_semantic/resources/mdtest/bidirectional.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,147 @@ | ||
# Bidirectional type inference | ||
|
||
ty partially supports bidirectional type inference. This is a mechanism for inferring the type of an | ||
expression "from the outside in". Normally, type inference proceeds "from the inside out". That is, | ||
in order to infer the type of an expression, the types of all sub-expressions must first be | ||
inferred. There is no reverse dependency. However, when performing complex type inference, such as | ||
when generics are involved, the type of an outer expression can sometimes be useful in inferring | ||
inner expressions. Bidirectional type inference is a mechanism that propagates such "expected types" | ||
to the inference of inner expressions. | ||
|
||
## Propagating target type annotation | ||
|
||
```toml | ||
[environment] | ||
python-version = "3.12" | ||
``` | ||
|
||
```py | ||
def list1[T](x: T) -> list[T]: | ||
return [x] | ||
|
||
l1 = list1(1) | ||
reveal_type(l1) # revealed: list[Literal[1]] | ||
l2: list[int] = list1(1) | ||
reveal_type(l2) # revealed: list[int] | ||
|
||
# `list[Literal[1]]` and `list[int]` are incompatible, since `list[T]` is invariant in `T`. | ||
# error: [invalid-assignment] "Object of type `list[Literal[1]]` is not assignable to `list[int]`" | ||
l2 = l1 | ||
|
||
intermediate = list1(1) | ||
# TODO: the error will not occur if we can infer the type of `intermediate` to be `list[int]` | ||
# error: [invalid-assignment] "Object of type `list[Literal[1]]` is not assignable to `list[int]`" | ||
l3: list[int] = intermediate | ||
# TODO: it would be nice if this were `list[int]` | ||
reveal_type(intermediate) # revealed: list[Literal[1]] | ||
reveal_type(l3) # revealed: list[int] | ||
|
||
l4: list[int | str] | None = list1(1) | ||
reveal_type(l4) # revealed: list[int | str] | ||
|
||
def _(l: list[int] | None = None): | ||
l1 = l or list() | ||
reveal_type(l1) # revealed: (list[int] & ~AlwaysFalsy) | list[Unknown] | ||
|
||
l2: list[int] = l or list() | ||
# it would be better if this were `list[int]`? (https://github.com/astral-sh/ty/issues/136) | ||
reveal_type(l2) # revealed: (list[int] & ~AlwaysFalsy) | list[Unknown] | ||
|
||
def f[T](x: T, cond: bool) -> T | list[T]: | ||
return x if cond else [x] | ||
|
||
# TODO: no error | ||
# error: [invalid-assignment] "Object of type `Literal[1] | list[Literal[1]]` is not assignable to `int | list[int]`" | ||
l5: int | list[int] = f(1, True) | ||
``` | ||
|
||
`typed_dict.py`: | ||
|
||
```py | ||
mtshiba marked this conversation as resolved.
Show resolved
Hide resolved
|
||
from typing import TypedDict | ||
|
||
class TD(TypedDict): | ||
x: int | ||
|
||
d1 = {"x": 1} | ||
d2: TD = {"x": 1} | ||
d3: dict[str, int] = {"x": 1} | ||
|
||
reveal_type(d1) # revealed: dict[Unknown | str, Unknown | int] | ||
reveal_type(d2) # revealed: TD | ||
reveal_type(d3) # revealed: dict[str, int] | ||
|
||
def _() -> TD: | ||
return {"x": 1} | ||
|
||
def _() -> TD: | ||
# error: [missing-typed-dict-key] "Missing required key 'x' in TypedDict `TD` constructor" | ||
return {} | ||
``` | ||
|
||
## Propagating return type annotation | ||
|
||
```toml | ||
[environment] | ||
python-version = "3.12" | ||
``` | ||
|
||
```py | ||
from typing import overload, Callable | ||
|
||
def list1[T](x: T) -> list[T]: | ||
return [x] | ||
|
||
def get_data() -> dict | None: | ||
return {} | ||
|
||
def wrap_data() -> list[dict]: | ||
if not (res := get_data()): | ||
return list1({}) | ||
reveal_type(list1(res)) # revealed: list[dict[Unknown, Unknown] & ~AlwaysFalsy] | ||
# `list[dict[Unknown, Unknown] & ~AlwaysFalsy]` and `list[dict[Unknown, Unknown]]` are incompatible, | ||
# but the return type check passes here because the type of `list1(res)` is inferred | ||
# by bidirectional type inference using the annotated return type, and the type of `res` is not used. | ||
return list1(res) | ||
|
||
def wrap_data2() -> list[dict] | None: | ||
if not (res := get_data()): | ||
return None | ||
reveal_type(list1(res)) # revealed: list[dict[Unknown, Unknown] & ~AlwaysFalsy] | ||
return list1(res) | ||
|
||
def deco[T](func: Callable[[], T]) -> Callable[[], T]: | ||
return func | ||
|
||
def outer() -> Callable[[], list[dict]]: | ||
@deco | ||
def inner() -> list[dict]: | ||
if not (res := get_data()): | ||
return list1({}) | ||
reveal_type(list1(res)) # revealed: list[dict[Unknown, Unknown] & ~AlwaysFalsy] | ||
return list1(res) | ||
return inner | ||
|
||
@overload | ||
def f(x: int) -> list[int]: ... | ||
@overload | ||
def f(x: str) -> list[str]: ... | ||
def f(x: int | str) -> list[int] | list[str]: | ||
# `list[int] | list[str]` is disjoint from `list[int | str]`. | ||
if isinstance(x, int): | ||
return list1(x) | ||
else: | ||
return list1(x) | ||
|
||
reveal_type(f(1)) # revealed: list[int] | ||
reveal_type(f("a")) # revealed: list[str] | ||
|
||
async def g() -> list[int | str]: | ||
return list1(1) | ||
|
||
def h[T](x: T, cond: bool) -> T | list[T]: | ||
return i(x, cond) | ||
|
||
def i[T](x: T, cond: bool) -> T | list[T]: | ||
return x if cond else [x] | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.