From ccab776cbd632ed47ff92cc2f418f1e42cf3a7db Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Thu, 5 Nov 2026 18:32:19 +0000 Subject: [PATCH 1/2] [mypyc] Allow native classes to support weak refs Fixes mypyc/mypyc#1102. Native classes support weak references if they opt in using `@mypyc_attr(weakrefs=True)`, which adds a weak reference list field to the object struct. The base class of a hierarchy must opt in, since the offset of the field must be the same in all subclasses. Native subclasses of non-native classes (other than dict/Exception subclasses) always support weak references, like interpreted subclasses. They already have `__dict__` storage, and the weak reference list goes next to it at no additional memory cost: in the managed pre-header on 3.12+ (Py_TPFLAGS_MANAGED_WEAKREF), and in a trailing slot after `__dict__` on older versions. This works the same way whether or not the base class supports weak references, so mypyc doesn't need to know anything about the base class. Previously some of these classes were weak-referenceable (on 3.11 and earlier, or if the base class supported them), but tp_dealloc never cleared the weak references, so they resurrected freed memory. Now tp_dealloc clears weak references for all classes that support them. On 3.11 and earlier, callable classes (used for nested functions, lambdas and singledispatch functions) and native dict/Exception subclasses used to accept weak references, but the result crashed or corrupted memory once the object died. They now reject weak references, as on 3.12+, and their instances are one pointer smaller. --- mypyc/codegen/emitclass.py | 72 +++++-- mypyc/doc/native_classes.rst | 59 ++++++ mypyc/ir/class_ir.py | 45 ++++- mypyc/irbuild/prepare.py | 38 ++++ mypyc/irbuild/specialize.py | 31 +++ mypyc/irbuild/util.py | 17 +- mypyc/lib-rt/CPy.h | 17 ++ mypyc/lib-rt/misc_ops.c | 16 ++ mypyc/test-data/irbuild-classes.test | 4 +- mypyc/test-data/irbuild-weakref.test | 56 ++++++ mypyc/test-data/run-multimodule.test | 55 +++++ mypyc/test-data/run-weakref.test | 289 +++++++++++++++++++++++++++ 12 files changed, 678 insertions(+), 21 deletions(-) diff --git a/mypyc/codegen/emitclass.py b/mypyc/codegen/emitclass.py index f528de5f5bfff..1ef8ff5269369 100644 --- a/mypyc/codegen/emitclass.py +++ b/mypyc/codegen/emitclass.py @@ -336,7 +336,11 @@ def generate_class( and not managed_dict and emitter.capi_version < (3, 12) ) - generate_dealloc_slots = generate_full or managed_dict or needs_builtin_dict_cleanup + # Weak references to a dead object must be cleared in tp_dealloc, or they will + # resurrect freed memory. + generate_dealloc_slots = ( + generate_full or managed_dict or needs_builtin_dict_cleanup or has_weakrefs(cl) + ) if generate_dealloc_slots: fields["tp_dealloc"] = f"(destructor){name_prefix}_dealloc" if not cl.is_acyclic: @@ -405,27 +409,36 @@ def emit_line() -> None: # values. PyType_Ready will inherit the offsets from tp_base but # that isn't what we want. - # XXX: there is no reason for the __weakref__ stuff to be mixed up with __dict__ - if cl.has_dict and not has_managed_dict(cl, emitter): - # __dict__ lives right after the struct and __weakref__ lives right after that + if cl.has_dict and not managed_dict: + # __dict__ lives right after the struct, and __weakref__ (if any) after that. # TODO: They should get members in the struct instead of doing this nonsense. - weak_offset = f"{base_size} + sizeof(PyObject *)" + # + # We can't inherit tp_dictoffset/tp_weaklistoffset from the base class, since + # the base class slots would overlap with fields of our object struct, which + # doesn't model the layout of the non-native base class at all. + needs_own_weak_slot = ( + emitter.capi_version < (3, 12) and has_weakrefs(cl) and not cl.has_weakref_slot() + ) emitter.emit_lines( f"PyMemberDef {members_name}[] = {{", f'{{"__dict__", T_OBJECT_EX, {base_size}, 0, NULL}},', - f'{{"__weakref__", T_OBJECT_EX, {weak_offset}, 0, NULL}},', "{0}", "};", ) fields["tp_members"] = members_name - fields["tp_basicsize"] = f"{base_size} + 2*sizeof(PyObject *)" + num_slots = 2 if needs_own_weak_slot else 1 + fields["tp_basicsize"] = f"{base_size} + {num_slots}*sizeof(PyObject *)" if emitter.capi_version < (3, 12): fields["tp_dictoffset"] = base_size - fields["tp_weaklistoffset"] = weak_offset + if needs_own_weak_slot: + fields["tp_weaklistoffset"] = f"{base_size} + sizeof(PyObject *)" else: fields["tp_basicsize"] = base_size + if cl.has_weakref_slot(): + fields["tp_weaklistoffset"] = f"offsetof({struct_name}, weakreflist)" + if generate_dealloc_slots: if not cl.is_acyclic: generate_traverse_for_class(cl, traverse_name, emitter) @@ -524,6 +537,11 @@ def emit_line() -> None: fields["tp_call"] = "PyVectorcall_Call" if managed_dict: flags.append("Py_TPFLAGS_MANAGED_DICT") + if has_weakrefs(cl) and not cl.has_weakref_slot(): + # The pre-header has room for both __dict__ and the weak reference list, so + # this is free. The flag is usually inherited from the base class, but not + # if the base class doesn't support weak references (e.g. abc.ABC). + flags.append("Py_TPFLAGS_MANAGED_WEAKREF") fields["tp_flags"] = " | ".join(flags) fields["tp_doc"] = f"PyDoc_STR({native_class_doc_initializer(cl)})" @@ -565,6 +583,10 @@ def generate_object_struct(cl: ClassIR, emitter: Emitter) -> None: seen_attrs: set[str] = set() lines: list[str] = [] lines += ["typedef struct {", "PyObject_HEAD", "CPyVTableItem *vtable;"] + if cl.has_weakref_slot(): + # This must come before any field whose presence depends on the class, since + # tp_weaklistoffset has to agree between a base class and its subclasses. + lines.append("PyObject *weakreflist;") if cl.has_method("__call__"): lines.append("vectorcallfunc vectorcall;") # The flag affects attribute offsets, so concrete bases must agree on its presence. @@ -1052,12 +1074,10 @@ def generate_traverse_for_class(cl: ClassIR, func_name: str, emitter: Emitter) - emitter.emit_line(f"rv = PyObject_VisitManagedDict({base_args});") emitter.emit_line("if (rv != 0) return rv;") elif cl.has_dict: - # __dict__ lives at tp_dictoffset (== base_size), __weakref__ right after it. + # __dict__ lives at tp_dictoffset (== base_size). The weak reference list, if + # any, is deliberately not visited: it holds borrowed references. base_size = f"sizeof({cl.builtin_base or cl.struct_name(emitter.names)})" emitter.emit_gc_visit(f"*((PyObject **)((char *)self + {base_size}))", object_rprimitive) - emitter.emit_gc_visit( - f"*((PyObject **)((char *)self + sizeof(PyObject *) + {base_size}))", object_rprimitive - ) emitter.emit_line("return rv;") emitter.emit_line("}") @@ -1111,12 +1131,11 @@ def generate_subtype_clear_body(cl: ClassIR, emitter: Emitter, skip_attrs: set[s if has_managed_dict(cl, emitter): emitter.emit_line(f"PyObject_ClearManagedDict({base_args});") elif cl.has_dict: - # __dict__ lives at tp_dictoffset (== base_size), __weakref__ right after it. + # __dict__ lives at tp_dictoffset (== base_size). The weak reference list, if + # any, is not cleared here: it holds borrowed references, and it's cleared in + # tp_dealloc instead. base_size = f"sizeof({cl.builtin_base or cl.struct_name(emitter.names)})" emitter.emit_gc_clear(f"*((PyObject **)((char *)self + {base_size}))", object_rprimitive) - emitter.emit_gc_clear( - f"*((PyObject **)((char *)self + sizeof(PyObject *) + {base_size}))", object_rprimitive - ) def generate_dealloc_for_class( @@ -1156,6 +1175,18 @@ def generate_dealloc_for_class( emitter.emit_line("}") if not cl.is_acyclic: emitter.emit_line("PyObject_GC_UnTrack(self);") + if has_weakrefs(cl): + # Invalidate all weak references to the object, and call their callbacks. + # This must happen after the finalizer has run, and before any of the + # attributes are cleared. + # + # TODO: Weak references created *inside* __del__ are not cleared. CPython + # handles these with a second _PyWeakref_ClearWeakRefsNoCallbacks pass. + if cl.has_weakref_slot(): + emitter.emit_line("CPy_ClearWeakrefs((PyObject *)self, &self->weakreflist);") + else: + # The list is next to __dict__, and the offset depends on the Python version + emitter.emit_line("PyObject_ClearWeakRefs((PyObject *)self);") if cl.builtin_base: emitter.emit_line(f"{clear_func_name}((PyObject *)self);") # For native subclasses of builtins such as dict, the base deallocator @@ -1339,6 +1370,10 @@ def generate_getseters_table(cl: ClassIR, name: str, emitter: Emitter) -> None: if cl.has_dict: emitter.emit_line('{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},') + if has_weakrefs(cl): + # Even if a non-native base class has a __weakref__ descriptor, we can't use it, + # since it uses the weak reference list offset of the base class. + emitter.emit_line('{"__weakref__", CPy_GetWeakrefs, NULL},') emitter.emit_line("{NULL} /* Sentinel */") emitter.emit_line("};") @@ -1650,6 +1685,11 @@ def has_managed_dict(cl: ClassIR, emitter: Emitter) -> bool: ) +def has_weakrefs(cl: ClassIR) -> bool: + """Do instances of a native class have a weak reference list (somewhere)?""" + return cl.is_ext_class and not cl.is_trait and cl.supports_weakrefs() + + def native_class_doc_initializer(cl: ClassIR) -> str: init_fn = cl.get_method("__init__") if init_fn is not None: diff --git a/mypyc/doc/native_classes.rst b/mypyc/doc/native_classes.rst index a97e4d39cbcad..b8727c88b92d9 100644 --- a/mypyc/doc/native_classes.rst +++ b/mypyc/doc/native_classes.rst @@ -360,6 +360,65 @@ of cyclic GC. leaks. Only use this for classes whose instances won't refer back to objects that (directly or indirectly) refer to the instance. +Weak references +--------------- + +By default, you can't create weak references to instances of native +classes, since supporting weak references requires an extra pointer in +every instance:: + + import weakref + + class Cls: + pass + + o = Cls() + r = weakref.ref(o) # Error + +You can enable support for weak references using +``@mypyc_attr(weakrefs=True)``:: + + import weakref + from mypy_extensions import mypyc_attr + + @mypyc_attr(weakrefs=True) + class Cls: + pass + + o = Cls() + r = weakref.ref(o) # OK + assert r() is o + +Unlike ``acyclic``, weak reference support is inherited by subclasses, +including subclasses defined in other modules and interpreted +subclasses. If a native base class doesn't support weak references, a +native subclass can't add support for them, since the location of the +extra pointer must be the same in all classes of a hierarchy -- you +must add ``@mypyc_attr(weakrefs=True)`` to the base class instead. + +Native classes that inherit from a non-native class other than +``object``, such as an interpreted class or ``abc.ABC``, always support +weak references, like interpreted subclasses do. Their instances +already have a ``__dict__``, and weak reference support costs no +additional memory. Native subclasses of built-in types such as ``dict`` +or ``Exception`` don't support weak references yet. + +.. note:: + + Mypyc only reports an error about an unsupported weak reference if + it can infer the precise native class of the target. Otherwise the + error is raised at runtime, as in interpreted Python:: + + o: object = Cls() + r = weakref.ref(o) # TypeError at runtime + +.. note:: + + Mypyc frees a local variable as soon as it's no longer used, which + can be before the end of the enclosing function. Weak references + to an object stored only in a local variable may thus be cleared + earlier than in interpreted Python. + Other properties ---------------- diff --git a/mypyc/ir/class_ir.py b/mypyc/ir/class_ir.py index e9ae115101253..7c0adc8c2c609 100644 --- a/mypyc/ir/class_ir.py +++ b/mypyc/ir/class_ir.py @@ -111,6 +111,9 @@ def __init__( self.is_decorated = False # Does this inherit from a Python class? self.inherits_python = False + # Is weak reference support explicitly requested via @mypyc_attr(weakrefs=True)? + # Use supports_weakrefs() to also consider base classes. + self._weakrefs = False # Do instances of this class have __dict__? self.has_dict = False # Do we allow interpreted subclasses? Derived from a mypyc_attr. @@ -321,7 +324,13 @@ def is_final_attr(self, name: str) -> bool: @property def needs_getseters_table(self) -> bool: """Do we generate a tp_getset table exposing the attributes to Python?""" - return self.needs_getseters or not self.is_generated or self.has_dict + return ( + self.needs_getseters + or not self.is_generated + or self.has_dict + # For the __weakref__ getset + or (self.is_ext_class and not self.is_trait and self.supports_weakrefs()) + ) def attrs_are_thread_confined(self) -> bool: """Can these attributes safely use plain access in free-threaded builds? @@ -498,6 +507,38 @@ def concrete_subclasses(self) -> list[ClassIR] | None: def is_serializable(self) -> bool: return any(ci._serializable for ci in self.mro) + def supports_weakrefs(self) -> bool: + """Can weak references to instances of this class be created? + + Native classes only support weak references if requested using + @mypyc_attr(weakrefs=True), since it has a per-instance memory cost. Like + Python subclasses, native subclasses of non-native classes always support weak + references, whether or not the base class does, since they already have + __dict__ storage, and adding weak reference storage next to it is free. + Subclasses of built-in types (such as Exception or dict) don't support weak + references yet. + """ + if not self.is_ext_class: + # Non-native classes are ordinary heap types, so they always work. + return True + if self.builtin_base: + return False + return self.inherits_python or any(ci._weakrefs for ci in self.mro) + + def has_weakref_slot(self) -> bool: + """Is the weak reference list stored in a field of the object struct? + + Otherwise the list is stored next to __dict__, if weak references are + supported. A native base class that uses the field determines the offset of + the list in all subclasses. + """ + return ( + self.is_ext_class + and not self.is_trait + and not self.builtin_base + and any(ci._weakrefs and not ci.inherits_python for ci in self.mro) + ) + def serialize(self) -> JsonDict: return { "name": self.name, @@ -510,6 +551,7 @@ def serialize(self) -> JsonDict: "is_decorated": self.is_decorated, "is_final_class": self.is_final_class, "inherits_python": self.inherits_python, + "_weakrefs": self._weakrefs, "has_dict": self.has_dict, "allow_interpreted_subclasses": self.allow_interpreted_subclasses, "needs_getseters": self.needs_getseters, @@ -581,6 +623,7 @@ def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> ClassIR: ir.is_decorated = data["is_decorated"] ir.is_final_class = data["is_final_class"] ir.inherits_python = data["inherits_python"] + ir._weakrefs = data["_weakrefs"] ir.has_dict = data["has_dict"] ir.allow_interpreted_subclasses = data["allow_interpreted_subclasses"] ir.needs_getseters = data["needs_getseters"] diff --git a/mypyc/irbuild/prepare.py b/mypyc/irbuild/prepare.py index 7c86ce5e06381..fa507f7474dc1 100644 --- a/mypyc/irbuild/prepare.py +++ b/mypyc/irbuild/prepare.py @@ -35,6 +35,7 @@ NameExpr, OverloadedFuncDef, RefExpr, + StrExpr, SymbolNode, TypeAlias, TypeInfo, @@ -80,6 +81,7 @@ dataclass_type, default_attr_name, get_func_def, + get_mypyc_attr_call, get_mypyc_attrs, is_class_body_final, is_dataclass, @@ -151,6 +153,7 @@ def build_type_map( with catch_errors(module.path, cdef.line): if mapper.type_to_ir[cdef.info].is_ext_class: validate_acyclic_class_bases(module.path, cdef, errors, mapper) + validate_weakrefs_class_base(module.path, cdef, errors, mapper) # Prepare implicit attribute accessors as needed if an attribute overrides a property. for module, cdef in classes: @@ -485,6 +488,26 @@ def validate_acyclic_class_bases( ) +def validate_weakrefs_class_base( + path: str, cdef: ClassDef, errors: Errors, mapper: Mapper +) -> None: + ir = mapper.type_to_ir[cdef.info] + if not ir.has_weakref_slot() or ir.base is None or ir.base.has_weakref_slot(): + return + # The weak reference list field is at a fixed offset that must be the same in a + # base class and all its subclasses, so only the class that starts the hierarchy + # can introduce it. + line = cdef.line + for dec in cdef.decorators: + call = get_mypyc_attr_call(dec) + if call is not None and any( + name == "weakrefs" or (isinstance(arg, StrExpr) and arg.value == "weakrefs") + for name, arg in zip(call.arg_names, call.args) + ): + line = call.line + errors.error(f'"weakrefs" must be used in the base class "{ir.base.name}" as well', path, line) + + def _has_own_default_attrs(cdef: ClassDef, ir: ClassIR) -> bool: """Whether this class's own body has any default attribute assignment that would be emitted into __mypyc_defaults_setup. @@ -669,6 +692,13 @@ def prepare_class_def( if attrs.get("acyclic") is True: ir.is_acyclic = True + if attrs.get("weakrefs") is True: + line = attrs_lines["weakrefs"] + if ir.is_trait: + errors.error('"weakrefs" can\'t be used with traits', path, line) + else: + ir._weakrefs = True + # Check for subclassing from builtin types reported_base = False for cls in info.mro: @@ -700,6 +730,14 @@ def prepare_class_def( cdef.line, ) + if ir.builtin_base and ir._weakrefs: + errors.error( + '"weakrefs" can\'t be used in a class that inherits from a built-in type', + path, + attrs_lines["weakrefs"], + ) + ir._weakrefs = False + free_list_len = attrs.get("free_list_len") if free_list_len is not None: line = attrs_lines["free_list_len"] diff --git a/mypyc/irbuild/specialize.py b/mypyc/irbuild/specialize.py index c7cc8d4959932..c446ef587043a 100644 --- a/mypyc/irbuild/specialize.py +++ b/mypyc/irbuild/specialize.py @@ -1782,3 +1782,34 @@ def translate_vec_pop(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Va index_value = Integer(-1, int64_rprimitive) return vec_pop(builder.builder, vec_value, index_value, vec_arg.line) return None + + +@specialize_function("weakref.ReferenceType") +@specialize_function("_weakref.proxy") +def check_weakref_target(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None: + """Report an error if a weak reference to a native instance can't be created. + + Native classes only support weak references if requested explicitly, so a + weakref.ref() or weakref.proxy() call would fail at runtime. This is best effort: + we only detect calls where the argument has a precise native class type. + + This doesn't generate any code, so translation continues as usual. + """ + if expr.args and expr.arg_kinds[0] == ARG_POS: + rtype = builder.node_type(expr.args[0]) + if ( + isinstance(rtype, RInstance) + and not rtype.class_ir.is_trait + and not rtype.class_ir.supports_weakrefs() + ): + builder.error( + "Cannot create weak reference to instance of native class " + f'"{rtype.class_ir.fullname}"', + expr.line, + ) + builder.note( + 'Add "@mypy_extensions.mypyc_attr(weakrefs=True)" to the class ' + "definition to enable support for weak references", + expr.line, + ) + return None diff --git a/mypyc/irbuild/util.py b/mypyc/irbuild/util.py index 9921651fce654..238bb78b67f24 100644 --- a/mypyc/irbuild/util.py +++ b/mypyc/irbuild/util.py @@ -38,14 +38,26 @@ from mypyc.ir.rtypes import RType, is_none_rprimitive, is_object_rprimitive, is_optional_type MYPYC_ATTRS: Final[frozenset[MypycAttr]] = frozenset( - ["native_class", "allow_interpreted_subclasses", "serializable", "free_list_len", "acyclic"] + [ + "native_class", + "allow_interpreted_subclasses", + "serializable", + "free_list_len", + "acyclic", + "weakrefs", + ] ) DATACLASS_DECORATORS: Final = frozenset(["dataclasses.dataclass", "attr.s", "attr.attrs"]) MypycAttr = Literal[ - "native_class", "allow_interpreted_subclasses", "serializable", "free_list_len", "acyclic" + "native_class", + "allow_interpreted_subclasses", + "serializable", + "free_list_len", + "acyclic", + "weakrefs", ] @@ -55,6 +67,7 @@ class MypycAttrs(TypedDict): serializable: NotRequired[bool] free_list_len: NotRequired[int] acyclic: NotRequired[bool] + weakrefs: NotRequired[bool] def is_final_decorator(d: Expression) -> bool: diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index 65cc8f038e508..72350dd7e989d 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -168,6 +168,23 @@ static inline size_t CPy_FindAttrOffset(PyTypeObject *trait, CPyVTableItem *vtab #define CPY_GET_METHOD_TRAIT(obj, trait, vtable_index, object_type, method_type) \ ((method_type)(CPy_FindTraitVtable(trait, ((object_type *)obj)->vtable)[vtable_index])) +// Clear the weak reference list of an object being deallocated, when the +// weakreflist field is at a statically known location. Must be called from +// tp_dealloc after PyObject_GC_UnTrack() and after running the finalizer. +static inline void CPy_ClearWeakrefs(PyObject *obj, PyObject **weakreflist) { +#ifdef Py_GIL_DISABLED + // The list can't be inspected without holding the per-object weakref lock, + // and PyObject_ClearWeakRefs() has its own fast path for an empty list. + (void)weakreflist; + PyObject_ClearWeakRefs(obj); +#else + if (*weakreflist != NULL) + PyObject_ClearWeakRefs(obj); +#endif +} + +PyObject *CPy_GetWeakrefs(PyObject *obj, void *closure); + // Int operations diff --git a/mypyc/lib-rt/misc_ops.c b/mypyc/lib-rt/misc_ops.c index 669c49f2313bf..d0111e861db91 100644 --- a/mypyc/lib-rt/misc_ops.c +++ b/mypyc/lib-rt/misc_ops.c @@ -1038,6 +1038,22 @@ PyObject *CPySingledispatch_RegisterFunction(PyObject *singledispatch_func, } +// Implementation of the '__weakref__' getter of native classes that support weak +// references. Adapted from subtype_getweakref in CPython's typeobject.c. +PyObject *CPy_GetWeakrefs(PyObject *obj, void *closure) +{ + Py_ssize_t offset = Py_TYPE(obj)->tp_weaklistoffset; + if (offset == 0) { + PyErr_SetString(PyExc_AttributeError, "This object has no __weakref__"); + return NULL; + } + PyObject **weaklistptr = (PyObject **)((char *)obj + offset); + if (*weaklistptr == NULL) { + return Py_NewRef(Py_None); + } + return Py_NewRef(*weaklistptr); +} + // Adapted from ceval.c GET_AITER PyObject *CPy_GetAIter(PyObject *obj) { diff --git a/mypyc/test-data/irbuild-classes.test b/mypyc/test-data/irbuild-classes.test index 6c1d288d84f6c..b4424cfa9e88d 100644 --- a/mypyc/test-data/irbuild-classes.test +++ b/mypyc/test-data/irbuild-classes.test @@ -4114,11 +4114,11 @@ L0: from mypy_extensions import mypyc_attr @mypyc_attr("allow_interpreted_subclasses", "invalid_arg") # E: "invalid_arg" is not a supported "mypyc_attr" \ - # N: supported keys: "acyclic", "allow_interpreted_subclasses", "free_list_len", "native_class", "serializable" + # N: supported keys: "acyclic", "allow_interpreted_subclasses", "free_list_len", "native_class", "serializable", "weakrefs" class InvalidArg: pass @mypyc_attr(invalid_kwarg=True) # E: "invalid_kwarg" is not a supported "mypyc_attr" \ - # N: supported keys: "acyclic", "allow_interpreted_subclasses", "free_list_len", "native_class", "serializable" + # N: supported keys: "acyclic", "allow_interpreted_subclasses", "free_list_len", "native_class", "serializable", "weakrefs" class InvalidKwarg: pass @mypyc_attr(str()) # E: All "mypyc_attr" positional arguments must be string literals. diff --git a/mypyc/test-data/irbuild-weakref.test b/mypyc/test-data/irbuild-weakref.test index 2180b1e747aab..e2b7970b29bf3 100644 --- a/mypyc/test-data/irbuild-weakref.test +++ b/mypyc/test-data/irbuild-weakref.test @@ -101,3 +101,59 @@ def f(x, cb): L0: r0 = PyWeakref_NewProxy(x, cb) return r0 + +[case testWeakrefToNativeClassErrors] +from typing import Any +import weakref +from mypy_extensions import mypyc_attr, trait + +class Plain: + pass + +@mypyc_attr(weakrefs=True) +class Supported: + pass + +class SupportedSub(Supported): + pass + +@mypyc_attr(native_class=False) +class NonNative: + pass + +@trait +class T: + pass + +def f(a: Plain, b: Supported, c: SupportedSub, d: NonNative, e: T, g: object) -> None: + weakref.ref(a) # E: Cannot create weak reference to instance of native class "__main__.Plain" \ + # N: Add "@mypy_extensions.mypyc_attr(weakrefs=True)" to the class definition to enable support for weak references + weakref.proxy(a) # E: Cannot create weak reference to instance of native class "__main__.Plain" \ + # N: Add "@mypy_extensions.mypyc_attr(weakrefs=True)" to the class definition to enable support for weak references + # These are all fine (or can't be checked statically) + weakref.ref(b) + weakref.ref(c) + weakref.ref(d) + weakref.ref(e) + weakref.ref(g) +[out] + +[case testWeakrefAttrErrors] +from mypy_extensions import mypyc_attr, trait + +@mypyc_attr(weakrefs=True) # E: "weakrefs" can't be used with traits +@trait +class T: + pass + +@mypyc_attr(weakrefs=True) # E: "weakrefs" can't be used in a class that inherits from a built-in type +class Dict(dict): + pass + +class Base: + pass + +@mypyc_attr(weakrefs=True) # E: "weakrefs" must be used in the base class "Base" as well +class Sub(Base): + pass +[out] diff --git a/mypyc/test-data/run-multimodule.test b/mypyc/test-data/run-multimodule.test index bcfc916448fc8..3c8b4ceb99957 100644 --- a/mypyc/test-data/run-multimodule.test +++ b/mypyc/test-data/run-multimodule.test @@ -562,6 +562,61 @@ def call_method(b: Base, x: int) -> int: [typing fixtures/typing-full.pyi] +[case testMultiModuleWeakrefs] +# Base classes are in a module that is prepared after this one (modules are +# processed in name order), and in another group in separate compilation mode. +import gc +import weakref +from typing import Any +from mypy_extensions import mypyc_attr +from other_base import WeakBase, ActionBase + +class Sub(WeakBase): + def __init__(self) -> None: + super().__init__() + self.y = 2 + +# Redundant, but allowed +@mypyc_attr(weakrefs=True) +class ExplicitSub(Sub): + pass + +class ActionSub(ActionBase): + def __init__(self) -> None: + super().__init__() + self.y = 2 + +def check(cls: Any) -> None: + objs = [cls() for i in range(100)] + refs = [weakref.ref(o) for o in objs] + assert objs[0].x == 1 and objs[0].y == 2 + assert refs[0]() is objs[0] + del objs + gc.collect() + keep = [cls() for i in range(100)] + assert [r() for r in refs] == [None] * 100 + assert len(keep) == 100 + +def test_weakrefs() -> None: + check(Sub) + check(ExplicitSub) + check(ActionSub) + assert getattr(Sub, "__weakrefoffset__") == getattr(WeakBase, "__weakrefoffset__") + +[file other_base.py] +import argparse +from mypy_extensions import mypyc_attr + +@mypyc_attr(weakrefs=True) +class WeakBase: + def __init__(self) -> None: + self.x = 1 + +class ActionBase(argparse.Action): + def __init__(self) -> None: + super().__init__(["-x"], "x") + self.x = 1 + [case testNonNativeImportInPackageFile] # The import is really non-native only in separate compilation mode where __init__.py and # other_cache.py are in different libraries and the import uses the standard Python procedure. diff --git a/mypyc/test-data/run-weakref.test b/mypyc/test-data/run-weakref.test index 0a0e180d635d7..b696af790b1da 100644 --- a/mypyc/test-data/run-weakref.test +++ b/mypyc/test-data/run-weakref.test @@ -50,3 +50,292 @@ def test_weakref_proxy_with_callback() -> None: with assertRaises(ReferenceError): p.some_meth() assert _callback_called_cache["proxy"] is True + +[case testWeakrefNativeClass] +import argparse +import gc +import weakref +from abc import ABC, abstractmethod +from typing import Any, Optional +from mypy_extensions import mypyc_attr +from testutil import assertRaises + +@mypyc_attr(weakrefs=True) +class C: + def __init__(self, x: int) -> None: + self.x = x + + def meth(self) -> int: + return self.x + +class Sub(C): + def __init__(self) -> None: + super().__init__(5) + self.y = 6 + +@mypyc_attr(weakrefs=True, acyclic=True) +class Acyclic: + def __init__(self) -> None: + self.x = 1 + +@mypyc_attr(weakrefs=True, free_list_len=1) +class FreeList: + def __init__(self) -> None: + self.x = 1 + +@mypyc_attr(weakrefs=True) +class WithDel: + def __del__(self) -> None: + deleted.append(1) + +deleted: list[int] = [] + +def test_ref() -> None: + obj: Optional[C] = C(3) + r = weakref.ref(obj) + assert r() is obj + assert obj is not None and obj.meth() == 3 + obj = None + gc.collect() + assert r() is None + +def test_ref_with_callback() -> None: + called = [] + obj: Optional[C] = C(3) + r = weakref.ref(obj, lambda x: called.append(1)) + assert r() is obj + obj = None + gc.collect() + assert r() is None + assert called == [1] + +def test_proxy() -> None: + obj: Optional[C] = C(4) + p = weakref.proxy(obj) + assert p.meth() == 4 + assert p.x == 4 + # Note: 'obj' must be read here, since mypyc frees a local as soon as it is + # no longer read, and the referent would otherwise be dead already above. + assert obj is not None + obj = None + gc.collect() + with assertRaises(ReferenceError): + p.meth() + +def test_multiple_refs() -> None: + obj: Optional[C] = C(1) + refs = [weakref.ref(obj) for _ in range(10)] + assert all(r() is obj for r in refs) + obj = None + gc.collect() + assert all(r() is None for r in refs) + +def test_dunder_weakref() -> None: + # Note: mypy doesn't know about '__weakref__', so use getattr(). + obj = C(1) + assert getattr(obj, "__weakref__") is None + r = weakref.ref(obj) + assert getattr(obj, "__weakref__") is r + +def test_subclass_inherits_support() -> None: + obj: Optional[Sub] = Sub() + r = weakref.ref(obj) + assert r() is obj + # Attribute offsets must not be perturbed by the weakref slot. + assert obj is not None and obj.x == 5 and obj.y == 6 and obj.meth() == 5 + obj = None + gc.collect() + assert r() is None + +def test_acyclic() -> None: + obj: Optional[Acyclic] = Acyclic() + r = weakref.ref(obj) + assert r() is obj + obj = None + assert r() is None + +def test_free_list() -> None: + # A recycled instance must not inherit the previous instance's weakrefs. + refs = [] + for i in range(100): + obj: Optional[FreeList] = FreeList() + refs.append(weakref.ref(obj)) + obj = None + gc.collect() + assert [r() for r in refs] == [None] * 100 + +def test_del() -> None: + obj: Optional[WithDel] = WithDel() + r = weakref.ref(obj) + obj = None + gc.collect() + assert deleted == [1] + assert r() is None + +def test_no_dangling_refs() -> None: + # Regression test: weakrefs to dead objects used to resurrect freed memory. + refs = [] + for i in range(1000): + obj: Optional[C] = C(i) + refs.append(weakref.ref(obj)) + obj = None + gc.collect() + # Allocate more objects so freed memory gets reused. + keep = [C(i) for i in range(1000)] + assert [r() for r in refs] == [None] * 1000 + assert len(keep) == 1000 + +# Native subclasses of non-native classes always support weak references, even if +# the base class doesn't (ABC defines empty __slots__). +class Abstract(ABC): + @abstractmethod + def meth(self) -> int: ... + +class Impl(Abstract): + def __init__(self) -> None: + self.x = 1 + + def meth(self) -> int: + return self.x + +# The attribute is redundant here, but it's allowed +@mypyc_attr(weakrefs=True) +class ExplicitAbstract(ABC): + pass + +# argparse.Action is an interpreted class, but it's defined in a stub. Use several +# attributes so that a weak reference list at a wrong offset would overwrite one. +class Action(argparse.Action): + def __init__(self) -> None: + super().__init__(["-x"], "x") + self.a = 1 + self.b = "b" + self.c = [1] + + def __call__(self, *args: Any) -> None: + pass + +@mypyc_attr(weakrefs=True) +class ExplicitAction(Action): + pass + +class SubAction(Action): + def __init__(self) -> None: + super().__init__() + self.d = 2 + +def check(cls: Any) -> None: + objs = [cls() for i in range(100)] + refs = [weakref.ref(o) for o in objs] + o: Any = objs[0] + o.extra = 5 + assert o.extra == 5 + assert getattr(o, "__weakref__") is refs[0] + weakref.proxy(o) + assert refs[0]() is o + del o, objs + gc.collect() + keep = [cls() for i in range(100)] + assert [r() for r in refs] == [None] * 100 + assert len(keep) == 100 + +def test_abc_base() -> None: + check(Impl) + check(ExplicitAbstract) + obj: Optional[Impl] = Impl() + r = weakref.ref(obj) + assert obj is not None and obj.meth() == 1 + obj = None + gc.collect() + assert r() is None + +def test_stub_interpreted_base() -> None: + check(Action) + check(ExplicitAction) + check(SubAction) + obj = SubAction() + weakref.ref(obj) + assert (obj.a, obj.b, obj.c, obj.d) == (1, "b", [1], 2) + assert obj.dest == "x" + +class NoWeakrefs: + pass + +class DictSub(dict): + pass + +def test_native_class_without_weakref_support() -> None: + # The static check is best effort, so it doesn't fire for 'object' values. + o: object = NoWeakrefs() + with assertRaises(TypeError, "cannot create weak reference to 'NoWeakrefs' object"): + weakref.ref(o) + d: object = DictSub() + with assertRaises(TypeError): + weakref.ref(d) + +[case testWeakrefWithInterpretedBaseClass] +import gc +import weakref +from typing import Optional +from mypy_extensions import mypyc_attr + +from interpbase import Base + +class Native(Base): + def __init__(self) -> None: + super().__init__() + self.x = 1 + +@mypyc_attr(allow_interpreted_subclasses=True, weakrefs=True) +class Open: + def __init__(self) -> None: + self.x = 1 + +def test_implicit_weakref_support() -> None: + obj: Optional[Native] = Native() + r = weakref.ref(obj) + assert r() is obj + # Note: mypy doesn't know about '__weakref__', so use getattr(). + assert getattr(obj, "__weakref__") is r + assert obj is not None and obj.x == 1 and obj.y == 2 + obj = None + gc.collect() + assert r() is None + +def test_no_dangling_refs() -> None: + # Regression test: mypyc's tp_dealloc didn't clear the weakref list inherited + # from an interpreted base class, which resurrected freed memory. + refs = [] + for i in range(1000): + obj: Optional[Native] = Native() + refs.append(weakref.ref(obj)) + obj = None + gc.collect() + keep = [Native() for i in range(1000)] + assert [r() for r in refs] == [None] * 1000 + assert len(keep) == 1000 + +[file interpbase.py] +class Base: + def __init__(self) -> None: + self.y = 2 + +[file driver.py] +import gc +import weakref +from native import Open, test_implicit_weakref_support, test_no_dangling_refs + +test_implicit_weakref_support() +test_no_dangling_refs() + +# An interpreted subclass of a native class with weakref support shares the slot. +class ISub(Open): + pass + +assert ISub.__weakrefoffset__ == Open.__weakrefoffset__ +obj = ISub() +r = weakref.ref(obj) +assert r() is obj +del obj +gc.collect() +assert r() is None From 44d2aaa4d77f0c6746e9ed048ca34c15315e4a3c Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 9 Nov 2026 11:32:49 +0000 Subject: [PATCH 2/2] Address feedback --- mypyc/codegen/emitclass.py | 15 +++++---------- mypyc/ir/class_ir.py | 13 ++++++++++++- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/mypyc/codegen/emitclass.py b/mypyc/codegen/emitclass.py index 1ef8ff5269369..a9d973425aa12 100644 --- a/mypyc/codegen/emitclass.py +++ b/mypyc/codegen/emitclass.py @@ -339,7 +339,7 @@ def generate_class( # Weak references to a dead object must be cleared in tp_dealloc, or they will # resurrect freed memory. generate_dealloc_slots = ( - generate_full or managed_dict or needs_builtin_dict_cleanup or has_weakrefs(cl) + generate_full or managed_dict or needs_builtin_dict_cleanup or cl.has_weakref_list() ) if generate_dealloc_slots: fields["tp_dealloc"] = f"(destructor){name_prefix}_dealloc" @@ -417,7 +417,7 @@ def emit_line() -> None: # the base class slots would overlap with fields of our object struct, which # doesn't model the layout of the non-native base class at all. needs_own_weak_slot = ( - emitter.capi_version < (3, 12) and has_weakrefs(cl) and not cl.has_weakref_slot() + emitter.capi_version < (3, 12) and cl.has_weakref_list() and not cl.has_weakref_slot() ) emitter.emit_lines( f"PyMemberDef {members_name}[] = {{", @@ -537,7 +537,7 @@ def emit_line() -> None: fields["tp_call"] = "PyVectorcall_Call" if managed_dict: flags.append("Py_TPFLAGS_MANAGED_DICT") - if has_weakrefs(cl) and not cl.has_weakref_slot(): + if cl.has_weakref_list() and not cl.has_weakref_slot(): # The pre-header has room for both __dict__ and the weak reference list, so # this is free. The flag is usually inherited from the base class, but not # if the base class doesn't support weak references (e.g. abc.ABC). @@ -1175,7 +1175,7 @@ def generate_dealloc_for_class( emitter.emit_line("}") if not cl.is_acyclic: emitter.emit_line("PyObject_GC_UnTrack(self);") - if has_weakrefs(cl): + if cl.has_weakref_list(): # Invalidate all weak references to the object, and call their callbacks. # This must happen after the finalizer has run, and before any of the # attributes are cleared. @@ -1370,7 +1370,7 @@ def generate_getseters_table(cl: ClassIR, name: str, emitter: Emitter) -> None: if cl.has_dict: emitter.emit_line('{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},') - if has_weakrefs(cl): + if cl.has_weakref_list(): # Even if a non-native base class has a __weakref__ descriptor, we can't use it, # since it uses the weak reference list offset of the base class. emitter.emit_line('{"__weakref__", CPy_GetWeakrefs, NULL},') @@ -1685,11 +1685,6 @@ def has_managed_dict(cl: ClassIR, emitter: Emitter) -> bool: ) -def has_weakrefs(cl: ClassIR) -> bool: - """Do instances of a native class have a weak reference list (somewhere)?""" - return cl.is_ext_class and not cl.is_trait and cl.supports_weakrefs() - - def native_class_doc_initializer(cl: ClassIR) -> str: init_fn = cl.get_method("__init__") if init_fn is not None: diff --git a/mypyc/ir/class_ir.py b/mypyc/ir/class_ir.py index 7c0adc8c2c609..1b06424fbbcc0 100644 --- a/mypyc/ir/class_ir.py +++ b/mypyc/ir/class_ir.py @@ -329,7 +329,7 @@ def needs_getseters_table(self) -> bool: or not self.is_generated or self.has_dict # For the __weakref__ getset - or (self.is_ext_class and not self.is_trait and self.supports_weakrefs()) + or self.has_weakref_list() ) def attrs_are_thread_confined(self) -> bool: @@ -525,6 +525,17 @@ def supports_weakrefs(self) -> bool: return False return self.inherits_python or any(ci._weakrefs for ci in self.mro) + def has_weakref_list(self) -> bool: + """Is this a native class with instances that have a weak reference list? + + This is false for non-native classes, even though they support weak + references, since CPython manages the list for them. For native classes, the + list is either a field of the object struct (see has_weakref_slot()), or + it's stored next to __dict__ (at tp_weaklistoffset): either right after the + object struct (before 3.12) or in the managed pre-header (3.12+). + """ + return self.is_ext_class and not self.is_trait and self.supports_weakrefs() + def has_weakref_slot(self) -> bool: """Is the weak reference list stored in a field of the object struct?