Skip to content

Commit 95cc933

Browse files
committed
[mypyc] Fix *args and **kwargs in super() calls to native methods
1 parent 47f4844 commit 95cc933

10 files changed

Lines changed: 408 additions & 30 deletions

File tree

‎mypyc/codegen/emitclass.py‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
generate_len_wrapper,
2626
generate_richcompare_wrapper,
2727
generate_set_del_item_wrapper,
28+
is_fastcall_supported,
2829
)
2930
from mypyc.common import (
3031
BITMAP_BITS,
@@ -1116,11 +1117,15 @@ def generate_methods_table(
11161117
continue
11171118
emitter.emit_line(f'{{"{fn.name}",')
11181119
emitter.emit_line(f" (PyCFunction){PREFIX}{fn.cname(emitter.names)},")
1119-
flags = ["METH_FASTCALL", "METH_KEYWORDS"]
1120-
if fn.decl.kind == FUNC_STATICMETHOD:
1121-
flags.append("METH_STATIC")
1122-
elif fn.decl.kind == FUNC_CLASSMETHOD:
1120+
if is_fastcall_supported(fn, emitter.capi_version):
1121+
flags = ["METH_FASTCALL", "METH_KEYWORDS"]
1122+
else:
1123+
flags = ["METH_VARARGS", "METH_KEYWORDS"]
1124+
if fn.decl.kind == FUNC_CLASSMETHOD or fn.name == "__new__":
1125+
# The wrapper function of __new__ takes the class as self, like a class method.
11231126
flags.append("METH_CLASS")
1127+
elif fn.decl.kind == FUNC_STATICMETHOD:
1128+
flags.append("METH_STATIC")
11241129

11251130
doc = native_function_doc_initializer(fn)
11261131
emitter.emit_line(" {}, PyDoc_STR({})}},".format(" | ".join(flags), doc))

‎mypyc/codegen/emitmodule.py‎

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
from mypyc.codegen.emitwrapper import (
4242
generate_legacy_wrapper_function,
4343
generate_wrapper_function,
44+
is_fastcall_supported,
4445
legacy_wrapper_function_header,
4546
wrapper_function_header,
4647
)
@@ -1726,16 +1727,6 @@ def visit(item: T) -> None:
17261727
return result
17271728

17281729

1729-
def is_fastcall_supported(fn: FuncIR, capi_version: tuple[int, int]) -> bool:
1730-
if fn.class_name is not None:
1731-
if fn.name == "__call__":
1732-
# We can use vectorcalls (PEP 590) when supported
1733-
return True
1734-
# TODO: Support fastcall for __init__ and __new__.
1735-
return fn.name != "__init__" and fn.name != "__new__"
1736-
return True
1737-
1738-
17391730
def collect_literals(fn: FuncIR, literals: Literals) -> None:
17401731
"""Store all Python literal object refs in fn.
17411732

‎mypyc/codegen/emitwrapper.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,17 @@
3737
)
3838
from mypyc.namegen import NameGenerator
3939

40+
41+
def is_fastcall_supported(fn: FuncIR, capi_version: tuple[int, int]) -> bool:
42+
if fn.class_name is not None:
43+
if fn.name == "__call__":
44+
# We can use vectorcalls (PEP 590) when supported
45+
return True
46+
# TODO: Support fastcall for __init__ and __new__.
47+
return fn.name != "__init__" and fn.name != "__new__"
48+
return True
49+
50+
4051
# Generic vectorcall wrapper functions (Python 3.7+)
4152
#
4253
# A wrapper function has a signature like this:

‎mypyc/irbuild/expression.py‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -507,7 +507,13 @@ def translate_method_call(builder: IRBuilder, expr: CallExpr, callee: MemberExpr
507507
and isinstance(callee.expr.node, TypeInfo)
508508
and callee.expr.node in builder.mapper.type_to_ir
509509
and builder.mapper.type_to_ir[callee.expr.node].has_method(callee.name)
510-
and all(kind in (ARG_POS, ARG_NAMED) for kind in expr.arg_kinds)
510+
and (
511+
all(kind in (ARG_POS, ARG_NAMED) for kind in expr.arg_kinds)
512+
# A lookup of __init__ would find the slot wrapper, and the __init__ slot of
513+
# a native class usually does nothing (__init__ is called when the object is
514+
# created instead).
515+
or is_native_init(builder.mapper.type_to_ir[callee.expr.node], callee.name)
516+
)
511517
):
512518
# Call a method via the *class*
513519
assert isinstance(callee.expr.node, TypeInfo), callee.expr.node
@@ -553,6 +559,15 @@ def translate_method_call(builder: IRBuilder, expr: CallExpr, callee: MemberExpr
553559
)
554560

555561

562+
def is_native_init(ir: ClassIR, name: str) -> bool:
563+
"""Is this the __init__ method of the class, and does an extension class define it?"""
564+
if name == "__init__":
565+
for base in ir.mro:
566+
if name in base.method_decls:
567+
return base.is_ext_class
568+
return False
569+
570+
556571
def call_classmethod(builder: IRBuilder, ir: ClassIR, expr: CallExpr, callee: MemberExpr) -> Value:
557572
decl = ir.method_decl(callee.name)
558573
args = []

‎mypyc/irbuild/ll_builder.py‎

Lines changed: 62 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@
149149
from mypyc.primitives.generic_ops import (
150150
generic_len_op,
151151
generic_ssize_t_len_op,
152+
method_wrapper_op,
152153
py_call_op,
153154
py_call_with_kwargs_op,
154155
py_call_with_posargs_op,
@@ -1365,12 +1366,36 @@ def call(
13651366
arguments used to track the presence of values for certain arguments. By
13661367
default, the values of the bitmap arguments are inferred from args.
13671368
"""
1369+
if decl.class_name is not None and not self.can_pass_args_natively(
1370+
arg_kinds, arg_names, decl.sig
1371+
):
1372+
return self.call_method_wrapper(decl, args, arg_kinds, arg_names, line)
13681373
# Normalize args to positionals.
13691374
args = self.native_args_to_positional(
13701375
args, arg_kinds, arg_names, decl.sig, line, bitmap_args=bitmap_args
13711376
)
13721377
return self.add(Call(decl, args, line))
13731378

1379+
def call_method_wrapper(
1380+
self,
1381+
decl: FuncDecl,
1382+
args: Sequence[Value],
1383+
arg_kinds: list[ArgKind],
1384+
arg_names: Sequence[str | None],
1385+
line: int,
1386+
) -> Value:
1387+
"""Call a native method through its wrapper function, which parses the arguments.
1388+
1389+
This is slower than a native call, but like a native call it calls the given
1390+
method without looking it up. A lookup could find an override, or the __init__
1391+
slot wrapper of a native class, which usually does nothing (__init__ is called
1392+
when the object is created instead).
1393+
"""
1394+
typ = self.load_native_type_object(f"{decl.module_name}.{decl.class_name}")
1395+
wrapper = self.call_c(method_wrapper_op, [typ, self.load_str(decl.name)], line)
1396+
result = self.py_call(wrapper, list(args), line, arg_kinds, arg_names)
1397+
return self.coerce(result, decl.sig.ret_type, line)
1398+
13741399
def native_args_to_positional(
13751400
self,
13761401
args: Sequence[Value],
@@ -1390,22 +1415,9 @@ def native_args_to_positional(
13901415
and coerce arguments to the appropriate type.
13911416
"""
13921417

1393-
sig_args = sig.args
1418+
sig_args = sig.real_args()
13941419
n = sig.num_bitmap_args
1395-
if n:
1396-
sig_args = sig_args[:-n]
1397-
1398-
sig_arg_kinds = [arg.kind for arg in sig_args]
1399-
sig_arg_names = [arg.name for arg in sig_args]
1400-
1401-
concrete_kinds = [concrete_arg_kind(arg_kind) for arg_kind in arg_kinds]
1402-
formal_to_actual = map_actuals_to_formals(
1403-
concrete_kinds,
1404-
arg_names,
1405-
sig_arg_kinds,
1406-
sig_arg_names,
1407-
lambda n: AnyType(TypeOfAny.special_form),
1408-
)
1420+
formal_to_actual = self.map_native_call_args(arg_kinds, arg_names, sig)
14091421

14101422
# First scan for */** and construct those
14111423
has_star = has_star2 = False
@@ -1465,6 +1477,41 @@ def native_args_to_positional(
14651477

14661478
return output_args
14671479

1480+
def map_native_call_args(
1481+
self, arg_kinds: list[ArgKind], arg_names: Sequence[str | None], sig: FuncSignature
1482+
) -> list[list[int]]:
1483+
"""Map the arguments of a call to the arguments of a native function.
1484+
1485+
Return the indexes of the call arguments that each argument of the function
1486+
(excluding bitmap arguments) may get its value from.
1487+
"""
1488+
sig_args = sig.real_args()
1489+
return map_actuals_to_formals(
1490+
[concrete_arg_kind(arg_kind) for arg_kind in arg_kinds],
1491+
arg_names,
1492+
[arg.kind for arg in sig_args],
1493+
[arg.name for arg in sig_args],
1494+
lambda n: AnyType(TypeOfAny.special_form),
1495+
)
1496+
1497+
def can_pass_args_natively(
1498+
self, arg_kinds: list[ArgKind], arg_names: Sequence[str | None], sig: FuncSignature
1499+
) -> bool:
1500+
"""Can native_args_to_positional() prepare the arguments of a call?
1501+
1502+
It can't unpack a *args or **kwargs argument, since we don't know at compile
1503+
time which arguments of the function the items are for. It can only pass one
1504+
on as a whole to the *args or **kwargs argument of the function.
1505+
"""
1506+
if not any(kind.is_star() for kind in arg_kinds):
1507+
return True
1508+
formal_to_actual = self.map_native_call_args(arg_kinds, arg_names, sig)
1509+
for formal, actuals in zip(sig.real_args(), formal_to_actual):
1510+
for actual in actuals:
1511+
if arg_kinds[actual].is_star() and arg_kinds[actual] != formal.kind:
1512+
return False
1513+
return True
1514+
14681515
def gen_method_call(
14691516
self,
14701517
base: Value,

‎mypyc/lib-rt/CPy.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -706,6 +706,7 @@ PyObject *CPyNumber_Power(PyObject *base, PyObject *index);
706706
PyObject *CPyNumber_InPlacePower(PyObject *base, PyObject *index);
707707
// An omitted slice bound is represented by CPY_INT_TAG.
708708
PyObject *CPyObject_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end);
709+
PyObject *CPy_GetMethodWrapper(PyObject *type, PyObject *name);
709710

710711

711712
// List operations

‎mypyc/lib-rt/generic_ops.c‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,3 +84,30 @@ PyObject *CPy_SetupObject(PyObject *type) {
8484
PyErr_SetString(PyExc_RuntimeError, "Internal mypyc error: Unable to find object setup function");
8585
return NULL;
8686
}
87+
88+
// Return a callable for the wrapper function of a method that a native class defines.
89+
// It takes the same arguments as the method when looked up on the class (including self
90+
// or cls). Unlike an attribute lookup, this doesn't find an override in a subclass or a
91+
// slot wrapper. The __init__ slot of a native class usually does nothing.
92+
PyObject *CPy_GetMethodWrapper(PyObject *type, PyObject *name) {
93+
PyTypeObject *tp = (PyTypeObject *)type;
94+
PyMethodDef *def = tp->tp_methods;
95+
const char *name_str = PyUnicode_AsUTF8(name);
96+
if (name_str == NULL) {
97+
return NULL;
98+
}
99+
for (; def != NULL && def->ml_name != NULL; def++) {
100+
if (strcmp(name_str, def->ml_name) == 0) {
101+
if (def->ml_flags & METH_STATIC) {
102+
return PyCFunction_NewEx(def, NULL, NULL);
103+
}
104+
if (def->ml_flags & METH_CLASS) {
105+
return PyDescr_NewClassMethod(tp, def);
106+
}
107+
return PyDescr_NewMethod(tp, def);
108+
}
109+
}
110+
111+
PyErr_SetString(PyExc_RuntimeError, "Internal mypyc error: Unable to find method wrapper");
112+
return NULL;
113+
}

‎mypyc/primitives/generic_ops.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,3 +432,12 @@
432432
c_function_name="CPy_SetupObject",
433433
error_kind=ERR_MAGIC,
434434
)
435+
436+
# Get a callable for the wrapper function of a method that a native class defines
437+
# (arguments: type object, method name).
438+
method_wrapper_op = custom_op(
439+
arg_types=[object_rprimitive, object_rprimitive],
440+
return_type=object_rprimitive,
441+
c_function_name="CPy_GetMethodWrapper",
442+
error_kind=ERR_MAGIC,
443+
)

‎mypyc/test-data/irbuild-classes.test‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -682,6 +682,79 @@ def D.g(cls, x):
682682
L0:
683683
return x
684684

685+
[case testNativeCallWithUnpackedArgs]
686+
from typing import Any
687+
688+
class A:
689+
def f(self, x: int, y: int = 0) -> int:
690+
return x + y
691+
692+
def g(self, *args: Any, **kwargs: Any) -> int:
693+
return len(args)
694+
695+
class B(A):
696+
def call_f(self, *args: int) -> int:
697+
# The items are for ordinary arguments, so the wrapper function has to unpack them
698+
return super().f(*args)
699+
700+
def call_g(self, *args: Any, **kwargs: Any) -> int:
701+
return super().g(*args, **kwargs)
702+
[out]
703+
def A.f(self, x, y):
704+
self :: __main__.A
705+
x, y, r0 :: int
706+
L0:
707+
if is_error(y) goto L1 else goto L2
708+
L1:
709+
y = 0
710+
L2:
711+
r0 = CPyTagged_Add(x, y)
712+
return r0
713+
def A.g(self, args, kwargs):
714+
self :: __main__.A
715+
args :: tuple
716+
kwargs :: dict
717+
r0 :: native_int
718+
r1 :: short_int
719+
L0:
720+
r0 = var_object_size args
721+
r1 = r0 << 1
722+
return r1
723+
def B.call_f(self, args):
724+
self :: __main__.B
725+
args :: tuple
726+
r0 :: object
727+
r1 :: str
728+
r2 :: object
729+
r3 :: list
730+
r4 :: ptr
731+
r5 :: object
732+
r6 :: tuple
733+
r7 :: object
734+
r8 :: int
735+
L0:
736+
r0 = __main__.A :: type
737+
r1 = 'f'
738+
r2 = CPy_GetMethodWrapper(r0, r1)
739+
r3 = PyList_New(1)
740+
r4 = list_items r3
741+
buf_init_item r4, 0, self
742+
keep_alive r3
743+
r5 = CPyList_Extend(r3, args)
744+
r6 = PyList_AsTuple(r3)
745+
r7 = PyObject_CallObject(r2, r6)
746+
r8 = unbox(int, r7)
747+
return r8
748+
def B.call_g(self, args, kwargs):
749+
self :: __main__.B
750+
args :: tuple
751+
kwargs, r0 :: dict
752+
r1 :: int
753+
L0:
754+
r0 = PyDict_Copy(kwargs)
755+
r1 = A.g(self, args, r0)
756+
return r1
757+
685758
[case testCannotAssignToClsArgument]
686759
from typing import Any, cast
687760

0 commit comments

Comments
 (0)