From 0eb36e43453fe207f730f0cd2804cd0ea80e3a8c Mon Sep 17 00:00:00 2001 From: David Peter Date: Wed, 13 Nov 2024 16:01:15 +0100 Subject: [PATCH] [red-knot] Avoid panic for generic type aliases (#14312) ## 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 #14307 ## Test Plan Added new example to the corpus. --- crates/red_knot_python_semantic/src/types/infer.rs | 7 +++---- .../resources/test/corpus/89_type_alias.py | 1 + 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/red_knot_python_semantic/src/types/infer.rs b/crates/red_knot_python_semantic/src/types/infer.rs index 676e520564..b0de7ca5c4 100644 --- a/crates/red_knot_python_semantic/src/types/infer.rs +++ b/crates/red_knot_python_semantic/src/types/infer.rs @@ -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) { diff --git a/crates/red_knot_workspace/resources/test/corpus/89_type_alias.py b/crates/red_knot_workspace/resources/test/corpus/89_type_alias.py index 5bdfc4b05b..3acd9fb91e 100644 --- a/crates/red_knot_workspace/resources/test/corpus/89_type_alias.py +++ b/crates/red_knot_workspace/resources/test/corpus/89_type_alias.py @@ -1 +1,2 @@ type foo = int +type ListOrSet[T] = list[T] | set[T]