From 564a8dc6b2aeb50849d03be42b4aba92e99dc8fd Mon Sep 17 00:00:00 2001 From: Douglas Creager Date: Tue, 2 Dec 2025 17:22:39 -0500 Subject: [PATCH] update the generic context too --- .../ty_python_semantic/src/types/function.rs | 2 +- .../src/types/signatures.rs | 26 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/ty_python_semantic/src/types/function.rs b/crates/ty_python_semantic/src/types/function.rs index 4eea97948f..a10eeffdd3 100644 --- a/crates/ty_python_semantic/src/types/function.rs +++ b/crates/ty_python_semantic/src/types/function.rs @@ -509,7 +509,7 @@ impl<'db> OverloadLiteral<'db> { ); let generic_context = raw_signature.generic_context; - raw_signature.add_implicit_self_annotation(|| { + raw_signature.add_implicit_self_annotation(db, || { if self.is_staticmethod(db) || self.is_classmethod(db) { return None; } diff --git a/crates/ty_python_semantic/src/types/signatures.rs b/crates/ty_python_semantic/src/types/signatures.rs index 5cbc174dcb..520cdc9e10 100644 --- a/crates/ty_python_semantic/src/types/signatures.rs +++ b/crates/ty_python_semantic/src/types/signatures.rs @@ -690,6 +690,7 @@ impl<'db> Signature<'db> { /// annotation. pub(crate) fn add_implicit_self_annotation( &mut self, + db: &'db dyn Db, self_type: impl FnOnce() -> Option>, ) { if let Some(first_parameter) = self.parameters.value.first_mut() @@ -699,6 +700,31 @@ impl<'db> Signature<'db> { { first_parameter.annotated_type = Some(self_type); first_parameter.inferred_annotation = true; + + // If we've added an implicit `self` annotation, we might need to update the + // signature's generic context, too. (The generic context should include any synthetic + // typevars created for `typing.Self`, even if the `typing.Self` annotation was added + // implicitly.) + if let Type::TypeVar(self_typevar) = self_type { + match self.generic_context.as_mut() { + Some(generic_context) + if generic_context + .binds_typevar(db, self_typevar.typevar(db)) + .is_some() => {} + Some(generic_context) => { + *generic_context = GenericContext::from_typevar_instances( + db, + std::iter::once(self_typevar).chain(generic_context.variables(db)), + ); + } + None => { + self.generic_context = Some(GenericContext::from_typevar_instances( + db, + std::iter::once(self_typevar), + )); + } + } + } } }