Skip to content

Commit

Permalink
[red-knot] Avoid panic for generic type aliases (astral-sh#14312)
Browse files Browse the repository at this point in the history
## Summary

This avoids a panic inside `TypeInferenceBuilder::infer_type_parameters`
when encountering generic type aliases:
```py
type ListOrSet[T] = list[T] | set[T]
```

To fix this properly, we would have to treat type aliases as being their own
annotation scope [1]. The left hand side is a definition for the type parameter
`T` which is being used in the special annotation scope on the right hand side.
Similar to how it works for generic functions and classes.

[1] https://docs.python.org/3/reference/compound_stmts.html#generic-type-aliases


closes astral-sh#14307

## Test Plan

Added new example to the corpus.
  • Loading branch information
sharkdp authored Nov 13, 2024
1 parent 5fcf0af commit 0eb36e4
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 4 deletions.
7 changes: 3 additions & 4 deletions crates/red_knot_python_semantic/src/types/infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1796,14 +1796,13 @@ impl<'db> TypeInferenceBuilder<'db> {
let ast::StmtTypeAlias {
range: _,
name,
type_params,
type_params: _,
value,
} = type_alias_statement;
self.infer_expression(value);
self.infer_expression(name);
if let Some(type_params) = type_params {
self.infer_type_parameters(type_params);
}

// TODO: properly handle generic type aliases, which need their own annotation scope
}

fn infer_for_statement(&mut self, for_statement: &ast::StmtFor) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
type foo = int
type ListOrSet[T] = list[T] | set[T]

0 comments on commit 0eb36e4

Please sign in to comment.