Skip to content

Commit ce360d8

Browse files
committed
[mypyc] Fix decorated and overloaded __init__ in native classes
1 parent 318bc57 commit ce360d8

8 files changed

Lines changed: 719 additions & 5 deletions

File tree

‎mypyc/analysis/attrdefined.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ def analyze_always_defined_attrs_in_class(cl: ClassIR, seen: set[ClassIR]) -> No
148148
for base in cl.mro[1:]:
149149
analyze_always_defined_attrs_in_class(base, seen)
150150

151-
m = cl.get_method("__init__")
151+
m = cl.get_native_init()
152152
if m is None:
153153
cl._always_initialized_attrs = cl.attrs_with_defaults.copy()
154154
cl._sometimes_initialized_attrs = cl.attrs_with_defaults.copy()

‎mypyc/codegen/emitclass.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -354,8 +354,8 @@ def emit_line() -> None:
354354
# values, we need to call it during initialization.
355355
defaults_fn = cl.get_method(MYPYC_DEFAULTS_SETUP)
356356

357-
# If there is a __init__ method, we'll use it in the native constructor.
358-
init_fn = cl.get_method("__init__")
357+
# If there is a native __init__ method, we'll use it in the native constructor.
358+
init_fn = cl.get_native_init()
359359

360360
# Fill out slots in the type object from dunder methods.
361361
fields.update(generate_slots(cl, SLOT_DEFS, emitter))
@@ -460,7 +460,7 @@ def emit_line() -> None:
460460
emitter.emit_line(native_function_header(cl.ctor, emitter) + ";")
461461

462462
emit_line()
463-
init_fn = cl.get_method("__init__")
463+
init_fn = cl.get_native_init()
464464
generate_new_for_class(cl, new_name, vtable_name, setup_name, init_fn, emitter)
465465
emit_line()
466466

@@ -950,6 +950,8 @@ def generate_init_for_class(cl: ClassIR, init_fn: FuncIR, emitter: Emitter) -> s
950950
or cl.builtin_base
951951
or cl.has_method("__new__")
952952
or cl.has_non_native_new()
953+
# tp_new doesn't call a decorated __init__.
954+
or cl.get_native_init() is None
953955
):
954956
emitter.emit_line(
955957
f"return {emitter.wrapper_function_call(init_fn.decl)}"

‎mypyc/ir/class_ir.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,18 @@ def get_method(self, name: str, *, prefer_method: bool = False) -> FuncIR | None
435435
res = self.get_method_and_class(name, prefer_method=prefer_method)
436436
return res[0] if res else None
437437

438+
def get_native_init(self) -> FuncIR | None:
439+
"""Return the __init__ method that is called natively to initialize instances, if any.
440+
441+
A decorated __init__ isn't one. Like any decorated method it has no method
442+
declaration, since only the decorated callable in the type dict can be called.
443+
Instances are then initialized through tp_init, as if __init__ wasn't native.
444+
"""
445+
res = self.get_method_and_class("__init__")
446+
if res is None or "__init__" not in res[1].method_decls:
447+
return None
448+
return res[0]
449+
438450
def has_method_decl(self, name: str) -> bool:
439451
return any(name in ir.method_decls for ir in self.mro)
440452

‎mypyc/irbuild/expression.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -606,6 +606,7 @@ def translate_method_call(builder: IRBuilder, expr: CallExpr, callee: MemberExpr
606606
and isinstance(callee.expr.node, TypeInfo)
607607
and callee.expr.node in builder.mapper.type_to_ir
608608
and builder.mapper.type_to_ir[callee.expr.node].has_method(callee.name)
609+
and not is_non_native_method(builder, callee.expr.node.mro, callee.name)
609610
and all(kind in (ARG_POS, ARG_NAMED) for kind in expr.arg_kinds)
610611
):
611612
# Call a method via the *class*
@@ -680,6 +681,20 @@ def call_classmethod(builder: IRBuilder, ir: ClassIR, expr: CallExpr, callee: Me
680681
)
681682

682683

684+
def is_non_native_method(builder: IRBuilder, mro: list[TypeInfo], name: str) -> bool:
685+
"""Does a method lookup in the MRO find a method of a compiled class that isn't native?
686+
687+
A decorated method is one. It has no method declaration, since only the decorated
688+
callable in the type dict can be called. A search for a native method must not skip
689+
it and use a method of a class that comes later in the MRO.
690+
"""
691+
for info in mro:
692+
if name in info.names:
693+
ir = builder.mapper.type_to_ir.get(info)
694+
return ir is not None and name not in ir.method_decls
695+
return False
696+
697+
683698
def translate_super_method_call(builder: IRBuilder, expr: CallExpr, callee: SuperExpr) -> Value:
684699
if callee.info is None or (len(callee.call.args) != 0 and len(callee.call.args) != 2):
685700
return translate_call(builder, expr, callee)
@@ -706,6 +721,9 @@ def translate_super_method_call(builder: IRBuilder, expr: CallExpr, callee: Supe
706721
else:
707722
self_var = implicit_super_arg(builder)
708723

724+
if is_non_native_method(builder, callee.info.mro[1:], callee.name):
725+
return translate_call(builder, expr, callee)
726+
709727
ir = builder.mapper.type_to_ir[callee.info]
710728
# Search for the method in the mro, skipping ourselves. We
711729
# determine targets of super calls to native methods statically.

‎mypyc/irbuild/prepare.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -866,6 +866,10 @@ def has_non_native_new(cdef: ClassDef, mapper: Mapper) -> bool:
866866
def prepare_init_method(cdef: ClassDef, ir: ClassIR, module_name: str, mapper: Mapper) -> None:
867867
# Set up a constructor decl
868868
init_node = cdef.info["__init__"].node
869+
if isinstance(init_node, OverloadedFuncDef):
870+
init_node = init_node.impl
871+
if isinstance(init_node, Decorator):
872+
init_node = init_node.func
869873

870874
new_node: SymbolNode | None = None
871875
new_symbol = cdef.info.get("__new__")
@@ -890,12 +894,15 @@ def prepare_init_method(cdef: ClassDef, ir: ClassIR, module_name: str, mapper: M
890894
defining_ir = mapper.type_to_ir.get(init_node.info)
891895
# If there is a nontrivial __init__ that wasn't defined in an
892896
# extension class, we need to make the constructor take *args,
893-
# **kwargs so it can call tp_init.
897+
# **kwargs so it can call tp_init. This includes a decorated
898+
# __init__, which has no method declaration since it isn't
899+
# called natively.
894900
if (
895901
(
896902
defining_ir is None
897903
or not defining_ir.is_ext_class
898904
or cdef.info["__init__"].plugin_generated
905+
or "__init__" not in defining_ir.method_decls
899906
)
900907
and init_node.info.fullname != "builtins.object"
901908
) or not args_match:

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

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -935,6 +935,168 @@ L0:
935935
r9 = PyObject_Vectorcall(r8, 0, 0, 0)
936936
return 1
937937

938+
[case testDecoratedInit_64bit]
939+
from typing import Any, Callable, TypeVar
940+
941+
F = TypeVar("F", bound=Callable[..., Any])
942+
943+
def deco(f: F) -> F:
944+
return f
945+
946+
class A:
947+
def __init__(self, x: int) -> None:
948+
pass
949+
950+
class B(A):
951+
@deco
952+
def __init__(self, x: int) -> None:
953+
super().__init__(x)
954+
955+
class C(B):
956+
def __init__(self, x: int) -> None:
957+
super().__init__(x)
958+
959+
class D(B):
960+
def __init__(self, x: int) -> None:
961+
B.__init__(self, x)
962+
963+
class E(B):
964+
pass
965+
966+
def f() -> None:
967+
B(1)
968+
E(2)
969+
[out]
970+
def deco(f):
971+
f :: object
972+
L0:
973+
return f
974+
def A.__init__(self, x):
975+
self :: __main__.A
976+
x :: int
977+
L0:
978+
return 1
979+
def B.__init__(self, x):
980+
self :: __main__.B
981+
x :: int
982+
r0 :: None
983+
L0:
984+
r0 = A.__init__(self, x)
985+
return 1
986+
def C.__init__(self, x):
987+
self :: __main__.C
988+
x :: int
989+
r0 :: object
990+
r1 :: str
991+
r2, r3 :: object
992+
r4 :: object[2]
993+
r5 :: object_ptr
994+
r6 :: object
995+
r7 :: str
996+
r8, r9 :: object
997+
r10 :: object[1]
998+
r11 :: object_ptr
999+
r12 :: object
1000+
L0:
1001+
r0 = builtins :: module
1002+
r1 = 'super'
1003+
r2 = CPyObject_GetAttr(r0, r1)
1004+
r3 = __main__.C :: type
1005+
r4 = [r3, self]
1006+
r5 = load_address r4
1007+
r6 = PyObject_Vectorcall(r2, r5, 2, 0)
1008+
keep_alive r3, self
1009+
r7 = '__init__'
1010+
r8 = CPyObject_GetAttr(r6, r7)
1011+
r9 = box(int, x)
1012+
r10 = [r9]
1013+
r11 = load_address r10
1014+
r12 = PyObject_Vectorcall(r8, r11, 1, 0)
1015+
keep_alive r9
1016+
return 1
1017+
def D.__init__(self, x):
1018+
self :: __main__.D
1019+
x :: int
1020+
r0 :: object
1021+
r1 :: str
1022+
r2 :: object
1023+
r3 :: object[3]
1024+
r4 :: object_ptr
1025+
r5 :: object
1026+
L0:
1027+
r0 = __main__.B :: type
1028+
r1 = '__init__'
1029+
r2 = box(int, x)
1030+
r3 = [r0, self, r2]
1031+
r4 = load_address r3
1032+
r5 = PyObject_VectorcallMethod(r1, r4, 9223372036854775811, 0)
1033+
keep_alive r0, self, r2
1034+
return 1
1035+
def f():
1036+
r0 :: object
1037+
r1 :: tuple
1038+
r2 :: dict
1039+
r3 :: __main__.B
1040+
r4 :: object
1041+
r5 :: tuple
1042+
r6 :: dict
1043+
r7 :: __main__.E
1044+
L0:
1045+
r0 = object 1
1046+
r1 = PyTuple_Pack(1, r0)
1047+
r2 = PyDict_New()
1048+
r3 = B(r1, r2)
1049+
r4 = object 2
1050+
r5 = PyTuple_Pack(1, r4)
1051+
r6 = PyDict_New()
1052+
r7 = E(r5, r6)
1053+
return 1
1054+
1055+
[case testFinalAndOverloadedInit]
1056+
from typing import final, overload
1057+
1058+
class A:
1059+
@final
1060+
def __init__(self, x: int) -> None:
1061+
pass
1062+
1063+
class B:
1064+
@overload
1065+
def __init__(self, x: int) -> None: ...
1066+
@overload
1067+
def __init__(self, x: str, y: int) -> None: ...
1068+
def __init__(self, x: object, y: int = 0) -> None:
1069+
pass
1070+
1071+
def f() -> None:
1072+
A(1)
1073+
B("x", 2)
1074+
[out]
1075+
def A.__init__(self, x):
1076+
self :: __main__.A
1077+
x :: int
1078+
L0:
1079+
return 1
1080+
def B.__init__(self, x, y):
1081+
self :: __main__.B
1082+
x :: object
1083+
y :: int
1084+
L0:
1085+
if is_error(y) goto L1 else goto L2
1086+
L1:
1087+
y = 0
1088+
L2:
1089+
return 1
1090+
def f():
1091+
r0 :: __main__.A
1092+
r1 :: str
1093+
r2 :: __main__.B
1094+
L0:
1095+
r0 = A(2)
1096+
r1 = 'x'
1097+
r2 = B(r1, 4)
1098+
return 1
1099+
9381100
[case testClassVariable]
9391101
from typing import ClassVar
9401102
class A:

0 commit comments

Comments
 (0)