Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 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
536d920
Merge branch 'master' into weakref-call
BobTheBuidler Aug 17, 2025
a047c78
Merge branch 'master' into weakref-call
BobTheBuidler Aug 20, 2025
40f1151
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 20, 2025
52c8ca9
Merge branch 'master' into weakref-call
BobTheBuidler Aug 23, 2025
cbd5b77
Merge branch 'master' into weakref-call
BobTheBuidler Sep 7, 2025
1bd5459
Merge branch 'master' into weakref-call
BobTheBuidler Sep 13, 2025
8029bce
Merge branch 'master' into weakref-call
BobTheBuidler Sep 30, 2025
fb4f81c
Merge branch 'master' into weakref-call
BobTheBuidler Oct 4, 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
10 changes: 10 additions & 0 deletions mypyc/ir/rtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,12 @@ 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
)


KNOWN_NATIVE_TYPES: Final = {
name: RPrimitive(name, is_unboxed=False, is_refcounted=True)
for name in ["native_internal.Buffer"]
Expand Down Expand Up @@ -653,6 +659,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 @@ -47,6 +47,7 @@
str_rprimitive,
tuple_rprimitive,
uint8_rprimitive,
weakref_rprimitive,
)


Expand Down Expand Up @@ -103,6 +104,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 @@ -70,6 +70,7 @@
is_int_rprimitive,
is_list_rprimitive,
is_uint8_rprimitive,
is_weakref_rprimitive,
list_rprimitive,
object_rprimitive,
set_rprimitive,
Expand Down Expand Up @@ -114,6 +115,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 @@ -151,6 +153,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:
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think there's gotta be a better place for this, but I wasn't able to figure out how to make function_op or method_op work with the __call__ method

Copy link
Contributor Author

@BobTheBuidler BobTheBuidler Sep 8, 2025

Choose a reason for hiding this comment

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

@JukkaL There's also one open question here blocking me, and then I can finish this up

edit: hmm. Well it was working, some recent change on master appears to have broken this one. So I guess we have 2 open questions as I don't particularly understand any of the casting code.

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 @@ -946,6 +946,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 @@ -1138,3 +1138,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,7 @@
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,
)
Expand All @@ -38,3 +38,11 @@
c_function_name="PyWeakref_NewProxy",
error_kind=ERR_MAGIC,
)

# TODO: generate specialized versions of this that return the proper 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,53 +2,73 @@
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

[case testWeakrefProxy]
import weakref
Expand Down
Loading