Debian Codegraph @

mypyc/codegen/emitwrapper.py

raw
1 """Generate CPython API wrapper functions for native functions.
2
3 The wrapper functions are used by the CPython runtime when calling
4 native functions from interpreted code, and when the called function
5 can't be determined statically in compiled code. They validate, match,
6 unbox and type check function arguments, and box return values as
7 needed. All wrappers accept and return 'PyObject *' (boxed) values.
8
9 The wrappers aren't used for most calls between two native functions
10 or methods in a single compilation unit.
11 """
12
13 from __future__ import annotations
14
15 from collections.abc import Sequence
16
17 from mypy.nodes import ARG_NAMED, ARG_NAMED_OPT, ARG_OPT, ARG_POS, ARG_STAR, ARG_STAR2, ArgKind
18 from mypy.operators import op_methods_to_symbols, reverse_op_method_names, reverse_op_methods
19 from mypyc.codegen.emit import AssignHandler, Emitter, ErrorHandler, GotoHandler, ReturnHandler
20 from mypyc.common import (
21 BITMAP_BITS,
22 BITMAP_TYPE,
23 DUNDER_PREFIX,
24 NATIVE_PREFIX,
25 PREFIX,
26 bitmap_name,
27 )
28 from mypyc.ir.class_ir import ClassIR
29 from mypyc.ir.func_ir import FUNC_STATICMETHOD, FuncIR, RuntimeArg
30 from mypyc.ir.rtypes import (
31 RInstance,
32 RType,
33 is_bool_rprimitive,
34 is_int_rprimitive,
35 is_object_rprimitive,
36 object_rprimitive,
37 )
38 from mypyc.namegen import NameGenerator
39
40 # Generic vectorcall wrapper functions (Python 3.7+)
41 #
42 # A wrapper function has a signature like this:
43 #
44 # PyObject *fn(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
45 #
46 # The function takes a self object, pointer to an array of arguments,
47 # the number of positional arguments, and a tuple of keyword argument
48 # names (that are stored starting in args[nargs]).
49 #
50 # It returns the returned object, or NULL on an exception.
51 #
52 # These are more efficient than legacy wrapper functions, since
53 # usually no tuple or dict objects need to be created for the
54 # arguments. Vectorcalls also use pre-constructed str objects for
55 # keyword argument names and other pre-computed information, instead
56 # of processing the argument format string on each call.
57
58
59 def wrapper_function_header(fn: FuncIR, names: NameGenerator) -> str:
60 """Return header of a vectorcall wrapper function.
61
62 See comment above for a summary of the arguments.
63 """
64 assert not fn.internal
65 return (
66 "PyObject *{prefix}{name}("
67 "PyObject *self, PyObject *const *args, size_t nargs, PyObject *kwnames)"
68 ).format(prefix=PREFIX, name=fn.cname(names))
69
70
71 def generate_traceback_code(
72 fn: FuncIR, emitter: Emitter, source_path: str, module_name: str
73 ) -> str:
74 # If we hit an error while processing arguments, then we emit a
75 # traceback frame to make it possible to debug where it happened.
76 # Unlike traceback frames added for exceptions seen in IR, we do this
77 # even if there is no `traceback_name`. This is because the error will
78 # have originated here and so we need it in the traceback.
79 globals_static = emitter.static_name("globals", module_name)
80 traceback_code = 'CPy_AddTraceback("%s", "%s", %d, %s);' % (
81 source_path.replace("\\", "\\\\"),
82 fn.traceback_name or fn.name,
83 fn.line,
84 globals_static,
85 )
86 return traceback_code
87
88
89 def make_arg_groups(args: list[RuntimeArg]) -> dict[ArgKind, list[RuntimeArg]]:
90 """Group arguments by kind."""
91 return {k: [arg for arg in args if arg.kind == k] for k in ArgKind}
92
93
94 def reorder_arg_groups(groups: dict[ArgKind, list[RuntimeArg]]) -> list[RuntimeArg]:
95 """Reorder argument groups to match their order in a format string."""
96 return groups[ARG_POS] + groups[ARG_OPT] + groups[ARG_NAMED_OPT] + groups[ARG_NAMED]
97
98
99 def make_static_kwlist(args: list[RuntimeArg]) -> str:
100 arg_names = "".join(f'"{arg.name}", ' for arg in args)
101 return f"static const char * const kwlist[] = {{{arg_names}0}};"
102
103
104 def make_format_string(func_name: str | None, groups: dict[ArgKind, list[RuntimeArg]]) -> str:
105 """Return a format string that specifies the accepted arguments.
106
107 The format string is an extended subset of what is supported by
108 PyArg_ParseTupleAndKeywords(). Only the type 'O' is used, and we
109 also support some extensions:
110
111 - Required keyword-only arguments are introduced after '@'
112 - If the function receives *args or **kwargs, we add a '%' prefix
113
114 Each group requires the previous groups' delimiters to be present
115 first.
116
117 These are used by both vectorcall and legacy wrapper functions.
118 """
119 format = ""
120 if groups[ARG_STAR] or groups[ARG_STAR2]:
121 format += "%"
122 format += "O" * len(groups[ARG_POS])
123 if groups[ARG_OPT] or groups[ARG_NAMED_OPT] or groups[ARG_NAMED]:
124 format += "|" + "O" * len(groups[ARG_OPT])
125 if groups[ARG_NAMED_OPT] or groups[ARG_NAMED]:
126 format += "$" + "O" * len(groups[ARG_NAMED_OPT])
127 if groups[ARG_NAMED]:
128 format += "@" + "O" * len(groups[ARG_NAMED])
129 if func_name is not None:
130 format += f":{func_name}"
131 return format
132
133
134 def generate_wrapper_function(
135 fn: FuncIR, emitter: Emitter, source_path: str, module_name: str
136 ) -> None:
137 """Generate a CPython-compatible vectorcall wrapper for a native function.
138
139 In particular, this handles unboxing the arguments, calling the native function, and
140 then boxing the return value.
141 """
142 emitter.emit_line(f"{wrapper_function_header(fn, emitter.names)} {{")
143
144 # If fn is a method, then the first argument is a self param
145 real_args = list(fn.args)
146 if fn.sig.num_bitmap_args:
147 real_args = real_args[: -fn.sig.num_bitmap_args]
148 if fn.class_name and fn.decl.kind != FUNC_STATICMETHOD:
149 arg = real_args.pop(0)
150 emitter.emit_line(f"PyObject *obj_{arg.name} = self;")
151
152 # Need to order args as: required, optional, kwonly optional, kwonly required
153 # This is because CPyArg_ParseStackAndKeywords format string requires
154 # them grouped in that way.
155 groups = make_arg_groups(real_args)
156 reordered_args = reorder_arg_groups(groups)
157
158 emitter.emit_line(make_static_kwlist(reordered_args))
159 fmt = make_format_string(fn.name, groups)
160 # Define the arguments the function accepts (but no types yet)
161 emitter.emit_line(f'static CPyArg_Parser parser = {{"{fmt}", kwlist, 0}};')
162
163 for arg in real_args:
164 emitter.emit_line(
165 "PyObject *obj_{}{};".format(arg.name, " = NULL" if arg.optional else "")
166 )
167
168 cleanups = [f"CPy_DECREF(obj_{arg.name});" for arg in groups[ARG_STAR] + groups[ARG_STAR2]]
169
170 arg_ptrs: list[str] = []
171 if groups[ARG_STAR] or groups[ARG_STAR2]:
172 arg_ptrs += [f"&obj_{groups[ARG_STAR][0].name}" if groups[ARG_STAR] else "NULL"]
173 arg_ptrs += [f"&obj_{groups[ARG_STAR2][0].name}" if groups[ARG_STAR2] else "NULL"]
174 arg_ptrs += [f"&obj_{arg.name}" for arg in reordered_args]
175
176 if fn.name == "__call__":
177 nargs = "PyVectorcall_NARGS(nargs)"
178 else:
179 nargs = "nargs"
180 parse_fn = "CPyArg_ParseStackAndKeywords"
181 # Special case some common signatures
182 if not real_args:
183 # No args
184 parse_fn = "CPyArg_ParseStackAndKeywordsNoArgs"
185 elif len(real_args) == 1 and len(groups[ARG_POS]) == 1:
186 # Single positional arg
187 parse_fn = "CPyArg_ParseStackAndKeywordsOneArg"
188 elif len(real_args) == len(groups[ARG_POS]) + len(groups[ARG_OPT]):
189 # No keyword-only args, *args or **kwargs
190 parse_fn = "CPyArg_ParseStackAndKeywordsSimple"
191 emitter.emit_lines(
192 "if (!{}(args, {}, kwnames, &parser{})) {{".format(
193 parse_fn, nargs, "".join(", " + n for n in arg_ptrs)
194 ),
195 "return NULL;",
196 "}",
197 )
198 for i in range(fn.sig.num_bitmap_args):
199 name = bitmap_name(i)
200 emitter.emit_line(f"{BITMAP_TYPE} {name} = 0;")
201 traceback_code = generate_traceback_code(fn, emitter, source_path, module_name)
202 generate_wrapper_core(
203 fn,
204 emitter,
205 groups[ARG_OPT] + groups[ARG_NAMED_OPT],
206 cleanups=cleanups,
207 traceback_code=traceback_code,
208 )
209
210 emitter.emit_line("}")
211
212
213 # Legacy generic wrapper functions
214 #
215 # These take a self object, a Python tuple of positional arguments,
216 # and a dict of keyword arguments. These are a lot slower than
217 # vectorcall wrappers, especially in calls involving keyword
218 # arguments.
219
220
221 def legacy_wrapper_function_header(fn: FuncIR, names: NameGenerator) -> str:
222 return "PyObject *{prefix}{name}(PyObject *self, PyObject *args, PyObject *kw)".format(
223 prefix=PREFIX, name=fn.cname(names)
224 )
225
226
227 def generate_legacy_wrapper_function(
228 fn: FuncIR, emitter: Emitter, source_path: str, module_name: str
229 ) -> None:
230 """Generates a CPython-compatible legacy wrapper for a native function.
231
232 In particular, this handles unboxing the arguments, calling the native function, and
233 then boxing the return value.
234 """
235 emitter.emit_line(f"{legacy_wrapper_function_header(fn, emitter.names)} {{")
236
237 # If fn is a method, then the first argument is a self param
238 real_args = list(fn.args)
239 if fn.sig.num_bitmap_args:
240 real_args = real_args[: -fn.sig.num_bitmap_args]
241 if fn.class_name and (fn.decl.name == "__new__" or fn.decl.kind != FUNC_STATICMETHOD):
242 arg = real_args.pop(0)
243 emitter.emit_line(f"PyObject *obj_{arg.name} = self;")
244
245 # Need to order args as: required, optional, kwonly optional, kwonly required
246 # This is because CPyArg_ParseTupleAndKeywords format string requires
247 # them grouped in that way.
248 groups = make_arg_groups(real_args)
249 reordered_args = reorder_arg_groups(groups)
250
251 emitter.emit_line(make_static_kwlist(reordered_args))
252 for arg in real_args:
253 emitter.emit_line(
254 "PyObject *obj_{}{};".format(arg.name, " = NULL" if arg.optional else "")
255 )
256
257 cleanups = [f"CPy_DECREF(obj_{arg.name});" for arg in groups[ARG_STAR] + groups[ARG_STAR2]]
258
259 arg_ptrs: list[str] = []
260 if groups[ARG_STAR] or groups[ARG_STAR2]:
261 arg_ptrs += [f"&obj_{groups[ARG_STAR][0].name}" if groups[ARG_STAR] else "NULL"]
262 arg_ptrs += [f"&obj_{groups[ARG_STAR2][0].name}" if groups[ARG_STAR2] else "NULL"]
263 arg_ptrs += [f"&obj_{arg.name}" for arg in reordered_args]
264
265 emitter.emit_lines(
266 'if (!CPyArg_ParseTupleAndKeywords(args, kw, "{}", "{}", kwlist{})) {{'.format(
267 make_format_string(None, groups), fn.name, "".join(", " + n for n in arg_ptrs)
268 ),
269 "return NULL;",
270 "}",
271 )
272 for i in range(fn.sig.num_bitmap_args):
273 name = bitmap_name(i)
274 emitter.emit_line(f"{BITMAP_TYPE} {name} = 0;")
275 traceback_code = generate_traceback_code(fn, emitter, source_path, module_name)
276 generate_wrapper_core(
277 fn,
278 emitter,
279 groups[ARG_OPT] + groups[ARG_NAMED_OPT],
280 cleanups=cleanups,
281 traceback_code=traceback_code,
282 )
283
284 emitter.emit_line("}")
285
286
287 # Specialized wrapper functions
288
289
290 def generate_dunder_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
291 """Generates a wrapper for native __dunder__ methods to be able to fit into the mapping
292 protocol slot. This specifically means that the arguments are taken as *PyObjects and returned
293 as *PyObjects.
294 """
295 gen = WrapperGenerator(cl, emitter)
296 gen.set_target(fn)
297 gen.emit_header()
298 gen.emit_arg_processing()
299 gen.emit_call()
300 gen.finish()
301 return gen.wrapper_name()
302
303
304 def generate_ipow_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
305 """Generate a wrapper for native __ipow__.
306
307 Since __ipow__ fills a ternary slot, but almost no one defines __ipow__ to take three
308 arguments, the wrapper needs to tweaked to force it to accept three arguments.
309 """
310 gen = WrapperGenerator(cl, emitter)
311 gen.set_target(fn)
312 assert len(fn.args) in (2, 3), "__ipow__ should only take 2 or 3 arguments"
313 gen.arg_names = ["self", "exp", "mod"]
314 gen.emit_header()
315 gen.emit_arg_processing()
316 handle_third_pow_argument(
317 fn,
318 emitter,
319 gen,
320 if_unsupported=[
321 'PyErr_SetString(PyExc_TypeError, "__ipow__ takes 2 positional arguments but 3 were given");',
322 "return NULL;",
323 ],
324 )
325 gen.emit_call()
326 gen.finish()
327 return gen.wrapper_name()
328
329
330 def generate_bin_op_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
331 """Generates a wrapper for a native binary dunder method.
332
333 The same wrapper that handles the forward method (e.g. __add__) also handles
334 the corresponding reverse method (e.g. __radd__), if defined.
335
336 Both arguments and the return value are PyObject *.
337 """
338 gen = WrapperGenerator(cl, emitter)
339 gen.set_target(fn)
340 if fn.name in ("__pow__", "__rpow__"):
341 gen.arg_names = ["left", "right", "mod"]
342 else:
343 gen.arg_names = ["left", "right"]
344 wrapper_name = gen.wrapper_name()
345
346 gen.emit_header()
347 if fn.name not in reverse_op_methods and fn.name in reverse_op_method_names:
348 # There's only a reverse operator method.
349 generate_bin_op_reverse_only_wrapper(fn, emitter, gen)
350 else:
351 rmethod = reverse_op_methods[fn.name]
352 fn_rev = cl.get_method(rmethod)
353 if fn_rev is None:
354 # There's only a forward operator method.
355 generate_bin_op_forward_only_wrapper(fn, emitter, gen)
356 else:
357 # There's both a forward and a reverse operator method.
358 generate_bin_op_both_wrappers(cl, fn, fn_rev, emitter, gen)
359 return wrapper_name
360
361
362 def generate_bin_op_forward_only_wrapper(
363 fn: FuncIR, emitter: Emitter, gen: WrapperGenerator
364 ) -> None:
365 gen.emit_arg_processing(error=GotoHandler("typefail"), raise_exception=False)
366 handle_third_pow_argument(fn, emitter, gen, if_unsupported=["goto typefail;"])
367 gen.emit_call(not_implemented_handler="goto typefail;")
368 gen.emit_error_handling()
369 emitter.emit_label("typefail")
370 # If some argument has an incompatible type, treat this the same as
371 # returning NotImplemented, and try to call the reverse operator method.
372 #
373 # Note that in normal Python you'd instead of an explicit
374 # return of NotImplemented, but it doesn't generally work here
375 # the body won't be executed at all if there is an argument
376 # type check failure.
377 #
378 # The recommended way is to still use a type check in the
379 # body. This will only be used in interpreted mode:
380 #
381 # def __add__(self, other: int) -> Foo:
382 # if not isinstance(other, int):
383 # return NotImplemented
384 # ...
385 generate_bin_op_reverse_dunder_call(fn, emitter, reverse_op_methods[fn.name])
386 gen.finish()
387
388
389 def generate_bin_op_reverse_only_wrapper(
390 fn: FuncIR, emitter: Emitter, gen: WrapperGenerator
391 ) -> None:
392 gen.arg_names = ["right", "left"]
393 gen.emit_arg_processing(error=GotoHandler("typefail"), raise_exception=False)
394 handle_third_pow_argument(fn, emitter, gen, if_unsupported=["goto typefail;"])
395 gen.emit_call()
396 gen.emit_error_handling()
397 emitter.emit_label("typefail")
398 emitter.emit_line("Py_INCREF(Py_NotImplemented);")
399 emitter.emit_line("return Py_NotImplemented;")
400 gen.finish()
401
402
403 def generate_bin_op_both_wrappers(
404 cl: ClassIR, fn: FuncIR, fn_rev: FuncIR, emitter: Emitter, gen: WrapperGenerator
405 ) -> None:
406 # There's both a forward and a reverse operator method. First
407 # check if we should try calling the forward one. If the
408 # argument type check fails, fall back to the reverse method.
409 #
410 # Similar to above, we can't perfectly match Python semantics.
411 # In regular Python code you'd return NotImplemented if the
412 # operand has the wrong type, but in compiled code we'll never
413 # get to execute the type check.
414 emitter.emit_line(
415 "if (PyObject_IsInstance(obj_left, (PyObject *){})) {{".format(
416 emitter.type_struct_name(cl)
417 )
418 )
419 gen.emit_arg_processing(error=GotoHandler("typefail"), raise_exception=False)
420 handle_third_pow_argument(fn, emitter, gen, if_unsupported=["goto typefail2;"])
421 # Ternary __rpow__ calls aren't a thing so immediately bail
422 # if ternary __pow__ returns NotImplemented.
423 if fn.name == "__pow__" and len(fn.args) == 3:
424 fwd_not_implemented_handler = "goto typefail2;"
425 else:
426 fwd_not_implemented_handler = "goto typefail;"
427 gen.emit_call(not_implemented_handler=fwd_not_implemented_handler)
428 gen.emit_error_handling()
429 emitter.emit_line("}")
430 emitter.emit_label("typefail")
431 emitter.emit_line(
432 "if (PyObject_IsInstance(obj_right, (PyObject *){})) {{".format(
433 emitter.type_struct_name(cl)
434 )
435 )
436 gen.set_target(fn_rev)
437 gen.arg_names = ["right", "left"]
438 gen.emit_arg_processing(error=GotoHandler("typefail2"), raise_exception=False)
439 handle_third_pow_argument(fn_rev, emitter, gen, if_unsupported=["goto typefail2;"])
440 gen.emit_call()
441 gen.emit_error_handling()
442 emitter.emit_line("} else {")
443 generate_bin_op_reverse_dunder_call(fn, emitter, fn_rev.name)
444 emitter.emit_line("}")
445 emitter.emit_label("typefail2")
446 emitter.emit_line("Py_INCREF(Py_NotImplemented);")
447 emitter.emit_line("return Py_NotImplemented;")
448 gen.finish()
449
450
451 def generate_bin_op_reverse_dunder_call(fn: FuncIR, emitter: Emitter, rmethod: str) -> None:
452 if fn.name in ("__pow__", "__rpow__"):
453 # Ternary pow() will never call the reverse dunder.
454 emitter.emit_line("if (obj_mod == Py_None) {")
455 emitter.emit_line(
456 'return CPy_CallReverseOpMethod(obj_left, obj_right, "{}", mypyc_interned_str.{});'.format(
457 op_methods_to_symbols[fn.name], rmethod
458 )
459 )
460 if fn.name in ("__pow__", "__rpow__"):
461 emitter.emit_line("} else {")
462 emitter.emit_line("Py_INCREF(Py_NotImplemented);")
463 emitter.emit_line("return Py_NotImplemented;")
464 emitter.emit_line("}")
465
466
467 def handle_third_pow_argument(
468 fn: FuncIR, emitter: Emitter, gen: WrapperGenerator, *, if_unsupported: list[str]
469 ) -> None:
470 if fn.name not in ("__pow__", "__rpow__", "__ipow__"):
471 return
472
473 if (fn.name in ("__pow__", "__ipow__") and len(fn.args) == 2) or fn.name == "__rpow__":
474 # If the power dunder only supports two arguments and the third
475 # argument (AKA mod) is set to a non-default value, simply bail.
476 #
477 # Importantly, this prevents any ternary __rpow__ calls from
478 # happening (as per the language specification).
479 emitter.emit_line("if (obj_mod != Py_None) {")
480 for line in if_unsupported:
481 emitter.emit_line(line)
482 emitter.emit_line("}")
483 # The slot wrapper will receive three arguments, but the call only
484 # supports two so make sure that the third argument isn't passed
485 # along. This is needed as two-argument __(i)pow__ is allowed and
486 # rather common.
487 if len(gen.arg_names) == 3:
488 gen.arg_names.pop()
489
490
491 RICHCOMPARE_OPS = {
492 "__lt__": "Py_LT",
493 "__gt__": "Py_GT",
494 "__le__": "Py_LE",
495 "__ge__": "Py_GE",
496 "__eq__": "Py_EQ",
497 "__ne__": "Py_NE",
498 }
499
500
501 def generate_richcompare_wrapper(cl: ClassIR, emitter: Emitter) -> str | None:
502 """Generates a wrapper for richcompare dunder methods."""
503 # Sort for determinism on Python 3.5
504 matches = sorted(name for name in RICHCOMPARE_OPS if cl.has_method(name))
505 if not matches:
506 return None
507
508 name = f"{DUNDER_PREFIX}_RichCompare_{cl.name_prefix(emitter.names)}"
509 emitter.emit_line(
510 "static PyObject *{name}(PyObject *obj_lhs, PyObject *obj_rhs, int op) {{".format(
511 name=name
512 )
513 )
514 emitter.emit_line("switch (op) {")
515 for func in matches:
516 emitter.emit_line(f"case {RICHCOMPARE_OPS[func]}: {{")
517 method = cl.get_method(func)
518 assert method is not None
519 generate_wrapper_core(method, emitter, arg_names=["lhs", "rhs"])
520 emitter.emit_line("}")
521 emitter.emit_line("}")
522
523 emitter.emit_line("Py_INCREF(Py_NotImplemented);")
524 emitter.emit_line("return Py_NotImplemented;")
525
526 emitter.emit_line("}")
527
528 return name
529
530
531 def generate_get_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
532 """Generates a wrapper for native __get__ methods."""
533 name = f"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}"
534 emitter.emit_line(
535 "static PyObject *{name}(PyObject *self, PyObject *instance, PyObject *owner) {{".format(
536 name=name
537 )
538 )
539 emitter.emit_line("instance = instance ? instance : Py_None;")
540 emitter.emit_line(f"return {emitter.native_function_call(fn.decl)}(self, instance, owner);")
541 emitter.emit_line("}")
542
543 return name
544
545
546 def generate_hash_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
547 """Generates a wrapper for native __hash__ methods."""
548 name = f"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}"
549 emitter.emit_line(f"static Py_ssize_t {name}(PyObject *self) {{")
550 emitter.emit_line(
551 "{}retval = {}{}{}(self);".format(
552 emitter.ctype_spaced(fn.ret_type),
553 emitter.get_group_prefix(fn.decl),
554 NATIVE_PREFIX,
555 fn.cname(emitter.names),
556 )
557 )
558 emitter.emit_error_check("retval", fn.ret_type, "return -1;")
559 if is_int_rprimitive(fn.ret_type):
560 emitter.emit_line("Py_ssize_t val = CPyTagged_AsSsize_t(retval);")
561 else:
562 emitter.emit_line("Py_ssize_t val = PyLong_AsSsize_t(retval);")
563 emitter.emit_dec_ref("retval", fn.ret_type)
564 emitter.emit_line("if (PyErr_Occurred()) return -1;")
565 # We can't return -1 from a hash function..
566 emitter.emit_line("if (val == -1) return -2;")
567 emitter.emit_line("return val;")
568 emitter.emit_line("}")
569
570 return name
571
572
573 def generate_len_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
574 """Generates a wrapper for native __len__ methods."""
575 name = f"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}"
576 emitter.emit_line(f"static Py_ssize_t {name}(PyObject *self) {{")
577 emitter.emit_line(
578 "{}retval = {}{}{}(self);".format(
579 emitter.ctype_spaced(fn.ret_type),
580 emitter.get_group_prefix(fn.decl),
581 NATIVE_PREFIX,
582 fn.cname(emitter.names),
583 )
584 )
585 emitter.emit_error_check("retval", fn.ret_type, "return -1;")
586 if is_int_rprimitive(fn.ret_type):
587 emitter.emit_line("Py_ssize_t val = CPyTagged_AsSsize_t(retval);")
588 else:
589 emitter.emit_line("Py_ssize_t val = PyLong_AsSsize_t(retval);")
590 emitter.emit_dec_ref("retval", fn.ret_type)
591 emitter.emit_line("if (PyErr_Occurred()) return -1;")
592 emitter.emit_line("return val;")
593 emitter.emit_line("}")
594
595 return name
596
597
598 def generate_bool_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
599 """Generates a wrapper for native __bool__ methods."""
600 name = f"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}"
601 emitter.emit_line(f"static int {name}(PyObject *self) {{")
602 emitter.emit_line(
603 "{}val = {}(self);".format(
604 emitter.ctype_spaced(fn.ret_type), emitter.native_function_call(fn.decl)
605 )
606 )
607 emitter.emit_error_check("val", fn.ret_type, "return -1;")
608 # This wouldn't be that hard to fix but it seems unimportant and
609 # getting error handling and unboxing right would be fiddly. (And
610 # way easier to do in IR!)
611 assert is_bool_rprimitive(fn.ret_type), "Only bool return supported for __bool__"
612 emitter.emit_line("return val;")
613 emitter.emit_line("}")
614
615 return name
616
617
618 def generate_del_item_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
619 """Generates a wrapper for native __delitem__.
620
621 This is only called from a combined __delitem__/__setitem__ wrapper.
622 """
623 name = "{}{}{}".format(DUNDER_PREFIX, "__delitem__", cl.name_prefix(emitter.names))
624 input_args = ", ".join(f"PyObject *obj_{arg.name}" for arg in fn.args)
625 emitter.emit_line(f"static int {name}({input_args}) {{")
626 generate_set_del_item_wrapper_inner(fn, emitter, fn.args)
627 return name
628
629
630 def generate_set_del_item_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
631 """Generates a wrapper for native __setitem__ method (also works for __delitem__).
632
633 This is used with the mapping protocol slot. Arguments are taken as *PyObjects and we
634 return a negative C int on error.
635
636 Create a separate wrapper function for __delitem__ as needed and have the
637 __setitem__ wrapper call it if the value is NULL. Return the name
638 of the outer (__setitem__) wrapper.
639 """
640 method_cls = cl.get_method_and_class("__delitem__")
641 del_name = None
642 if method_cls and method_cls[1] == cl:
643 # Generate a separate wrapper for __delitem__
644 del_name = generate_del_item_wrapper(cl, method_cls[0], emitter)
645
646 args = fn.args
647 if fn.name == "__delitem__":
648 # Add an extra argument for value that we expect to be NULL.
649 args = list(args) + [RuntimeArg("___value", object_rprimitive, ARG_POS)]
650
651 name = "{}{}{}".format(DUNDER_PREFIX, "__setitem__", cl.name_prefix(emitter.names))
652 input_args = ", ".join(f"PyObject *obj_{arg.name}" for arg in args)
653 emitter.emit_line(f"static int {name}({input_args}) {{")
654
655 # First check if this is __delitem__
656 emitter.emit_line(f"if (obj_{args[2].name} == NULL) {{")
657 if del_name is not None:
658 # We have a native implementation, so call it
659 emitter.emit_line(f"return {del_name}(obj_{args[0].name}, obj_{args[1].name});")
660 else:
661 # Try to call superclass method instead
662 emitter.emit_line(f"PyObject *super = CPy_Super(CPyModule_builtins, obj_{args[0].name});")
663 emitter.emit_line("if (super == NULL) return -1;")
664 emitter.emit_line(
665 'PyObject *result = PyObject_CallMethod(super, "__delitem__", "O", obj_{});'.format(
666 args[1].name
667 )
668 )
669 emitter.emit_line("Py_DECREF(super);")
670 emitter.emit_line("Py_XDECREF(result);")
671 emitter.emit_line("return result == NULL ? -1 : 0;")
672 emitter.emit_line("}")
673
674 method_cls = cl.get_method_and_class("__setitem__")
675 if method_cls and method_cls[1] == cl:
676 generate_set_del_item_wrapper_inner(fn, emitter, args)
677 else:
678 emitter.emit_line(f"PyObject *super = CPy_Super(CPyModule_builtins, obj_{args[0].name});")
679 emitter.emit_line("if (super == NULL) return -1;")
680 emitter.emit_line("PyObject *result;")
681
682 if method_cls is None and cl.builtin_base is None:
683 msg = f"'{cl.name}' object does not support item assignment"
684 emitter.emit_line(f'PyErr_SetString(PyExc_TypeError, "{msg}");')
685 emitter.emit_line("result = NULL;")
686 else:
687 # A base class may have __setitem__
688 emitter.emit_line(
689 'result = PyObject_CallMethod(super, "__setitem__", "OO", obj_{}, obj_{});'.format(
690 args[1].name, args[2].name
691 )
692 )
693 emitter.emit_line("Py_DECREF(super);")
694 emitter.emit_line("Py_XDECREF(result);")
695 emitter.emit_line("return result == NULL ? -1 : 0;")
696 emitter.emit_line("}")
697 return name
698
699
700 def generate_set_del_item_wrapper_inner(
701 fn: FuncIR, emitter: Emitter, args: Sequence[RuntimeArg]
702 ) -> None:
703 for arg in args:
704 generate_arg_check(arg.name, arg.type, emitter, GotoHandler("fail"))
705 native_args = ", ".join(f"arg_{arg.name}" for arg in args)
706 emitter.emit_line(
707 "{}val = {}({});".format(
708 emitter.ctype_spaced(fn.ret_type), emitter.native_function_call(fn.decl), native_args
709 )
710 )
711 emitter.emit_error_check("val", fn.ret_type, "goto fail;")
712 emitter.emit_dec_ref("val", fn.ret_type)
713 emitter.emit_line("return 0;")
714 emitter.emit_label("fail")
715 emitter.emit_line("return -1;")
716 emitter.emit_line("}")
717
718
719 def generate_contains_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
720 """Generates a wrapper for a native __contains__ method."""
721 name = f"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}"
722 emitter.emit_line(f"static int {name}(PyObject *self, PyObject *obj_item) {{")
723 generate_arg_check("item", fn.args[1].type, emitter, ReturnHandler("-1"))
724 emitter.emit_line(
725 "{}val = {}(self, arg_item);".format(
726 emitter.ctype_spaced(fn.ret_type), emitter.native_function_call(fn.decl)
727 )
728 )
729 emitter.emit_error_check("val", fn.ret_type, "return -1;")
730 if is_bool_rprimitive(fn.ret_type):
731 emitter.emit_line("return val;")
732 else:
733 emitter.emit_line("int boolval = PyObject_IsTrue(val);")
734 emitter.emit_dec_ref("val", fn.ret_type)
735 emitter.emit_line("return boolval;")
736 emitter.emit_line("}")
737
738 return name
739
740
741 # Helpers
742
743
744 def generate_wrapper_core(
745 fn: FuncIR,
746 emitter: Emitter,
747 optional_args: list[RuntimeArg] | None = None,
748 arg_names: list[str] | None = None,
749 cleanups: list[str] | None = None,
750 traceback_code: str | None = None,
751 ) -> None:
752 """Generates the core part of a wrapper function for a native function.
753
754 This expects each argument as a PyObject * named obj_{arg} as a precondition.
755 It converts the PyObject *s to the necessary types, checking and unboxing if necessary,
756 makes the call, then boxes the result if necessary and returns it.
757 """
758 gen = WrapperGenerator(None, emitter)
759 gen.set_target(fn)
760 if arg_names:
761 gen.arg_names = arg_names
762 gen.cleanups = cleanups or []
763 gen.optional_args = optional_args or []
764 gen.traceback_code = traceback_code or ""
765
766 error = ReturnHandler("NULL") if not gen.use_goto() else GotoHandler("fail")
767 gen.emit_arg_processing(error=error)
768 gen.emit_call()
769 gen.emit_error_handling()
770
771
772 def generate_arg_check(
773 name: str,
774 typ: RType,
775 emitter: Emitter,
776 error: ErrorHandler | None = None,
777 *,
778 optional: bool = False,
779 raise_exception: bool = True,
780 bitmap_arg_index: int = 0,
781 ) -> None:
782 """Insert a runtime check for argument and unbox if necessary.
783
784 The object is named PyObject *obj_{}. This is expected to generate
785 a value of name arg_{} (unboxed if necessary). For each primitive a runtime
786 check ensures the correct type.
787 """
788 error = error or AssignHandler()
789 if typ.is_unboxed:
790 if typ.error_overlap and optional:
791 # Update bitmap is value is provided.
792 init = emitter.c_undefined_value(typ)
793 emitter.emit_line(f"{emitter.ctype(typ)} arg_{name} = {init};")
794 emitter.emit_line(f"if (obj_{name} != NULL) {{")
795 bitmap = bitmap_name(bitmap_arg_index // BITMAP_BITS)
796 emitter.emit_line(f"{bitmap} |= 1 << {bitmap_arg_index & (BITMAP_BITS - 1)};")
797 emitter.emit_unbox(
798 f"obj_{name}",
799 f"arg_{name}",
800 typ,
801 declare_dest=False,
802 raise_exception=raise_exception,
803 error=error,
804 borrow=True,
805 )
806 emitter.emit_line("}")
807 else:
808 # Borrow when unboxing to avoid reference count manipulation.
809 emitter.emit_unbox(
810 f"obj_{name}",
811 f"arg_{name}",
812 typ,
813 declare_dest=True,
814 raise_exception=raise_exception,
815 error=error,
816 borrow=True,
817 optional=optional,
818 )
819 elif is_object_rprimitive(typ):
820 # Object is trivial since any object is valid
821 if optional:
822 emitter.emit_line(f"PyObject *arg_{name};")
823 emitter.emit_line(f"if (obj_{name} == NULL) {{")
824 emitter.emit_line(f"arg_{name} = {emitter.c_error_value(typ)};")
825 emitter.emit_lines("} else {", f"arg_{name} = obj_{name}; ", "}")
826 else:
827 emitter.emit_line(f"PyObject *arg_{name} = obj_{name};")
828 else:
829 emitter.emit_cast(
830 f"obj_{name}",
831 f"arg_{name}",
832 typ,
833 declare_dest=True,
834 raise_exception=raise_exception,
835 error=error,
836 optional=optional,
837 )
838
839
840 class WrapperGenerator:
841 """Helper that simplifies the generation of wrapper functions."""
842
843 # TODO: Use this for more wrappers
844
845 def __init__(self, cl: ClassIR | None, emitter: Emitter) -> None:
846 self.cl = cl
847 self.emitter = emitter
848 self.cleanups: list[str] = []
849 self.optional_args: list[RuntimeArg] = []
850 self.traceback_code = ""
851
852 def set_target(self, fn: FuncIR) -> None:
853 """Set the wrapped function.
854
855 It's fine to modify the attributes initialized here later to customize
856 the wrapper function.
857 """
858 self.target_name = fn.name
859 self.target_cname = fn.cname(self.emitter.names)
860 # Cached native-call expression so cross-group targets go through the
861 # exports table; same as `NATIVE_PREFIX + cname` for in-group calls.
862 self.target_native_call = self.emitter.native_function_call(fn.decl)
863 self.num_bitmap_args = fn.sig.num_bitmap_args
864 if self.num_bitmap_args:
865 self.args = fn.args[: -self.num_bitmap_args]
866 else:
867 self.args = fn.args
868 self.arg_names = [arg.name for arg in self.args]
869 self.ret_type = fn.ret_type
870
871 def wrapper_name(self) -> str:
872 """Return the name of the wrapper function."""
873 return "{}{}{}".format(
874 DUNDER_PREFIX,
875 self.target_name,
876 self.cl.name_prefix(self.emitter.names) if self.cl else "",
877 )
878
879 def use_goto(self) -> bool:
880 """Do we use a goto for error handling (instead of straight return)?"""
881 return bool(self.cleanups or self.traceback_code)
882
883 def emit_header(self) -> None:
884 """Emit the function header of the wrapper implementation."""
885 input_args = ", ".join(f"PyObject *obj_{arg}" for arg in self.arg_names)
886 self.emitter.emit_line(
887 "static PyObject *{name}({input_args}) {{".format(
888 name=self.wrapper_name(), input_args=input_args
889 )
890 )
891
892 def emit_arg_processing(
893 self, error: ErrorHandler | None = None, raise_exception: bool = True
894 ) -> None:
895 """Emit validation and unboxing of arguments."""
896 error = error or self.error()
897 bitmap_arg_index = 0
898 for arg_name, arg in zip(self.arg_names, self.args):
899 # Suppress the argument check for *args/**kwargs, since we know it must be right.
900 typ = arg.type if arg.kind not in (ARG_STAR, ARG_STAR2) else object_rprimitive
901 optional = arg in self.optional_args
902 generate_arg_check(
903 arg_name,
904 typ,
905 self.emitter,
906 error,
907 raise_exception=raise_exception,
908 optional=optional,
909 bitmap_arg_index=bitmap_arg_index,
910 )
911 if optional and typ.error_overlap:
912 bitmap_arg_index += 1
913
914 def emit_call(self, not_implemented_handler: str = "") -> None:
915 """Emit call to the wrapper function.
916
917 If not_implemented_handler is non-empty, use this C code to handle
918 a NotImplemented return value (if it's possible based on the return type).
919 """
920 native_args = ", ".join(f"arg_{arg}" for arg in self.arg_names)
921 if self.num_bitmap_args:
922 bitmap_args = ", ".join(
923 [bitmap_name(i) for i in reversed(range(self.num_bitmap_args))]
924 )
925 native_args = f"{native_args}, {bitmap_args}"
926
927 ret_type = self.ret_type
928 emitter = self.emitter
929 if ret_type.is_unboxed or self.use_goto():
930 # TODO: The Py_RETURN macros return the correct PyObject * with reference count
931 # handling. Are they relevant?
932 emitter.emit_line(
933 "{}retval = {}({});".format(
934 emitter.ctype_spaced(ret_type), self.target_native_call, native_args
935 )
936 )
937 emitter.emit_lines(*self.cleanups)
938 if ret_type.is_unboxed:
939 emitter.emit_error_check("retval", ret_type, "return NULL;")
940 emitter.emit_box("retval", "retbox", ret_type, declare_dest=True)
941
942 emitter.emit_line("return {};".format("retbox" if ret_type.is_unboxed else "retval"))
943 else:
944 if not_implemented_handler and not isinstance(ret_type, RInstance):
945 # The return value type may overlap with NotImplemented.
946 emitter.emit_line(f"PyObject *retbox = {self.target_native_call}({native_args});")
947 emitter.emit_lines(
948 "if (retbox == Py_NotImplemented) {",
949 not_implemented_handler,
950 "}",
951 "return retbox;",
952 )
953 else:
954 emitter.emit_line(f"return {self.target_native_call}({native_args});")
955 # TODO: Tracebacks?
956
957 def error(self) -> ErrorHandler:
958 """Figure out how to deal with errors in the wrapper."""
959 if self.cleanups or self.traceback_code:
960 # We'll have a label at the end with error handling code.
961 return GotoHandler("fail")
962 else:
963 # Nothing special needs to done to handle errors, so just return.
964 return ReturnHandler("NULL")
965
966 def emit_error_handling(self) -> None:
967 """Emit error handling block at the end of the wrapper, if needed."""
968 emitter = self.emitter
969 if self.use_goto():
970 emitter.emit_label("fail")
971 emitter.emit_lines(*self.cleanups)
972 if self.traceback_code:
973 emitter.emit_line(self.traceback_code)
974 emitter.emit_line("return NULL;")
975
976 def finish(self) -> None:
977 self.emitter.emit_line("}")