Emit code for casting a value of given type. Somewhat strangely, this supports unboxed types but only operates on boxed versions. This is necessary to properly handle types such as Optional[int] in compatibility glue. By default, assign NULL (error value) to dest i
(
self,
src: str,
dest: str,
typ: RType,
*,
declare_dest: bool = False,
error: ErrorHandler | None = None,
raise_exception: bool = True,
optional: bool = False,
src_type: RType | None = None,
likely: bool = True,
)
| 651 | return str(typ) |
| 652 | |
| 653 | def emit_cast( |
| 654 | self, |
| 655 | src: str, |
| 656 | dest: str, |
| 657 | typ: RType, |
| 658 | *, |
| 659 | declare_dest: bool = False, |
| 660 | error: ErrorHandler | None = None, |
| 661 | raise_exception: bool = True, |
| 662 | optional: bool = False, |
| 663 | src_type: RType | None = None, |
| 664 | likely: bool = True, |
| 665 | ) -> None: |
| 666 | """Emit code for casting a value of given type. |
| 667 | |
| 668 | Somewhat strangely, this supports unboxed types but only |
| 669 | operates on boxed versions. This is necessary to properly |
| 670 | handle types such as Optional[int] in compatibility glue. |
| 671 | |
| 672 | By default, assign NULL (error value) to dest if the value has |
| 673 | an incompatible type and raise TypeError. These can be customized |
| 674 | using 'error' and 'raise_exception'. |
| 675 | |
| 676 | Always copy/steal the reference in 'src'. |
| 677 | |
| 678 | Args: |
| 679 | src: Name of source C variable |
| 680 | dest: Name of target C variable |
| 681 | typ: Type of value |
| 682 | declare_dest: If True, also declare the variable 'dest' |
| 683 | error: What happens on error |
| 684 | raise_exception: If True, also raise TypeError on failure |
| 685 | likely: If the cast is likely to succeed (can be False for unions) |
| 686 | """ |
| 687 | error = error or AssignHandler() |
| 688 | |
| 689 | # Special case casting *from* optional |
| 690 | if src_type and is_optional_type(src_type) and not is_object_rprimitive(typ): |
| 691 | value_type = optional_value_type(src_type) |
| 692 | assert value_type is not None |
| 693 | if is_same_type(value_type, typ): |
| 694 | if declare_dest: |
| 695 | self.emit_line(f"PyObject *{dest};") |
| 696 | check = "({} != Py_None)" |
| 697 | if likely: |
| 698 | check = f"(likely{check})" |
| 699 | self.emit_arg_check(src, dest, typ, check.format(src), optional) |
| 700 | self.emit_lines(f" {dest} = {src};", "else {") |
| 701 | self.emit_cast_error_handler(error, src, dest, typ, raise_exception) |
| 702 | self.emit_line("}") |
| 703 | return |
| 704 | |
| 705 | # TODO: Verify refcount handling. |
| 706 | if ( |
| 707 | is_list_rprimitive(typ) |
| 708 | or is_dict_rprimitive(typ) |
| 709 | or is_set_rprimitive(typ) |
| 710 | or is_frozenset_rprimitive(typ) |
no test coverage detected