Debian Codegraph @

mypyc/codegen/emit.py

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