Debian Codegraph @

mypyc/codegen/emit.py

raw
1 """Utilities for emitting C code."""
2
3 from __future__ import annotations
4
5 import pprint
6 import sys
7 import textwrap
8 from collections.abc import Callable
9 from typing import Final
10
11 from mypyc.codegen.cstring import c_string_initializer
12 from mypyc.codegen.literals import Literals
13 from mypyc.common import (
14 ATTR_PREFIX,
15 BITMAP_BITS,
16 FAST_ISINSTANCE_MAX_SUBCLASSES,
17 HAVE_IMMORTAL,
18 MODULE_PREFIX,
19 NATIVE_PREFIX,
20 PREFIX,
21 REG_PREFIX,
22 STATIC_PREFIX,
23 TYPE_PREFIX,
24 TYPE_VAR_PREFIX,
25 )
26 from mypyc.ir.class_ir import ClassIR, all_concrete_classes
27 from mypyc.ir.func_ir import FUNC_STATICMETHOD, FuncDecl, FuncIR, get_text_signature
28 from mypyc.ir.ops import (
29 NAMESPACE_MODULE,
30 NAMESPACE_STATIC,
31 NAMESPACE_TYPE,
32 NAMESPACE_TYPE_VAR,
33 BasicBlock,
34 Value,
35 )
36 from mypyc.ir.rtypes import (
37 RInstance,
38 RPrimitive,
39 RTuple,
40 RType,
41 RUnion,
42 RVec,
43 int_rprimitive,
44 is_bool_or_bit_rprimitive,
45 is_bytearray_rprimitive,
46 is_bytes_rprimitive,
47 is_dict_rprimitive,
48 is_fixed_width_rtype,
49 is_float_rprimitive,
50 is_frozenset_rprimitive,
51 is_int16_rprimitive,
52 is_int32_rprimitive,
53 is_int64_rprimitive,
54 is_int_rprimitive,
55 is_list_rprimitive,
56 is_native_rprimitive,
57 is_none_rprimitive,
58 is_object_rprimitive,
59 is_optional_type,
60 is_range_rprimitive,
61 is_set_rprimitive,
62 is_short_int_rprimitive,
63 is_str_rprimitive,
64 is_tuple_rprimitive,
65 is_uint8_rprimitive,
66 object_rprimitive,
67 optional_value_type,
68 vec_api_by_item_type,
69 vec_item_type_tags,
70 )
71 from mypyc.namegen import NameGenerator, exported_name
72 from mypyc.primitives.registry import builtin_names
73 from mypyc.sametype import is_same_type
74
75 # Whether to insert debug asserts for all error handling, to quickly
76 # catch errors propagating without exceptions set.
77 DEBUG_ERRORS: Final = False
78
79 PREFIX_MAP: Final = {
80 NAMESPACE_STATIC: STATIC_PREFIX,
81 NAMESPACE_TYPE: TYPE_PREFIX,
82 NAMESPACE_MODULE: MODULE_PREFIX,
83 NAMESPACE_TYPE_VAR: TYPE_VAR_PREFIX,
84 }
85
86 # Map from RVec._ctype to C macro prefix for VEC_*_INCREF/DECREF/BUF macros
87 VEC_MACRO_PREFIX: Final = {
88 "VecI64": "VEC_I64",
89 "VecI32": "VEC_I32",
90 "VecI16": "VEC_I16",
91 "VecU8": "VEC_U8",
92 "VecFloat": "VEC_FLOAT",
93 "VecBool": "VEC_BOOL",
94 "VecT": "VEC_T",
95 "VecNested": "VEC_NESTED",
96 }
97
98
99 class HeaderDeclaration:
100 """A representation of a declaration in C.
101
102 This is used to generate declarations in header files and
103 (optionally) definitions in source files.
104
105 Attributes:
106 decl: C source code for the declaration.
107 defn: Optionally, C source code for a definition.
108 dependencies: The names of any objects that must be declared prior.
109 is_type: Whether the declaration is of a C type. (C types will be declared in
110 external header files and not marked 'extern'.)
111 needs_export: Whether the declared object needs to be exported to
112 other modules in the linking table.
113 """
114
115 def __init__(
116 self,
117 decl: str | list[str],
118 defn: list[str] | None = None,
119 *,
120 dependencies: set[str] | None = None,
121 is_type: bool = False,
122 needs_export: bool = False,
123 ) -> None:
124 self.decl = [decl] if isinstance(decl, str) else decl
125 self.defn = defn
126 self.dependencies = dependencies or set()
127 self.is_type = is_type
128 self.needs_export = needs_export
129
130
131 class EmitterContext:
132 """Shared emitter state for a compilation group."""
133
134 def __init__(
135 self,
136 names: NameGenerator,
137 strict_traceback_checks: bool,
138 group_name: str | None = None,
139 group_map: dict[str, str | None] | None = None,
140 ) -> None:
141 """Setup shared emitter state.
142
143 Args:
144 names: The name generator to use
145 group_map: Map from module names to group name
146 group_name: Current group name
147 """
148 self.temp_counter = 0
149 self.names = names
150 self.group_name = group_name
151 self.group_map = group_map or {}
152 # Groups that this group depends on
153 self.group_deps: set[str] = set()
154
155 # The map below is used for generating declarations and
156 # definitions at the top of the C file. The main idea is that they can
157 # be generated at any time during the emit phase.
158
159 # A map of a C identifier to whatever the C identifier declares. Currently this is
160 # used for declaring structs and the key corresponds to the name of the struct.
161 # The declaration contains the body of the struct.
162 self.declarations: dict[str, HeaderDeclaration] = {}
163
164 self.literals = Literals()
165 # See mypyc/options.py for context.
166 self.strict_traceback_checks = strict_traceback_checks
167
168
169 class ErrorHandler:
170 """Describes handling errors in unbox/cast operations."""
171
172
173 class AssignHandler(ErrorHandler):
174 """Assign an error value on error."""
175
176
177 class GotoHandler(ErrorHandler):
178 """Goto label on error."""
179
180 def __init__(self, label: str) -> None:
181 self.label = label
182
183
184 class TracebackAndGotoHandler(ErrorHandler):
185 """Add traceback item and goto label on error."""
186
187 def __init__(
188 self, label: str, source_path: str, module_name: str, traceback_entry: tuple[str, int]
189 ) -> None:
190 self.label = label
191 self.source_path = source_path
192 self.module_name = module_name
193 self.traceback_entry = traceback_entry
194
195
196 class ReturnHandler(ErrorHandler):
197 """Return a constant value on error."""
198
199 def __init__(self, value: str) -> None:
200 self.value = value
201
202
203 class Emitter:
204 """Helper for C code generation."""
205
206 def __init__(
207 self,
208 context: EmitterContext,
209 value_names: dict[Value, str] | None = None,
210 capi_version: tuple[int, int] | None = None,
211 filepath: str | None = None,
212 ) -> None:
213 self.context = context
214 self.capi_version = capi_version or sys.version_info[:2]
215 self.names = context.names
216 self.value_names = value_names or {}
217 self.fragments: list[str] = []
218 self._indent = 0
219 self.filepath = filepath
220
221 # Low-level operations
222
223 def indent(self) -> None:
224 self._indent += 4
225
226 def dedent(self) -> None:
227 self._indent -= 4
228 assert self._indent >= 0
229
230 def label(self, label: BasicBlock) -> str:
231 return "CPyL%s" % label.label
232
233 def reg(self, reg: Value) -> str:
234 return REG_PREFIX + self.value_names[reg]
235
236 def attr(self, name: str) -> str:
237 return ATTR_PREFIX + name
238
239 def object_annotation(self, obj: object, line: str) -> str:
240 """Build a C comment with an object's string representation.
241
242 If the comment exceeds the line length limit, it's wrapped into a
243 multiline string (with the extra lines indented to be aligned with
244 the first line's comment).
245
246 If it contains illegal characters, an empty string is returned."""
247 line_width = self._indent + len(line)
248 formatted = pprint.pformat(obj, compact=True, indent=1, width=max(90 - line_width, 20))
249 if any(x in formatted for x in ("/*", "*/", "\0")):
250 return ""
251
252 if "\n" in formatted:
253 first_line, rest = formatted.split("\n", maxsplit=1)
254 comment_continued = textwrap.indent(rest, (line_width + 3) * " ")
255 return f" /* {first_line}\n{comment_continued} */"
256 else:
257 return f" /* {formatted} */"
258
259 def emit_line(self, line: str = "", *, ann: object = None) -> None:
260 if line.startswith("}"):
261 self.dedent()
262 comment = self.object_annotation(ann, line) if ann is not None else ""
263 self.fragments.append(self._indent * " " + line + comment + "\n")
264 if line.endswith("{"):
265 self.indent()
266
267 def emit_lines(self, *lines: str) -> None:
268 for line in lines:
269 self.emit_line(line)
270
271 def emit_label(self, label: BasicBlock | str) -> None:
272 if isinstance(label, str):
273 text = label
274 else:
275 if label.label == 0 or not label.referenced:
276 return
277
278 text = self.label(label)
279 # Extra semicolon prevents an error when the next line declares a tempvar
280 self.fragments.append(f"{text}: ;\n")
281
282 def emit_from_emitter(self, emitter: Emitter) -> None:
283 self.fragments.extend(emitter.fragments)
284
285 def emit_printf(self, fmt: str, *args: str) -> None:
286 fmt = fmt.replace("\n", "\\n")
287 self.emit_line("printf(%s);" % ", ".join(['"%s"' % fmt] + list(args)))
288 self.emit_line("fflush(stdout);")
289
290 def temp_name(self) -> str:
291 self.context.temp_counter += 1
292 return "__tmp%d" % self.context.temp_counter
293
294 def new_label(self) -> str:
295 self.context.temp_counter += 1
296 return "__LL%d" % self.context.temp_counter
297
298 def get_module_group_prefix(self, module_name: str) -> str:
299 """Get the group prefix for a module (relative to the current group).
300
301 The prefix should be prepended to the object name whenever
302 accessing an object from this module.
303
304 If the module lives is in the current compilation group, there is
305 no prefix. But if it lives in a different group (and hence a separate
306 extension module), we need to access objects from it indirectly via an
307 export table.
308
309 For example, for code in group `a` to call a function `bar` in group `b`,
310 it would need to do `exports_b.CPyDef_bar(...)`, while code that is
311 also in group `b` can simply do `CPyDef_bar(...)`.
312
313 Thus the prefix for a module in group `b` is 'exports_b.' if the current
314 group is *not* b and just '' if it is.
315 """
316 groups = self.context.group_map
317 target_group_name = groups.get(module_name)
318 if target_group_name and target_group_name != self.context.group_name:
319 self.context.group_deps.add(target_group_name)
320 return f"exports_{exported_name(target_group_name)}."
321 else:
322 return ""
323
324 def get_group_prefix(self, obj: ClassIR | FuncDecl) -> str:
325 """Get the group prefix for an object."""
326 # See docs above
327 return self.get_module_group_prefix(obj.module_name)
328
329 def register_group_dep(self, cl: ClassIR) -> None:
330 """Record `cl`'s defining group as a cross-group dep, if any.
331
332 Call this when emitting code that refers to `cl`'s struct
333 layout: the .c file consuming that layout needs the defining
334 group's `__native_*.h` included, and group_deps drives which
335 headers get pulled in.
336 """
337 target_group = self.context.group_map.get(cl.module_name)
338 if target_group and target_group != self.context.group_name:
339 self.context.group_deps.add(target_group)
340
341 def static_name(self, id: str, module: str | None, prefix: str = STATIC_PREFIX) -> str:
342 """Create name of a C static variable.
343
344 These are used for literals and imported modules, among other
345 things.
346
347 The caller should ensure that the (id, module) pair cannot
348 overlap with other calls to this method within a compilation
349 group.
350 """
351 lib_prefix = "" if not module else self.get_module_group_prefix(module)
352 # If we are accessing static via the export table, we need to dereference
353 # the pointer also.
354 star_maybe = "*" if lib_prefix else ""
355 suffix = self.names.private_name(module or "", id)
356 return f"{star_maybe}{lib_prefix}{prefix}{suffix}"
357
358 def type_struct_name(self, cl: ClassIR) -> str:
359 return self.static_name(cl.name, cl.module_name, prefix=TYPE_PREFIX)
360
361 def ctype(self, rtype: RType) -> str:
362 return rtype._ctype
363
364 def ctype_spaced(self, rtype: RType) -> str:
365 """Adds a space after ctype for non-pointers."""
366 ctype = self.ctype(rtype)
367 if ctype[-1] == "*":
368 return ctype
369 else:
370 return ctype + " "
371
372 def set_undefined_value(self, target: str, rtype: RType) -> None:
373 if isinstance(rtype, RVec):
374 self.emit_line(f"{target}.len = -1;")
375 self.emit_line(f"{target}.items = NULL;")
376 else:
377 self.emit_line(f"{target} = {self.c_undefined_value(rtype)};")
378
379 def c_undefined_value(self, rtype: RType) -> str:
380 if not rtype.is_unboxed:
381 return "NULL"
382 elif isinstance(rtype, RPrimitive):
383 return rtype.c_undefined
384 elif isinstance(rtype, RTuple):
385 return self.tuple_undefined_value(rtype)
386 elif isinstance(rtype, RVec):
387 return f"({self.ctype(rtype)}) {{ -1, NULL }}"
388 assert False, rtype
389
390 def c_error_value(self, rtype: RType) -> str:
391 return self.c_undefined_value(rtype)
392
393 def native_function_name(self, fn: FuncDecl) -> str:
394 return f"{NATIVE_PREFIX}{fn.cname(self.names)}"
395
396 def native_function_call(self, fn: FuncDecl) -> str:
397 """Return the C expression for a call to `fn`'s native (CPyDef_) entry.
398
399 For cross-group references under `separate=True`, this prepends the
400 exports-table indirection (e.g. `exports_other.CPyDef_foo`). Same as
401 `native_function_name()` for in-group calls.
402 """
403 return f"{self.get_group_prefix(fn)}{self.native_function_name(fn)}"
404
405 def wrapper_function_call(self, fn: FuncDecl) -> str:
406 """Return the C expression for a call to `fn`'s Python-wrapper (CPyPy_) entry.
407
408 Like `native_function_call`, but for the PyObject-level wrapper that
409 boxes/unboxes arguments. Used from slot generators (tp_init, etc.).
410 """
411 return f"{self.get_group_prefix(fn)}{PREFIX}{fn.cname(self.names)}"
412
413 def tuple_c_declaration(self, rtuple: RTuple) -> list[str]:
414 result = [
415 f"#ifndef MYPYC_DECLARED_{rtuple.struct_name}",
416 f"#define MYPYC_DECLARED_{rtuple.struct_name}",
417 f"typedef struct {rtuple.struct_name} {{",
418 ]
419 if len(rtuple.types) == 0: # empty tuple
420 # Empty tuples contain a flag so that they can still indicate
421 # error values.
422 result.append("int empty_struct_error_flag;")
423 else:
424 i = 0
425 for typ in rtuple.types:
426 result.append(f"{self.ctype_spaced(typ)}f{i};")
427 i += 1
428 result.append(f"}} {rtuple.struct_name};")
429 result.append("#endif")
430 result.append("")
431
432 return result
433
434 def bitmap_field(self, index: int) -> str:
435 """Return C field name used for attribute bitmap."""
436 n = index // BITMAP_BITS
437 if n == 0:
438 return "bitmap"
439 return f"bitmap{n + 1}"
440
441 def attr_bitmap_expr(self, obj: str, cl: ClassIR, index: int) -> str:
442 """Return reference to the attribute definedness bitmap."""
443 cast = f"({cl.struct_name(self.names)} *)"
444 attr = self.bitmap_field(index)
445 return f"({cast}{obj})->{attr}"
446
447 def emit_attr_bitmap_set(
448 self, value: str, obj: str, rtype: RType, cl: ClassIR, attr: str
449 ) -> None:
450 """Mark an attribute as defined in the attribute bitmap.
451
452 Assumes that the attribute is tracked in the bitmap (only some attributes
453 use the bitmap). If 'value' is not equal to the error value, do nothing.
454 """
455 self._emit_attr_bitmap_update(value, obj, rtype, cl, attr, clear=False)
456
457 def emit_attr_bitmap_clear(self, obj: str, rtype: RType, cl: ClassIR, attr: str) -> None:
458 """Mark an attribute as undefined in the attribute bitmap.
459
460 Unlike emit_attr_bitmap_set, clear unconditionally.
461 """
462 self._emit_attr_bitmap_update("", obj, rtype, cl, attr, clear=True)
463
464 def _emit_attr_bitmap_update(
465 self, value: str, obj: str, rtype: RType, cl: ClassIR, attr: str, clear: bool
466 ) -> None:
467 if value:
468 check = self.error_value_check(rtype, value, "==")
469 self.emit_line(f"if (unlikely({check})) {{")
470 index = cl.bitmap_attrs.index(attr)
471 mask = 1 << (index & (BITMAP_BITS - 1))
472 bitmap = self.attr_bitmap_expr(obj, cl, index)
473 if clear:
474 self.emit_line(f"{bitmap} &= ~{mask};")
475 else:
476 self.emit_line(f"{bitmap} |= {mask};")
477 if value:
478 self.emit_line("}")
479
480 def emit_undefined_attr_check(
481 self,
482 rtype: RType,
483 attr_expr: str,
484 compare: str,
485 obj: str,
486 attr: str,
487 cl: ClassIR,
488 *,
489 unlikely: bool = False,
490 ) -> None:
491 check = self.error_value_check(rtype, attr_expr, compare)
492 if unlikely:
493 check = f"unlikely({check})"
494 if rtype.error_overlap:
495 index = cl.bitmap_attrs.index(attr)
496 bit = 1 << (index & (BITMAP_BITS - 1))
497 attr = self.bitmap_field(index)
498 obj_expr = f"({cl.struct_name(self.names)} *){obj}"
499 check = f"{check} && !(({obj_expr})->{attr} & {bit})"
500 self.emit_line(f"if ({check}) {{")
501
502 def error_value_check(self, rtype: RType, value: str, compare: str) -> str:
503 if isinstance(rtype, RTuple):
504 return self.tuple_undefined_check_cond(
505 rtype, value, self.c_error_value, compare, check_exception=False
506 )
507 elif isinstance(rtype, RVec):
508 if compare == "==":
509 return f"{value}.len < 0"
510 elif compare == "!=":
511 return f"{value}.len >= 0"
512 assert False, compare
513 else:
514 return f"{value} {compare} {self.c_error_value(rtype)}"
515
516 def tuple_undefined_check_cond(
517 self,
518 rtuple: RTuple,
519 tuple_expr_in_c: str,
520 c_type_compare_val: Callable[[RType], str],
521 compare: str,
522 *,
523 check_exception: bool = True,
524 ) -> str:
525 if len(rtuple.types) == 0:
526 # empty tuple
527 return "{}.empty_struct_error_flag {} {}".format(
528 tuple_expr_in_c, compare, c_type_compare_val(int_rprimitive)
529 )
530 if rtuple.error_overlap:
531 i = 0
532 item_type = rtuple.types[0]
533 else:
534 for i, typ in enumerate(rtuple.types):
535 if not typ.error_overlap:
536 item_type = rtuple.types[i]
537 break
538 else:
539 assert False, "not expecting tuple with error overlap"
540 if isinstance(item_type, RTuple):
541 return self.tuple_undefined_check_cond(
542 item_type, tuple_expr_in_c + f".f{i}", c_type_compare_val, compare
543 )
544 elif isinstance(item_type, RVec):
545 return f"{tuple_expr_in_c}.f{i}.len {compare} -1"
546 else:
547 check = f"{tuple_expr_in_c}.f{i} {compare} {c_type_compare_val(item_type)}"
548 if rtuple.error_overlap and check_exception:
549 check += " && PyErr_Occurred()"
550 return check
551
552 def tuple_undefined_value(self, rtuple: RTuple) -> str:
553 """Undefined tuple value suitable in an expression."""
554 return f"({rtuple.struct_name}) {self.c_initializer_undefined_value(rtuple)}"
555
556 def c_initializer_undefined_value(self, rtype: RType) -> str:
557 """Undefined value represented in a form suitable for variable initialization."""
558 if isinstance(rtype, RTuple):
559 if not rtype.types:
560 # Empty tuples contain a flag so that they can still indicate
561 # error values.
562 return f"{{ {int_rprimitive.c_undefined} }}"
563 items = ", ".join([self.c_initializer_undefined_value(t) for t in rtype.types])
564 return f"{{ {items} }}"
565 elif isinstance(rtype, RVec):
566 return "{ -1, NULL }"
567 else:
568 return self.c_undefined_value(rtype)
569
570 # Higher-level operations
571
572 def declare_tuple_struct(self, tuple_type: RTuple) -> None:
573 if tuple_type.struct_name not in self.context.declarations:
574 dependencies = set()
575 for typ in tuple_type.types:
576 # XXX other types might eventually need similar behavior
577 if isinstance(typ, RTuple):
578 dependencies.add(typ.struct_name)
579
580 self.context.declarations[tuple_type.struct_name] = HeaderDeclaration(
581 self.tuple_c_declaration(tuple_type), dependencies=dependencies, is_type=True
582 )
583
584 def emit_inc_ref(self, dest: str, rtype: RType, *, rare: bool = False) -> None:
585 """Increment reference count of C expression `dest`.
586
587 For composite unboxed structures (e.g. tuples) recursively
588 increment reference counts for each component.
589
590 If rare is True, optimize for code size and compilation speed.
591 """
592 if is_int_rprimitive(rtype):
593 if rare:
594 self.emit_line("CPyTagged_IncRef(%s);" % dest)
595 else:
596 self.emit_line("CPyTagged_INCREF(%s);" % dest)
597 elif isinstance(rtype, RTuple):
598 for i, item_type in enumerate(rtype.types):
599 self.emit_inc_ref(f"{dest}.f{i}", item_type)
600 elif isinstance(rtype, RVec):
601 prefix = VEC_MACRO_PREFIX[rtype._ctype]
602 self.emit_line(f"{prefix}_INCREF({dest});")
603 elif not rtype.is_unboxed:
604 # Always inline, since this is a simple but very hot op
605 if rtype.may_be_immortal or not HAVE_IMMORTAL:
606 self.emit_line("CPy_INCREF(%s);" % dest)
607 else:
608 self.emit_line("CPy_INCREF_NO_IMM(%s);" % dest)
609 # Otherwise assume it's an unboxed, pointerless value and do nothing.
610
611 def emit_dec_ref(
612 self, dest: str, rtype: RType, *, is_xdec: bool = False, rare: bool = False
613 ) -> None:
614 """Decrement reference count of C expression `dest`.
615
616 For composite unboxed structures (e.g. tuples) recursively
617 decrement reference counts for each component.
618
619 If rare is True, optimize for code size and compilation speed.
620 """
621 x = "X" if is_xdec else ""
622 if is_int_rprimitive(rtype):
623 if rare:
624 self.emit_line(f"CPyTagged_{x}DecRef({dest});")
625 else:
626 # Inlined
627 self.emit_line(f"CPyTagged_{x}DECREF({dest});")
628 elif isinstance(rtype, RTuple):
629 for i, item_type in enumerate(rtype.types):
630 self.emit_dec_ref(f"{dest}.f{i}", item_type, is_xdec=is_xdec, rare=rare)
631 elif isinstance(rtype, RVec):
632 prefix = VEC_MACRO_PREFIX[rtype._ctype]
633 self.emit_line(f"{prefix}_DECREF({dest});")
634 elif not rtype.is_unboxed:
635 if rare:
636 self.emit_line(f"CPy_{x}DecRef({dest});")
637 else:
638 # Inlined
639 if rtype.may_be_immortal or not HAVE_IMMORTAL:
640 self.emit_line(f"CPy_{x}DECREF({dest});")
641 else:
642 self.emit_line(f"CPy_{x}DECREF_NO_IMM({dest});")
643 elif rtype.is_refcounted:
644 assert False, f"dec_ref not implemented for {rtype}"
645 # Otherwise assume it's an unboxed, pointerless value and do nothing.
646
647 def pretty_name(self, typ: RType) -> str:
648 value_type = optional_value_type(typ)
649 if value_type is not None:
650 return "%s or None" % self.pretty_name(value_type)
651 return str(typ)
652
653 def emit_cast(
654 self,
655 src: str,
656 dest: str,
657 typ: RType,
658 *,
659 declare_dest: bool = False,
660 error: ErrorHandler | None = None,
661 raise_exception: bool = True,
662 optional: bool = False,
663 src_type: RType | None = None,
664 likely: bool = True,
665 ) -> None:
666 """Emit code for casting a value of given type.
667
668 Somewhat strangely, this supports unboxed types but only
669 operates on boxed versions. This is necessary to properly
670 handle types such as Optional[int] in compatibility glue.
671
672 By default, assign NULL (error value) to dest if the value has
673 an incompatible type and raise TypeError. These can be customized
674 using 'error' and 'raise_exception'.
675
676 Always copy/steal the reference in 'src'.
677
678 Args:
679 src: Name of source C variable
680 dest: Name of target C variable
681 typ: Type of value
682 declare_dest: If True, also declare the variable 'dest'
683 error: What happens on error
684 raise_exception: If True, also raise TypeError on failure
685 likely: If the cast is likely to succeed (can be False for unions)
686 """
687 error = error or AssignHandler()
688
689 # Special case casting *from* optional
690 if src_type and is_optional_type(src_type) and not is_object_rprimitive(typ):
691 value_type = optional_value_type(src_type)
692 assert value_type is not None
693 if is_same_type(value_type, typ):
694 if declare_dest:
695 self.emit_line(f"PyObject *{dest};")
696 check = "({} != Py_None)"
697 if likely:
698 check = f"(likely{check})"
699 self.emit_arg_check(src, dest, typ, check.format(src), optional)
700 self.emit_lines(f" {dest} = {src};", "else {")
701 self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
702 self.emit_line("}")
703 return
704
705 # TODO: Verify refcount handling.
706 if (
707 is_list_rprimitive(typ)
708 or is_dict_rprimitive(typ)
709 or is_set_rprimitive(typ)
710 or is_frozenset_rprimitive(typ)
711 or is_str_rprimitive(typ)
712 or is_range_rprimitive(typ)
713 or is_float_rprimitive(typ)
714 or is_int_rprimitive(typ)
715 or is_bool_or_bit_rprimitive(typ)
716 or is_fixed_width_rtype(typ)
717 ):
718 if declare_dest:
719 self.emit_line(f"PyObject *{dest};")
720 if is_list_rprimitive(typ):
721 prefix = "PyList"
722 elif is_dict_rprimitive(typ):
723 prefix = "PyDict"
724 elif is_set_rprimitive(typ):
725 prefix = "PySet"
726 elif is_frozenset_rprimitive(typ):
727 prefix = "PyFrozenSet"
728 elif is_str_rprimitive(typ):
729 prefix = "PyUnicode"
730 elif is_range_rprimitive(typ):
731 prefix = "PyRange"
732 elif is_float_rprimitive(typ):
733 prefix = "CPyFloat"
734 elif is_int_rprimitive(typ) or is_fixed_width_rtype(typ):
735 # TODO: Range check for fixed-width types?
736 prefix = "PyLong"
737 elif is_bool_or_bit_rprimitive(typ):
738 prefix = "PyBool"
739 else:
740 assert False, f"unexpected primitive type: {typ}"
741 check = "({}_Check({}))"
742 if likely:
743 check = f"(likely{check})"
744 self.emit_arg_check(src, dest, typ, check.format(prefix, src), optional)
745 self.emit_lines(f" {dest} = {src};", "else {")
746 self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
747 self.emit_line("}")
748 elif is_bytes_rprimitive(typ):
749 if declare_dest:
750 self.emit_line(f"PyObject *{dest};")
751 check = "(PyBytes_Check({}))"
752 if likely:
753 check = f"(likely{check})"
754 self.emit_arg_check(src, dest, typ, check.format(src, src), optional)
755 self.emit_lines(f" {dest} = {src};", "else {")
756 self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
757 self.emit_line("}")
758 elif is_bytearray_rprimitive(typ):
759 if declare_dest:
760 self.emit_line(f"PyObject *{dest};")
761 check = "(PyByteArray_Check({}))"
762 if likely:
763 check = f"(likely{check})"
764 self.emit_arg_check(src, dest, typ, check.format(src, src), optional)
765 self.emit_lines(f" {dest} = {src};", "else {")
766 self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
767 self.emit_line("}")
768 elif is_tuple_rprimitive(typ):
769 if declare_dest:
770 self.emit_line(f"{self.ctype(typ)} {dest};")
771 check = "(PyTuple_Check({}))"
772 if likely:
773 check = f"(likely{check})"
774 self.emit_arg_check(src, dest, typ, check.format(src), optional)
775 self.emit_lines(f" {dest} = {src};", "else {")
776 self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
777 self.emit_line("}")
778 elif isinstance(typ, RInstance):
779 if declare_dest:
780 self.emit_line(f"PyObject *{dest};")
781 concrete = all_concrete_classes(typ.class_ir)
782 # If there are too many concrete subclasses or we can't find any
783 # (meaning the code ought to be dead or we aren't doing global opts),
784 # fall back to a normal typecheck.
785 # Otherwise check all the subclasses.
786 if not concrete or len(concrete) > FAST_ISINSTANCE_MAX_SUBCLASSES + 1:
787 check = "(PyObject_TypeCheck({}, {}))".format(
788 src, self.type_struct_name(typ.class_ir)
789 )
790 else:
791 full_str = "(Py_TYPE({src}) == {targets[0]})"
792 for i in range(1, len(concrete)):
793 full_str += " || (Py_TYPE({src}) == {targets[%d]})" % i
794 if len(concrete) > 1:
795 full_str = "(%s)" % full_str
796 check = full_str.format(
797 src=src, targets=[self.type_struct_name(ir) for ir in concrete]
798 )
799 if likely:
800 check = f"(likely{check})"
801 self.emit_arg_check(src, dest, typ, check, optional)
802 self.emit_lines(f" {dest} = {src};", "else {")
803 self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
804 self.emit_line("}")
805 elif is_none_rprimitive(typ):
806 if declare_dest:
807 self.emit_line(f"PyObject *{dest};")
808 check = "({} == Py_None)"
809 if likely:
810 check = f"(likely{check})"
811 self.emit_arg_check(src, dest, typ, check.format(src), optional)
812 self.emit_lines(f" {dest} = {src};", "else {")
813 self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
814 self.emit_line("}")
815 elif is_object_rprimitive(typ):
816 if declare_dest:
817 self.emit_line(f"PyObject *{dest};")
818 self.emit_arg_check(src, dest, typ, "", optional)
819 self.emit_line(f"{dest} = {src};")
820 if optional:
821 self.emit_line("}")
822 elif is_native_rprimitive(typ):
823 # Native primitive types have type check functions of form "CPy<Name>_Check(...)".
824 if declare_dest:
825 self.emit_line(f"PyObject *{dest};")
826 short_name = typ.name.rsplit(".", 1)[-1]
827 check = f"(CPy{short_name}_Check({src}))"
828 if likely:
829 check = f"(likely{check})"
830 self.emit_arg_check(src, dest, typ, check, optional)
831 self.emit_lines(f" {dest} = {src};", "else {")
832 self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
833 self.emit_line("}")
834 elif isinstance(typ, RUnion):
835 self.emit_union_cast(
836 src, dest, typ, declare_dest, error, optional, src_type, raise_exception
837 )
838 elif isinstance(typ, RTuple):
839 assert not optional
840 self.emit_tuple_cast(src, dest, typ, declare_dest, error, src_type)
841 elif isinstance(typ, RVec):
842 if declare_dest:
843 self.emit_line(f"PyObject *{dest};")
844 # Build type check expression based on vec kind
845 api_name = vec_api_by_item_type.get(typ.item_type)
846 depth = typ.depth()
847 if api_name:
848 # Specialized vec types (vec[i64], vec[i32], etc.)
849 check = f"(Py_TYPE({src}) == {api_name}.boxed_type)"
850 elif depth == 0:
851 # Generic vec types (vec[T], vec[T | None]) with reference type items
852 item_type_c = self.vec_item_type_c(typ)
853 check = (
854 f"(Py_TYPE({src}) == VecTApi.boxed_type && "
855 f"VEC_T_BUF(((VecTObject *){src})->vec)->item_type == {item_type_c})"
856 )
857 else:
858 # Nested vec types (vec[vec[...]]). Check boxed type, item type, and depth.
859 unwrapped = typ.unwrap_item_type()
860 if unwrapped in vec_item_type_tags:
861 type_value = str(vec_item_type_tags[unwrapped])
862 else:
863 type_value = self.vec_item_type_c(typ)
864 check = (
865 f"(Py_TYPE({src}) == VecNestedApi.boxed_type && "
866 f"VEC_NESTED_BUF(((VecNestedObject *){src})->vec)->item_type == {type_value} && "
867 f"VEC_NESTED_BUF(((VecNestedObject *){src})->vec)->depth == {depth})"
868 )
869 if likely:
870 check = f"(likely{check})"
871 self.emit_arg_check(src, dest, typ, check, optional)
872 self.emit_lines(f" {dest} = {src};", "else {")
873 self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
874 self.emit_line("}")
875 else:
876 assert False, "Cast not implemented: %s" % typ
877
878 def emit_cast_error_handler(
879 self, error: ErrorHandler, src: str, dest: str, typ: RType, raise_exception: bool
880 ) -> None:
881 if raise_exception:
882 if isinstance(error, TracebackAndGotoHandler):
883 # Merge raising and emitting traceback entry into a single call.
884 self.emit_type_error_traceback(
885 error.source_path, error.module_name, error.traceback_entry, typ=typ, src=src
886 )
887 self.emit_line("goto %s;" % error.label)
888 return
889 self.emit_line(f'CPy_TypeError("{self.pretty_name(typ)}", {src}); ')
890 if isinstance(error, AssignHandler):
891 self.emit_line("%s = NULL;" % dest)
892 elif isinstance(error, GotoHandler):
893 self.emit_line("goto %s;" % error.label)
894 elif isinstance(error, TracebackAndGotoHandler):
895 self.emit_line("%s = NULL;" % dest)
896 self.emit_traceback(error.source_path, error.module_name, error.traceback_entry)
897 self.emit_line("goto %s;" % error.label)
898 else:
899 assert isinstance(error, ReturnHandler), error
900 self.emit_line("return %s;" % error.value)
901
902 def emit_union_cast(
903 self,
904 src: str,
905 dest: str,
906 typ: RUnion,
907 declare_dest: bool,
908 error: ErrorHandler,
909 optional: bool,
910 src_type: RType | None,
911 raise_exception: bool,
912 ) -> None:
913 """Emit cast to a union type.
914
915 The arguments are similar to emit_cast.
916 """
917 if declare_dest:
918 self.emit_line(f"PyObject *{dest};")
919 good_label = self.new_label()
920 if optional:
921 self.emit_line(f"if ({src} == NULL) {{")
922 self.emit_line(f"{dest} = {self.c_error_value(typ)};")
923 self.emit_line(f"goto {good_label};")
924 self.emit_line("}")
925 for item in typ.items:
926 self.emit_cast(
927 src,
928 dest,
929 item,
930 declare_dest=False,
931 raise_exception=False,
932 optional=False,
933 likely=False,
934 )
935 self.emit_line(f"if ({dest} != NULL) goto {good_label};")
936 # Handle cast failure.
937 self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
938 self.emit_label(good_label)
939
940 def emit_tuple_cast(
941 self,
942 src: str,
943 dest: str,
944 typ: RTuple,
945 declare_dest: bool,
946 error: ErrorHandler,
947 src_type: RType | None,
948 ) -> None:
949 """Emit cast to a tuple type.
950
951 The arguments are similar to emit_cast.
952 """
953 if declare_dest:
954 self.emit_line(f"PyObject *{dest};")
955 # This reuse of the variable is super dodgy. We don't even
956 # care about the values except to check whether they are
957 # invalid.
958 out_label = self.new_label()
959 self.emit_lines(
960 "if (unlikely(!(PyTuple_Check({r}) && PyTuple_GET_SIZE({r}) == {size}))) {{".format(
961 r=src, size=len(typ.types)
962 ),
963 f"{dest} = NULL;",
964 f"goto {out_label};",
965 "}",
966 )
967 for i, item in enumerate(typ.types):
968 # Since we did the checks above this should never fail
969 self.emit_cast(
970 f"PyTuple_GET_ITEM({src}, {i})",
971 dest,
972 item,
973 declare_dest=False,
974 raise_exception=False,
975 optional=False,
976 )
977 self.emit_line(f"if ({dest} == NULL) goto {out_label};")
978
979 self.emit_line(f"{dest} = {src};")
980 self.emit_label(out_label)
981
982 def emit_arg_check(self, src: str, dest: str, typ: RType, check: str, optional: bool) -> None:
983 if optional:
984 self.emit_line(f"if ({src} == NULL) {{")
985 self.emit_line(f"{dest} = {self.c_error_value(typ)};")
986 if check != "":
987 self.emit_line("{}if {}".format("} else " if optional else "", check))
988 elif optional:
989 self.emit_line("else {")
990
991 def emit_unbox(
992 self,
993 src: str,
994 dest: str,
995 typ: RType,
996 *,
997 declare_dest: bool = False,
998 error: ErrorHandler | None = None,
999 raise_exception: bool = True,
1000 optional: bool = False,
1001 borrow: bool = False,
1002 ) -> None:
1003 """Emit code for unboxing a value of given type (from PyObject *).
1004
1005 By default, assign error value to dest if the value has an
1006 incompatible type and raise TypeError. These can be customized
1007 using 'error' and 'raise_exception'.
1008
1009 Generate a new reference unless 'borrow' is True.
1010
1011 Args:
1012 src: Name of source C variable
1013 dest: Name of target C variable
1014 typ: Type of value
1015 declare_dest: If True, also declare the variable 'dest'
1016 error: What happens on error
1017 raise_exception: If True, also raise TypeError on failure
1018 optional: If True, NULL src value is allowed and will map to error value
1019 borrow: If True, create a borrowed reference
1020
1021 """
1022 error = error or AssignHandler()
1023 # TODO: Verify refcount handling.
1024 if isinstance(error, AssignHandler):
1025 failure = f"{dest} = {self.c_error_value(typ)};"
1026 elif isinstance(error, GotoHandler):
1027 failure = "goto %s;" % error.label
1028 else:
1029 assert isinstance(error, ReturnHandler), error
1030 failure = "return %s;" % error.value
1031 if raise_exception:
1032 raise_exc = f'CPy_TypeError("{self.pretty_name(typ)}", {src}); '
1033 failure = raise_exc + failure
1034 if is_int_rprimitive(typ) or is_short_int_rprimitive(typ):
1035 if declare_dest:
1036 self.emit_line(f"CPyTagged {dest};")
1037 self.emit_arg_check(src, dest, typ, f"(likely(PyLong_Check({src})))", optional)
1038 if borrow:
1039 self.emit_line(f" {dest} = CPyTagged_BorrowFromObject({src});")
1040 else:
1041 self.emit_line(f" {dest} = CPyTagged_FromObject({src});")
1042 self.emit_line("else {")
1043 self.emit_line(failure)
1044 self.emit_line("}")
1045 elif is_bool_or_bit_rprimitive(typ):
1046 # Whether we are borrowing or not makes no difference.
1047 if declare_dest:
1048 self.emit_line(f"char {dest};")
1049 self.emit_arg_check(src, dest, typ, f"(unlikely(!PyBool_Check({src}))) {{", optional)
1050 self.emit_line(failure)
1051 self.emit_line("} else")
1052 conversion = f"{src} == Py_True"
1053 self.emit_line(f" {dest} = {conversion};")
1054 elif is_none_rprimitive(typ):
1055 # Whether we are borrowing or not makes no difference.
1056 if declare_dest:
1057 self.emit_line(f"char {dest};")
1058 self.emit_arg_check(src, dest, typ, f"(unlikely({src} != Py_None)) {{", optional)
1059 self.emit_line(failure)
1060 self.emit_line("} else")
1061 self.emit_line(f" {dest} = 1;")
1062 elif is_int64_rprimitive(typ):
1063 # Whether we are borrowing or not makes no difference.
1064 assert not optional # Not supported for overlapping error values
1065 if declare_dest:
1066 self.emit_line(f"int64_t {dest};")
1067 self.emit_line(f"{dest} = CPyLong_AsInt64({src});")
1068 if not isinstance(error, AssignHandler):
1069 self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure)
1070 elif is_int32_rprimitive(typ):
1071 # Whether we are borrowing or not makes no difference.
1072 assert not optional # Not supported for overlapping error values
1073 if declare_dest:
1074 self.emit_line(f"int32_t {dest};")
1075 self.emit_line(f"{dest} = CPyLong_AsInt32({src});")
1076 if not isinstance(error, AssignHandler):
1077 self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure)
1078 elif is_int16_rprimitive(typ):
1079 # Whether we are borrowing or not makes no difference.
1080 assert not optional # Not supported for overlapping error values
1081 if declare_dest:
1082 self.emit_line(f"int16_t {dest};")
1083 self.emit_line(f"{dest} = CPyLong_AsInt16({src});")
1084 if not isinstance(error, AssignHandler):
1085 self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure)
1086 elif is_uint8_rprimitive(typ):
1087 # Whether we are borrowing or not makes no difference.
1088 assert not optional # Not supported for overlapping error values
1089 if declare_dest:
1090 self.emit_line(f"uint8_t {dest};")
1091 self.emit_line(f"{dest} = CPyLong_AsUInt8({src});")
1092 if not isinstance(error, AssignHandler):
1093 self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure)
1094 elif is_float_rprimitive(typ):
1095 assert not optional # Not supported for overlapping error values
1096 if declare_dest:
1097 self.emit_line(f"double {dest};")
1098 # TODO: Don't use __float__ and __index__
1099 self.emit_line(f"{dest} = PyFloat_AsDouble({src});")
1100 self.emit_lines(f"if ({dest} == -1.0 && PyErr_Occurred()) {{", failure, "}")
1101 elif isinstance(typ, RTuple):
1102 self.declare_tuple_struct(typ)
1103 if declare_dest:
1104 self.emit_line(f"{self.ctype(typ)} {dest};")
1105 # HACK: The error handling for unboxing tuples is busted
1106 # and instead of fixing it I am just wrapping it in the
1107 # cast code which I think is right. This is not good.
1108 if optional:
1109 self.emit_line(f"if ({src} == NULL) {{")
1110 self.emit_line(f"{dest} = {self.c_error_value(typ)};")
1111 self.emit_line("} else {")
1112
1113 cast_temp = self.temp_name()
1114 self.emit_tuple_cast(
1115 src, cast_temp, typ, declare_dest=True, error=error, src_type=None
1116 )
1117 self.emit_line(f"if (unlikely({cast_temp} == NULL)) {{")
1118
1119 # self.emit_arg_check(src, dest, typ,
1120 # '(!PyTuple_Check({}) || PyTuple_Size({}) != {}) {{'.format(
1121 # src, src, len(typ.types)), optional)
1122 self.emit_line(failure) # TODO: Decrease refcount?
1123 self.emit_line("} else {")
1124 if not typ.types:
1125 self.emit_line(f"{dest}.empty_struct_error_flag = 0;")
1126 for i, item_type in enumerate(typ.types):
1127 temp = self.temp_name()
1128 # emit_tuple_cast above checks the size, so this should not fail
1129 self.emit_line(f"PyObject *{temp} = PyTuple_GET_ITEM({src}, {i});")
1130 temp2 = self.temp_name()
1131 # Unbox or check the item.
1132 if item_type.is_unboxed:
1133 self.emit_unbox(
1134 temp,
1135 temp2,
1136 item_type,
1137 raise_exception=raise_exception,
1138 error=error,
1139 declare_dest=True,
1140 borrow=borrow,
1141 )
1142 else:
1143 if not borrow:
1144 self.emit_inc_ref(temp, object_rprimitive)
1145 self.emit_cast(temp, temp2, item_type, declare_dest=True)
1146 self.emit_line(f"{dest}.f{i} = {temp2};")
1147 self.emit_line("}")
1148 if optional:
1149 self.emit_line("}")
1150 elif isinstance(typ, RVec):
1151 if declare_dest:
1152 self.emit_line(f"{self.ctype(typ)} {dest};")
1153
1154 if optional:
1155 self.emit_line(f"if ({src} == NULL) {{")
1156 self.emit_line(f"{dest} = {self.c_error_value(typ)};")
1157 self.emit_line("} else {")
1158
1159 specialized_api_name = vec_api_by_item_type.get(typ.item_type)
1160 if specialized_api_name is not None:
1161 self.emit_line(f"{dest} = {specialized_api_name}.unbox({src});")
1162 else:
1163 depth = typ.depth()
1164 unwrapped = typ.unwrap_item_type()
1165 if unwrapped in vec_item_type_tags:
1166 type_value = str(vec_item_type_tags[unwrapped])
1167 else:
1168 type_value = self.vec_item_type_c(typ)
1169 if depth == 0:
1170 self.emit_line(f"{dest} = VecTApi.unbox({src}, {type_value});")
1171 else:
1172 self.emit_line(f"{dest} = VecNestedApi.unbox({src}, {type_value}, {depth});")
1173
1174 self.emit_line(f"if (VEC_IS_ERROR({dest})) {{")
1175 self.emit_line(failure)
1176 self.emit_line("}")
1177
1178 if optional:
1179 self.emit_line("}")
1180 else:
1181 assert False, "Unboxing not implemented: %s" % typ
1182
1183 def vec_item_type_c(self, typ: RVec) -> str:
1184 item_type = typ.unwrap_item_type()
1185 type_c_ptr = self.type_c_ptr(item_type)
1186 # Can never be None, since we unwrapped the item type above
1187 assert type_c_ptr is not None
1188 type_value = f"(size_t){type_c_ptr}"
1189 if typ.is_optional():
1190 type_value = f"({type_value} | 1)"
1191 return type_value
1192
1193 def type_c_ptr(self, typ: RPrimitive | RInstance) -> str | None:
1194 if isinstance(typ, RPrimitive) and typ.is_refcounted:
1195 return "&" + builtin_names[typ.name][1]
1196 elif isinstance(typ, RInstance):
1197 return self.type_struct_name(typ.class_ir)
1198 return None
1199
1200 def emit_box(
1201 self, src: str, dest: str, typ: RType, declare_dest: bool = False, can_borrow: bool = False
1202 ) -> None:
1203 """Emit code for boxing a value of given type.
1204
1205 Generate a simple assignment if no boxing is needed.
1206
1207 The source reference count is stolen for the result (no need to decref afterwards).
1208 """
1209 # TODO: Always generate a new reference (if a reference type)
1210 if declare_dest:
1211 declaration = "PyObject *"
1212 else:
1213 declaration = ""
1214 if is_int_rprimitive(typ) or is_short_int_rprimitive(typ):
1215 # Steal the existing reference if it exists.
1216 self.emit_line(f"{declaration}{dest} = CPyTagged_StealAsObject({src});")
1217 elif is_bool_or_bit_rprimitive(typ):
1218 # N.B: bool is special cased to produce a borrowed value
1219 # after boxing, so we don't need to increment the refcount
1220 # when this comes directly from a Box op.
1221 self.emit_lines(f"{declaration}{dest} = {src} ? Py_True : Py_False;")
1222 if not can_borrow:
1223 self.emit_inc_ref(dest, object_rprimitive)
1224 elif is_none_rprimitive(typ):
1225 # N.B: None is special cased to produce a borrowed value
1226 # after boxing, so we don't need to increment the refcount
1227 # when this comes directly from a Box op.
1228 self.emit_lines(f"{declaration}{dest} = Py_None;")
1229 if not can_borrow:
1230 self.emit_inc_ref(dest, object_rprimitive)
1231 elif is_int32_rprimitive(typ) or is_int16_rprimitive(typ) or is_uint8_rprimitive(typ):
1232 self.emit_line(f"{declaration}{dest} = PyLong_FromLong({src});")
1233 elif is_int64_rprimitive(typ):
1234 self.emit_line(f"{declaration}{dest} = PyLong_FromLongLong({src});")
1235 elif is_float_rprimitive(typ):
1236 self.emit_line(f"{declaration}{dest} = PyFloat_FromDouble({src});")
1237 elif isinstance(typ, RTuple):
1238 self.declare_tuple_struct(typ)
1239 if not typ.types:
1240 self.emit_line(f"{declaration}{dest} = CPyTuple_LoadEmptyTupleConstant();")
1241 else:
1242 self.emit_line(f"{declaration}{dest} = PyTuple_New({len(typ.types)});")
1243 self.emit_line(f"if (unlikely({dest} == NULL))")
1244 self.emit_line(" CPyError_OutOfMemory();")
1245
1246 # TODO: Fail if dest is None
1247 for i in range(len(typ.types)):
1248 if not typ.is_unboxed:
1249 self.emit_line(f"PyTuple_SET_ITEM({dest}, {i}, {src}.f{i}")
1250 else:
1251 inner_name = self.temp_name()
1252 self.emit_box(f"{src}.f{i}", inner_name, typ.types[i], declare_dest=True)
1253 self.emit_line(f"PyTuple_SET_ITEM({dest}, {i}, {inner_name});")
1254 elif isinstance(typ, RVec):
1255 specialized_api_name = vec_api_by_item_type.get(typ.item_type)
1256 if specialized_api_name is not None:
1257 api = specialized_api_name
1258 elif typ.depth() > 0:
1259 api = "VecNestedApi"
1260 else:
1261 api = "VecTApi"
1262 # Empty vecs of this sort don't describe item type, so it needs to be
1263 # passed explicitly.
1264 item_type = self.vec_item_type_c(typ)
1265 self.emit_line(f"{declaration}{dest} = {api}.box({src}, {item_type});")
1266 return
1267 self.emit_line(f"{declaration}{dest} = {api}.box({src});")
1268 else:
1269 assert not typ.is_unboxed
1270 # Type is boxed -- trivially just assign.
1271 self.emit_line(f"{declaration}{dest} = {src};")
1272
1273 def emit_error_check(self, value: str, rtype: RType, failure: str) -> None:
1274 """Emit code for checking a native function return value for uncaught exception."""
1275 if isinstance(rtype, RTuple):
1276 if len(rtype.types) == 0:
1277 return # empty tuples can't fail.
1278 else:
1279 cond = self.tuple_undefined_check_cond(rtype, value, self.c_error_value, "==")
1280 self.emit_line(f"if ({cond}) {{")
1281 elif isinstance(rtype, RVec):
1282 self.emit_line(f"if ({value}.len < 0) {{")
1283 elif rtype.error_overlap:
1284 # The error value is also valid as a normal value, so we need to also check
1285 # for a raised exception.
1286 self.emit_line(f"if ({value} == {self.c_error_value(rtype)} && PyErr_Occurred()) {{")
1287 else:
1288 self.emit_line(f"if ({value} == {self.c_error_value(rtype)}) {{")
1289 self.emit_lines(failure, "}")
1290
1291 def emit_gc_visit(self, target: str, rtype: RType) -> None:
1292 """Emit code for GC visiting a C variable reference.
1293
1294 Assume that 'target' represents a C expression that refers to a
1295 struct member, such as 'self->x'.
1296 """
1297 if not rtype.is_refcounted:
1298 # Not refcounted -> no pointers -> no GC interaction.
1299 return
1300 elif isinstance(rtype, RPrimitive) and rtype.name == "builtins.int":
1301 self.emit_line(f"if (CPyTagged_CheckLong({target})) {{")
1302 self.emit_line(f"Py_VISIT(CPyTagged_LongAsObject({target}));")
1303 self.emit_line("}")
1304 elif isinstance(rtype, RTuple):
1305 for i, item_type in enumerate(rtype.types):
1306 self.emit_gc_visit(f"{target}.f{i}", item_type)
1307 elif isinstance(rtype, RVec):
1308 prefix = VEC_MACRO_PREFIX[rtype._ctype]
1309 self.emit_line(f"if ({target}.items) {{ Py_VISIT({prefix}_BUF({target})); }}")
1310 elif self.ctype(rtype) == "PyObject *":
1311 # The simplest case.
1312 self.emit_line(f"Py_VISIT({target});")
1313 else:
1314 assert False, "emit_gc_visit() not implemented for %s" % repr(rtype)
1315
1316 def emit_gc_clear(self, target: str, rtype: RType) -> None:
1317 """Emit code for clearing a C attribute reference for GC.
1318
1319 Assume that 'target' represents a C expression that refers to a
1320 struct member, such as 'self->x'.
1321 """
1322 if not rtype.is_refcounted:
1323 # Not refcounted -> no pointers -> no GC interaction.
1324 return
1325 elif isinstance(rtype, RPrimitive) and rtype.name == "builtins.int":
1326 self.emit_line(f"if (CPyTagged_CheckLong({target})) {{")
1327 self.emit_line(f"CPyTagged __tmp = {target};")
1328 self.emit_line(f"{target} = {self.c_undefined_value(rtype)};")
1329 self.emit_line("Py_XDECREF(CPyTagged_LongAsObject(__tmp));")
1330 self.emit_line("}")
1331 elif isinstance(rtype, RTuple):
1332 for i, item_type in enumerate(rtype.types):
1333 self.emit_gc_clear(f"{target}.f{i}", item_type)
1334 elif isinstance(rtype, RVec):
1335 prefix = VEC_MACRO_PREFIX[rtype._ctype]
1336 self.emit_line(f"if ({target}.items) {{")
1337 self.emit_line(f" Py_DECREF({prefix}_BUF({target}));")
1338 self.emit_line(f" {target}.items = NULL;")
1339 self.emit_line("}")
1340 elif self.ctype(rtype) == "PyObject *" and self.c_undefined_value(rtype) == "NULL":
1341 # The simplest case.
1342 self.emit_line(f"Py_CLEAR({target});")
1343 else:
1344 assert False, "emit_gc_clear() not implemented for %s" % repr(rtype)
1345
1346 def emit_reuse_clear(self, target: str, rtype: RType) -> None:
1347 """Emit attribute clear before object is added into freelist.
1348
1349 Assume that 'target' represents a C expression that refers to a
1350 struct member, such as 'self->x'.
1351
1352 Unlike emit_gc_clear(), initialize attribute value to match a freshly
1353 allocated object.
1354 """
1355 if isinstance(rtype, RTuple):
1356 for i, item_type in enumerate(rtype.types):
1357 self.emit_reuse_clear(f"{target}.f{i}", item_type)
1358 elif not rtype.is_refcounted:
1359 self.emit_line(f"{target} = {rtype.c_undefined};")
1360 elif isinstance(rtype, RPrimitive) and rtype.name == "builtins.int":
1361 self.emit_line(f"if (CPyTagged_CheckLong({target})) {{")
1362 self.emit_line(f"CPyTagged __tmp = {target};")
1363 self.emit_line(f"{target} = {self.c_undefined_value(rtype)};")
1364 self.emit_line("Py_XDECREF(CPyTagged_LongAsObject(__tmp));")
1365 self.emit_line("} else {")
1366 self.emit_line(f"{target} = {self.c_undefined_value(rtype)};")
1367 self.emit_line("}")
1368 else:
1369 self.emit_gc_clear(target, rtype)
1370
1371 def emit_traceback(
1372 self, source_path: str, module_name: str, traceback_entry: tuple[str, int]
1373 ) -> None:
1374 return self._emit_traceback("CPy_AddTraceback", source_path, module_name, traceback_entry)
1375
1376 def emit_type_error_traceback(
1377 self,
1378 source_path: str,
1379 module_name: str,
1380 traceback_entry: tuple[str, int],
1381 *,
1382 typ: RType,
1383 src: str,
1384 ) -> None:
1385 func = "CPy_TypeErrorTraceback"
1386 type_str = f'"{self.pretty_name(typ)}"'
1387 return self._emit_traceback(
1388 func, source_path, module_name, traceback_entry, type_str=type_str, src=src
1389 )
1390
1391 def _emit_traceback(
1392 self,
1393 func: str,
1394 source_path: str,
1395 module_name: str,
1396 traceback_entry: tuple[str, int],
1397 type_str: str = "",
1398 src: str = "",
1399 ) -> None:
1400 if self.context.strict_traceback_checks:
1401 assert traceback_entry[1] >= 0, "Traceback cannot have a negative line number"
1402 globals_static = self.static_name("globals", module_name)
1403 line = '%s("%s", "%s", %d, %s' % (
1404 func,
1405 source_path.replace("\\", "\\\\"),
1406 traceback_entry[0],
1407 traceback_entry[1],
1408 globals_static,
1409 )
1410 if type_str:
1411 assert src
1412 line += f", {type_str}, {src}"
1413 line += ");"
1414 self.emit_line(line)
1415 if DEBUG_ERRORS:
1416 self.emit_line('assert(PyErr_Occurred() != NULL && "failure w/o err!");')
1417
1418 def emit_unbox_failure_with_overlapping_error_value(
1419 self, dest: str, typ: RType, failure: str
1420 ) -> None:
1421 self.emit_line(f"if ({dest} == {self.c_error_value(typ)} && PyErr_Occurred()) {{")
1422 self.emit_line(failure)
1423 self.emit_line("}")
1424
1425 def emit_cpyfunction_instance(
1426 self, fn: FuncIR, name: str, filepath: str, error_stmt: str
1427 ) -> str:
1428 module = self.static_name(fn.decl.module_name, None, prefix=MODULE_PREFIX)
1429 cname = f"{PREFIX}{fn.cname(self.names)}"
1430 wrapper_name = f"{cname}_wrapper"
1431 cfunc = f"(PyCFunction){cname}"
1432 func_flags = "METH_FASTCALL | METH_KEYWORDS"
1433 doc = f"PyDoc_STR({native_function_doc_initializer(fn)})"
1434 has_self_arg = "true" if fn.class_name and fn.decl.kind != FUNC_STATICMETHOD else "false"
1435
1436 code_flags = "CO_COROUTINE"
1437 self.emit_line(
1438 f'PyObject* {wrapper_name} = CPyFunction_New({module}, "{filepath}", "{name}", {cfunc}, {func_flags}, {doc}, {fn.line}, {code_flags}, {has_self_arg});'
1439 )
1440 self.emit_line(f"if (unlikely(!{wrapper_name}))")
1441 self.emit_line(error_stmt)
1442 return wrapper_name
1443
1444 def emit_base_tp_function_call(
1445 self, derived_cl: ClassIR, tp_func: str, args: str, *, prefix: str = ""
1446 ) -> None:
1447 type_obj = self.type_struct_name(derived_cl)
1448 self.emit_line(f"{prefix}{type_obj}->tp_base->{tp_func}({args});")
1449
1450
1451 def c_array_initializer(components: list[str], *, indented: bool = False) -> str:
1452 """Construct an initializer for a C array variable.
1453
1454 Components are C expressions valid in an initializer.
1455
1456 For example, if components are ["1", "2"], the result
1457 would be "{1, 2}", which can be used like this:
1458
1459 int a[] = {1, 2};
1460
1461 If the result is long, split it into multiple lines.
1462 """
1463 indent = " " * 4 if indented else ""
1464 res = []
1465 current: list[str] = []
1466 cur_len = 0
1467 for c in components:
1468 if not current or cur_len + 2 + len(indent) + len(c) < 70:
1469 current.append(c)
1470 cur_len += len(c) + 2
1471 else:
1472 res.append(indent + ", ".join(current))
1473 current = [c]
1474 cur_len = len(c)
1475 if not res:
1476 # Result fits on a single line
1477 return "{%s}" % ", ".join(current)
1478 # Multi-line result
1479 res.append(indent + ", ".join(current))
1480 return "{\n " + ",\n ".join(res) + "\n" + indent + "}"
1481
1482
1483 def native_function_doc_initializer(func: FuncIR) -> str:
1484 text_sig = get_text_signature(func)
1485 if text_sig is None:
1486 return "NULL"
1487 docstring = f"{text_sig}\n--\n\n"
1488 return c_string_initializer(docstring.encode("ascii", errors="backslashreplace"))