diff --git a/pyrefly/lib/alt/class/class_metadata.rs b/pyrefly/lib/alt/class/class_metadata.rs index 69008550d8..af4005dc88 100644 --- a/pyrefly/lib/alt/class/class_metadata.rs +++ b/pyrefly/lib/alt/class/class_metadata.rs @@ -14,6 +14,7 @@ use pyrefly_graph::index::Idx; use pyrefly_python::ast::Ast; use pyrefly_python::dunder; use pyrefly_python::short_identifier::ShortIdentifier; +use pyrefly_python::sys_info::PythonVersion; use pyrefly_types::annotation::Annotation; use pyrefly_types::callable::Params; use pyrefly_types::known_class::KnownClass; @@ -93,6 +94,52 @@ use crate::types::literal::Lit; use crate::types::types::CalleeKind; use crate::types::types::Type; +const RUNTIME_EXCLUDED_ATTRIBUTES: &[&str] = &[ + "_is_protocol", + "_is_runtime_protocol", + "__abstractmethods__", + "__annotations__", + "__dict__", + "__doc__", + "__init__", + "__module__", + "__new__", + "__orig_bases__", + "__orig_class__", + "__parameters__", + "__slots__", + "__subclasshook__", + "__weakref__", +]; + +fn is_excluded_runtime_attribute(name: &Name, version: PythonVersion) -> bool { + let name = name.as_str(); + if RUNTIME_EXCLUDED_ATTRIBUTES.contains(&name) { + return true; + } + // Ignore internal `_abc_*` attributes injected into class dictionaries by `ABCMeta`. + if name.starts_with("_abc_") { + return true; + } + match name { + // Users assign `= classmethod(types.GenericAlias)` for PEP 585-style generic + // subscription, or `= None` to disable it. + "__class_getitem__" => version.at_least(3, 9), + + // CPython 3.13 stops treating a declared `__match_args__` as a runtime protocol + // member (gh-110682). + "__match_args__" => version.at_least(3, 13), + + // PEP 749 exposes `__annotate__` as a public attribute of types and functions, + // making it part of the typing surface. + "__annotate__" => version.at_least(3, 14), + + // Falling through here means either there is no realistic use case or the name + // should not be excluded. If you insist it should be, please open an issue. + _ => false, + } +} + #[derive(Debug, Clone)] struct ParsedBaseClass<'a> { class_object: Class, @@ -209,7 +256,6 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { }); // Compute data that depends on the `BaseClass` representation of base classes. - let initial_protocol_metadata = self.initial_protocol_metadata(cls, bases); let has_generic_base_class = bases.iter().any(|x| x.is_generic()); let has_typed_dict_base_class = bases.iter().any(|x| x.is_typed_dict()); @@ -220,12 +266,6 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { .map(|x| self.parse_base_class(x, is_new_type)) .collect::>(); let contains_base_class_any = parsed_results.iter().any(|x| x.is_any()); - let protocol_metadata = self.final_protocol_metadata( - initial_protocol_metadata, - &decorators, - &parsed_results, - errors, - ); let protocol_base_name = Name::new_static("Protocol"); let base_metaclasses = bases @@ -307,6 +347,16 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { } } let metaclass = calculated_metaclass.as_ref().map(|m| m.get()); + + let explicit_slots = self.explicit_slots(cls, metaclass, errors); + let initial_protocol_metadata = self.initial_protocol_metadata(cls, bases, &explicit_slots); + let protocol_metadata = self.final_protocol_metadata( + initial_protocol_metadata, + &decorators, + &parsed_results, + errors, + ); + // Compute base classes with metadata. let bases_with_metadata = self.bases_with_metadata(parsed_results, is_new_type, errors); self.check_init_subclass_keywords( @@ -465,7 +515,6 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { .iter() .find_map(|(decorator, _)| decorator.deprecation.clone()); - let explicit_slots = self.explicit_slots(cls, metaclass, errors); let has_nonempty_explicit_slots = explicit_slots .slots_info() .is_some_and(|slots| !slots.names.is_empty()); @@ -808,6 +857,7 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { &self, cls: &Class, bases: &[BaseClass], + explicit_slots: &ExplicitSlots, ) -> Option { if bases.iter().any(|x| { matches!( @@ -818,11 +868,33 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { }) ) }) { + // CPython excludes the literal `__slots__` but exposes non-excluded slot + // names as runtime attributes. An unresolvable declaration cannot prove + // data slots, so no error is reported for it. + let version = self.bindings().sys_info().version(); + let mut members = SmallSet::new(); + let mut runtime_members: SmallSet = explicit_slots + .slots_info() + .map(|slots| { + slots + .names + .iter() + .filter(|name| !is_excluded_runtime_attribute(name, version)) + .cloned() + .collect() + }) + .unwrap_or_default(); + if let Some(fields) = self.get_class_fields(cls) { + for name in fields.class_body_fields() { + members.insert(name.clone()); + if !is_excluded_runtime_attribute(name, version) { + runtime_members.insert(name.clone()); + } + } + } Some(ProtocolMetadata { - members: self - .get_class_fields(cls) - .map(|f| f.class_body_fields().cloned().collect()) - .unwrap_or_default(), + members, + runtime_members, is_runtime_checkable: false, }) } else { @@ -848,6 +920,9 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { { if let Some(base_proto) = metadata.protocol_metadata() { proto.members.extend(base_proto.members.iter().cloned()); + proto + .runtime_members + .extend(base_proto.runtime_members.iter().cloned()); if base_proto.is_runtime_checkable { proto.is_runtime_checkable = true; } diff --git a/pyrefly/lib/alt/special_calls.rs b/pyrefly/lib/alt/special_calls.rs index 18eeda2218..87185a957c 100644 --- a/pyrefly/lib/alt/special_calls.rs +++ b/pyrefly/lib/alt/special_calls.rs @@ -11,6 +11,8 @@ * file contains the implementations of a few special calls that need to be hard-coded. */ +use std::iter; + use pyrefly_python::dunder; use pyrefly_types::display::TypeDisplayContext; use pyrefly_types::known_class::KnownClass; @@ -683,38 +685,49 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { } // Check for unsafe overlap: // https://typing.python.org/en/latest/spec/protocol.html#runtime-checkable-decorator-and-narrowing-types-by-isinstance - // We need to check if there is any field with unassignable types, since the `isinstance` check only - // checks for the presence of the fields, not their types. + // Presence decides whether an overlap is reported, but every static + // member is type-checked, including runtime-excluded ones the + // implementation does not provide. // // Type arguments for the protocol are not provided, so we'll use - // fresh vars and solve them during the `is_subset_eq` check below. + // fresh vars and solve them during the member checks below. let class_info_protocol = class_info_metadata.protocol_metadata().unwrap(); if let Some(object_type) = &object_or_class && !object_type.is_never() && let (vs, Type::ClassType(protocol_class_type)) = self.instantiate_fresh_class(class_info_cls) { - let mut all_members_present = true; + let all_runtime_members_present = class_info_protocol + .runtime_members + .iter() + .all(|field_name| self.has_attr(object_type, field_name)); let mut unsafe_overlap_errors = vec![]; - for field_name in &class_info_protocol.members { - if !self.has_attr(object_type, field_name) { - all_members_present = false; - break; - } - if let Err(subset_err) = self.is_protocol_subset_at_attr( - object_type, - &protocol_class_type, - field_name, - &mut |x, y| self.is_subset_eq_with_reason(x, y), - ) { - let error_msg = subset_err - .to_error_msg(self) - .map(|msg| format!(": {msg}")) - .unwrap_or_default(); - unsafe_overlap_errors.push(format!( - "Attribute `{}` has incompatible types{}", - field_name, error_msg, - )); + if all_runtime_members_present { + for field_name in &class_info_protocol.members { + // Protocol machinery, not instance members; `subset.rs`'s + // `is_subset_protocol_inner` skips the same four names. + if field_name == &dunder::INIT + || field_name == &dunder::NEW + || field_name == &dunder::SLOTS + || field_name == &dunder::CLASS_GETITEM + { + continue; + } + if let Err(subset_err) = self.is_protocol_subset_at_attr( + object_type, + &protocol_class_type, + field_name, + &mut |x, y| self.is_subset_eq_with_reason(x, y), + ) { + let error_msg = subset_err + .to_error_msg(self) + .map(|msg| format!(": {msg}")) + .unwrap_or_default(); + unsafe_overlap_errors.push(format!( + "Attribute `{}` has incompatible types{}", + field_name, error_msg, + )); + } } } if let Err(specialization_errors) = self.finish_quantified(vs, false) { @@ -722,7 +735,7 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { unsafe_overlap_errors.push(e.to_error_msg(self)) } } - if all_members_present && !unsafe_overlap_errors.is_empty() { + if all_runtime_members_present && !unsafe_overlap_errors.is_empty() { errors.error_builder( range, ErrorKind::UnsafeOverlap, @@ -791,29 +804,58 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { } /// Check if a protocol is a data protocol (has non-method members) + /// + /// Mirrors CPython's runtime check `callable(getattr(cls, name))`: + /// - `property` objects and `__slots__` descriptors are never callable (data members). + /// - Other members fall back to checking if their declared read type is callable. fn is_data_protocol(&self, cls: &Class, range: TextRange) -> bool { - // A data protocol has at least one non-method member - // Use protocol metadata to get the member names - let metadata = self.get_metadata_for_class(cls); - if let Some(protocol_metadata) = metadata.protocol_metadata() { - for field_name in &protocol_metadata.members { - // Use the class type to access the field - let class_type = self.as_class_type_unchecked(cls); - let ty = self.type_of_attr_get( - &self.heap.mk_class_type(class_type), - field_name, - range, - &self.error_swallower(), - ErrorKind::MissingAttribute, - None, - "is_data_protocol", - ); - - // If it's not a callable type, it's a data member - if !ty.is_toplevel_callable() { + let Some(protocol_metadata) = self.get_metadata_for_class(cls).protocol_metadata() else { + return false; + }; + let class_type = self.heap.mk_class_type(self.as_class_type_unchecked(cls)); + // Skips `Protocol`, `Generic`, and `object`, matching CPython. + let ancestors = self.get_mro_for_class(cls).ancestors_no_object(); + for field_name in &protocol_metadata.runtime_members { + for ancestor in + iter::once(cls).chain(ancestors.iter().map(|ancestor| ancestor.class_object())) + { + if self.get_class_fields(ancestor).is_some_and(|fields| { + fields.class_body_fields().any(|name| name == field_name) + && fields.is_field_initialized_on_class(field_name) + }) { + // `property`s cannot be `callable` -> data member + if self + .get_field_from_current_class_only(ancestor, field_name) + .is_some_and(|field| field.is_property()) + { + return true; + } + // Otherwise the declared read type decides. + break; + } + if self + .get_metadata_for_class(ancestor) + .slots_info() + .is_some_and(|slots| slots.names.contains(field_name)) + { + // Slot descriptors cannot be `callable` -> data member return true; } } + let ty = self.type_of_attr_get( + &class_type, + field_name, + range, + &self.error_swallower(), + ErrorKind::MissingAttribute, + None, + "is_data_protocol", + ); + + // If it's not a callable type, it's a data member + if !ty.is_toplevel_callable() { + return true; + } } false } diff --git a/pyrefly/lib/alt/types/class_metadata.rs b/pyrefly/lib/alt/types/class_metadata.rs index d1306ee906..4405aef6e7 100644 --- a/pyrefly/lib/alt/types/class_metadata.rs +++ b/pyrefly/lib/alt/types/class_metadata.rs @@ -770,8 +770,10 @@ impl VisitTrait for DjangoReverseRelationIndex { #[derive(Clone, Debug, TypeEq, PartialEq, Eq)] pub struct ProtocolMetadata { - /// All members of the protocol, excluding ones defined on `object` and not overridden in a subclass. + /// All static members of the protocol, excluding ones defined on `object` and not overridden in a subclass. pub members: SmallSet, + /// Attribute names CPython inspects when it checks this protocol at runtime. + pub runtime_members: SmallSet, /// Whether this protocol is decorated with @runtime_checkable pub is_runtime_checkable: bool, } diff --git a/pyrefly/lib/test/protocol.rs b/pyrefly/lib/test/protocol.rs index 852fe047ac..2c9c81d565 100644 --- a/pyrefly/lib/test/protocol.rs +++ b/pyrefly/lib/test/protocol.rs @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +use pyrefly_python::sys_info::PythonVersion; + use crate::test::util::TestEnv; use crate::testcase; @@ -1529,6 +1531,554 @@ issubclass(Implementation, DataOnlyProtocol) # E: Protocol `DataOnlyProtocol` "#, ); +testcase!( + test_issubclass_with_empty_slots, + r#" +from collections.abc import Buffer +from typing import SupportsInt, runtime_checkable, Protocol + +# >>> stdlib + +issubclass(int, SupportsInt) +issubclass(bytes, Buffer) + +# >>> user-defined + +@runtime_checkable +class MyBufferProtocol(Protocol): + __slots__ = () + + def __buffer__(self, flags: int, /) -> memoryview: ... + +class MyBufferImpl: + def __buffer__(self, flags: int, /) -> memoryview: ... + +issubclass(MyBufferImpl, MyBufferProtocol) +"#, +); + +testcase!( + test_issubclass_with_annotated_slots, + r#" +from typing import runtime_checkable, Protocol + +@runtime_checkable +class MyBufferProtocol(Protocol): + __slots__: tuple[str, ...] + + def __buffer__(self, flags: int, /) -> memoryview: ... + +class MyBufferImpl: + def __buffer__(self, flags: int, /) -> memoryview: ... + +issubclass(MyBufferImpl, MyBufferProtocol) +"#, +); + +testcase!( + test_issubclass_with_generic_and_empty_slots, + TestEnv::new_with_version(PythonVersion::new(3, 12, 0)), + r#" +from typing import Protocol, runtime_checkable + +@runtime_checkable +class P[T](Protocol): + __slots__ = () + def m(self, value: T) -> T: ... + +class Impl: + def m(self, value: int) -> int: ... + +issubclass(Impl, P) +"#, +); + +testcase!( + test_isinstance_raise_unsafe_overlap_by_wrong_typing_with_empty_slots, + r#" +from collections.abc import Buffer + +class WrongBufferImpl: + def __buffer__(self, flags: int, /) -> bytes: ... + +isinstance(WrongBufferImpl(), Buffer) # E: Runtime checkable protocol `Buffer` has an unsafe overlap with type `WrongBufferImpl` +"#, +); + +testcase!( + test_issubclass_raise_non_method_members_by_static_typed_member_with_empty_slots, + r#" +from typing import Protocol, runtime_checkable + +@runtime_checkable +class MyDataProtocol(Protocol): + __slots__ = () + name: str + +issubclass(bytes, MyDataProtocol) # E: Protocol `MyDataProtocol` has non-method members and cannot be used with issubclass() +"#, +); + +testcase!( + test_issubclass_raise_non_method_members_by_non_empty_slots, + r#" +from typing import Protocol, runtime_checkable + +@runtime_checkable +class MyDataProtocolStr(Protocol): + __slots__ = "name" + +@runtime_checkable +class MyDataProtocolTuple(Protocol): + __slots__ = ("name",) + +@runtime_checkable +class MyDataProtocolDict(Protocol): + __slots__ = {"name": "doc"} + + +issubclass(bytes, MyDataProtocolStr) # E: Protocol `MyDataProtocolStr` has non-method members and cannot be used with issubclass() +issubclass(bytes, MyDataProtocolTuple) # E: Protocol `MyDataProtocolTuple` has non-method members and cannot be used with issubclass() +issubclass(bytes, MyDataProtocolDict) # E: Protocol `MyDataProtocolDict` has non-method members and cannot be used with issubclass() +"#, +); + +testcase!( + bug = "Unresolved `__slots__` cannot be simply treated as non-data or data", + test_issubclass_with_unresolved_slots, + r#" +from typing import Protocol, runtime_checkable + +def get_slots() -> tuple[str, ...]: + return ("name",) + +SLOTS: tuple[str, ...] = ("name",) + +@runtime_checkable +class UnknownSlots(Protocol): + __slots__ = get_slots() + + def m(self) -> None: ... + +@runtime_checkable +class ConstantSlots(Protocol): + __slots__ = SLOTS + + def m(self) -> None: ... + +class Impl: + def m(self) -> None: ... + +issubclass(Impl, UnknownSlots) +issubclass(Impl, ConstantSlots) +"#, +); + +testcase!( + test_issubclass_runtime_excluded_attributes, + r#" +# `typing.EXCLUDED_ATTRIBUTES` names are excluded from runtime protocol members even when the +# protocol declares them explicitly. + +from typing import Any, Protocol, runtime_checkable + +@runtime_checkable +class ProtocolWithDunders(Protocol): + __doc__: str | None + __module__: str + __annotations__: dict[str, Any] + __match_args__: tuple[str, ...] + + def m(self) -> None: ... + + +@runtime_checkable +class DictSlot(Protocol): + __slots__ = ("__dict__",) + def m(self) -> None: ... + + +class Impl: + def m(self) -> None: ... + + +# Runtime-excluded names remain static protocol members. The runtime check ignores +# them, but an implementation that lacks them is still an unsafe overlap. +issubclass(Impl, ProtocolWithDunders) # E: Runtime checkable protocol `ProtocolWithDunders` has an unsafe overlap with type `Impl` + +# `__dict__` is runtime-excluded and has no static member declaration, so there +# is nothing to compare and no unsafe overlap is reported. +issubclass(Impl, DictSlot) +"#, +); + +testcase!( + test_issubclass_skips_abc_marker_at_runtime, + r#" +# CPython skips `_abc_*` when collecting runtime protocol members. + +from typing import Protocol, runtime_checkable + +@runtime_checkable +class Annotated(Protocol): + _abc_marker: int + def m(self) -> None: ... + +@runtime_checkable +class SlotNamed(Protocol): + __slots__ = ("_abc_marker",) + def m(self) -> None: ... + +class Impl: + def m(self) -> None: ... + +issubclass(Impl, Annotated) # E: Runtime checkable protocol `Annotated` has an unsafe overlap with type `Impl` +issubclass(Impl, SlotNamed) +"#, +); + +testcase!( + test_isinstance_raise_unsafe_overlap_by_wrong_typing_with_abc_marker, + r#" +from typing import Protocol, runtime_checkable + +@runtime_checkable +class P(Protocol): + _abc_marker: int + def m(self) -> None: ... + +class AnnotatedWrong: + _abc_marker: str + def m(self) -> None: ... + +class AssignedWrong: + _abc_marker = "wrong" + def m(self) -> None: ... + +class Missing: + def m(self) -> None: ... + +isinstance(AnnotatedWrong(), P) # E: Runtime checkable protocol `P` has an unsafe overlap with type `AnnotatedWrong` +isinstance(AssignedWrong(), P) # E: Runtime checkable protocol `P` has an unsafe overlap with type `AssignedWrong` +isinstance(Missing(), P) # E: Runtime checkable protocol `P` has an unsafe overlap with type `Missing` +"#, +); + +testcase!( + test_issubclass_with_child_slots_shadowing_inherited_method, + r#" +# A slot in the child shadows an inherited method at runtime. + +from typing import Protocol, runtime_checkable + +@runtime_checkable +class Base(Protocol): + def value(self) -> None: ... + +@runtime_checkable +class Child(Base, Protocol): + __slots__ = ("value",) + +class Impl: + def value(self) -> None: ... + +issubclass(Impl, Child) # E: Protocol `Child` has non-method members and cannot be used with issubclass() +"#, +); + +testcase!( + test_issubclass_with_child_method_shadowing_inherited_slots, + r#" +# A method in the child shadows an inherited slot at runtime. + +from typing import Protocol, runtime_checkable + +@runtime_checkable +class SlotBase(Protocol): + __slots__ = ("value",) + +@runtime_checkable +class MethodChild(SlotBase, Protocol): + def value(self) -> None: ... + +class Impl: + def value(self) -> None: ... + +issubclass(Impl, MethodChild) +"#, +); + +testcase!( + test_issubclass_with_annotation_never_shadowing_slots, + r#" +# An annotation-only declaration does not create a class attribute, so `getattr` +# still finds the inherited slot descriptor at runtime. + +from typing import Callable, Protocol, runtime_checkable + +@runtime_checkable +class SlotBase(Protocol): + __slots__ = ("value",) + +@runtime_checkable +class AnnotatedChild(SlotBase, Protocol): + value: Callable[[], None] + +class Impl: + def value(self) -> None: ... + +issubclass(Impl, AnnotatedChild) # E: Protocol `AnnotatedChild` has non-method members and cannot be used with issubclass() +"#, +); + +testcase!( + test_issubclass_with_shadowing_by_mro, + r#" +from typing import Protocol, runtime_checkable + +@runtime_checkable +class SlotBase(Protocol): + __slots__ = ("value",) + +@runtime_checkable +class MethodBase(Protocol): + def value(self) -> None: ... + +class MethodFirst(MethodBase, SlotBase, Protocol): ... + +class SlotFirst(SlotBase, MethodBase, Protocol): ... + +class Impl: + def value(self) -> None: ... + +issubclass(Impl, MethodFirst) +issubclass(Impl, SlotFirst) # E: Protocol `SlotFirst` has non-method members and cannot be used with issubclass() +"#, +); + +testcase!( + test_issubclass_property_member_is_data_member, + r#" +from typing import Callable, Protocol, runtime_checkable + +@runtime_checkable +class P(Protocol): + @property + def value(self) -> Callable[[], None]: ... + +class Impl: + def value(self) -> None: ... + +issubclass(Impl, P) # E: Protocol `P` has non-method members and cannot be used with issubclass() +"#, +); + +testcase!( + test_issubclass_decorated_method_is_non_data_member, + r#" +from typing import Protocol, runtime_checkable + +@runtime_checkable +class ClassMethodChild(Protocol): + @classmethod + def value(cls) -> None: ... + +@runtime_checkable +class StaticMethodChild(Protocol): + @staticmethod + def value() -> None: ... + +class Impl: + def value(self) -> None: ... + +issubclass(Impl, ClassMethodChild) +issubclass(Impl, StaticMethodChild) +"#, +); + +testcase!( + bug = "CPython rejects an annotation-only member as callable at runtime", + test_issubclass_callable_annotation_member_considered_as_non_data_member, + r#" +from typing import Callable, Protocol, runtime_checkable + +@runtime_checkable +class P(Protocol): + __slots__ = () + f: Callable[[], None] + def m(self) -> None: ... + +class Impl: + def f(self) -> None: ... + def m(self) -> None: ... + +issubclass(Impl, P) +"#, +); + +testcase!( + test_issubclass_with_match_args_3_12, + TestEnv::new_with_version(PythonVersion::new(3, 12, 0)), + r#" +# `__match_args__` is a real protocol member on 3.12 + +from typing import Protocol, runtime_checkable + +@runtime_checkable +class P(Protocol): + __match_args__: tuple[str, ...] + def m(self) -> None: ... + +class Impl: + def m(self) -> None: ... + +issubclass(Impl, P) # E: Protocol `P` has non-method members and cannot be used with issubclass() +"#, +); + +testcase!( + test_isinstance_excludes_match_args_3_13, + TestEnv::new_with_version(PythonVersion::new(3, 13, 0)), + r#" +# `__match_args__` is an excluded attribute name on 3.13+ + +from typing import Protocol, runtime_checkable + +@runtime_checkable +class P(Protocol): + __match_args__: tuple[str, ...] + def m(self) -> None: ... + +class Impl: + def m(self) -> None: ... + +isinstance(Impl(), P) # E: Runtime checkable protocol `P` has an unsafe overlap with type `Impl` +"#, +); + +testcase!( + test_issubclass_with_class_getitem_3_8, + TestEnv::new_with_version(PythonVersion::new(3, 8, 0)), + r#" +# `__class_getitem__` is a real protocol member on 3.8 + +from typing import Protocol, runtime_checkable + +@runtime_checkable +class P(Protocol): + __class_getitem__ = None + def m(self) -> None: ... + +class Impl: + def m(self) -> None: ... + +issubclass(Impl, P) # E: Protocol `P` has non-method members and cannot be used with issubclass() +"#, +); + +testcase!( + test_issubclass_excludes_class_getitem_3_9, + TestEnv::new_with_version(PythonVersion::new(3, 9, 0)), + r#" +# `__class_getitem__` is an excluded attribute name on 3.9+ + +from typing import Protocol, runtime_checkable + +@runtime_checkable +class P(Protocol): + __class_getitem__: None + def m(self) -> None: ... + +class Impl: + def m(self) -> None: ... + +# `__class_getitem__` is runtime-excluded on 3.9+, and pyrefly also skips it +# in the unsafe-overlap type check. +issubclass(Impl, P) +"#, +); + +testcase!( + test_issubclass_with_annotate_3_13, + TestEnv::new_with_version(PythonVersion::new(3, 13, 0)), + r#" +# `__annotate__` is not runtime-excluded on 3.13, so an explicit annotation is a +# non-method member and `issubclass()` rejects the protocol. + +from typing import Protocol, runtime_checkable + +@runtime_checkable +class P(Protocol): + __annotate__: object + def m(self) -> None: ... + +class Impl: + def m(self) -> None: ... + +issubclass(Impl, P) # E: Protocol `P` has non-method members and cannot be used with issubclass() +"#, +); + +testcase!( + test_issubclass_excludes_annotate_3_14, + TestEnv::new_with_version(PythonVersion::new(3, 14, 0)), + r#" +# `__annotate__` is an excluded attribute name on 3.14+ + +from typing import Protocol, runtime_checkable + +@runtime_checkable +class P(Protocol): + __annotate__: object + def m(self) -> None: ... + +class Impl: + def m(self) -> None: ... + +issubclass(Impl, P) # E: Runtime checkable protocol `P` has an unsafe overlap with type `Impl` +"#, +); + +testcase!( + test_isinstance_raise_unsafe_overlap_by_retyping_slot_attributes_and_misaligning_impl, + r#" +from typing import Protocol, runtime_checkable + +@runtime_checkable +class P(Protocol): + __slots__ = ("name",) + name: int + def m(self) -> int: ... + +class Mismatched: + name: str + def m(self) -> int: ... + +isinstance(Mismatched(), P) # E: Runtime checkable protocol `P` has an unsafe overlap with type `Mismatched` +"#, +); + +testcase!( + bug = "Private attribute names are not mangled, so both presence and type check use the wrong name", + test_isinstance_with_private_attribute_name, + r#" +from typing import Protocol, runtime_checkable + +@runtime_checkable +class P(Protocol): + __x: int + +class WrongImpl: + __x = None + +class WorkableImpl: + _P__x = None + +isinstance(WrongImpl(), P) # E: Runtime checkable protocol `P` has an unsafe overlap with type `WrongImpl` +isinstance(WorkableImpl(), P) +"#, +); + testcase!( test_runtime_checkable_non_protocol, r#"