@@ -9576,6 +9576,51 @@ impl<'db> Type<'db> {
95769576 tcx: TypeContext<'db>,
95779577 visitor: &ApplyTypeMappingVisitor<'_, 'db>,
95789578 ) -> Type<'db> {
9579+ if let TypeMapping::GeneralizeLocalTypes(scope) = type_mapping {
9580+ let is_local = |definition: Definition<'db>| {
9581+ definition.program_file(db) == scope.program_file(db)
9582+ && semantic_index(db, scope.program_file(db))
9583+ .ancestor_scopes(definition.file_scope(db))
9584+ .any(|(id, _)| id == scope.file_scope_id(db))
9585+ };
9586+
9587+ let class = match self {
9588+ Type::ClassLiteral(class) => Some(class),
9589+ Type::GenericAlias(alias) => Some(alias.origin(db).into()),
9590+ Type::NominalInstance(instance) => Some(instance.class_literal(db, visitor.env)),
9591+ Type::SubclassOf(subclass) => match subclass.subclass_of() {
9592+ SubclassOfInner::Class(class) => Some(class.class_literal(db)),
9593+ _ => None,
9594+ },
9595+ _ => None,
9596+ };
9597+ if class
9598+ .and_then(|class| class.definition(db))
9599+ .is_some_and(is_local)
9600+ {
9601+ // See doc comment for `TypeMapping::GeneralizeLocalTypes`: we might want to
9602+ // create a synthetic protocol that represents the local class, instead of
9603+ // returning `Unknown`.
9604+ return Type::unknown();
9605+ }
9606+
9607+ if let Type::FunctionLiteral(function) = self
9608+ && is_local(function.definition(db))
9609+ {
9610+ // Preserve the signature, but not the identity of a function object.
9611+ return visitor.visit(db, self, type_mapping, || {
9612+ Type::Callable(CallableType::new(
9613+ db,
9614+ function
9615+ .signature_with_inferred_return_type(db)
9616+ .into_owned(),
9617+ function.callable_type_kind(db),
9618+ ))
9619+ .apply_type_mapping_impl(db, type_mapping, tcx, visitor)
9620+ });
9621+ }
9622+ }
9623+
95799624 // If we are binding `typing.Self`, and this type is what we are binding `Self` to, return
95809625 // early. This is not just an optimization, it also prevents us from infinitely expanding
95819626 // the type, if it's something that can contain a `Self` reference.
@@ -9916,6 +9961,7 @@ impl<'db> Type<'db> {
99169961 | TypeMapping::Materialize(_)
99179962 | TypeMapping::ReplaceParameterDefaults
99189963 | TypeMapping::EagerExpansion
9964+ | TypeMapping::GeneralizeLocalTypes(_)
99199965 | TypeMapping::RescopeReturnCallables(_)
99209966 | TypeMapping::Promote(PromotionMode::Off, _)
99219967 | TypeMapping::Promote(
@@ -9938,6 +9984,7 @@ impl<'db> Type<'db> {
99389984 | TypeMapping::Promote(..)
99399985 | TypeMapping::ReplaceParameterDefaults
99409986 | TypeMapping::EagerExpansion
9987+ | TypeMapping::GeneralizeLocalTypes(_)
99419988 | TypeMapping::RescopeReturnCallables(_) => self,
99429989 TypeMapping::Materialize(materialization_kind) => match materialization_kind {
99439990 MaterializationKind::Top => Type::object(),
@@ -11309,6 +11356,29 @@ pub enum TypeMapping<'a, 'db> {
1130911356
1131011357 /// Updates any `Callable` types in a function signature return type to be generic if possible.
1131111358 RescopeReturnCallables(&'a FxHashMap<CallableType<'db>, CallableType<'db>>),
11359+
11360+ /// This type mapping is used in return type inference. It "promotes" certain types to supertypes
11361+ /// or to dynamic types in order to prevent nested definitions from leaking into the inferred
11362+ /// return type.
11363+ ///
11364+ /// For example, consider this unannotated decorator:
11365+ /// ```python
11366+ /// def register(event: str):
11367+ /// def wrapper(func):
11368+ /// # ...
11369+ /// return func
11370+ ///
11371+ /// return wrapper
11372+ /// ```
11373+ ///
11374+ /// We do not want to infer `def wrapper(func) -> Unknown` as the return type of `register`. This would
11375+ /// not just expose internal details, it would also incorrectly suggest that each call to `register`
11376+ /// returns the same function object. Instead, we generalize to an anonymous `(func) -> Unknown` callable.
11377+ ///
11378+ /// For nested classes, we cannot easily do the same, so we return `Unknown` instead. In the future, to
11379+ /// improve this, we might want to synthesize a protocol that has the same attributes and methods as the
11380+ /// nested class.
11381+ GeneralizeLocalTypes(ScopeId<'db>),
1131211382}
1131311383
1131411384impl<'db> TypeMapping<'_, 'db> {
@@ -11372,6 +11442,7 @@ impl<'db> TypeMapping<'_, 'db> {
1137211442 | TypeMapping::Materialize(_)
1137311443 | TypeMapping::ReplaceParameterDefaults
1137411444 | TypeMapping::EagerExpansion
11445+ | TypeMapping::GeneralizeLocalTypes(_)
1137511446 | TypeMapping::RescopeReturnCallables(_) => Some(context),
1137611447 TypeMapping::BindSelf(binding) => {
1137711448 if binding.binding_context().is_some() {
@@ -11424,6 +11495,7 @@ impl<'db> TypeMapping<'_, 'db> {
1142411495 | TypeMapping::ReplaceSelf { .. }
1142511496 | TypeMapping::ReplaceParameterDefaults
1142611497 | TypeMapping::EagerExpansion
11498+ | TypeMapping::GeneralizeLocalTypes(_)
1142711499 | TypeMapping::RescopeReturnCallables(_) => self.clone(),
1142811500 }
1142911501 }
0 commit comments