emit.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  1. """Utilities for emitting C code."""
  2. from __future__ import annotations
  3. import pprint
  4. import sys
  5. import textwrap
  6. from typing import Callable, Final
  7. from mypyc.codegen.literals import Literals
  8. from mypyc.common import (
  9. ATTR_PREFIX,
  10. BITMAP_BITS,
  11. FAST_ISINSTANCE_MAX_SUBCLASSES,
  12. NATIVE_PREFIX,
  13. REG_PREFIX,
  14. STATIC_PREFIX,
  15. TYPE_PREFIX,
  16. use_vectorcall,
  17. )
  18. from mypyc.ir.class_ir import ClassIR, all_concrete_classes
  19. from mypyc.ir.func_ir import FuncDecl
  20. from mypyc.ir.ops import BasicBlock, Value
  21. from mypyc.ir.rtypes import (
  22. RInstance,
  23. RPrimitive,
  24. RTuple,
  25. RType,
  26. RUnion,
  27. int_rprimitive,
  28. is_bit_rprimitive,
  29. is_bool_rprimitive,
  30. is_bytes_rprimitive,
  31. is_dict_rprimitive,
  32. is_fixed_width_rtype,
  33. is_float_rprimitive,
  34. is_int16_rprimitive,
  35. is_int32_rprimitive,
  36. is_int64_rprimitive,
  37. is_int_rprimitive,
  38. is_list_rprimitive,
  39. is_none_rprimitive,
  40. is_object_rprimitive,
  41. is_optional_type,
  42. is_range_rprimitive,
  43. is_set_rprimitive,
  44. is_short_int_rprimitive,
  45. is_str_rprimitive,
  46. is_tuple_rprimitive,
  47. is_uint8_rprimitive,
  48. object_rprimitive,
  49. optional_value_type,
  50. )
  51. from mypyc.namegen import NameGenerator, exported_name
  52. from mypyc.sametype import is_same_type
  53. # Whether to insert debug asserts for all error handling, to quickly
  54. # catch errors propagating without exceptions set.
  55. DEBUG_ERRORS: Final = False
  56. class HeaderDeclaration:
  57. """A representation of a declaration in C.
  58. This is used to generate declarations in header files and
  59. (optionally) definitions in source files.
  60. Attributes:
  61. decl: C source code for the declaration.
  62. defn: Optionally, C source code for a definition.
  63. dependencies: The names of any objects that must be declared prior.
  64. is_type: Whether the declaration is of a C type. (C types will be declared in
  65. external header files and not marked 'extern'.)
  66. needs_export: Whether the declared object needs to be exported to
  67. other modules in the linking table.
  68. """
  69. def __init__(
  70. self,
  71. decl: str | list[str],
  72. defn: list[str] | None = None,
  73. *,
  74. dependencies: set[str] | None = None,
  75. is_type: bool = False,
  76. needs_export: bool = False,
  77. ) -> None:
  78. self.decl = [decl] if isinstance(decl, str) else decl
  79. self.defn = defn
  80. self.dependencies = dependencies or set()
  81. self.is_type = is_type
  82. self.needs_export = needs_export
  83. class EmitterContext:
  84. """Shared emitter state for a compilation group."""
  85. def __init__(
  86. self,
  87. names: NameGenerator,
  88. group_name: str | None = None,
  89. group_map: dict[str, str | None] | None = None,
  90. ) -> None:
  91. """Setup shared emitter state.
  92. Args:
  93. names: The name generator to use
  94. group_map: Map from module names to group name
  95. group_name: Current group name
  96. """
  97. self.temp_counter = 0
  98. self.names = names
  99. self.group_name = group_name
  100. self.group_map = group_map or {}
  101. # Groups that this group depends on
  102. self.group_deps: set[str] = set()
  103. # The map below is used for generating declarations and
  104. # definitions at the top of the C file. The main idea is that they can
  105. # be generated at any time during the emit phase.
  106. # A map of a C identifier to whatever the C identifier declares. Currently this is
  107. # used for declaring structs and the key corresponds to the name of the struct.
  108. # The declaration contains the body of the struct.
  109. self.declarations: dict[str, HeaderDeclaration] = {}
  110. self.literals = Literals()
  111. class ErrorHandler:
  112. """Describes handling errors in unbox/cast operations."""
  113. class AssignHandler(ErrorHandler):
  114. """Assign an error value on error."""
  115. class GotoHandler(ErrorHandler):
  116. """Goto label on error."""
  117. def __init__(self, label: str) -> None:
  118. self.label = label
  119. class TracebackAndGotoHandler(ErrorHandler):
  120. """Add traceback item and goto label on error."""
  121. def __init__(
  122. self, label: str, source_path: str, module_name: str, traceback_entry: tuple[str, int]
  123. ) -> None:
  124. self.label = label
  125. self.source_path = source_path
  126. self.module_name = module_name
  127. self.traceback_entry = traceback_entry
  128. class ReturnHandler(ErrorHandler):
  129. """Return a constant value on error."""
  130. def __init__(self, value: str) -> None:
  131. self.value = value
  132. class Emitter:
  133. """Helper for C code generation."""
  134. def __init__(
  135. self,
  136. context: EmitterContext,
  137. value_names: dict[Value, str] | None = None,
  138. capi_version: tuple[int, int] | None = None,
  139. ) -> None:
  140. self.context = context
  141. self.capi_version = capi_version or sys.version_info[:2]
  142. self.names = context.names
  143. self.value_names = value_names or {}
  144. self.fragments: list[str] = []
  145. self._indent = 0
  146. # Low-level operations
  147. def indent(self) -> None:
  148. self._indent += 4
  149. def dedent(self) -> None:
  150. self._indent -= 4
  151. assert self._indent >= 0
  152. def label(self, label: BasicBlock) -> str:
  153. return "CPyL%s" % label.label
  154. def reg(self, reg: Value) -> str:
  155. return REG_PREFIX + self.value_names[reg]
  156. def attr(self, name: str) -> str:
  157. return ATTR_PREFIX + name
  158. def object_annotation(self, obj: object, line: str) -> str:
  159. """Build a C comment with an object's string represention.
  160. If the comment exceeds the line length limit, it's wrapped into a
  161. multiline string (with the extra lines indented to be aligned with
  162. the first line's comment).
  163. If it contains illegal characters, an empty string is returned."""
  164. line_width = self._indent + len(line)
  165. formatted = pprint.pformat(obj, compact=True, width=max(90 - line_width, 20))
  166. if any(x in formatted for x in ("/*", "*/", "\0")):
  167. return ""
  168. if "\n" in formatted:
  169. first_line, rest = formatted.split("\n", maxsplit=1)
  170. comment_continued = textwrap.indent(rest, (line_width + 3) * " ")
  171. return f" /* {first_line}\n{comment_continued} */"
  172. else:
  173. return f" /* {formatted} */"
  174. def emit_line(self, line: str = "", *, ann: object = None) -> None:
  175. if line.startswith("}"):
  176. self.dedent()
  177. comment = self.object_annotation(ann, line) if ann is not None else ""
  178. self.fragments.append(self._indent * " " + line + comment + "\n")
  179. if line.endswith("{"):
  180. self.indent()
  181. def emit_lines(self, *lines: str) -> None:
  182. for line in lines:
  183. self.emit_line(line)
  184. def emit_label(self, label: BasicBlock | str) -> None:
  185. if isinstance(label, str):
  186. text = label
  187. else:
  188. if label.label == 0 or not label.referenced:
  189. return
  190. text = self.label(label)
  191. # Extra semicolon prevents an error when the next line declares a tempvar
  192. self.fragments.append(f"{text}: ;\n")
  193. def emit_from_emitter(self, emitter: Emitter) -> None:
  194. self.fragments.extend(emitter.fragments)
  195. def emit_printf(self, fmt: str, *args: str) -> None:
  196. fmt = fmt.replace("\n", "\\n")
  197. self.emit_line("printf(%s);" % ", ".join(['"%s"' % fmt] + list(args)))
  198. self.emit_line("fflush(stdout);")
  199. def temp_name(self) -> str:
  200. self.context.temp_counter += 1
  201. return "__tmp%d" % self.context.temp_counter
  202. def new_label(self) -> str:
  203. self.context.temp_counter += 1
  204. return "__LL%d" % self.context.temp_counter
  205. def get_module_group_prefix(self, module_name: str) -> str:
  206. """Get the group prefix for a module (relative to the current group).
  207. The prefix should be prepended to the object name whenever
  208. accessing an object from this module.
  209. If the module lives is in the current compilation group, there is
  210. no prefix. But if it lives in a different group (and hence a separate
  211. extension module), we need to access objects from it indirectly via an
  212. export table.
  213. For example, for code in group `a` to call a function `bar` in group `b`,
  214. it would need to do `exports_b.CPyDef_bar(...)`, while code that is
  215. also in group `b` can simply do `CPyDef_bar(...)`.
  216. Thus the prefix for a module in group `b` is 'exports_b.' if the current
  217. group is *not* b and just '' if it is.
  218. """
  219. groups = self.context.group_map
  220. target_group_name = groups.get(module_name)
  221. if target_group_name and target_group_name != self.context.group_name:
  222. self.context.group_deps.add(target_group_name)
  223. return f"exports_{exported_name(target_group_name)}."
  224. else:
  225. return ""
  226. def get_group_prefix(self, obj: ClassIR | FuncDecl) -> str:
  227. """Get the group prefix for an object."""
  228. # See docs above
  229. return self.get_module_group_prefix(obj.module_name)
  230. def static_name(self, id: str, module: str | None, prefix: str = STATIC_PREFIX) -> str:
  231. """Create name of a C static variable.
  232. These are used for literals and imported modules, among other
  233. things.
  234. The caller should ensure that the (id, module) pair cannot
  235. overlap with other calls to this method within a compilation
  236. group.
  237. """
  238. lib_prefix = "" if not module else self.get_module_group_prefix(module)
  239. # If we are accessing static via the export table, we need to dereference
  240. # the pointer also.
  241. star_maybe = "*" if lib_prefix else ""
  242. suffix = self.names.private_name(module or "", id)
  243. return f"{star_maybe}{lib_prefix}{prefix}{suffix}"
  244. def type_struct_name(self, cl: ClassIR) -> str:
  245. return self.static_name(cl.name, cl.module_name, prefix=TYPE_PREFIX)
  246. def ctype(self, rtype: RType) -> str:
  247. return rtype._ctype
  248. def ctype_spaced(self, rtype: RType) -> str:
  249. """Adds a space after ctype for non-pointers."""
  250. ctype = self.ctype(rtype)
  251. if ctype[-1] == "*":
  252. return ctype
  253. else:
  254. return ctype + " "
  255. def c_undefined_value(self, rtype: RType) -> str:
  256. if not rtype.is_unboxed:
  257. return "NULL"
  258. elif isinstance(rtype, RPrimitive):
  259. return rtype.c_undefined
  260. elif isinstance(rtype, RTuple):
  261. return self.tuple_undefined_value(rtype)
  262. assert False, rtype
  263. def c_error_value(self, rtype: RType) -> str:
  264. return self.c_undefined_value(rtype)
  265. def native_function_name(self, fn: FuncDecl) -> str:
  266. return f"{NATIVE_PREFIX}{fn.cname(self.names)}"
  267. def tuple_c_declaration(self, rtuple: RTuple) -> list[str]:
  268. result = [
  269. f"#ifndef MYPYC_DECLARED_{rtuple.struct_name}",
  270. f"#define MYPYC_DECLARED_{rtuple.struct_name}",
  271. f"typedef struct {rtuple.struct_name} {{",
  272. ]
  273. if len(rtuple.types) == 0: # empty tuple
  274. # Empty tuples contain a flag so that they can still indicate
  275. # error values.
  276. result.append("int empty_struct_error_flag;")
  277. else:
  278. i = 0
  279. for typ in rtuple.types:
  280. result.append(f"{self.ctype_spaced(typ)}f{i};")
  281. i += 1
  282. result.append(f"}} {rtuple.struct_name};")
  283. result.append("#endif")
  284. result.append("")
  285. return result
  286. def bitmap_field(self, index: int) -> str:
  287. """Return C field name used for attribute bitmap."""
  288. n = index // BITMAP_BITS
  289. if n == 0:
  290. return "bitmap"
  291. return f"bitmap{n + 1}"
  292. def attr_bitmap_expr(self, obj: str, cl: ClassIR, index: int) -> str:
  293. """Return reference to the attribute definedness bitmap."""
  294. cast = f"({cl.struct_name(self.names)} *)"
  295. attr = self.bitmap_field(index)
  296. return f"({cast}{obj})->{attr}"
  297. def emit_attr_bitmap_set(
  298. self, value: str, obj: str, rtype: RType, cl: ClassIR, attr: str
  299. ) -> None:
  300. """Mark an attribute as defined in the attribute bitmap.
  301. Assumes that the attribute is tracked in the bitmap (only some attributes
  302. use the bitmap). If 'value' is not equal to the error value, do nothing.
  303. """
  304. self._emit_attr_bitmap_update(value, obj, rtype, cl, attr, clear=False)
  305. def emit_attr_bitmap_clear(self, obj: str, rtype: RType, cl: ClassIR, attr: str) -> None:
  306. """Mark an attribute as undefined in the attribute bitmap.
  307. Unlike emit_attr_bitmap_set, clear unconditionally.
  308. """
  309. self._emit_attr_bitmap_update("", obj, rtype, cl, attr, clear=True)
  310. def _emit_attr_bitmap_update(
  311. self, value: str, obj: str, rtype: RType, cl: ClassIR, attr: str, clear: bool
  312. ) -> None:
  313. if value:
  314. check = self.error_value_check(rtype, value, "==")
  315. self.emit_line(f"if (unlikely({check})) {{")
  316. index = cl.bitmap_attrs.index(attr)
  317. mask = 1 << (index & (BITMAP_BITS - 1))
  318. bitmap = self.attr_bitmap_expr(obj, cl, index)
  319. if clear:
  320. self.emit_line(f"{bitmap} &= ~{mask};")
  321. else:
  322. self.emit_line(f"{bitmap} |= {mask};")
  323. if value:
  324. self.emit_line("}")
  325. def use_vectorcall(self) -> bool:
  326. return use_vectorcall(self.capi_version)
  327. def emit_undefined_attr_check(
  328. self,
  329. rtype: RType,
  330. attr_expr: str,
  331. compare: str,
  332. obj: str,
  333. attr: str,
  334. cl: ClassIR,
  335. *,
  336. unlikely: bool = False,
  337. ) -> None:
  338. check = self.error_value_check(rtype, attr_expr, compare)
  339. if unlikely:
  340. check = f"unlikely({check})"
  341. if rtype.error_overlap:
  342. index = cl.bitmap_attrs.index(attr)
  343. bit = 1 << (index & (BITMAP_BITS - 1))
  344. attr = self.bitmap_field(index)
  345. obj_expr = f"({cl.struct_name(self.names)} *){obj}"
  346. check = f"{check} && !(({obj_expr})->{attr} & {bit})"
  347. self.emit_line(f"if ({check}) {{")
  348. def error_value_check(self, rtype: RType, value: str, compare: str) -> str:
  349. if isinstance(rtype, RTuple):
  350. return self.tuple_undefined_check_cond(
  351. rtype, value, self.c_error_value, compare, check_exception=False
  352. )
  353. else:
  354. return f"{value} {compare} {self.c_error_value(rtype)}"
  355. def tuple_undefined_check_cond(
  356. self,
  357. rtuple: RTuple,
  358. tuple_expr_in_c: str,
  359. c_type_compare_val: Callable[[RType], str],
  360. compare: str,
  361. *,
  362. check_exception: bool = True,
  363. ) -> str:
  364. if len(rtuple.types) == 0:
  365. # empty tuple
  366. return "{}.empty_struct_error_flag {} {}".format(
  367. tuple_expr_in_c, compare, c_type_compare_val(int_rprimitive)
  368. )
  369. if rtuple.error_overlap:
  370. i = 0
  371. item_type = rtuple.types[0]
  372. else:
  373. for i, typ in enumerate(rtuple.types):
  374. if not typ.error_overlap:
  375. item_type = rtuple.types[i]
  376. break
  377. else:
  378. assert False, "not expecting tuple with error overlap"
  379. if isinstance(item_type, RTuple):
  380. return self.tuple_undefined_check_cond(
  381. item_type, tuple_expr_in_c + f".f{i}", c_type_compare_val, compare
  382. )
  383. else:
  384. check = f"{tuple_expr_in_c}.f{i} {compare} {c_type_compare_val(item_type)}"
  385. if rtuple.error_overlap and check_exception:
  386. check += " && PyErr_Occurred()"
  387. return check
  388. def tuple_undefined_value(self, rtuple: RTuple) -> str:
  389. """Undefined tuple value suitable in an expression."""
  390. return f"({rtuple.struct_name}) {self.c_initializer_undefined_value(rtuple)}"
  391. def c_initializer_undefined_value(self, rtype: RType) -> str:
  392. """Undefined value represented in a form suitable for variable initialization."""
  393. if isinstance(rtype, RTuple):
  394. if not rtype.types:
  395. # Empty tuples contain a flag so that they can still indicate
  396. # error values.
  397. return f"{{ {int_rprimitive.c_undefined} }}"
  398. items = ", ".join([self.c_initializer_undefined_value(t) for t in rtype.types])
  399. return f"{{ {items} }}"
  400. else:
  401. return self.c_undefined_value(rtype)
  402. # Higher-level operations
  403. def declare_tuple_struct(self, tuple_type: RTuple) -> None:
  404. if tuple_type.struct_name not in self.context.declarations:
  405. dependencies = set()
  406. for typ in tuple_type.types:
  407. # XXX other types might eventually need similar behavior
  408. if isinstance(typ, RTuple):
  409. dependencies.add(typ.struct_name)
  410. self.context.declarations[tuple_type.struct_name] = HeaderDeclaration(
  411. self.tuple_c_declaration(tuple_type), dependencies=dependencies, is_type=True
  412. )
  413. def emit_inc_ref(self, dest: str, rtype: RType, *, rare: bool = False) -> None:
  414. """Increment reference count of C expression `dest`.
  415. For composite unboxed structures (e.g. tuples) recursively
  416. increment reference counts for each component.
  417. If rare is True, optimize for code size and compilation speed.
  418. """
  419. if is_int_rprimitive(rtype):
  420. if rare:
  421. self.emit_line("CPyTagged_IncRef(%s);" % dest)
  422. else:
  423. self.emit_line("CPyTagged_INCREF(%s);" % dest)
  424. elif isinstance(rtype, RTuple):
  425. for i, item_type in enumerate(rtype.types):
  426. self.emit_inc_ref(f"{dest}.f{i}", item_type)
  427. elif not rtype.is_unboxed:
  428. # Always inline, since this is a simple op
  429. self.emit_line("CPy_INCREF(%s);" % dest)
  430. # Otherwise assume it's an unboxed, pointerless value and do nothing.
  431. def emit_dec_ref(
  432. self, dest: str, rtype: RType, *, is_xdec: bool = False, rare: bool = False
  433. ) -> None:
  434. """Decrement reference count of C expression `dest`.
  435. For composite unboxed structures (e.g. tuples) recursively
  436. decrement reference counts for each component.
  437. If rare is True, optimize for code size and compilation speed.
  438. """
  439. x = "X" if is_xdec else ""
  440. if is_int_rprimitive(rtype):
  441. if rare:
  442. self.emit_line(f"CPyTagged_{x}DecRef({dest});")
  443. else:
  444. # Inlined
  445. self.emit_line(f"CPyTagged_{x}DECREF({dest});")
  446. elif isinstance(rtype, RTuple):
  447. for i, item_type in enumerate(rtype.types):
  448. self.emit_dec_ref(f"{dest}.f{i}", item_type, is_xdec=is_xdec, rare=rare)
  449. elif not rtype.is_unboxed:
  450. if rare:
  451. self.emit_line(f"CPy_{x}DecRef({dest});")
  452. else:
  453. # Inlined
  454. self.emit_line(f"CPy_{x}DECREF({dest});")
  455. # Otherwise assume it's an unboxed, pointerless value and do nothing.
  456. def pretty_name(self, typ: RType) -> str:
  457. value_type = optional_value_type(typ)
  458. if value_type is not None:
  459. return "%s or None" % self.pretty_name(value_type)
  460. return str(typ)
  461. def emit_cast(
  462. self,
  463. src: str,
  464. dest: str,
  465. typ: RType,
  466. *,
  467. declare_dest: bool = False,
  468. error: ErrorHandler | None = None,
  469. raise_exception: bool = True,
  470. optional: bool = False,
  471. src_type: RType | None = None,
  472. likely: bool = True,
  473. ) -> None:
  474. """Emit code for casting a value of given type.
  475. Somewhat strangely, this supports unboxed types but only
  476. operates on boxed versions. This is necessary to properly
  477. handle types such as Optional[int] in compatibility glue.
  478. By default, assign NULL (error value) to dest if the value has
  479. an incompatible type and raise TypeError. These can be customized
  480. using 'error' and 'raise_exception'.
  481. Always copy/steal the reference in 'src'.
  482. Args:
  483. src: Name of source C variable
  484. dest: Name of target C variable
  485. typ: Type of value
  486. declare_dest: If True, also declare the variable 'dest'
  487. error: What happens on error
  488. raise_exception: If True, also raise TypeError on failure
  489. likely: If the cast is likely to succeed (can be False for unions)
  490. """
  491. error = error or AssignHandler()
  492. # Special case casting *from* optional
  493. if src_type and is_optional_type(src_type) and not is_object_rprimitive(typ):
  494. value_type = optional_value_type(src_type)
  495. assert value_type is not None
  496. if is_same_type(value_type, typ):
  497. if declare_dest:
  498. self.emit_line(f"PyObject *{dest};")
  499. check = "({} != Py_None)"
  500. if likely:
  501. check = f"(likely{check})"
  502. self.emit_arg_check(src, dest, typ, check.format(src), optional)
  503. self.emit_lines(f" {dest} = {src};", "else {")
  504. self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
  505. self.emit_line("}")
  506. return
  507. # TODO: Verify refcount handling.
  508. if (
  509. is_list_rprimitive(typ)
  510. or is_dict_rprimitive(typ)
  511. or is_set_rprimitive(typ)
  512. or is_str_rprimitive(typ)
  513. or is_range_rprimitive(typ)
  514. or is_float_rprimitive(typ)
  515. or is_int_rprimitive(typ)
  516. or is_bool_rprimitive(typ)
  517. or is_bit_rprimitive(typ)
  518. or is_fixed_width_rtype(typ)
  519. ):
  520. if declare_dest:
  521. self.emit_line(f"PyObject *{dest};")
  522. if is_list_rprimitive(typ):
  523. prefix = "PyList"
  524. elif is_dict_rprimitive(typ):
  525. prefix = "PyDict"
  526. elif is_set_rprimitive(typ):
  527. prefix = "PySet"
  528. elif is_str_rprimitive(typ):
  529. prefix = "PyUnicode"
  530. elif is_range_rprimitive(typ):
  531. prefix = "PyRange"
  532. elif is_float_rprimitive(typ):
  533. prefix = "CPyFloat"
  534. elif is_int_rprimitive(typ) or is_fixed_width_rtype(typ):
  535. # TODO: Range check for fixed-width types?
  536. prefix = "PyLong"
  537. elif is_bool_rprimitive(typ) or is_bit_rprimitive(typ):
  538. prefix = "PyBool"
  539. else:
  540. assert False, f"unexpected primitive type: {typ}"
  541. check = "({}_Check({}))"
  542. if likely:
  543. check = f"(likely{check})"
  544. self.emit_arg_check(src, dest, typ, check.format(prefix, src), optional)
  545. self.emit_lines(f" {dest} = {src};", "else {")
  546. self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
  547. self.emit_line("}")
  548. elif is_bytes_rprimitive(typ):
  549. if declare_dest:
  550. self.emit_line(f"PyObject *{dest};")
  551. check = "(PyBytes_Check({}) || PyByteArray_Check({}))"
  552. if likely:
  553. check = f"(likely{check})"
  554. self.emit_arg_check(src, dest, typ, check.format(src, src), optional)
  555. self.emit_lines(f" {dest} = {src};", "else {")
  556. self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
  557. self.emit_line("}")
  558. elif is_tuple_rprimitive(typ):
  559. if declare_dest:
  560. self.emit_line(f"{self.ctype(typ)} {dest};")
  561. check = "(PyTuple_Check({}))"
  562. if likely:
  563. check = f"(likely{check})"
  564. self.emit_arg_check(src, dest, typ, check.format(src), optional)
  565. self.emit_lines(f" {dest} = {src};", "else {")
  566. self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
  567. self.emit_line("}")
  568. elif isinstance(typ, RInstance):
  569. if declare_dest:
  570. self.emit_line(f"PyObject *{dest};")
  571. concrete = all_concrete_classes(typ.class_ir)
  572. # If there are too many concrete subclasses or we can't find any
  573. # (meaning the code ought to be dead or we aren't doing global opts),
  574. # fall back to a normal typecheck.
  575. # Otherwise check all the subclasses.
  576. if not concrete or len(concrete) > FAST_ISINSTANCE_MAX_SUBCLASSES + 1:
  577. check = "(PyObject_TypeCheck({}, {}))".format(
  578. src, self.type_struct_name(typ.class_ir)
  579. )
  580. else:
  581. full_str = "(Py_TYPE({src}) == {targets[0]})"
  582. for i in range(1, len(concrete)):
  583. full_str += " || (Py_TYPE({src}) == {targets[%d]})" % i
  584. if len(concrete) > 1:
  585. full_str = "(%s)" % full_str
  586. check = full_str.format(
  587. src=src, targets=[self.type_struct_name(ir) for ir in concrete]
  588. )
  589. if likely:
  590. check = f"(likely{check})"
  591. self.emit_arg_check(src, dest, typ, check, optional)
  592. self.emit_lines(f" {dest} = {src};".format(dest, src), "else {")
  593. self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
  594. self.emit_line("}")
  595. elif is_none_rprimitive(typ):
  596. if declare_dest:
  597. self.emit_line(f"PyObject *{dest};")
  598. check = "({} == Py_None)"
  599. if likely:
  600. check = f"(likely{check})"
  601. self.emit_arg_check(src, dest, typ, check.format(src), optional)
  602. self.emit_lines(f" {dest} = {src};", "else {")
  603. self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
  604. self.emit_line("}")
  605. elif is_object_rprimitive(typ):
  606. if declare_dest:
  607. self.emit_line(f"PyObject *{dest};")
  608. self.emit_arg_check(src, dest, typ, "", optional)
  609. self.emit_line(f"{dest} = {src};")
  610. if optional:
  611. self.emit_line("}")
  612. elif isinstance(typ, RUnion):
  613. self.emit_union_cast(
  614. src, dest, typ, declare_dest, error, optional, src_type, raise_exception
  615. )
  616. elif isinstance(typ, RTuple):
  617. assert not optional
  618. self.emit_tuple_cast(src, dest, typ, declare_dest, error, src_type)
  619. else:
  620. assert False, "Cast not implemented: %s" % typ
  621. def emit_cast_error_handler(
  622. self, error: ErrorHandler, src: str, dest: str, typ: RType, raise_exception: bool
  623. ) -> None:
  624. if raise_exception:
  625. if isinstance(error, TracebackAndGotoHandler):
  626. # Merge raising and emitting traceback entry into a single call.
  627. self.emit_type_error_traceback(
  628. error.source_path, error.module_name, error.traceback_entry, typ=typ, src=src
  629. )
  630. self.emit_line("goto %s;" % error.label)
  631. return
  632. self.emit_line(f'CPy_TypeError("{self.pretty_name(typ)}", {src}); ')
  633. if isinstance(error, AssignHandler):
  634. self.emit_line("%s = NULL;" % dest)
  635. elif isinstance(error, GotoHandler):
  636. self.emit_line("goto %s;" % error.label)
  637. elif isinstance(error, TracebackAndGotoHandler):
  638. self.emit_line("%s = NULL;" % dest)
  639. self.emit_traceback(error.source_path, error.module_name, error.traceback_entry)
  640. self.emit_line("goto %s;" % error.label)
  641. else:
  642. assert isinstance(error, ReturnHandler)
  643. self.emit_line("return %s;" % error.value)
  644. def emit_union_cast(
  645. self,
  646. src: str,
  647. dest: str,
  648. typ: RUnion,
  649. declare_dest: bool,
  650. error: ErrorHandler,
  651. optional: bool,
  652. src_type: RType | None,
  653. raise_exception: bool,
  654. ) -> None:
  655. """Emit cast to a union type.
  656. The arguments are similar to emit_cast.
  657. """
  658. if declare_dest:
  659. self.emit_line(f"PyObject *{dest};")
  660. good_label = self.new_label()
  661. if optional:
  662. self.emit_line(f"if ({src} == NULL) {{")
  663. self.emit_line(f"{dest} = {self.c_error_value(typ)};")
  664. self.emit_line(f"goto {good_label};")
  665. self.emit_line("}")
  666. for item in typ.items:
  667. self.emit_cast(
  668. src,
  669. dest,
  670. item,
  671. declare_dest=False,
  672. raise_exception=False,
  673. optional=False,
  674. likely=False,
  675. )
  676. self.emit_line(f"if ({dest} != NULL) goto {good_label};")
  677. # Handle cast failure.
  678. self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
  679. self.emit_label(good_label)
  680. def emit_tuple_cast(
  681. self,
  682. src: str,
  683. dest: str,
  684. typ: RTuple,
  685. declare_dest: bool,
  686. error: ErrorHandler,
  687. src_type: RType | None,
  688. ) -> None:
  689. """Emit cast to a tuple type.
  690. The arguments are similar to emit_cast.
  691. """
  692. if declare_dest:
  693. self.emit_line(f"PyObject *{dest};")
  694. # This reuse of the variable is super dodgy. We don't even
  695. # care about the values except to check whether they are
  696. # invalid.
  697. out_label = self.new_label()
  698. self.emit_lines(
  699. "if (unlikely(!(PyTuple_Check({r}) && PyTuple_GET_SIZE({r}) == {size}))) {{".format(
  700. r=src, size=len(typ.types)
  701. ),
  702. f"{dest} = NULL;",
  703. f"goto {out_label};",
  704. "}",
  705. )
  706. for i, item in enumerate(typ.types):
  707. # Since we did the checks above this should never fail
  708. self.emit_cast(
  709. f"PyTuple_GET_ITEM({src}, {i})",
  710. dest,
  711. item,
  712. declare_dest=False,
  713. raise_exception=False,
  714. optional=False,
  715. )
  716. self.emit_line(f"if ({dest} == NULL) goto {out_label};")
  717. self.emit_line(f"{dest} = {src};")
  718. self.emit_label(out_label)
  719. def emit_arg_check(self, src: str, dest: str, typ: RType, check: str, optional: bool) -> None:
  720. if optional:
  721. self.emit_line(f"if ({src} == NULL) {{")
  722. self.emit_line(f"{dest} = {self.c_error_value(typ)};")
  723. if check != "":
  724. self.emit_line("{}if {}".format("} else " if optional else "", check))
  725. elif optional:
  726. self.emit_line("else {")
  727. def emit_unbox(
  728. self,
  729. src: str,
  730. dest: str,
  731. typ: RType,
  732. *,
  733. declare_dest: bool = False,
  734. error: ErrorHandler | None = None,
  735. raise_exception: bool = True,
  736. optional: bool = False,
  737. borrow: bool = False,
  738. ) -> None:
  739. """Emit code for unboxing a value of given type (from PyObject *).
  740. By default, assign error value to dest if the value has an
  741. incompatible type and raise TypeError. These can be customized
  742. using 'error' and 'raise_exception'.
  743. Generate a new reference unless 'borrow' is True.
  744. Args:
  745. src: Name of source C variable
  746. dest: Name of target C variable
  747. typ: Type of value
  748. declare_dest: If True, also declare the variable 'dest'
  749. error: What happens on error
  750. raise_exception: If True, also raise TypeError on failure
  751. borrow: If True, create a borrowed reference
  752. """
  753. error = error or AssignHandler()
  754. # TODO: Verify refcount handling.
  755. if isinstance(error, AssignHandler):
  756. failure = f"{dest} = {self.c_error_value(typ)};"
  757. elif isinstance(error, GotoHandler):
  758. failure = "goto %s;" % error.label
  759. else:
  760. assert isinstance(error, ReturnHandler)
  761. failure = "return %s;" % error.value
  762. if raise_exception:
  763. raise_exc = f'CPy_TypeError("{self.pretty_name(typ)}", {src}); '
  764. failure = raise_exc + failure
  765. if is_int_rprimitive(typ) or is_short_int_rprimitive(typ):
  766. if declare_dest:
  767. self.emit_line(f"CPyTagged {dest};")
  768. self.emit_arg_check(src, dest, typ, f"(likely(PyLong_Check({src})))", optional)
  769. if borrow:
  770. self.emit_line(f" {dest} = CPyTagged_BorrowFromObject({src});")
  771. else:
  772. self.emit_line(f" {dest} = CPyTagged_FromObject({src});")
  773. self.emit_line("else {")
  774. self.emit_line(failure)
  775. self.emit_line("}")
  776. elif is_bool_rprimitive(typ) or is_bit_rprimitive(typ):
  777. # Whether we are borrowing or not makes no difference.
  778. if declare_dest:
  779. self.emit_line(f"char {dest};")
  780. self.emit_arg_check(src, dest, typ, f"(unlikely(!PyBool_Check({src}))) {{", optional)
  781. self.emit_line(failure)
  782. self.emit_line("} else")
  783. conversion = f"{src} == Py_True"
  784. self.emit_line(f" {dest} = {conversion};")
  785. elif is_none_rprimitive(typ):
  786. # Whether we are borrowing or not makes no difference.
  787. if declare_dest:
  788. self.emit_line(f"char {dest};")
  789. self.emit_arg_check(src, dest, typ, f"(unlikely({src} != Py_None)) {{", optional)
  790. self.emit_line(failure)
  791. self.emit_line("} else")
  792. self.emit_line(f" {dest} = 1;")
  793. elif is_int64_rprimitive(typ):
  794. # Whether we are borrowing or not makes no difference.
  795. assert not optional # Not supported for overlapping error values
  796. if declare_dest:
  797. self.emit_line(f"int64_t {dest};")
  798. self.emit_line(f"{dest} = CPyLong_AsInt64({src});")
  799. if not isinstance(error, AssignHandler):
  800. self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure)
  801. elif is_int32_rprimitive(typ):
  802. # Whether we are borrowing or not makes no difference.
  803. assert not optional # Not supported for overlapping error values
  804. if declare_dest:
  805. self.emit_line(f"int32_t {dest};")
  806. self.emit_line(f"{dest} = CPyLong_AsInt32({src});")
  807. if not isinstance(error, AssignHandler):
  808. self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure)
  809. elif is_int16_rprimitive(typ):
  810. # Whether we are borrowing or not makes no difference.
  811. assert not optional # Not supported for overlapping error values
  812. if declare_dest:
  813. self.emit_line(f"int16_t {dest};")
  814. self.emit_line(f"{dest} = CPyLong_AsInt16({src});")
  815. if not isinstance(error, AssignHandler):
  816. self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure)
  817. elif is_uint8_rprimitive(typ):
  818. # Whether we are borrowing or not makes no difference.
  819. assert not optional # Not supported for overlapping error values
  820. if declare_dest:
  821. self.emit_line(f"uint8_t {dest};")
  822. self.emit_line(f"{dest} = CPyLong_AsUInt8({src});")
  823. if not isinstance(error, AssignHandler):
  824. self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure)
  825. elif is_float_rprimitive(typ):
  826. assert not optional # Not supported for overlapping error values
  827. if declare_dest:
  828. self.emit_line(f"double {dest};")
  829. # TODO: Don't use __float__ and __index__
  830. self.emit_line(f"{dest} = PyFloat_AsDouble({src});")
  831. self.emit_lines(f"if ({dest} == -1.0 && PyErr_Occurred()) {{", failure, "}")
  832. elif isinstance(typ, RTuple):
  833. self.declare_tuple_struct(typ)
  834. if declare_dest:
  835. self.emit_line(f"{self.ctype(typ)} {dest};")
  836. # HACK: The error handling for unboxing tuples is busted
  837. # and instead of fixing it I am just wrapping it in the
  838. # cast code which I think is right. This is not good.
  839. if optional:
  840. self.emit_line(f"if ({src} == NULL) {{")
  841. self.emit_line(f"{dest} = {self.c_error_value(typ)};")
  842. self.emit_line("} else {")
  843. cast_temp = self.temp_name()
  844. self.emit_tuple_cast(
  845. src, cast_temp, typ, declare_dest=True, error=error, src_type=None
  846. )
  847. self.emit_line(f"if (unlikely({cast_temp} == NULL)) {{")
  848. # self.emit_arg_check(src, dest, typ,
  849. # '(!PyTuple_Check({}) || PyTuple_Size({}) != {}) {{'.format(
  850. # src, src, len(typ.types)), optional)
  851. self.emit_line(failure) # TODO: Decrease refcount?
  852. self.emit_line("} else {")
  853. if not typ.types:
  854. self.emit_line(f"{dest}.empty_struct_error_flag = 0;")
  855. for i, item_type in enumerate(typ.types):
  856. temp = self.temp_name()
  857. # emit_tuple_cast above checks the size, so this should not fail
  858. self.emit_line(f"PyObject *{temp} = PyTuple_GET_ITEM({src}, {i});")
  859. temp2 = self.temp_name()
  860. # Unbox or check the item.
  861. if item_type.is_unboxed:
  862. self.emit_unbox(
  863. temp,
  864. temp2,
  865. item_type,
  866. raise_exception=raise_exception,
  867. error=error,
  868. declare_dest=True,
  869. borrow=borrow,
  870. )
  871. else:
  872. if not borrow:
  873. self.emit_inc_ref(temp, object_rprimitive)
  874. self.emit_cast(temp, temp2, item_type, declare_dest=True)
  875. self.emit_line(f"{dest}.f{i} = {temp2};")
  876. self.emit_line("}")
  877. if optional:
  878. self.emit_line("}")
  879. else:
  880. assert False, "Unboxing not implemented: %s" % typ
  881. def emit_box(
  882. self, src: str, dest: str, typ: RType, declare_dest: bool = False, can_borrow: bool = False
  883. ) -> None:
  884. """Emit code for boxing a value of given type.
  885. Generate a simple assignment if no boxing is needed.
  886. The source reference count is stolen for the result (no need to decref afterwards).
  887. """
  888. # TODO: Always generate a new reference (if a reference type)
  889. if declare_dest:
  890. declaration = "PyObject *"
  891. else:
  892. declaration = ""
  893. if is_int_rprimitive(typ) or is_short_int_rprimitive(typ):
  894. # Steal the existing reference if it exists.
  895. self.emit_line(f"{declaration}{dest} = CPyTagged_StealAsObject({src});")
  896. elif is_bool_rprimitive(typ) or is_bit_rprimitive(typ):
  897. # N.B: bool is special cased to produce a borrowed value
  898. # after boxing, so we don't need to increment the refcount
  899. # when this comes directly from a Box op.
  900. self.emit_lines(f"{declaration}{dest} = {src} ? Py_True : Py_False;")
  901. if not can_borrow:
  902. self.emit_inc_ref(dest, object_rprimitive)
  903. elif is_none_rprimitive(typ):
  904. # N.B: None is special cased to produce a borrowed value
  905. # after boxing, so we don't need to increment the refcount
  906. # when this comes directly from a Box op.
  907. self.emit_lines(f"{declaration}{dest} = Py_None;")
  908. if not can_borrow:
  909. self.emit_inc_ref(dest, object_rprimitive)
  910. elif is_int32_rprimitive(typ) or is_int16_rprimitive(typ) or is_uint8_rprimitive(typ):
  911. self.emit_line(f"{declaration}{dest} = PyLong_FromLong({src});")
  912. elif is_int64_rprimitive(typ):
  913. self.emit_line(f"{declaration}{dest} = PyLong_FromLongLong({src});")
  914. elif is_float_rprimitive(typ):
  915. self.emit_line(f"{declaration}{dest} = PyFloat_FromDouble({src});")
  916. elif isinstance(typ, RTuple):
  917. self.declare_tuple_struct(typ)
  918. self.emit_line(f"{declaration}{dest} = PyTuple_New({len(typ.types)});")
  919. self.emit_line(f"if (unlikely({dest} == NULL))")
  920. self.emit_line(" CPyError_OutOfMemory();")
  921. # TODO: Fail if dest is None
  922. for i in range(0, len(typ.types)):
  923. if not typ.is_unboxed:
  924. self.emit_line(f"PyTuple_SET_ITEM({dest}, {i}, {src}.f{i}")
  925. else:
  926. inner_name = self.temp_name()
  927. self.emit_box(f"{src}.f{i}", inner_name, typ.types[i], declare_dest=True)
  928. self.emit_line(f"PyTuple_SET_ITEM({dest}, {i}, {inner_name});")
  929. else:
  930. assert not typ.is_unboxed
  931. # Type is boxed -- trivially just assign.
  932. self.emit_line(f"{declaration}{dest} = {src};")
  933. def emit_error_check(self, value: str, rtype: RType, failure: str) -> None:
  934. """Emit code for checking a native function return value for uncaught exception."""
  935. if isinstance(rtype, RTuple):
  936. if len(rtype.types) == 0:
  937. return # empty tuples can't fail.
  938. else:
  939. cond = self.tuple_undefined_check_cond(rtype, value, self.c_error_value, "==")
  940. self.emit_line(f"if ({cond}) {{")
  941. elif rtype.error_overlap:
  942. # The error value is also valid as a normal value, so we need to also check
  943. # for a raised exception.
  944. self.emit_line(f"if ({value} == {self.c_error_value(rtype)} && PyErr_Occurred()) {{")
  945. else:
  946. self.emit_line(f"if ({value} == {self.c_error_value(rtype)}) {{")
  947. self.emit_lines(failure, "}")
  948. def emit_gc_visit(self, target: str, rtype: RType) -> None:
  949. """Emit code for GC visiting a C variable reference.
  950. Assume that 'target' represents a C expression that refers to a
  951. struct member, such as 'self->x'.
  952. """
  953. if not rtype.is_refcounted:
  954. # Not refcounted -> no pointers -> no GC interaction.
  955. return
  956. elif isinstance(rtype, RPrimitive) and rtype.name == "builtins.int":
  957. self.emit_line(f"if (CPyTagged_CheckLong({target})) {{")
  958. self.emit_line(f"Py_VISIT(CPyTagged_LongAsObject({target}));")
  959. self.emit_line("}")
  960. elif isinstance(rtype, RTuple):
  961. for i, item_type in enumerate(rtype.types):
  962. self.emit_gc_visit(f"{target}.f{i}", item_type)
  963. elif self.ctype(rtype) == "PyObject *":
  964. # The simplest case.
  965. self.emit_line(f"Py_VISIT({target});")
  966. else:
  967. assert False, "emit_gc_visit() not implemented for %s" % repr(rtype)
  968. def emit_gc_clear(self, target: str, rtype: RType) -> None:
  969. """Emit code for clearing a C attribute reference for GC.
  970. Assume that 'target' represents a C expression that refers to a
  971. struct member, such as 'self->x'.
  972. """
  973. if not rtype.is_refcounted:
  974. # Not refcounted -> no pointers -> no GC interaction.
  975. return
  976. elif isinstance(rtype, RPrimitive) and rtype.name == "builtins.int":
  977. self.emit_line(f"if (CPyTagged_CheckLong({target})) {{")
  978. self.emit_line(f"CPyTagged __tmp = {target};")
  979. self.emit_line(f"{target} = {self.c_undefined_value(rtype)};")
  980. self.emit_line("Py_XDECREF(CPyTagged_LongAsObject(__tmp));")
  981. self.emit_line("}")
  982. elif isinstance(rtype, RTuple):
  983. for i, item_type in enumerate(rtype.types):
  984. self.emit_gc_clear(f"{target}.f{i}", item_type)
  985. elif self.ctype(rtype) == "PyObject *" and self.c_undefined_value(rtype) == "NULL":
  986. # The simplest case.
  987. self.emit_line(f"Py_CLEAR({target});")
  988. else:
  989. assert False, "emit_gc_clear() not implemented for %s" % repr(rtype)
  990. def emit_traceback(
  991. self, source_path: str, module_name: str, traceback_entry: tuple[str, int]
  992. ) -> None:
  993. return self._emit_traceback("CPy_AddTraceback", source_path, module_name, traceback_entry)
  994. def emit_type_error_traceback(
  995. self,
  996. source_path: str,
  997. module_name: str,
  998. traceback_entry: tuple[str, int],
  999. *,
  1000. typ: RType,
  1001. src: str,
  1002. ) -> None:
  1003. func = "CPy_TypeErrorTraceback"
  1004. type_str = f'"{self.pretty_name(typ)}"'
  1005. return self._emit_traceback(
  1006. func, source_path, module_name, traceback_entry, type_str=type_str, src=src
  1007. )
  1008. def _emit_traceback(
  1009. self,
  1010. func: str,
  1011. source_path: str,
  1012. module_name: str,
  1013. traceback_entry: tuple[str, int],
  1014. type_str: str = "",
  1015. src: str = "",
  1016. ) -> None:
  1017. globals_static = self.static_name("globals", module_name)
  1018. line = '%s("%s", "%s", %d, %s' % (
  1019. func,
  1020. source_path.replace("\\", "\\\\"),
  1021. traceback_entry[0],
  1022. traceback_entry[1],
  1023. globals_static,
  1024. )
  1025. if type_str:
  1026. assert src
  1027. line += f", {type_str}, {src}"
  1028. line += ");"
  1029. self.emit_line(line)
  1030. if DEBUG_ERRORS:
  1031. self.emit_line('assert(PyErr_Occurred() != NULL && "failure w/o err!");')
  1032. def emit_unbox_failure_with_overlapping_error_value(
  1033. self, dest: str, typ: RType, failure: str
  1034. ) -> None:
  1035. self.emit_line(f"if ({dest} == {self.c_error_value(typ)} && PyErr_Occurred()) {{")
  1036. self.emit_line(failure)
  1037. self.emit_line("}")
  1038. def c_array_initializer(components: list[str], *, indented: bool = False) -> str:
  1039. """Construct an initializer for a C array variable.
  1040. Components are C expressions valid in an initializer.
  1041. For example, if components are ["1", "2"], the result
  1042. would be "{1, 2}", which can be used like this:
  1043. int a[] = {1, 2};
  1044. If the result is long, split it into multiple lines.
  1045. """
  1046. indent = " " * 4 if indented else ""
  1047. res = []
  1048. current: list[str] = []
  1049. cur_len = 0
  1050. for c in components:
  1051. if not current or cur_len + 2 + len(indent) + len(c) < 70:
  1052. current.append(c)
  1053. cur_len += len(c) + 2
  1054. else:
  1055. res.append(indent + ", ".join(current))
  1056. current = [c]
  1057. cur_len = len(c)
  1058. if not res:
  1059. # Result fits on a single line
  1060. return "{%s}" % ", ".join(current)
  1061. # Multi-line result
  1062. res.append(indent + ", ".join(current))
  1063. return "{\n " + ",\n ".join(res) + "\n" + indent + "}"