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