Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 51 additions & 16 deletions mypyc/codegen/emitclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 cl.has_weakref_list()
)
if generate_dealloc_slots:
fields["tp_dealloc"] = f"(destructor){name_prefix}_dealloc"
if not cl.is_acyclic:
Expand Down Expand Up @@ -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 cl.has_weakref_list() 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)
Expand Down Expand Up @@ -524,6 +537,11 @@ def emit_line() -> None:
fields["tp_call"] = "PyVectorcall_Call"
if managed_dict:
flags.append("Py_TPFLAGS_MANAGED_DICT")
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).
flags.append("Py_TPFLAGS_MANAGED_WEAKREF")
fields["tp_flags"] = " | ".join(flags)

fields["tp_doc"] = f"PyDoc_STR({native_class_doc_initializer(cl)})"
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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("}")

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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 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.
#
# 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
Expand Down Expand Up @@ -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 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},')

emitter.emit_line("{NULL} /* Sentinel */")
emitter.emit_line("};")
Expand Down
59 changes: 59 additions & 0 deletions mypyc/doc/native_classes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
----------------

Expand Down
56 changes: 55 additions & 1 deletion mypyc/ir/class_ir.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.has_weakref_list()
)

def attrs_are_thread_confined(self) -> bool:
"""Can these attributes safely use plain access in free-threaded builds?
Expand Down Expand Up @@ -498,6 +507,49 @@ 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_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?
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,
Expand All @@ -510,6 +562,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,
Expand Down Expand Up @@ -581,6 +634,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"]
Expand Down
38 changes: 38 additions & 0 deletions mypyc/irbuild/prepare.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
NameExpr,
OverloadedFuncDef,
RefExpr,
StrExpr,
SymbolNode,
TypeAlias,
TypeInfo,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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"]
Expand Down
Loading
Loading