From 7c34ed337473a761ac09e02bd262b9170cf8a114 Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Thu, 14 Aug 2025 21:54:14 +0100 Subject: [PATCH] fix panic --- .../resources/mdtest/narrow/type.md | 11 +++++++++++ crates/ty_python_semantic/src/types/generics.rs | 17 +++++++++++------ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/crates/ty_python_semantic/resources/mdtest/narrow/type.md b/crates/ty_python_semantic/resources/mdtest/narrow/type.md index 004d53be3f..98d71497c2 100644 --- a/crates/ty_python_semantic/resources/mdtest/narrow/type.md +++ b/crates/ty_python_semantic/resources/mdtest/narrow/type.md @@ -133,6 +133,17 @@ def _[T](x: A | B): reveal_type(x) # revealed: A[int] | B ``` +## Narrowing for tuple + +An early version of caused us to crash on this: + +```py +def _(val): + if type(val) is tuple: + # TODO: better would be `Unknown & tuple[object, ...]` + reveal_type(val) # revealed: Unknown & tuple[Unknown, ...] +``` + ## Limitations ```py diff --git a/crates/ty_python_semantic/src/types/generics.rs b/crates/ty_python_semantic/src/types/generics.rs index c542cc9763..2fbfef5ddd 100644 --- a/crates/ty_python_semantic/src/types/generics.rs +++ b/crates/ty_python_semantic/src/types/generics.rs @@ -353,12 +353,17 @@ impl<'db> GenericContext<'db> { db: &'db dyn Db, types: Box<[Type<'db>]>, ) -> Specialization<'db> { - assert_eq!(self.variables(db).len(), types.len()); - debug_assert!( - matches!(self.inner(db), GenericContextInner::NonTuple(_)), - "Should never call `GenericContext::specialize` on a tuple context" - ); - Specialization::new(db, self, SpecializationInner::NonTuple(types)) + match self.inner(db) { + GenericContextInner::Tuple { .. } => { + assert_eq!(types.len(), 1); + let tuple = TupleType::homogeneous(db, types[0]); + Specialization::new(db, self, SpecializationInner::Tuple(tuple)) + } + GenericContextInner::NonTuple(variables) => { + assert_eq!(variables.len(), types.len()); + Specialization::new(db, self, SpecializationInner::NonTuple(types)) + } + } } /// Creates a specialization of this generic context for the `tuple` class.