Debian Codegraph @

mypyc/codegen/emitclass.py

raw
1 """Code generation for native classes and related wrappers."""
2
3 from __future__ import annotations
4
5 from collections.abc import Callable, Mapping
6
7 from mypy.nodes import ARG_STAR, ARG_STAR2
8 from mypyc.codegen.cstring import c_string_initializer
9 from mypyc.codegen.emit import (
10 Emitter,
11 HeaderDeclaration,
12 ReturnHandler,
13 native_function_doc_initializer,
14 )
15 from mypyc.codegen.emitfunc import native_function_header
16 from mypyc.codegen.emitwrapper import (
17 generate_bin_op_wrapper,
18 generate_bool_wrapper,
19 generate_contains_wrapper,
20 generate_dunder_wrapper,
21 generate_get_wrapper,
22 generate_hash_wrapper,
23 generate_ipow_wrapper,
24 generate_len_wrapper,
25 generate_richcompare_wrapper,
26 generate_set_del_item_wrapper,
27 )
28 from mypyc.common import (
29 BITMAP_BITS,
30 BITMAP_TYPE,
31 CPYFUNCTION_NAME,
32 MYPYC_DEFAULTS_SETUP,
33 NATIVE_PREFIX,
34 PREFIX,
35 REG_PREFIX,
36 short_id_from_name,
37 )
38 from mypyc.ir.class_ir import ClassIR, VTableEntries
39 from mypyc.ir.func_ir import (
40 FUNC_CLASSMETHOD,
41 FUNC_STATICMETHOD,
42 FuncDecl,
43 FuncIR,
44 get_text_signature,
45 )
46 from mypyc.ir.rtypes import RTuple, RType, object_rprimitive
47 from mypyc.namegen import NameGenerator
48 from mypyc.sametype import is_same_type
49
50
51 def native_slot(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
52 return f"{NATIVE_PREFIX}{fn.cname(emitter.names)}"
53
54
55 def dunder_attr_slot(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
56 wrapper_fn = cl.get_method(fn.name + "__wrapper")
57 assert wrapper_fn
58 return f"{NATIVE_PREFIX}{wrapper_fn.cname(emitter.names)}"
59
60
61 # We maintain a table from dunder function names to struct slots they
62 # correspond to and functions that generate a wrapper (if necessary)
63 # and return the function name to stick in the slot.
64 # TODO: Add remaining dunder methods
65 SlotGenerator = Callable[[ClassIR, FuncIR, Emitter], str]
66 SlotTable = Mapping[str, tuple[str, SlotGenerator]]
67
68 SLOT_DEFS: SlotTable = {
69 "__init__": ("tp_init", lambda c, t, e: generate_init_for_class(c, t, e)),
70 "__call__": ("tp_call", lambda c, t, e: generate_call_wrapper(c, t, e)),
71 "__str__": ("tp_str", native_slot),
72 "__repr__": ("tp_repr", native_slot),
73 "__next__": ("tp_iternext", native_slot),
74 "__iter__": ("tp_iter", native_slot),
75 "__hash__": ("tp_hash", generate_hash_wrapper),
76 "__get__": ("tp_descr_get", generate_get_wrapper),
77 "__getattr__": ("tp_getattro", dunder_attr_slot),
78 "__setattr__": ("tp_setattro", dunder_attr_slot),
79 }
80
81 AS_MAPPING_SLOT_DEFS: SlotTable = {
82 "__getitem__": ("mp_subscript", generate_dunder_wrapper),
83 "__setitem__": ("mp_ass_subscript", generate_set_del_item_wrapper),
84 "__delitem__": ("mp_ass_subscript", generate_set_del_item_wrapper),
85 "__len__": ("mp_length", generate_len_wrapper),
86 }
87
88 AS_SEQUENCE_SLOT_DEFS: SlotTable = {"__contains__": ("sq_contains", generate_contains_wrapper)}
89
90 AS_NUMBER_SLOT_DEFS: SlotTable = {
91 # Unary operations.
92 "__bool__": ("nb_bool", generate_bool_wrapper),
93 "__int__": ("nb_int", generate_dunder_wrapper),
94 "__float__": ("nb_float", generate_dunder_wrapper),
95 "__neg__": ("nb_negative", generate_dunder_wrapper),
96 "__pos__": ("nb_positive", generate_dunder_wrapper),
97 "__abs__": ("nb_absolute", generate_dunder_wrapper),
98 "__invert__": ("nb_invert", generate_dunder_wrapper),
99 # Binary operations.
100 "__add__": ("nb_add", generate_bin_op_wrapper),
101 "__radd__": ("nb_add", generate_bin_op_wrapper),
102 "__sub__": ("nb_subtract", generate_bin_op_wrapper),
103 "__rsub__": ("nb_subtract", generate_bin_op_wrapper),
104 "__mul__": ("nb_multiply", generate_bin_op_wrapper),
105 "__rmul__": ("nb_multiply", generate_bin_op_wrapper),
106 "__mod__": ("nb_remainder", generate_bin_op_wrapper),
107 "__rmod__": ("nb_remainder", generate_bin_op_wrapper),
108 "__truediv__": ("nb_true_divide", generate_bin_op_wrapper),
109 "__rtruediv__": ("nb_true_divide", generate_bin_op_wrapper),
110 "__floordiv__": ("nb_floor_divide", generate_bin_op_wrapper),
111 "__rfloordiv__": ("nb_floor_divide", generate_bin_op_wrapper),
112 "__divmod__": ("nb_divmod", generate_bin_op_wrapper),
113 "__rdivmod__": ("nb_divmod", generate_bin_op_wrapper),
114 "__lshift__": ("nb_lshift", generate_bin_op_wrapper),
115 "__rlshift__": ("nb_lshift", generate_bin_op_wrapper),
116 "__rshift__": ("nb_rshift", generate_bin_op_wrapper),
117 "__rrshift__": ("nb_rshift", generate_bin_op_wrapper),
118 "__and__": ("nb_and", generate_bin_op_wrapper),
119 "__rand__": ("nb_and", generate_bin_op_wrapper),
120 "__or__": ("nb_or", generate_bin_op_wrapper),
121 "__ror__": ("nb_or", generate_bin_op_wrapper),
122 "__xor__": ("nb_xor", generate_bin_op_wrapper),
123 "__rxor__": ("nb_xor", generate_bin_op_wrapper),
124 "__matmul__": ("nb_matrix_multiply", generate_bin_op_wrapper),
125 "__rmatmul__": ("nb_matrix_multiply", generate_bin_op_wrapper),
126 # In-place binary operations.
127 "__iadd__": ("nb_inplace_add", generate_dunder_wrapper),
128 "__isub__": ("nb_inplace_subtract", generate_dunder_wrapper),
129 "__imul__": ("nb_inplace_multiply", generate_dunder_wrapper),
130 "__imod__": ("nb_inplace_remainder", generate_dunder_wrapper),
131 "__itruediv__": ("nb_inplace_true_divide", generate_dunder_wrapper),
132 "__ifloordiv__": ("nb_inplace_floor_divide", generate_dunder_wrapper),
133 "__ilshift__": ("nb_inplace_lshift", generate_dunder_wrapper),
134 "__irshift__": ("nb_inplace_rshift", generate_dunder_wrapper),
135 "__iand__": ("nb_inplace_and", generate_dunder_wrapper),
136 "__ior__": ("nb_inplace_or", generate_dunder_wrapper),
137 "__ixor__": ("nb_inplace_xor", generate_dunder_wrapper),
138 "__imatmul__": ("nb_inplace_matrix_multiply", generate_dunder_wrapper),
139 # Ternary operations. (yes, really)
140 # These are special cased in generate_bin_op_wrapper().
141 "__pow__": ("nb_power", generate_bin_op_wrapper),
142 "__rpow__": ("nb_power", generate_bin_op_wrapper),
143 "__ipow__": ("nb_inplace_power", generate_ipow_wrapper),
144 }
145
146 AS_ASYNC_SLOT_DEFS: SlotTable = {
147 "__await__": ("am_await", native_slot),
148 "__aiter__": ("am_aiter", native_slot),
149 "__anext__": ("am_anext", native_slot),
150 }
151
152 SIDE_TABLES = [
153 ("as_mapping", "PyMappingMethods", AS_MAPPING_SLOT_DEFS),
154 ("as_sequence", "PySequenceMethods", AS_SEQUENCE_SLOT_DEFS),
155 ("as_number", "PyNumberMethods", AS_NUMBER_SLOT_DEFS),
156 ("as_async", "PyAsyncMethods", AS_ASYNC_SLOT_DEFS),
157 ]
158
159 # Slots that need to always be filled in because they don't get
160 # inherited right.
161 ALWAYS_FILL = {"__hash__"}
162
163
164 def generate_call_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
165 return "PyVectorcall_Call"
166
167
168 def slot_key(attr: str) -> str:
169 """Map dunder method name to sort key.
170
171 Sort reverse operator methods and __delitem__ after others ('x' > '_').
172 """
173 if (attr.startswith("__r") and attr != "__rshift__") or attr == "__delitem__":
174 return "x" + attr
175 return attr
176
177
178 def generate_slots(cl: ClassIR, table: SlotTable, emitter: Emitter) -> dict[str, str]:
179 fields: dict[str, str] = {}
180 generated: dict[str, str] = {}
181 # Sort for determinism on Python 3.5
182 for name, (slot, generator) in sorted(table.items(), key=lambda x: slot_key(x[0])):
183 method_cls = cl.get_method_and_class(name)
184 if method_cls and (method_cls[1] == cl or name in ALWAYS_FILL):
185 if slot in generated:
186 # Reuse previously generated wrapper.
187 fields[slot] = generated[slot]
188 else:
189 # Generate new wrapper.
190 name = generator(cl, method_cls[0], emitter)
191 fields[slot] = name
192 generated[slot] = name
193
194 return fields
195
196
197 def generate_class_type_decl(
198 cl: ClassIR, c_emitter: Emitter, external_emitter: Emitter, emitter: Emitter
199 ) -> None:
200 context = c_emitter.context
201 name = emitter.type_struct_name(cl)
202 context.declarations[name] = HeaderDeclaration(
203 f"PyTypeObject *{emitter.type_struct_name(cl)};", needs_export=True
204 )
205
206 # If this is a non-extension class, all we want is the type object decl.
207 if not cl.is_ext_class:
208 return
209
210 generate_object_struct(cl, external_emitter)
211 generate_full = not cl.is_trait and not cl.builtin_base
212 if generate_full:
213 context.declarations[emitter.native_function_name(cl.ctor)] = HeaderDeclaration(
214 f"{native_function_header(cl.ctor, emitter)};", needs_export=True
215 )
216
217
218 def generate_class_reuse(
219 cl: ClassIR, c_emitter: Emitter, external_emitter: Emitter, emitter: Emitter
220 ) -> None:
221 """Generate a definition of a single-object per-class free "list".
222
223 This speeds up object allocation and freeing when there are many short-lived
224 objects.
225
226 TODO: Generalize to support a free list with up to N objects.
227 """
228 assert cl.reuse_freed_instance
229 context = c_emitter.context
230 name = cl.name_prefix(c_emitter.names) + "_free_instance"
231 struct_name = cl.struct_name(c_emitter.names)
232 # Not exported: the free-instance slot is only read/written by the class's
233 # own setup/dealloc code, which lives in the defining group. Exporting it
234 # also trips a C diagnostic under `Py_GIL_DISABLED`, where `CPyThreadLocal`
235 # expands to `__thread` and can't legally appear inside the exports struct.
236 context.declarations[name] = HeaderDeclaration(f"CPyThreadLocal {struct_name} *{name};")
237
238
239 def generate_class(cl: ClassIR, module: str, emitter: Emitter) -> None:
240 """Generate C code for a class.
241
242 This is the main entry point to the module.
243 """
244 name = cl.name
245 name_prefix = cl.name_prefix(emitter.names)
246
247 setup_name = emitter.native_function_name(cl.setup)
248 new_name = f"{name_prefix}_new"
249 finalize_name = f"{name_prefix}_finalize"
250 members_name = f"{name_prefix}_members"
251 getseters_name = f"{name_prefix}_getseters"
252 vtable_name = f"{name_prefix}_vtable"
253 traverse_name = f"{name_prefix}_traverse"
254 clear_name = f"{name_prefix}_clear"
255 dealloc_name = f"{name_prefix}_dealloc"
256 methods_name = f"{name_prefix}_methods"
257 vtable_setup_name = f"{name_prefix}_trait_vtable_setup"
258 coroutine_setup_name = f"{name_prefix}_coroutine_setup"
259
260 fields: dict[str, str] = {"tp_name": f'"{name}"'}
261
262 generate_full = not cl.is_trait and not cl.builtin_base
263 needs_getseters = cl.needs_getseters or not cl.is_generated or cl.has_dict
264
265 if not cl.builtin_base:
266 fields["tp_new"] = new_name
267
268 managed_dict = has_managed_dict(cl, emitter)
269 if generate_full or managed_dict:
270 fields["tp_dealloc"] = f"(destructor){name_prefix}_dealloc"
271 if not cl.is_acyclic:
272 fields["tp_traverse"] = f"(traverseproc){name_prefix}_traverse"
273 fields["tp_clear"] = f"(inquiry){name_prefix}_clear"
274 # Populate .tp_finalize and generate a finalize method only if __del__ is defined for this class.
275 del_method = next((e.method for e in cl.vtable_entries if e.name == "__del__"), None)
276 if del_method:
277 fields["tp_finalize"] = f"(destructor){finalize_name}"
278 if needs_getseters:
279 fields["tp_getset"] = getseters_name
280 fields["tp_methods"] = methods_name
281
282 def emit_line() -> None:
283 emitter.emit_line()
284
285 emit_line()
286
287 # If the class has a method to initialize default attribute
288 # values, we need to call it during initialization.
289 defaults_fn = cl.get_method(MYPYC_DEFAULTS_SETUP)
290
291 # If there is a __init__ method, we'll use it in the native constructor.
292 init_fn = cl.get_method("__init__")
293
294 # Fill out slots in the type object from dunder methods.
295 fields.update(generate_slots(cl, SLOT_DEFS, emitter))
296
297 # Fill out dunder methods that live in tables hanging off the side.
298 for table_name, type, slot_defs in SIDE_TABLES:
299 slots = generate_slots(cl, slot_defs, emitter)
300 if slots:
301 table_struct_name = generate_side_table_for_class(cl, table_name, type, slots, emitter)
302 fields[f"tp_{table_name}"] = f"&{table_struct_name}"
303
304 richcompare_name = generate_richcompare_wrapper(cl, emitter)
305 if richcompare_name:
306 fields["tp_richcompare"] = richcompare_name
307
308 # If the class inherits from python, make space for a __dict__
309 struct_name = cl.struct_name(emitter.names)
310 if cl.builtin_base:
311 base_size = f"sizeof({cl.builtin_base})"
312 elif cl.is_trait:
313 base_size = "sizeof(PyObject)"
314 else:
315 base_size = f"sizeof({struct_name})"
316 # Since our types aren't allocated using type() we need to
317 # populate these fields ourselves if we want them to have correct
318 # values. PyType_Ready will inherit the offsets from tp_base but
319 # that isn't what we want.
320
321 # XXX: there is no reason for the __weakref__ stuff to be mixed up with __dict__
322 if cl.has_dict and not has_managed_dict(cl, emitter):
323 # __dict__ lives right after the struct and __weakref__ lives right after that
324 # TODO: They should get members in the struct instead of doing this nonsense.
325 weak_offset = f"{base_size} + sizeof(PyObject *)"
326 emitter.emit_lines(
327 f"PyMemberDef {members_name}[] = {{",
328 f'{{"__dict__", T_OBJECT_EX, {base_size}, 0, NULL}},',
329 f'{{"__weakref__", T_OBJECT_EX, {weak_offset}, 0, NULL}},',
330 "{0}",
331 "};",
332 )
333
334 fields["tp_members"] = members_name
335 fields["tp_basicsize"] = f"{base_size} + 2*sizeof(PyObject *)"
336 if emitter.capi_version < (3, 12):
337 fields["tp_dictoffset"] = base_size
338 fields["tp_weaklistoffset"] = weak_offset
339 else:
340 fields["tp_basicsize"] = base_size
341
342 if generate_full or managed_dict:
343 if not cl.is_acyclic:
344 generate_traverse_for_class(cl, traverse_name, emitter)
345 emit_line()
346 generate_clear_for_class(cl, clear_name, emitter)
347 emit_line()
348 generate_dealloc_for_class(cl, dealloc_name, clear_name, bool(del_method), emitter)
349 emit_line()
350 if generate_full:
351 assert cl.setup is not None
352 emitter.emit_line(native_function_header(cl.setup, emitter) + ";")
353 assert cl.ctor is not None
354 emitter.emit_line(native_function_header(cl.ctor, emitter) + ";")
355
356 emit_line()
357 init_fn = cl.get_method("__init__")
358 generate_new_for_class(cl, new_name, vtable_name, setup_name, init_fn, emitter)
359 emit_line()
360
361 if cl.allow_interpreted_subclasses:
362 shadow_vtable_name: str | None = generate_vtables(
363 cl, vtable_setup_name + "_shadow", vtable_name + "_shadow", emitter, shadow=True
364 )
365 emit_line()
366 else:
367 shadow_vtable_name = None
368 vtable_name = generate_vtables(cl, vtable_setup_name, vtable_name, emitter, shadow=False)
369 emit_line()
370 generate_coroutine_setup(cl, coroutine_setup_name, module, emitter)
371 emit_line()
372 if del_method:
373 generate_finalize_for_class(del_method, finalize_name, emitter)
374 emit_line()
375 if needs_getseters:
376 generate_getseter_declarations(cl, emitter)
377 emit_line()
378 generate_getseters_table(cl, getseters_name, emitter)
379 emit_line()
380
381 if cl.is_trait:
382 generate_new_for_trait(cl, new_name, emitter)
383
384 generate_methods_table(cl, methods_name, setup_name if generate_full else None, emitter)
385 emit_line()
386
387 flags = ["Py_TPFLAGS_DEFAULT", "Py_TPFLAGS_HEAPTYPE", "Py_TPFLAGS_BASETYPE"]
388 if (generate_full or managed_dict) and not cl.is_acyclic:
389 flags.append("Py_TPFLAGS_HAVE_GC")
390 if cl.has_method("__call__"):
391 fields["tp_vectorcall_offset"] = "offsetof({}, vectorcall)".format(
392 cl.struct_name(emitter.names)
393 )
394 flags.append("_Py_TPFLAGS_HAVE_VECTORCALL")
395 if not fields.get("tp_vectorcall"):
396 # This is just a placeholder to please CPython. It will be
397 # overridden during setup.
398 fields["tp_call"] = "PyVectorcall_Call"
399 if managed_dict:
400 flags.append("Py_TPFLAGS_MANAGED_DICT")
401 fields["tp_flags"] = " | ".join(flags)
402
403 fields["tp_doc"] = f"PyDoc_STR({native_class_doc_initializer(cl)})"
404
405 emitter.emit_line(f"static PyTypeObject {emitter.type_struct_name(cl)}_template_ = {{")
406 emitter.emit_line("PyVarObject_HEAD_INIT(NULL, 0)")
407 for field, value in fields.items():
408 emitter.emit_line(f".{field} = {value},")
409 emitter.emit_line("};")
410 emitter.emit_line(
411 "static PyTypeObject *{t}_template = &{t}_template_;".format(
412 t=emitter.type_struct_name(cl)
413 )
414 )
415
416 if cl.coroutine_name:
417 cpyfunction = emitter.static_name(cl.name + "_cpyfunction", module)
418 emitter.emit_line(f"static PyObject *{cpyfunction} = NULL;")
419
420 emitter.emit_line()
421 if generate_full:
422 generate_setup_for_class(cl, defaults_fn, vtable_name, shadow_vtable_name, emitter)
423 emitter.emit_line()
424 generate_constructor_for_class(cl, cl.ctor, init_fn, setup_name, vtable_name, emitter)
425 emitter.emit_line()
426 if needs_getseters:
427 generate_getseters(cl, emitter)
428
429
430 def getter_name(cl: ClassIR, attribute: str, names: NameGenerator) -> str:
431 return names.private_name(cl.module_name, f"{cl.name}_get_{attribute}")
432
433
434 def setter_name(cl: ClassIR, attribute: str, names: NameGenerator) -> str:
435 return names.private_name(cl.module_name, f"{cl.name}_set_{attribute}")
436
437
438 def generate_object_struct(cl: ClassIR, emitter: Emitter) -> None:
439 seen_attrs: set[str] = set()
440 lines: list[str] = []
441 lines += ["typedef struct {", "PyObject_HEAD", "CPyVTableItem *vtable;"]
442 if cl.has_method("__call__"):
443 lines.append("vectorcallfunc vectorcall;")
444 bitmap_attrs = []
445 for base in reversed(cl.base_mro):
446 if not base.is_trait:
447 if base.bitmap_attrs:
448 # Do we need another attribute bitmap field?
449 if emitter.bitmap_field(len(base.bitmap_attrs) - 1) not in bitmap_attrs:
450 for i in range(0, len(base.bitmap_attrs), BITMAP_BITS):
451 attr = emitter.bitmap_field(i)
452 if attr not in bitmap_attrs:
453 lines.append(f"{BITMAP_TYPE} {attr};")
454 bitmap_attrs.append(attr)
455 for attr, rtype in base.attributes.items():
456 # Generated class may redefine certain attributes with different
457 # types in subclasses (this would be unsafe for user-defined classes).
458 if attr not in seen_attrs:
459 lines.append(f"{emitter.ctype_spaced(rtype)}{emitter.attr(attr)};")
460 seen_attrs.add(attr)
461
462 if isinstance(rtype, RTuple):
463 emitter.declare_tuple_struct(rtype)
464
465 lines.append(f"}} {cl.struct_name(emitter.names)};")
466 lines.append("")
467 emitter.context.declarations[cl.struct_name(emitter.names)] = HeaderDeclaration(
468 lines, is_type=True
469 )
470
471
472 def generate_vtables(
473 base: ClassIR, vtable_setup_name: str, vtable_name: str, emitter: Emitter, shadow: bool
474 ) -> str:
475 """Emit the vtables and vtable setup functions for a class.
476
477 This includes both the primary vtable and any trait implementation vtables.
478 The trait vtables go before the main vtable, and have the following layout:
479 {
480 CPyType_T1, // pointer to type object
481 C_T1_trait_vtable, // pointer to array of method pointers
482 C_T1_offset_table, // pointer to array of attribute offsets
483 CPyType_T2,
484 C_T2_trait_vtable,
485 C_T2_offset_table,
486 ...
487 }
488 The method implementations are calculated at the end of IR pass, attribute
489 offsets are {offsetof(native__C, _x1), offsetof(native__C, _y1), ...}.
490
491 To account for both dynamic loading and dynamic class creation,
492 vtables are populated dynamically at class creation time, so we
493 emit empty array definitions to store the vtables and a function to
494 populate them.
495
496 If shadow is True, generate "shadow vtables" that point to the
497 shadow glue methods (which should dispatch via the Python C-API).
498
499 Returns the expression to use to refer to the vtable, which might be
500 different than the name, if there are trait vtables.
501 """
502
503 def trait_vtable_name(trait: ClassIR) -> str:
504 return "{}_{}_trait_vtable{}".format(
505 base.name_prefix(emitter.names),
506 trait.name_prefix(emitter.names),
507 "_shadow" if shadow else "",
508 )
509
510 def trait_offset_table_name(trait: ClassIR) -> str:
511 return "{}_{}_offset_table".format(
512 base.name_prefix(emitter.names), trait.name_prefix(emitter.names)
513 )
514
515 # Emit array definitions with enough space for all the entries
516 emitter.emit_line(
517 "static CPyVTableItem {}[{}];".format(
518 vtable_name, max(1, len(base.vtable_entries) + 3 * len(base.trait_vtables))
519 )
520 )
521
522 for trait, vtable in base.trait_vtables.items():
523 # Trait methods entry (vtable index -> method implementation).
524 emitter.emit_line(
525 f"static CPyVTableItem {trait_vtable_name(trait)}[{max(1, len(vtable))}];"
526 )
527 # Trait attributes entry (attribute number in trait -> offset in actual struct).
528 emitter.emit_line(
529 "static size_t {}[{}];".format(
530 trait_offset_table_name(trait), max(1, len(trait.attributes))
531 )
532 )
533
534 # Emit vtable setup function
535 emitter.emit_line("static bool")
536 emitter.emit_line(f"{NATIVE_PREFIX}{vtable_setup_name}(void)")
537 emitter.emit_line("{")
538
539 if base.allow_interpreted_subclasses and not shadow:
540 emitter.emit_line(f"{NATIVE_PREFIX}{vtable_setup_name}_shadow();")
541
542 subtables = []
543 for trait, vtable in base.trait_vtables.items():
544 name = trait_vtable_name(trait)
545 offset_name = trait_offset_table_name(trait)
546 generate_vtable(vtable, name, emitter, [], shadow)
547 generate_offset_table(offset_name, emitter, trait, base)
548 subtables.append((trait, name, offset_name))
549
550 generate_vtable(base.vtable_entries, vtable_name, emitter, subtables, shadow)
551
552 emitter.emit_line("return 1;")
553 emitter.emit_line("}")
554
555 return vtable_name if not subtables else f"{vtable_name} + {len(subtables) * 3}"
556
557
558 def generate_offset_table(
559 trait_offset_table_name: str, emitter: Emitter, trait: ClassIR, cl: ClassIR
560 ) -> None:
561 """Generate attribute offset row of a trait vtable."""
562 emitter.emit_line(f"size_t {trait_offset_table_name}_scratch[] = {{")
563 for attr in trait.attributes:
564 emitter.emit_line(f"offsetof({cl.struct_name(emitter.names)}, {emitter.attr(attr)}),")
565 if not trait.attributes:
566 # This is for msvc.
567 emitter.emit_line("0")
568 emitter.emit_line("};")
569 emitter.emit_line(
570 "memcpy({name}, {name}_scratch, sizeof({name}));".format(name=trait_offset_table_name)
571 )
572
573
574 def generate_vtable(
575 entries: VTableEntries,
576 vtable_name: str,
577 emitter: Emitter,
578 subtables: list[tuple[ClassIR, str, str]],
579 shadow: bool,
580 ) -> None:
581 emitter.emit_line(f"CPyVTableItem {vtable_name}_scratch[] = {{")
582 if subtables:
583 emitter.emit_line("/* Array of trait vtables */")
584 for trait, table, offset_table in subtables:
585 emitter.emit_line(
586 "(CPyVTableItem){}, (CPyVTableItem){}, (CPyVTableItem){},".format(
587 emitter.type_struct_name(trait), table, offset_table
588 )
589 )
590 emitter.emit_line("/* Start of real vtable */")
591
592 for entry in entries:
593 method = entry.shadow_method if shadow and entry.shadow_method else entry.method
594 emitter.emit_line(
595 "(CPyVTableItem){}{}{},".format(
596 emitter.get_group_prefix(entry.method.decl),
597 NATIVE_PREFIX,
598 method.cname(emitter.names),
599 )
600 )
601
602 # msvc doesn't allow empty arrays; maybe allowing them at all is an extension?
603 if not entries:
604 emitter.emit_line("NULL")
605 emitter.emit_line("};")
606 emitter.emit_line("memcpy({name}, {name}_scratch, sizeof({name}));".format(name=vtable_name))
607
608
609 def generate_setup_for_class(
610 cl: ClassIR,
611 defaults_fn: FuncIR | None,
612 vtable_name: str,
613 shadow_vtable_name: str | None,
614 emitter: Emitter,
615 ) -> None:
616 """Generate a native function that allocates an instance of a class."""
617 emitter.emit_line(native_function_header(cl.setup, emitter))
618 emitter.emit_line("{")
619 type_arg_name = REG_PREFIX + cl.setup.sig.args[0].name
620 emitter.emit_line(f"PyTypeObject *type = (PyTypeObject*){type_arg_name};")
621 struct_name = cl.struct_name(emitter.names)
622 emitter.emit_line(f"{struct_name} *self;")
623
624 prefix = cl.name_prefix(emitter.names)
625 if cl.reuse_freed_instance:
626 # Attempt to use a per-type free list first (a free "list" with up to one object only).
627 emitter.emit_line(f"if ({prefix}_free_instance != NULL) {{")
628 emitter.emit_line(f"self = {prefix}_free_instance;")
629 emitter.emit_line(f"{prefix}_free_instance = NULL;")
630 emitter.emit_line("Py_SET_REFCNT(self, 1);")
631 if not cl.is_acyclic:
632 emitter.emit_line("PyObject_GC_Track(self);")
633 if defaults_fn is not None:
634 emit_attr_defaults_func_call(defaults_fn, "self", emitter)
635 emitter.emit_line("return (PyObject *)self;")
636 emitter.emit_line("}")
637
638 emitter.emit_line(f"self = ({cl.struct_name(emitter.names)} *)type->tp_alloc(type, 0);")
639 emitter.emit_line("if (self == NULL)")
640 emitter.emit_line(" return NULL;")
641
642 if shadow_vtable_name:
643 emitter.emit_line(f"if (type != {emitter.type_struct_name(cl)}) {{")
644 emitter.emit_line(f"self->vtable = {shadow_vtable_name};")
645 emitter.emit_line("} else {")
646 emitter.emit_line(f"self->vtable = {vtable_name};")
647 emitter.emit_line("}")
648 else:
649 emitter.emit_line(f"self->vtable = {vtable_name};")
650
651 emit_clear_bitmaps(cl, emitter)
652
653 if cl.has_method("__call__"):
654 name = cl.method_decl("__call__").cname(emitter.names)
655 emitter.emit_line(f"self->vectorcall = {PREFIX}{name};")
656
657 for base in reversed(cl.base_mro):
658 for attr, rtype in base.attributes.items():
659 value = emitter.c_undefined_value(rtype)
660
661 # We don't need to set this field to NULL since tp_alloc() already
662 # zero-initializes `self`.
663 if value != "NULL":
664 emitter.set_undefined_value(f"self->{emitter.attr(attr)}", rtype)
665
666 # Initialize attributes to default values, if necessary
667 if defaults_fn is not None:
668 emit_attr_defaults_func_call(defaults_fn, "self", emitter)
669
670 emitter.emit_line("return (PyObject *)self;")
671 emitter.emit_line("}")
672
673
674 def emit_clear_bitmaps(cl: ClassIR, emitter: Emitter) -> None:
675 """Emit C code to clear bitmaps that track if attributes have an assigned value."""
676 for i in range(0, len(cl.bitmap_attrs), BITMAP_BITS):
677 field = emitter.bitmap_field(i)
678 emitter.emit_line(f"self->{field} = 0;")
679
680
681 def emit_attr_defaults_func_call(defaults_fn: FuncIR, self_name: str, emitter: Emitter) -> None:
682 """Emit C code to initialize attribute defaults by calling defaults_fn.
683
684 The code returns NULL on a raised exception.
685 """
686 emitter.emit_lines(
687 "if ({}((PyObject *){}) == 0) {{".format(
688 emitter.native_function_call(defaults_fn.decl), self_name
689 ),
690 "Py_DECREF(self);",
691 "return NULL;",
692 "}",
693 )
694
695
696 def emit_setup_or_dunder_new_call(
697 cl: ClassIR,
698 setup_name: str,
699 type_arg: str,
700 native_prefix: bool,
701 new_args: str,
702 emitter: Emitter,
703 ) -> None:
704 def emit_null_check() -> None:
705 emitter.emit_line("if (self == NULL)")
706 emitter.emit_line(" return NULL;")
707
708 new_fn = cl.get_method("__new__")
709 if not new_fn:
710 emitter.emit_line(f"PyObject *self = {setup_name}({type_arg});")
711 emit_null_check()
712 return
713 call = (
714 emitter.native_function_call(new_fn.decl)
715 if native_prefix
716 else emitter.wrapper_function_call(new_fn.decl)
717 )
718 all_args = type_arg
719 if new_args != "":
720 all_args += ", " + new_args
721 emitter.emit_line(f"PyObject *self = {call}({all_args});")
722 emit_null_check()
723
724 # skip __init__ if __new__ returns some other type
725 emitter.emit_line(f"if (Py_TYPE(self) != {emitter.type_struct_name(cl)})")
726 emitter.emit_line(" return self;")
727
728
729 def generate_constructor_for_class(
730 cl: ClassIR,
731 fn: FuncDecl,
732 init_fn: FuncIR | None,
733 setup_name: str,
734 vtable_name: str,
735 emitter: Emitter,
736 ) -> None:
737 """Generate a native function that allocates and initializes an instance of a class."""
738 emitter.emit_line(f"{native_function_header(fn, emitter)}")
739 emitter.emit_line("{")
740
741 fn_args = [REG_PREFIX + arg.name for arg in fn.sig.args]
742 type_arg = "(PyObject *)" + emitter.type_struct_name(cl)
743 new_args = ", ".join(fn_args)
744
745 use_wrapper = (
746 cl.has_method("__new__")
747 and len(fn.sig.args) == 2
748 and fn.sig.args[0].kind == ARG_STAR
749 and fn.sig.args[1].kind == ARG_STAR2
750 )
751 emit_setup_or_dunder_new_call(cl, setup_name, type_arg, not use_wrapper, new_args, emitter)
752
753 args = ", ".join(["self"] + fn_args)
754 if init_fn is not None:
755 call = (
756 emitter.wrapper_function_call(init_fn.decl)
757 if use_wrapper
758 else emitter.native_function_call(init_fn.decl)
759 )
760 cast = "!= NULL ? 0 : -1" if use_wrapper else ""
761 emitter.emit_line(f"char res = {call}({args}){cast};")
762 emitter.emit_line("if (res == 2) {")
763 emitter.emit_line("Py_DECREF(self);")
764 emitter.emit_line("return NULL;")
765 emitter.emit_line("}")
766
767 # If there is a nontrivial ctor that we didn't define, invoke it via tp_init
768 elif len(fn.sig.args) > 1:
769 emitter.emit_line(f"int res = {emitter.type_struct_name(cl)}->tp_init({args});")
770
771 emitter.emit_line("if (res < 0) {")
772 emitter.emit_line("Py_DECREF(self);")
773 emitter.emit_line("return NULL;")
774 emitter.emit_line("}")
775
776 emitter.emit_line("return self;")
777 emitter.emit_line("}")
778
779
780 def generate_init_for_class(cl: ClassIR, init_fn: FuncIR, emitter: Emitter) -> str:
781 """Generate an init function suitable for use as tp_init.
782
783 tp_init needs to be a function that returns an int, and our
784 __init__ methods return a PyObject. Translate NULL to -1,
785 everything else to 0.
786 """
787 func_name = f"{cl.name_prefix(emitter.names)}_init"
788
789 emitter.emit_line("static int")
790 emitter.emit_line(f"{func_name}(PyObject *self, PyObject *args, PyObject *kwds)")
791 emitter.emit_line("{")
792 if cl.allow_interpreted_subclasses or cl.builtin_base or cl.has_method("__new__"):
793 emitter.emit_line(
794 f"return {emitter.wrapper_function_call(init_fn.decl)}"
795 "(self, args, kwds) != NULL ? 0 : -1;"
796 )
797 else:
798 emitter.emit_line("return 0;")
799 emitter.emit_line("}")
800
801 return func_name
802
803
804 def generate_new_for_class(
805 cl: ClassIR,
806 func_name: str,
807 vtable_name: str,
808 setup_name: str,
809 init_fn: FuncIR | None,
810 emitter: Emitter,
811 ) -> None:
812 emitter.emit_line("static PyObject *")
813 emitter.emit_line(f"{func_name}(PyTypeObject *type, PyObject *args, PyObject *kwds)")
814 emitter.emit_line("{")
815 # TODO: Check and unbox arguments
816 if not cl.allow_interpreted_subclasses:
817 emitter.emit_line(f"if (type != {emitter.type_struct_name(cl)}) {{")
818 emitter.emit_line(
819 'PyErr_SetString(PyExc_TypeError, "interpreted classes cannot inherit from compiled");'
820 )
821 emitter.emit_line("return NULL;")
822 emitter.emit_line("}")
823
824 type_arg = "(PyObject*)type"
825 new_args = "args, kwds"
826 emit_setup_or_dunder_new_call(cl, setup_name, type_arg, False, new_args, emitter)
827 if (
828 not init_fn
829 or cl.allow_interpreted_subclasses
830 or cl.builtin_base
831 or cl.is_serializable()
832 or cl.has_method("__new__")
833 ):
834 # Match Python semantics -- __new__ doesn't call __init__.
835 emitter.emit_line("return self;")
836 else:
837 # __new__ of a native class implicitly calls __init__ so that we
838 # can enforce that instances are always properly initialized. This
839 # is needed to support always defined attributes.
840 emitter.emit_line(
841 f"PyObject *ret = {emitter.wrapper_function_call(init_fn.decl)}(self, args, kwds);"
842 )
843 emitter.emit_lines("if (ret == NULL) {", " Py_DECREF(self);", " return NULL;", "}")
844 emitter.emit_line("Py_DECREF(ret);")
845 emitter.emit_line("return self;")
846 emitter.emit_line("}")
847
848
849 def generate_new_for_trait(cl: ClassIR, func_name: str, emitter: Emitter) -> None:
850 emitter.emit_line("static PyObject *")
851 emitter.emit_line(f"{func_name}(PyTypeObject *type, PyObject *args, PyObject *kwds)")
852 emitter.emit_line("{")
853 emitter.emit_line(f"if (type != {emitter.type_struct_name(cl)}) {{")
854 emitter.emit_line(
855 "PyErr_SetString(PyExc_TypeError, "
856 '"interpreted classes cannot inherit from compiled traits");'
857 )
858 emitter.emit_line("} else {")
859 emitter.emit_line('PyErr_SetString(PyExc_TypeError, "traits may not be directly created");')
860 emitter.emit_line("}")
861 emitter.emit_line("return NULL;")
862 emitter.emit_line("}")
863
864
865 def generate_traverse_for_class(cl: ClassIR, func_name: str, emitter: Emitter) -> None:
866 """Emit function that performs cycle GC traversal of an instance."""
867 emitter.emit_line("static int")
868 emitter.emit_line(
869 f"{func_name}({cl.struct_name(emitter.names)} *self, visitproc visit, void *arg)"
870 )
871 emitter.emit_line("{")
872 for base in reversed(cl.base_mro):
873 for attr, rtype in base.attributes.items():
874 emitter.emit_gc_visit(f"self->{emitter.attr(attr)}", rtype)
875 base_args = "(PyObject *)self, visit, arg"
876 emitter.emit_line("int rv = 0;")
877 if cl.builtin_base:
878 emitter.emit_base_tp_function_call(cl, "tp_traverse", base_args, prefix="rv = ")
879 emitter.emit_line("if (rv != 0) return rv;")
880 if has_managed_dict(cl, emitter):
881 emitter.emit_line(f"rv = PyObject_VisitManagedDict({base_args});")
882 emitter.emit_line("if (rv != 0) return rv;")
883 elif cl.has_dict:
884 struct_name = cl.struct_name(emitter.names)
885 # __dict__ lives right after the struct and __weakref__ lives right after that
886 emitter.emit_gc_visit(
887 f"*((PyObject **)((char *)self + sizeof({struct_name})))", object_rprimitive
888 )
889 emitter.emit_gc_visit(
890 f"*((PyObject **)((char *)self + sizeof(PyObject *) + sizeof({struct_name})))",
891 object_rprimitive,
892 )
893 emitter.emit_line("return rv;")
894 emitter.emit_line("}")
895
896
897 def generate_clear_for_class(cl: ClassIR, func_name: str, emitter: Emitter) -> None:
898 emitter.emit_line("static int")
899 emitter.emit_line(f"{func_name}({cl.struct_name(emitter.names)} *self)")
900 emitter.emit_line("{")
901 for base in reversed(cl.base_mro):
902 for attr, rtype in base.attributes.items():
903 emitter.emit_gc_clear(f"self->{emitter.attr(attr)}", rtype)
904 base_args = "(PyObject *)self"
905 if cl.builtin_base:
906 emitter.emit_base_tp_function_call(cl, "tp_clear", base_args)
907 if has_managed_dict(cl, emitter):
908 emitter.emit_line(f"PyObject_ClearManagedDict({base_args});")
909 elif cl.has_dict:
910 struct_name = cl.struct_name(emitter.names)
911 # __dict__ lives right after the struct and __weakref__ lives right after that
912 emitter.emit_gc_clear(
913 f"*((PyObject **)((char *)self + sizeof({struct_name})))", object_rprimitive
914 )
915 emitter.emit_gc_clear(
916 f"*((PyObject **)((char *)self + sizeof(PyObject *) + sizeof({struct_name})))",
917 object_rprimitive,
918 )
919 emitter.emit_line("return 0;")
920 emitter.emit_line("}")
921
922
923 def generate_dealloc_for_class(
924 cl: ClassIR,
925 dealloc_func_name: str,
926 clear_func_name: str,
927 has_tp_finalize: bool,
928 emitter: Emitter,
929 ) -> None:
930 emitter.emit_line("static void")
931 emitter.emit_line(f"{dealloc_func_name}({cl.struct_name(emitter.names)} *self)")
932 emitter.emit_line("{")
933 if has_tp_finalize:
934 emitter.emit_line("PyObject *type, *value, *traceback;")
935 emitter.emit_line("PyErr_Fetch(&type, &value, &traceback);")
936 emitter.emit_line("int res = PyObject_CallFinalizerFromDealloc((PyObject *)self);")
937 # CPython interpreter uses PyErr_WriteUnraisable: https://docs.python.org/3/c-api/exceptions.html#c.PyErr_WriteUnraisable
938 # However, the message is slightly different due to the way mypyc compiles classes.
939 # CPython interpreter prints: Exception ignored in: <function F.__del__ at 0x100aed940>
940 # mypyc prints: Exception ignored in: <slot wrapper '__del__' of 'F' objects>
941 emitter.emit_line("if (PyErr_Occurred() != NULL) {")
942 # Don't untrack instance if error occurred
943 emitter.emit_line("PyErr_WriteUnraisable((PyObject *)self);")
944 emitter.emit_line("res = -1;")
945 emitter.emit_line("}")
946 emitter.emit_line("PyErr_Restore(type, value, traceback);")
947 emitter.emit_line("if (res < 0) {")
948 emitter.emit_line("goto done;")
949 emitter.emit_line("}")
950 if not cl.is_acyclic:
951 emitter.emit_line("PyObject_GC_UnTrack(self);")
952 if cl.builtin_base:
953 emitter.emit_line(f"{clear_func_name}(self);")
954 # For native subclasses of builtins such as dict, the base deallocator
955 # is responsible for tearing down base-owned storage and freeing memory.
956 # Re-track self if base is GC-aware to match cpython's subtype_dealloc.
957 base = f"{emitter.type_struct_name(cl)}->tp_base"
958 base_arg = "(PyObject *)self"
959 emitter.emit_line(f"if (PyType_IS_GC({base})) PyObject_GC_Track({base_arg});")
960 emitter.emit_base_tp_function_call(cl, "tp_dealloc", base_arg)
961 emitter.emit_line("done: ;")
962 emitter.emit_line("}")
963 return
964 if cl.reuse_freed_instance:
965 emit_reuse_dealloc(cl, emitter)
966 # The trashcan is needed to handle deep recursive deallocations
967 emitter.emit_line(f"CPy_TRASHCAN_BEGIN(self, {dealloc_func_name})")
968 emitter.emit_line(f"{clear_func_name}(self);")
969 emitter.emit_line("Py_TYPE(self)->tp_free((PyObject *)self);")
970 emitter.emit_line("CPy_TRASHCAN_END(self)")
971 emitter.emit_line("done: ;")
972 emitter.emit_line("}")
973
974
975 def emit_reuse_dealloc(cl: ClassIR, emitter: Emitter) -> None:
976 """Emit code to deallocate object by putting it to per-type free list.
977
978 The free "list" currently can have up to one object.
979 """
980 prefix = cl.name_prefix(emitter.names)
981 emitter.emit_line(f"if ({prefix}_free_instance == NULL) {{")
982 emitter.emit_line(f"{prefix}_free_instance = self;")
983
984 # Clear attributes and free referenced objects.
985
986 emit_clear_bitmaps(cl, emitter)
987
988 for base in reversed(cl.base_mro):
989 for attr, rtype in base.attributes.items():
990 emitter.emit_reuse_clear(f"self->{emitter.attr(attr)}", rtype)
991
992 emitter.emit_line("return;")
993 emitter.emit_line("}")
994
995
996 def generate_finalize_for_class(
997 del_method: FuncIR, finalize_func_name: str, emitter: Emitter
998 ) -> None:
999 emitter.emit_line("static void")
1000 emitter.emit_line(f"{finalize_func_name}(PyObject *self)")
1001 emitter.emit_line("{")
1002 emitter.emit_line(
1003 "{}{}{}(self);".format(
1004 emitter.get_group_prefix(del_method.decl),
1005 NATIVE_PREFIX,
1006 del_method.cname(emitter.names),
1007 )
1008 )
1009 emitter.emit_line("}")
1010
1011
1012 def generate_methods_table(
1013 cl: ClassIR, name: str, setup_name: str | None, emitter: Emitter
1014 ) -> None:
1015 emitter.emit_line(f"static PyMethodDef {name}[] = {{")
1016 if setup_name:
1017 # Store pointer to the setup function so it can be resolved dynamically
1018 # in case of instance creation in __new__.
1019 # CPy_SetupObject expects this method to be the first one in tp_methods.
1020 emitter.emit_line(
1021 f'{{"__internal_mypyc_setup", (PyCFunction){setup_name}, METH_O, NULL}},'
1022 )
1023 for fn in cl.methods.values():
1024 if fn.decl.is_prop_setter or fn.decl.is_prop_getter or fn.internal:
1025 continue
1026 emitter.emit_line(f'{{"{fn.name}",')
1027 emitter.emit_line(f" (PyCFunction){PREFIX}{fn.cname(emitter.names)},")
1028 flags = ["METH_FASTCALL", "METH_KEYWORDS"]
1029 if fn.decl.kind == FUNC_STATICMETHOD:
1030 flags.append("METH_STATIC")
1031 elif fn.decl.kind == FUNC_CLASSMETHOD:
1032 flags.append("METH_CLASS")
1033
1034 doc = native_function_doc_initializer(fn)
1035 emitter.emit_line(" {}, PyDoc_STR({})}},".format(" | ".join(flags), doc))
1036
1037 # Provide a default __getstate__ and __setstate__
1038 if not cl.has_method("__setstate__") and not cl.has_method("__getstate__"):
1039 emitter.emit_lines(
1040 '{"__setstate__", (PyCFunction)CPyPickle_SetState, METH_O, NULL},',
1041 '{"__getstate__", (PyCFunction)CPyPickle_GetState, METH_NOARGS, NULL},',
1042 )
1043
1044 emitter.emit_line("{NULL} /* Sentinel */")
1045 emitter.emit_line("};")
1046
1047
1048 def generate_side_table_for_class(
1049 cl: ClassIR, name: str, type: str, slots: dict[str, str], emitter: Emitter
1050 ) -> str | None:
1051 name = f"{cl.name_prefix(emitter.names)}_{name}"
1052 emitter.emit_line(f"static {type} {name} = {{")
1053 for field, value in slots.items():
1054 emitter.emit_line(f".{field} = {value},")
1055 emitter.emit_line("};")
1056 return name
1057
1058
1059 def generate_getseter_declarations(cl: ClassIR, emitter: Emitter) -> None:
1060 if not cl.is_trait:
1061 for attr in cl.attributes:
1062 emitter.emit_line("static PyObject *")
1063 emitter.emit_line(
1064 "{}({} *self, void *closure);".format(
1065 getter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)
1066 )
1067 )
1068 emitter.emit_line("static int")
1069 emitter.emit_line(
1070 "{}({} *self, PyObject *value, void *closure);".format(
1071 setter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)
1072 )
1073 )
1074
1075 for prop, (getter, setter) in cl.properties.items():
1076 if getter.decl.implicit:
1077 continue
1078
1079 # Generate getter declaration
1080 emitter.emit_line("static PyObject *")
1081 emitter.emit_line(
1082 "{}({} *self, void *closure);".format(
1083 getter_name(cl, prop, emitter.names), cl.struct_name(emitter.names)
1084 )
1085 )
1086
1087 # Generate property setter declaration if a setter exists
1088 if setter:
1089 emitter.emit_line("static int")
1090 emitter.emit_line(
1091 "{}({} *self, PyObject *value, void *closure);".format(
1092 setter_name(cl, prop, emitter.names), cl.struct_name(emitter.names)
1093 )
1094 )
1095
1096
1097 def generate_getseters_table(cl: ClassIR, name: str, emitter: Emitter) -> None:
1098 emitter.emit_line(f"static PyGetSetDef {name}[] = {{")
1099 if not cl.is_trait:
1100 for attr in cl.attributes:
1101 emitter.emit_line(f'{{"{attr}",')
1102 emitter.emit_line(
1103 " (getter){}, (setter){},".format(
1104 getter_name(cl, attr, emitter.names), setter_name(cl, attr, emitter.names)
1105 )
1106 )
1107 emitter.emit_line(" NULL, NULL},")
1108 for prop, (getter, setter) in cl.properties.items():
1109 if getter.decl.implicit:
1110 continue
1111
1112 emitter.emit_line(f'{{"{prop}",')
1113 emitter.emit_line(f" (getter){getter_name(cl, prop, emitter.names)},")
1114
1115 if setter:
1116 emitter.emit_line(f" (setter){setter_name(cl, prop, emitter.names)},")
1117 emitter.emit_line("NULL, NULL},")
1118 else:
1119 emitter.emit_line("NULL, NULL, NULL},")
1120
1121 if cl.has_dict:
1122 emitter.emit_line('{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},')
1123
1124 emitter.emit_line("{NULL} /* Sentinel */")
1125 emitter.emit_line("};")
1126
1127
1128 def generate_getseters(cl: ClassIR, emitter: Emitter) -> None:
1129 if not cl.is_trait:
1130 for i, (attr, rtype) in enumerate(cl.attributes.items()):
1131 generate_getter(cl, attr, rtype, emitter)
1132 emitter.emit_line("")
1133 generate_setter(cl, attr, rtype, emitter)
1134 if i < len(cl.attributes) - 1:
1135 emitter.emit_line("")
1136 for prop, (getter, setter) in cl.properties.items():
1137 if getter.decl.implicit:
1138 continue
1139
1140 rtype = getter.sig.ret_type
1141 emitter.emit_line("")
1142 generate_readonly_getter(cl, prop, rtype, getter, emitter)
1143 if setter:
1144 arg_type = setter.sig.args[1].type
1145 emitter.emit_line("")
1146 generate_property_setter(cl, prop, arg_type, setter, emitter)
1147
1148
1149 def generate_getter(cl: ClassIR, attr: str, rtype: RType, emitter: Emitter) -> None:
1150 attr_field = emitter.attr(attr)
1151 emitter.emit_line("static PyObject *")
1152 emitter.emit_line(
1153 "{}({} *self, void *closure)".format(
1154 getter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)
1155 )
1156 )
1157 emitter.emit_line("{")
1158 attr_expr = f"self->{attr_field}"
1159
1160 # HACK: Don't consider refcounted values as always defined, since it's possible to
1161 # access uninitialized values via 'gc.get_objects()'. Accessing non-refcounted
1162 # values is benign.
1163 always_defined = cl.is_always_defined(attr) and not rtype.is_refcounted
1164
1165 if not always_defined:
1166 emitter.emit_undefined_attr_check(rtype, attr_expr, "==", "self", attr, cl, unlikely=True)
1167 emitter.emit_line("PyErr_SetString(PyExc_AttributeError,")
1168 emitter.emit_line(f' "attribute {repr(attr)} of {repr(cl.name)} undefined");')
1169 emitter.emit_line("return NULL;")
1170 emitter.emit_line("}")
1171 emitter.emit_inc_ref(f"self->{attr_field}", rtype)
1172 emitter.emit_box(f"self->{attr_field}", "retval", rtype, declare_dest=True)
1173 emitter.emit_line("return retval;")
1174 emitter.emit_line("}")
1175
1176
1177 def generate_setter(cl: ClassIR, attr: str, rtype: RType, emitter: Emitter) -> None:
1178 attr_field = emitter.attr(attr)
1179 emitter.emit_line("static int")
1180 emitter.emit_line(
1181 "{}({} *self, PyObject *value, void *closure)".format(
1182 setter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)
1183 )
1184 )
1185 emitter.emit_line("{")
1186
1187 deletable = cl.is_deletable(attr)
1188 if not deletable:
1189 emitter.emit_line("if (value == NULL) {")
1190 emitter.emit_line("PyErr_SetString(PyExc_AttributeError,")
1191 emitter.emit_line(
1192 f' "{repr(cl.name)} object attribute {repr(attr)} cannot be deleted");'
1193 )
1194 emitter.emit_line("return -1;")
1195 emitter.emit_line("}")
1196
1197 # HACK: Don't consider refcounted values as always defined, since it's possible to
1198 # access uninitialized values via 'gc.get_objects()'. Accessing non-refcounted
1199 # values is benign.
1200 always_defined = cl.is_always_defined(attr) and not rtype.is_refcounted
1201
1202 if rtype.is_refcounted:
1203 attr_expr = f"self->{attr_field}"
1204 if not always_defined:
1205 emitter.emit_undefined_attr_check(rtype, attr_expr, "!=", "self", attr, cl)
1206 emitter.emit_dec_ref(f"self->{attr_field}", rtype)
1207 if not always_defined:
1208 emitter.emit_line("}")
1209
1210 if deletable:
1211 emitter.emit_line("if (value != NULL) {")
1212
1213 if rtype.is_unboxed:
1214 emitter.emit_unbox("value", "tmp", rtype, error=ReturnHandler("-1"), declare_dest=True)
1215 elif is_same_type(rtype, object_rprimitive):
1216 emitter.emit_line("PyObject *tmp = value;")
1217 else:
1218 emitter.emit_cast("value", "tmp", rtype, declare_dest=True)
1219 emitter.emit_lines("if (!tmp)", " return -1;")
1220 emitter.emit_inc_ref("tmp", rtype)
1221 emitter.emit_line(f"self->{attr_field} = tmp;")
1222 if rtype.error_overlap and not always_defined:
1223 emitter.emit_attr_bitmap_set("tmp", "self", rtype, cl, attr)
1224
1225 if deletable:
1226 emitter.emit_line("} else {")
1227 emitter.set_undefined_value(f"self->{attr_field}", rtype)
1228 if rtype.error_overlap:
1229 emitter.emit_attr_bitmap_clear("self", rtype, cl, attr)
1230 emitter.emit_line("}")
1231 emitter.emit_line("return 0;")
1232 emitter.emit_line("}")
1233
1234
1235 def generate_readonly_getter(
1236 cl: ClassIR, attr: str, rtype: RType, func_ir: FuncIR, emitter: Emitter
1237 ) -> None:
1238 emitter.emit_line("static PyObject *")
1239 emitter.emit_line(
1240 "{}({} *self, void *closure)".format(
1241 getter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)
1242 )
1243 )
1244 emitter.emit_line("{")
1245 if rtype.is_unboxed:
1246 emitter.emit_line(
1247 "{}retval = {}{}((PyObject *) self);".format(
1248 emitter.ctype_spaced(rtype), NATIVE_PREFIX, func_ir.cname(emitter.names)
1249 )
1250 )
1251 emitter.emit_error_check("retval", rtype, "return NULL;")
1252 emitter.emit_box("retval", "retbox", rtype, declare_dest=True)
1253 emitter.emit_line("return retbox;")
1254 else:
1255 emitter.emit_line(
1256 f"return {NATIVE_PREFIX}{func_ir.cname(emitter.names)}((PyObject *) self);"
1257 )
1258 emitter.emit_line("}")
1259
1260
1261 def generate_property_setter(
1262 cl: ClassIR, attr: str, arg_type: RType, func_ir: FuncIR, emitter: Emitter
1263 ) -> None:
1264 emitter.emit_line("static int")
1265 emitter.emit_line(
1266 "{}({} *self, PyObject *value, void *closure)".format(
1267 setter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)
1268 )
1269 )
1270 emitter.emit_line("{")
1271 if arg_type.is_unboxed:
1272 emitter.emit_unbox("value", "tmp", arg_type, error=ReturnHandler("-1"), declare_dest=True)
1273 emitter.emit_line(
1274 f"{NATIVE_PREFIX}{func_ir.cname(emitter.names)}((PyObject *) self, tmp);"
1275 )
1276 else:
1277 emitter.emit_line(
1278 f"{NATIVE_PREFIX}{func_ir.cname(emitter.names)}((PyObject *) self, value);"
1279 )
1280 emitter.emit_line("return 0;")
1281 emitter.emit_line("}")
1282
1283
1284 def has_managed_dict(cl: ClassIR, emitter: Emitter) -> bool:
1285 """Should the class get the Py_TPFLAGS_MANAGED_DICT flag?"""
1286 # On 3.11 and earlier the flag doesn't exist and we use
1287 # tp_dictoffset instead. If a class inherits from Exception, the
1288 # flag conflicts with tp_dictoffset set in the base class.
1289 return (
1290 emitter.capi_version >= (3, 12)
1291 and cl.has_dict
1292 and cl.builtin_base != "PyBaseExceptionObject"
1293 )
1294
1295
1296 def native_class_doc_initializer(cl: ClassIR) -> str:
1297 init_fn = cl.get_method("__init__")
1298 if init_fn is not None:
1299 text_sig = get_text_signature(init_fn, bound=True)
1300 if text_sig is None:
1301 return "NULL"
1302 text_sig = text_sig.replace("__init__", cl.name, 1)
1303 else:
1304 text_sig = f"{cl.name}()"
1305 docstring = f"{text_sig}\n--\n\n"
1306 return c_string_initializer(docstring.encode("ascii", errors="backslashreplace"))
1307
1308
1309 def generate_coroutine_setup(
1310 cl: ClassIR, coroutine_setup_name: str, module_name: str, emitter: Emitter
1311 ) -> None:
1312 emitter.emit_line("static bool")
1313 emitter.emit_line(f"{NATIVE_PREFIX}{coroutine_setup_name}(PyObject *type)")
1314 emitter.emit_line("{")
1315
1316 error_stmt = " return 2;"
1317
1318 def emit_instance(fn: FuncIR, fn_name: str) -> str:
1319 filepath = emitter.filepath or ""
1320 return emitter.emit_cpyfunction_instance(fn, fn_name, filepath, error_stmt)
1321
1322 def success() -> None:
1323 emitter.emit_line("return 1;")
1324 emitter.emit_line("}")
1325
1326 if cl.coroutine_name:
1327 # Callable class generated for a coroutine. It stores its function wrapper as an attribute.
1328 wrapper_name = emit_instance(cl.methods["__call__"], cl.coroutine_name)
1329 struct_name = cl.struct_name(emitter.names)
1330 attr = emitter.attr(CPYFUNCTION_NAME)
1331 emitter.emit_line(f"(({struct_name} *)type)->{attr} = {wrapper_name};")
1332 return success()
1333
1334 if not any(fn.decl.is_coroutine for fn in cl.methods.values()):
1335 return success()
1336
1337 emitter.emit_line("PyTypeObject *tp = (PyTypeObject *)type;")
1338
1339 for fn in cl.methods.values():
1340 if not fn.decl.is_coroutine:
1341 continue
1342
1343 name = short_id_from_name(fn.name, fn.decl.shortname, fn.line)
1344 wrapper_name = emit_instance(fn, name)
1345 name_obj = f"{wrapper_name}_name"
1346 emitter.emit_line(f'PyObject *{name_obj} = PyUnicode_FromString("{fn.name}");')
1347 emitter.emit_line(f"if (unlikely(!{name_obj}))")
1348 emitter.emit_line(error_stmt)
1349 emitter.emit_line(f"if (PyDict_SetItem(tp->tp_dict, {name_obj}, {wrapper_name}) < 0)")
1350 emitter.emit_line(error_stmt)
1351
1352 return success()