Commit 43b174c
authored
[ty] Infer lambda parameter types with
Improves #22633 to infer the use
of lambda parameters in a lambda body with type context, e.g.,
```py
x: Callable[[str], str] = lambda x: reveal_type(x) # revealed: str
reveal_type(x) # revealed: (x: str) -> str
```
Unlike other definitions, lambda parameter types cannot be determined
purely syntactically in semantic indexing. Instead, they depend on the
inferred type of the lambda to access its parameter types.
Unfortunately, this makes lambda inference cyclic, as the body of the
lambda depends on the outer lambda type, and there is no obvious way of
splitting out inference of the lambda parameter types from its return
type.
To avoid initiating cycles on the entire scope containing the lambda,
this PR introduces a new inference query — statement-level inference.
Statements are a minimal unit of code that encapsulate any internal type
context. This makes them very useful to infer a given sub-expression
"naturally" without having to provide any external type context. There
are other places where we currently rely on scope-level inference for
this purpose (e.g., see `infer_complete_scope_types`, the current
implementation of #23761, and the
discussion in astral-sh/ty#3124). Note that
statement-level inference is not perfectly fine-grained, e.g., the test
expression of an `if` statement does not require external type context
and is independent from its body, so statement-level inference may lead
to unnecessarily large cycles, but having the unit of code being
generalized to an AST structure allows us to avoid the need for such
special cases, but this can always change in the future.
Additionally, many statements are simply wrappers around definitions or
standalone expressions, so we can avoid extra salsa allocations in the
common case.Callable type context (#24317)1 parent 4f449ae commit 43b174c
13 files changed
Lines changed: 1041 additions & 133 deletions
File tree
- crates
- ty_ide/src
- ty_python_core/src
- ty_python_semantic
- resources/mdtest
- diagnostics
- src/types
- ide_support
- infer
- builder
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
43 | 43 | | |
44 | 44 | | |
45 | 45 | | |
46 | | - | |
| 46 | + | |
47 | 47 | | |
48 | 48 | | |
49 | 49 | | |
| |||
314 | 314 | | |
315 | 315 | | |
316 | 316 | | |
317 | | - | |
| 317 | + | |
318 | 318 | | |
319 | 319 | | |
320 | 320 | | |
| |||
342 | 342 | | |
343 | 343 | | |
344 | 344 | | |
345 | | - | |
346 | | - | |
347 | | - | |
348 | | - | |
349 | | - | |
350 | | - | |
| 345 | + | |
351 | 346 | | |
352 | 347 | | |
353 | 348 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
150 | 150 | | |
151 | 151 | | |
152 | 152 | | |
| 153 | + | |
| 154 | + | |
| 155 | + | |
| 156 | + | |
| 157 | + | |
| 158 | + | |
153 | 159 | | |
154 | 160 | | |
155 | 161 | | |
| |||
0 commit comments