Skip to content

WIP: new mypyc primitive for weakref.ref.__call__ #19145

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
5b87bdc
feat: new primitive for `weakref.__call__`
BobTheBuidler Aug 4, 2025
d0ee2f0
fix: error: "ReferenceType[object]" not callable
BobTheBuidler Aug 4, 2025
da46e55
fix: return type
BobTheBuidler Aug 4, 2025
56a6ef5
fix: testdata
BobTheBuidler Aug 4, 2025
6eb7b5a
fix: use custom_op
BobTheBuidler Aug 4, 2025
1de78bf
fix: add CPyWeakref_GetRef to headers
BobTheBuidler Aug 4, 2025
e320430
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 4, 2025
47ab0d4
Update weakref.pyi
BobTheBuidler Aug 4, 2025
1f3d146
Update mapper.py
BobTheBuidler Aug 5, 2025
c943f4f
fix IR for new mapping
BobTheBuidler Aug 5, 2025
9ead556
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 5, 2025
1a14d97
Update specialize.py
BobTheBuidler Aug 5, 2025
82483eb
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 5, 2025
7c2d36b
fix: missing import
BobTheBuidler Aug 6, 2025
0f8c2f7
Merge branch 'weakref-call' of https://github.com/BobTheBuidler/mypy …
BobTheBuidler Aug 6, 2025
6e8b738
fix mypy err
BobTheBuidler Aug 6, 2025
fe27d2c
Update specialize.py
BobTheBuidler Aug 6, 2025
533501f
Update emit.py
BobTheBuidler Aug 6, 2025
828447b
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 6, 2025
3b51373
Update emit.py
BobTheBuidler Aug 6, 2025
6acc2c9
Merge branch 'master' into weakref-call
BobTheBuidler Aug 10, 2025
fab0733
Merge branch 'master' into weakref-call
BobTheBuidler Aug 13, 2025
6a532b2
Merge branch 'master' into weakref-call
BobTheBuidler Aug 14, 2025
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
9 changes: 9 additions & 0 deletions mypyc/ir/rtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,11 @@ def __hash__(self) -> int:
# Python range object.
range_rprimitive: Final = RPrimitive("builtins.range", is_unboxed=False, is_refcounted=True)

# Python weak reference object
weakref_rprimitive: Final = RPrimitive(
"weakref.ReferenceType", is_unboxed=False, is_refcounted=True
)


def is_tagged(rtype: RType) -> TypeGuard[RPrimitive]:
return rtype is int_rprimitive or rtype is short_int_rprimitive
Expand Down Expand Up @@ -644,6 +649,10 @@ def is_immutable_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
)


def is_weakref_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
return isinstance(rtype, RPrimitive) and rtype.name == "weakref.ReferenceType"


class TupleNameVisitor(RTypeVisitor[str]):
"""Produce a tuple name based on the concrete representations of types."""

Expand Down
3 changes: 3 additions & 0 deletions mypyc/irbuild/mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
str_rprimitive,
tuple_rprimitive,
uint8_rprimitive,
weakref_rprimitive,
)


Expand Down Expand Up @@ -102,6 +103,8 @@ def type_to_rtype(self, typ: Type | None) -> RType:
return tuple_rprimitive # Varying-length tuple
elif typ.type.fullname == "builtins.range":
return range_rprimitive
elif typ.type.fullname == "weakref.ReferenceType":
return weakref_rprimitive
elif typ.type in self.type_to_ir:
inst = RInstance(self.type_to_ir[typ.type])
# Treat protocols as Union[protocol, object], so that we can do fast
Expand Down
4 changes: 4 additions & 0 deletions mypyc/irbuild/specialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
is_int_rprimitive,
is_list_rprimitive,
is_uint8_rprimitive,
is_weakref_rprimitive,
list_rprimitive,
set_rprimitive,
str_rprimitive,
Expand Down Expand Up @@ -103,6 +104,7 @@
str_encode_utf8_strict,
)
from mypyc.primitives.tuple_ops import isinstance_tuple, new_tuple_set_item_op
from mypyc.primitives.weakref_ops import weakref_deref_op

# Specializers are attempted before compiling the arguments to the
# function. Specializers can return None to indicate that they failed
Expand Down Expand Up @@ -140,6 +142,8 @@ def apply_function_specialization(
builder: IRBuilder, expr: CallExpr, callee: RefExpr
) -> Value | None:
"""Invoke the Specializer callback for a function if one has been registered"""
if is_weakref_rprimitive(builder.node_type(callee)) and len(expr.args) == 0:
return builder.call_c(weakref_deref_op, [builder.accept(expr.callee)], expr.line)
return _apply_specialization(builder, expr, callee, callee.fullname)


Expand Down
1 change: 1 addition & 0 deletions mypyc/lib-rt/CPy.h
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,7 @@ PyObject *CPySingledispatch_RegisterFunction(PyObject *singledispatch_func, PyOb

PyObject *CPy_GetAIter(PyObject *obj);
PyObject *CPy_GetANext(PyObject *aiter);
PyObject *CPyWeakref_GetRef(PyObject *ref);
void CPy_SetTypeAliasTypeComputeFunction(PyObject *alias, PyObject *compute_value);
void CPyTrace_LogEvent(const char *location, const char *line, const char *op, const char *details);

Expand Down
15 changes: 15 additions & 0 deletions mypyc/lib-rt/misc_ops.c
Original file line number Diff line number Diff line change
Expand Up @@ -1113,3 +1113,18 @@ void CPy_SetImmortal(PyObject *obj) {
}

#endif


PyObject *CPyWeakref_GetRef(PyObject *ref)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need a new C function because of the variability of PyWeakref_GetRef

{
PyObject *obj = NULL;
int success = PyWeakref_GetRef(ref, &obj);
if (success == -1) {
return NULL;
} else if (obj == NULL) {
Py_INCREF(Py_None);
return Py_None;
} else {
return obj;
}
}
16 changes: 12 additions & 4 deletions mypyc/primitives/weakref_ops.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
from mypyc.ir.ops import ERR_MAGIC
from mypyc.ir.rtypes import object_rprimitive, pointer_rprimitive
from mypyc.primitives.registry import function_op
from mypyc.ir.rtypes import object_rprimitive, pointer_rprimitive, weakref_rprimitive
from mypyc.primitives.registry import custom_op, function_op

# Weakref operations

new_ref_op = function_op(
name="weakref.ReferenceType",
arg_types=[object_rprimitive],
return_type=object_rprimitive,
return_type=weakref_rprimitive,
c_function_name="PyWeakref_NewRef",
extra_int_constants=[(0, pointer_rprimitive)],
error_kind=ERR_MAGIC,
Expand All @@ -16,7 +16,15 @@
new_ref__with_callback_op = function_op(
name="weakref.ReferenceType",
arg_types=[object_rprimitive, object_rprimitive],
return_type=object_rprimitive,
return_type=weakref_rprimitive,
c_function_name="PyWeakref_NewRef",
error_kind=ERR_MAGIC,
)

# TODO: generate specialized versions of this that return the properr rtype
weakref_deref_op = custom_op(
arg_types=[weakref_rprimitive],
return_type=object_rprimitive,
c_function_name="CPyWeakref_GetRef",
error_kind=ERR_MAGIC,
)
44 changes: 32 additions & 12 deletions mypyc/test-data/irbuild-weakref.test
Original file line number Diff line number Diff line change
Expand Up @@ -2,50 +2,70 @@
import weakref
from typing import Any, Callable
def f(x: object) -> object:
return weakref.ref(x)
ref = weakref.ref(x)
return ref()

[out]
def f(x):
x, r0 :: object
x :: object
r0, ref :: weakref.ReferenceType
r1 :: object
L0:
r0 = PyWeakref_NewRef(x, 0)
return r0
ref = r0
r1 = CPyWeakref_GetRef(ref)
return r1

[case testWeakrefRefCallback]
import weakref
from typing import Any, Callable
def f(x: object, cb: Callable[[object], Any]) -> object:
return weakref.ref(x, cb)
ref = weakref.ref(x, cb)
return ref()

[out]
def f(x, cb):
x, cb, r0 :: object
x, cb :: object
r0, ref :: weakref.ReferenceType
r1 :: object
L0:
r0 = PyWeakref_NewRef(x, cb)
return r0
ref = r0
r1 = CPyWeakref_GetRef(ref)
return r1

[case testFromWeakrefRef]
from typing import Any, Callable
from weakref import ref
def f(x: object) -> object:
return ref(x)
r = ref(x)
return r()

[out]
def f(x):
x, r0 :: object
x :: object
r0, r :: weakref.ReferenceType
r1 :: object
L0:
r0 = PyWeakref_NewRef(x, 0)
return r0
r = r0
r1 = CPyWeakref_GetRef(r)
return r1

[case testFromWeakrefRefCallback]
from typing import Any, Callable
from weakref import ref
def f(x: object, cb: Callable[[object], Any]) -> object:
return ref(x, cb)
r = ref(x, cb)
return r()

[out]
def f(x, cb):
x, cb, r0 :: object
x, cb :: object
r0, r :: weakref.ReferenceType
r1 :: object
L0:
r0 = PyWeakref_NewRef(x, cb)
return r0
r = r0
r1 = CPyWeakref_GetRef(r)
return r1
3 changes: 2 additions & 1 deletion test-data/unit/lib-stub/weakref.pyi
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from collections.abc import Callable
from typing import Any, Generic, TypeVar
from typing import Any, Generic, Optional, TypeVar
from typing_extensions import Self

_T = TypeVar("_T")

class ReferenceType(Generic[_T]): # "weakref"
__callback__: Callable[[Self], Any]
def __new__(cls, o: _T, callback: Callable[[Self], Any] | None = ..., /) -> Self: ...
def __call__(self) -> Optional[_T]: ...

ref = ReferenceType
Loading