From dd8a2fcc814759fbff19f9f08b4e480615400992 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Sat, 19 Sep 2026 19:33:02 +0100 Subject: [PATCH 1/2] [mypyc] Support the u64 native integer type u64 is an unsigned 64-bit integer. The implementation mostly follows u16 (#22368). Major differences: - Boxing uses PyLong_FromUnsignedLongLong. - A u64 may not fit in a short tagged int, so converting to int checks the range and calls CPyTagged_FromUInt64 for large values. Converting from int accepts any non-negative short int directly and uses CPyLong_AsUInt64 for long ints. - Add list get/set item primitives that take a u64 index. Work on mypyc/mypyc#1226. --- mypy/types.py | 1 + .../stubs/mypy-extensions/mypy_extensions.pyi | 37 ++ mypyc/codegen/emit.py | 10 + mypyc/doc/int_operations.rst | 44 +- mypyc/doc/using_type_annotations.rst | 3 +- mypyc/ir/rtypes.py | 6 +- mypyc/irbuild/ll_builder.py | 21 +- mypyc/irbuild/mapper.py | 3 + mypyc/irbuild/specialize.py | 45 +- mypyc/lib-rt/CPy.h | 46 ++ mypyc/lib-rt/int_ops.c | 26 + mypyc/lib-rt/list_ops.c | 32 ++ mypyc/primitives/int_ops.py | 24 + mypyc/primitives/list_ops.py | 39 +- mypyc/test-data/irbuild-u64.test | 444 ++++++++++++++++++ mypyc/test-data/run-u64.test | 364 ++++++++++++++ mypyc/test/test_irbuild.py | 1 + mypyc/test/test_run.py | 1 + mypyc/test/test_tuplename.py | 2 + mypyc/test/test_typeops.py | 11 +- test-data/unit/lib-stub/mypy_extensions.pyi | 32 +- 21 files changed, 1171 insertions(+), 21 deletions(-) create mode 100644 mypyc/test-data/irbuild-u64.test create mode 100644 mypyc/test-data/run-u64.test diff --git a/mypy/types.py b/mypy/types.py index a50d7fec4ee40..0628f3e20b2ed 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -203,6 +203,7 @@ class SentinelValue(NamedTuple): "mypy_extensions.i64", "mypy_extensions.i32", "mypy_extensions.i16", + "mypy_extensions.u64", "mypy_extensions.u32", "mypy_extensions.u16", "mypy_extensions.u8", diff --git a/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi b/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi index a1625eab68e42..a982db1463568 100644 --- a/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi +++ b/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi @@ -188,6 +188,43 @@ class i16: def __eq__(self, x: object) -> bool: ... def __bool__(self) -> bool: ... +class u64: + @overload + def __new__(cls, __x: str | ReadableBuffer | SupportsInt | SupportsIndex | SupportsTrunc = ...) -> u64: ... + @overload + def __new__(cls, __x: str | bytes | bytearray, base: SupportsIndex) -> u64: ... + + def __add__(self, x: u64) -> u64: ... + def __radd__(self, x: u64) -> u64: ... + def __sub__(self, x: u64) -> u64: ... + def __rsub__(self, x: u64) -> u64: ... + def __mul__(self, x: u64) -> u64: ... + def __rmul__(self, x: u64) -> u64: ... + def __floordiv__(self, x: u64) -> u64: ... + def __rfloordiv__(self, x: u64) -> u64: ... + def __mod__(self, x: u64) -> u64: ... + def __rmod__(self, x: u64) -> u64: ... + def __and__(self, x: u64) -> u64: ... + def __rand__(self, x: u64) -> u64: ... + def __or__(self, x: u64) -> u64: ... + def __ror__(self, x: u64) -> u64: ... + def __xor__(self, x: u64) -> u64: ... + def __rxor__(self, x: u64) -> u64: ... + def __lshift__(self, x: u64) -> u64: ... + def __rlshift__(self, x: u64) -> u64: ... + def __rshift__(self, x: u64) -> u64: ... + def __rrshift__(self, x: u64) -> u64: ... + def __neg__(self) -> u64: ... + def __invert__(self) -> u64: ... + def __pos__(self) -> u64: ... + def __lt__(self, x: u64) -> bool: ... + def __le__(self, x: u64) -> bool: ... + def __ge__(self, x: u64) -> bool: ... + def __gt__(self, x: u64) -> bool: ... + def __index__(self) -> int: ... + def __eq__(self, x: object) -> bool: ... + def __bool__(self) -> bool: ... + class u32: @overload def __new__(cls, __x: str | ReadableBuffer | SupportsInt | SupportsIndex | SupportsTrunc = ...) -> u32: ... diff --git a/mypyc/codegen/emit.py b/mypyc/codegen/emit.py index 24bce8cb05fae..82f4641b09cf8 100644 --- a/mypyc/codegen/emit.py +++ b/mypyc/codegen/emit.py @@ -67,6 +67,7 @@ is_uint8_rprimitive, is_uint16_rprimitive, is_uint32_rprimitive, + is_uint64_rprimitive, object_rprimitive, optional_value_type, vec_api_by_item_type, @@ -1175,6 +1176,13 @@ def emit_unbox( self.emit_line(f"{dest} = CPyLong_AsUInt32({src});") if not isinstance(error, AssignHandler): self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure) + elif is_uint64_rprimitive(typ): + assert not optional + if declare_dest: + self.emit_line(f"uint64_t {dest};") + self.emit_line(f"{dest} = CPyLong_AsUInt64({src});") + if not isinstance(error, AssignHandler): + self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure) elif is_uint16_rprimitive(typ): # Whether we are borrowing or not makes no difference. assert not optional # Not supported for overlapping error values @@ -1348,6 +1356,8 @@ def emit_box( self.emit_inc_ref(dest, object_rprimitive) elif is_uint32_rprimitive(typ): self.emit_line(f"{declaration}{dest} = PyLong_FromUnsignedLong({src});") + elif is_uint64_rprimitive(typ): + self.emit_line(f"{declaration}{dest} = PyLong_FromUnsignedLongLong({src});") elif ( is_int32_rprimitive(typ) or is_int16_rprimitive(typ) diff --git a/mypyc/doc/int_operations.rst b/mypyc/doc/int_operations.rst index 75e1b3af499a8..dfa5c5b270c7f 100644 --- a/mypyc/doc/int_operations.rst +++ b/mypyc/doc/int_operations.rst @@ -9,11 +9,12 @@ Mypyc supports these integer types: * ``i64`` (64-bit signed integer) * ``i32`` (32-bit signed integer) * ``i16`` (16-bit signed integer) +* ``u64`` (64-bit unsigned integer) * ``u32`` (32-bit unsigned integer) * ``u16`` (16-bit unsigned integer) * ``u8`` (8-bit unsigned integer) -``i64``, ``i32``, ``i16``, ``u32``, ``u16`` and ``u8`` are *native integer types* and +``i64``, ``i32``, ``i16``, ``u64``, ``u32``, ``u16`` and ``u8`` are *native integer types* and are available in the ``mypy_extensions`` module. ``int`` corresponds to the Python ``int`` type, but uses a more efficient runtime representation (tagged pointer). Native integer types are value types. @@ -37,6 +38,7 @@ Construction * ``int(x: i64)`` * ``int(x: i32)`` * ``int(x: i16)`` +* ``int(x: u64)`` * ``int(x: u32)`` * ``int(x: u16)`` * ``int(x: u8)`` @@ -51,6 +53,7 @@ Construction * ``i64(x: i64)`` (no-op) * ``i64(x: i32)`` * ``i64(x: i16)`` +* ``i64(x: u64)`` * ``i64(x: u32)`` * ``i64(x: u16)`` * ``i64(x: u8)`` @@ -64,7 +67,8 @@ Construction * ``i32(x: i64)`` (truncate) * ``i32(x: i32)`` (no-op) * ``i32(x: i16)`` -* ``i32(x: u32)`` (truncate) +* ``i32(x: u64)`` (truncate) +* ``i32(x: u32)`` * ``i32(x: u16)`` * ``i32(x: u8)`` * ``i32(x: str)`` @@ -77,19 +81,35 @@ Construction * ``i16(x: i64)`` (truncate) * ``i16(x: i32)`` (truncate) * ``i16(x: i16)`` (no-op) +* ``i16(x: u64)`` (truncate) * ``i16(x: u32)`` (truncate) -* ``i16(x: u16)`` (truncate) +* ``i16(x: u16)`` * ``i16(x: u8)`` * ``i16(x: str)`` * ``i16(x: str, base: int)`` +``u64`` type: + +* ``u64(x: int)`` +* ``u64(x: float)`` +* ``u64(x: i64)`` +* ``u64(x: i32)`` +* ``u64(x: i16)`` +* ``u64(x: u64)`` (no-op) +* ``u64(x: u32)`` +* ``u64(x: u16)`` +* ``u64(x: u8)`` +* ``u64(x: str)`` +* ``u64(x: str, base: int)`` + ``u32`` type: * ``u32(x: int)`` * ``u32(x: float)`` * ``u32(x: i64)`` (truncate) -* ``u32(x: i32)`` (truncate) -* ``u32(x: i16)`` (truncate) +* ``u32(x: i32)`` +* ``u32(x: i16)`` +* ``u32(x: u64)`` (truncate) * ``u32(x: u32)`` (no-op) * ``u32(x: u16)`` * ``u32(x: u8)`` @@ -101,9 +121,10 @@ Construction * ``u16(x: int)`` * ``u16(x: float)`` * ``u16(x: i64)`` (truncate) -* ``u16(x: u32)`` (truncate) * ``u16(x: i32)`` (truncate) -* ``u16(x: i16)`` (truncate) +* ``u16(x: i16)`` +* ``u16(x: u64)`` (truncate) +* ``u16(x: u32)`` (truncate) * ``u16(x: u16)`` (no-op) * ``u16(x: u8)`` * ``u16(x: str)`` @@ -116,6 +137,8 @@ Construction * ``u8(x: i64)`` (truncate) * ``u8(x: i32)`` (truncate) * ``u8(x: i16)`` (truncate) +* ``u8(x: u64)`` (truncate) +* ``u8(x: u32)`` (truncate) * ``u8(x: u16)`` (truncate) * ``u8(x: u8)`` (no-op) * ``u8(x: str)`` @@ -124,8 +147,11 @@ Construction Conversions from ``int`` to a native integer type raise ``OverflowError`` if the value is too large or small. Conversions from a wider native integer type to a narrower one truncate the value and never -fail. More generally, operations between native integer types don't -check for overflow. +fail. Conversions between signed and unsigned types of the same or larger +size don't fail either: a value outside the target range wraps around +(for example, ``u64(i32(-1))`` is ``2**64 - 1`` and ``i64(u64(2**63))`` +is ``-2**63``). More generally, operations between +native integer types don't check for overflow. Implicit conversions -------------------- diff --git a/mypyc/doc/using_type_annotations.rst b/mypyc/doc/using_type_annotations.rst index 57830da75c2c9..1a9d38654963d 100644 --- a/mypyc/doc/using_type_annotations.rst +++ b/mypyc/doc/using_type_annotations.rst @@ -33,6 +33,7 @@ implementations: * ``i64`` (:ref:`documentation `, :ref:`native operations `) * ``i32`` (:ref:`documentation `, :ref:`native operations `) * ``i16`` (:ref:`documentation `, :ref:`native operations `) +* ``u64`` (:ref:`documentation `, :ref:`native operations `) * ``u32`` (:ref:`documentation `, :ref:`native operations `) * ``u16`` (:ref:`documentation `, :ref:`native operations `) * ``u8`` (:ref:`documentation `, :ref:`native operations `) @@ -351,7 +352,7 @@ Native integer types You can use the native integer types ``i64`` (64-bit signed integer), ``i32`` (32-bit signed integer), ``i16`` (16-bit signed integer), -``u32`` (32-bit unsigned integer), ``u16`` (16-bit unsigned integer), and ``u8`` (8-bit unsigned integer) +``u64`` (64-bit unsigned integer), ``u32`` (32-bit unsigned integer), ``u16`` (16-bit unsigned integer), and ``u8`` (8-bit unsigned integer) if you know that integer values will always fit within fixed bounds. These types are faster than the arbitrary-precision ``int`` type, since they don't require overflow diff --git a/mypyc/ir/rtypes.py b/mypyc/ir/rtypes.py index 82a5473435b6d..918766579a0e0 100644 --- a/mypyc/ir/rtypes.py +++ b/mypyc/ir/rtypes.py @@ -431,9 +431,6 @@ def __hash__(self) -> int: error_overlap=True, ) -# The following unsigned native int types (u64) are not -# exposed to the user. They are for internal use within mypyc only. - uint64_rprimitive: Final = RPrimitive( "u64", is_unboxed=True, @@ -633,6 +630,7 @@ def is_fixed_width_rtype(rtype: RType) -> TypeGuard[RPrimitive]: is_int64_rprimitive(rtype) or is_int32_rprimitive(rtype) or is_int16_rprimitive(rtype) + or is_uint64_rprimitive(rtype) or is_uint32_rprimitive(rtype) or is_uint16_rprimitive(rtype) or is_uint8_rprimitive(rtype) @@ -768,6 +766,8 @@ def visit_rprimitive(self, t: RPrimitive) -> str: return "4" # "4 byte integer" elif t._ctype == "int16_t": return "2" # "2 byte integer" + elif t._ctype == "uint64_t": + return "U8" elif t._ctype == "uint32_t": return "U4" elif t._ctype == "uint16_t": diff --git a/mypyc/irbuild/ll_builder.py b/mypyc/irbuild/ll_builder.py index 01ee6dc6442d9..30c38e3a24a50 100644 --- a/mypyc/irbuild/ll_builder.py +++ b/mypyc/irbuild/ll_builder.py @@ -124,6 +124,7 @@ is_uint8_rprimitive, is_uint16_rprimitive, is_uint32_rprimitive, + is_uint64_rprimitive, none_rprimitive, object_pointer_rprimitive, object_rprimitive, @@ -172,11 +173,14 @@ int_to_int32_op, int_to_int64_op, int_to_uint32_op, + int_to_uint64_op, ssize_t_to_int_op, uint8_overflow, uint16_overflow, uint32_overflow, uint32_to_int_op, + uint64_overflow, + uint64_to_int_op, ) from mypyc.primitives.list_ops import list_build_op, list_extend_op, list_items, new_list_op from mypyc.primitives.misc_ops import ( @@ -587,10 +591,10 @@ def coerce_int_to_fixed_width(self, src: Value, target_type: RType, line: int) - self.activate_block(fast) size = target_type.size - needs_unsigned_fast_range_check = not target_type.is_signed and size == int_rprimitive.size + needs_unsigned_fast_range_check = not target_type.is_signed and size >= int_rprimitive.size if needs_unsigned_fast_range_check: # A tagged short int always fits in an unsigned type of the same - # width, except for negative values. Don't send those to the slow + # width or larger, except for negative values. Don't send those to the slow # path, which expects a tagged pointer rather than a short int. nonnegative = self.add(ComparisonOp(src, Integer(0, src.type), ComparisonOp.SGE, line)) valid = BasicBlock() @@ -616,6 +620,7 @@ def coerce_int_to_fixed_width(self, src: Value, target_type: RType, line: int) - self.activate_block(slow) if ( is_int64_rprimitive(target_type) + or is_uint64_rprimitive(target_type) or (is_int32_rprimitive(target_type) and size == int_rprimitive.size) or (is_uint32_rprimitive(target_type) and size == int_rprimitive.size) ): @@ -627,6 +632,8 @@ def coerce_int_to_fixed_width(self, src: Value, target_type: RType, line: int) - self.add(Assign(ptr2, ptr)) if is_int64_rprimitive(target_type): conv_op = int_to_int64_op + elif is_uint64_rprimitive(target_type): + conv_op = int_to_uint64_op elif is_uint32_rprimitive(target_type): conv_op = int_to_uint32_op else: @@ -744,6 +751,8 @@ def emit_fixed_width_overflow_error(self, target_type: RType, line: int) -> None self.call_c(int32_overflow, [], line) elif is_int16_rprimitive(target_type): self.call_c(int16_overflow, [], line) + elif is_uint64_rprimitive(target_type): + self.call_c(uint64_overflow, [], line) elif is_uint32_rprimitive(target_type): self.call_c(uint32_overflow, [], line) elif is_uint16_rprimitive(target_type): @@ -845,6 +854,8 @@ def coerce_fixed_width_to_int(self, src: Value, line: int) -> Value: elif is_int32_rprimitive(src_type): assert PLATFORM_SIZE == 4 conv_op = ssize_t_to_int_op + elif is_uint64_rprimitive(src_type): + conv_op = uint64_to_int_op elif is_uint32_rprimitive(src_type): assert PLATFORM_SIZE == 4 conv_op = uint32_to_int_op @@ -2782,6 +2793,9 @@ def fixed_width_int_op( prim = int32_divide_op elif is_int16_rprimitive(type): prim = int16_divide_op + elif is_uint64_rprimitive(type): + self.check_for_zero_division(rhs, type, line) + return self.int_op(type, lhs, rhs, op, line) elif is_uint32_rprimitive(type): self.check_for_zero_division(rhs, type, line) return self.int_op(type, lhs, rhs, op, line) @@ -2808,6 +2822,9 @@ def fixed_width_int_op( prim = int32_mod_op elif is_int16_rprimitive(type): prim = int16_mod_op + elif is_uint64_rprimitive(type): + self.check_for_zero_division(rhs, type, line) + return self.int_op(type, lhs, rhs, op, line) elif is_uint32_rprimitive(type): self.check_for_zero_division(rhs, type, line) return self.int_op(type, lhs, rhs, op, line) diff --git a/mypyc/irbuild/mapper.py b/mypyc/irbuild/mapper.py index 2e771040a5a1e..caa11f5d87460 100644 --- a/mypyc/irbuild/mapper.py +++ b/mypyc/irbuild/mapper.py @@ -52,6 +52,7 @@ uint8_rprimitive, uint16_rprimitive, uint32_rprimitive, + uint64_rprimitive, ) @@ -125,6 +126,8 @@ def type_to_rtype(self, typ: Type | None) -> RType: return int32_rprimitive elif typ.type.fullname == "mypy_extensions.i16": return int16_rprimitive + elif typ.type.fullname == "mypy_extensions.u64": + return uint64_rprimitive elif typ.type.fullname == "mypy_extensions.u32": return uint32_rprimitive elif typ.type.fullname == "mypy_extensions.u16": diff --git a/mypyc/irbuild/specialize.py b/mypyc/irbuild/specialize.py index c7cc8d4959932..918e983140fef 100644 --- a/mypyc/irbuild/specialize.py +++ b/mypyc/irbuild/specialize.py @@ -85,6 +85,7 @@ is_uint8_rprimitive, is_uint16_rprimitive, is_uint32_rprimitive, + is_uint64_rprimitive, list_rprimitive, object_rprimitive, set_rprimitive, @@ -93,6 +94,7 @@ uint8_rprimitive, uint16_rprimitive, uint32_rprimitive, + uint64_rprimitive, ) from mypyc.irbuild.builder import IRBuilder, find_walrus_targets, get_call_target_fullname from mypyc.irbuild.constant_fold import constant_fold_expr @@ -323,6 +325,7 @@ def translate_globals(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Va @specialize_function("mypy_extensions.i64") @specialize_function("mypy_extensions.i32") @specialize_function("mypy_extensions.i16") +@specialize_function("mypy_extensions.u64") @specialize_function("mypy_extensions.u32") @specialize_function("mypy_extensions.u16") @specialize_function("mypy_extensions.u8") @@ -337,7 +340,7 @@ def translate_builtins_with_unary_dunder( arg = expr.args[0] arg_typ = builder.node_type(arg) shortname = callee.fullname.split(".")[1] - if shortname in ("i64", "i32", "i16", "u32", "u16", "u8"): + if shortname in ("i64", "i32", "i16", "u64", "u32", "u16", "u8"): method = "__int__" else: method = f"__{shortname}__" @@ -1181,6 +1184,9 @@ def translate_i64(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value elif is_int32_rprimitive(arg_type) or is_int16_rprimitive(arg_type): val = builder.accept(arg) return builder.add(Extend(val, int64_rprimitive, signed=True, line=expr.line)) + elif is_uint64_rprimitive(arg_type): + val = builder.accept(arg) + return builder.add(Truncate(val, int64_rprimitive, line=expr.line)) elif is_uint32_rprimitive(arg_type): val = builder.accept(arg) return builder.add(Extend(val, int64_rprimitive, signed=False, line=expr.line)) @@ -1210,6 +1216,9 @@ def translate_i32(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value elif is_int16_rprimitive(arg_type): val = builder.accept(arg) return builder.add(Extend(val, int32_rprimitive, signed=True, line=expr.line)) + elif is_uint64_rprimitive(arg_type): + val = builder.accept(arg) + return builder.add(Truncate(val, int32_rprimitive, line=expr.line)) elif is_uint32_rprimitive(arg_type): val = builder.accept(arg) return builder.add(Truncate(val, int32_rprimitive, line=expr.line)) @@ -1237,6 +1246,9 @@ def translate_i16(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value elif is_int32_rprimitive(arg_type) or is_int64_rprimitive(arg_type): val = builder.accept(arg) return builder.add(Truncate(val, int16_rprimitive, line=expr.line)) + elif is_uint64_rprimitive(arg_type): + val = builder.accept(arg) + return builder.add(Truncate(val, int16_rprimitive, line=expr.line)) elif is_uint32_rprimitive(arg_type): val = builder.accept(arg) return builder.add(Truncate(val, int16_rprimitive, line=expr.line)) @@ -1253,6 +1265,34 @@ def translate_i16(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value return None +@specialize_function("mypy_extensions.u64") +def translate_u64(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None: + if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS: + return None + arg = expr.args[0] + arg_type = builder.node_type(arg) + if is_uint64_rprimitive(arg_type): + return builder.accept(arg) + elif is_int64_rprimitive(arg_type): + val = builder.accept(arg) + return builder.add(Truncate(val, uint64_rprimitive, line=expr.line)) + elif is_int32_rprimitive(arg_type) or is_int16_rprimitive(arg_type): + val = builder.accept(arg) + return builder.add(Extend(val, uint64_rprimitive, signed=True, line=expr.line)) + elif ( + is_uint32_rprimitive(arg_type) + or is_uint16_rprimitive(arg_type) + or is_uint8_rprimitive(arg_type) + ): + val = builder.accept(arg) + return builder.add(Extend(val, uint64_rprimitive, signed=False, line=expr.line)) + elif is_int_rprimitive(arg_type) or is_bool_rprimitive(arg_type): + val = builder.accept(arg) + val = truncate_literal(val, uint64_rprimitive) + return builder.coerce(val, uint64_rprimitive, expr.line) + return None + + @specialize_function("mypy_extensions.u32") def translate_u32(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None: if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS: @@ -1265,6 +1305,7 @@ def translate_u32(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value is_int16_rprimitive(arg_type) or is_int32_rprimitive(arg_type) or is_int64_rprimitive(arg_type) + or is_uint64_rprimitive(arg_type) or is_uint16_rprimitive(arg_type) or is_uint8_rprimitive(arg_type) ): @@ -1293,6 +1334,7 @@ def translate_u16(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value is_int16_rprimitive(arg_type) or is_int32_rprimitive(arg_type) or is_int64_rprimitive(arg_type) + or is_uint64_rprimitive(arg_type) or is_uint32_rprimitive(arg_type) or is_uint8_rprimitive(arg_type) ): @@ -1319,6 +1361,7 @@ def translate_u8(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | is_int16_rprimitive(arg_type) or is_int32_rprimitive(arg_type) or is_int64_rprimitive(arg_type) + or is_uint64_rprimitive(arg_type) or is_uint32_rprimitive(arg_type) or is_uint16_rprimitive(arg_type) ): diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index 65cc8f038e508..5dd6ebf67e63c 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -175,6 +175,7 @@ static inline size_t CPy_FindAttrOffset(PyTypeObject *trait, CPyVTableItem *vtab CPyTagged CPyTagged_FromSsize_t(Py_ssize_t value); CPyTagged CPyTagged_FromVoidPtr(void *ptr); CPyTagged CPyTagged_FromInt64(int64_t value); +CPyTagged CPyTagged_FromUInt64(uint64_t value); CPyTagged CPyTagged_FromUInt32(uint32_t value); PyObject *CPyTagged_AsObject(CPyTagged x); PyObject *CPyTagged_StealAsObject(CPyTagged x); @@ -219,6 +220,8 @@ int16_t CPyLong_AsInt16_(PyObject *o); int16_t CPyInt16_Divide(int16_t x, int16_t y); int16_t CPyInt16_Remainder(int16_t x, int16_t y); void CPyInt16_Overflow(void); +uint64_t CPyLong_AsUInt64_(PyObject *o); +void CPyUInt64_Overflow(void); uint32_t CPyLong_AsUInt32_(PyObject *o); void CPyUInt32_Overflow(void); uint16_t CPyLong_AsUInt16_(PyObject *o); @@ -488,6 +491,29 @@ static inline uint32_t CPyLong_AsUInt32(PyObject *o) { return CPyLong_AsUInt32_(o); } +static inline uint64_t CPyLong_AsUInt64(PyObject *o) { + if (likely(PyLong_Check(o))) { + #if CPY_3_12_FEATURES + PyLongObject *lobj = (PyLongObject *)o; + size_t tag = CPY_LONG_TAG(lobj); + if (likely(tag == (1 << CPY_NON_SIZE_BITS))) { + return CPY_LONG_DIGIT(lobj, 0); + } else if (likely(tag == CPY_SIGN_ZERO)) { + return 0; + } + #else + PyLongObject *lobj = (PyLongObject *)o; + Py_ssize_t size = lobj->ob_base.ob_size; + if (likely(size == 1)) { + return lobj->ob_digit[0]; + } else if (likely(size == 0)) { + return 0; + } + #endif + } + return CPyLong_AsUInt64_(o); +} + static inline uint16_t CPyLong_AsUInt16(PyObject *o) { if (likely(PyLong_Check(o))) { #if CPY_3_12_FEATURES @@ -876,6 +902,8 @@ PyObject *CPyList_GetItemShort(PyObject *list, CPyTagged index); PyObject *CPyList_GetItemInt64(PyObject *list, int64_t index); bool CPyList_SetItem(PyObject *list, CPyTagged index, PyObject *value); bool CPyList_SetItemInt64(PyObject *list, int64_t index, PyObject *value); +PyObject *CPyList_GetItemUInt64(PyObject *list, uint64_t index); +bool CPyList_SetItemUInt64(PyObject *list, uint64_t index, PyObject *value); #else @@ -924,11 +952,29 @@ static inline bool CPyList_SetItemInt64(PyObject *list, int64_t index, PyObject return PyList_SetItem(list, index, value) >= 0; } +static inline PyObject *CPyList_GetItemUInt64(PyObject *list, uint64_t index) { + if (unlikely(index > (uint64_t)PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_IndexError, "list index out of range"); + return NULL; + } + return PyList_GetItemRef(list, (Py_ssize_t)index); +} + +static inline bool CPyList_SetItemUInt64(PyObject *list, uint64_t index, PyObject *value) { + if (unlikely(index > (uint64_t)PY_SSIZE_T_MAX)) { + Py_DECREF(value); + PyErr_SetString(PyExc_IndexError, "list assignment index out of range"); + return false; + } + return PyList_SetItem(list, (Py_ssize_t)index, value) >= 0; +} + #endif PyObject *CPyList_GetItemBorrow(PyObject *list, CPyTagged index); PyObject *CPyList_GetItemShortBorrow(PyObject *list, CPyTagged index); PyObject *CPyList_GetItemInt64Borrow(PyObject *list, int64_t index); +PyObject *CPyList_GetItemUInt64Borrow(PyObject *list, uint64_t index); void CPyList_SetItemUnsafe(PyObject *list, Py_ssize_t index, PyObject *value); PyObject *CPyList_Build(Py_ssize_t len, ...); PyObject *CPyList_PopLast(PyObject *obj); diff --git a/mypyc/lib-rt/int_ops.c b/mypyc/lib-rt/int_ops.c index edf2fc2f1b967..7f265bf00cad4 100644 --- a/mypyc/lib-rt/int_ops.c +++ b/mypyc/lib-rt/int_ops.c @@ -59,6 +59,15 @@ CPyTagged CPyTagged_FromInt64(int64_t value) { } } +CPyTagged CPyTagged_FromUInt64(uint64_t value) { + if (unlikely(value > CPY_TAGGED_MAX)) { + PyObject *object = PyLong_FromUnsignedLongLong(value); + return ((CPyTagged)object) | CPY_INT_TAG; + } else { + return ((CPyTagged)value) << 1; + } +} + CPyTagged CPyTagged_FromUInt32(uint32_t value) { #if SIZEOF_SIZE_T == 4 // Only 32-bit platforms can have values that don't fit in a short int. Doing @@ -581,6 +590,23 @@ void CPyInt16_Overflow() { PyErr_SetString(PyExc_ValueError, "int too large to convert to i16"); } +// u64 unboxing slow path +uint64_t CPyLong_AsUInt64_(PyObject *o) { + unsigned long long result = PyLong_AsUnsignedLongLong(o); + if (result == (unsigned long long)-1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) { + PyErr_Clear(); + PyErr_SetString(PyExc_ValueError, "int too large or small to convert to u64"); + } + return CPY_LL_UINT_ERROR; + } + return (uint64_t)result; +} + +void CPyUInt64_Overflow() { + PyErr_SetString(PyExc_ValueError, "int too large or small to convert to u64"); +} + // u32 unboxing slow path uint32_t CPyLong_AsUInt32_(PyObject *o) { unsigned long result = PyLong_AsUnsignedLong(o); diff --git a/mypyc/lib-rt/list_ops.c b/mypyc/lib-rt/list_ops.c index 9e4a64d48064f..4aa72ed56aa01 100644 --- a/mypyc/lib-rt/list_ops.c +++ b/mypyc/lib-rt/list_ops.c @@ -177,6 +177,30 @@ bool CPyList_SetItemInt64(PyObject *list, int64_t index, PyObject *value) { return true; } +PyObject *CPyList_GetItemUInt64(PyObject *list, uint64_t index) { + if (likely(index < (uint64_t)PyList_GET_SIZE(list))) { + PyObject *result = PyList_GET_ITEM(list, index); + Py_INCREF(result); + return result; + } + PyErr_SetString(PyExc_IndexError, "list index out of range"); + return NULL; +} + +bool CPyList_SetItemUInt64(PyObject *list, uint64_t index, PyObject *value) { + if (unlikely(index >= (uint64_t)PyList_GET_SIZE(list))) { + Py_DECREF(value); + PyErr_SetString(PyExc_IndexError, "list assignment index out of range"); + return false; + } + // Set the replacement before decref, which may run reentrant Python code. + PyObject *old = PyList_GET_ITEM(list, index); + // N.B: Steals reference + PyList_SET_ITEM(list, index, value); + Py_DECREF(old); + return true; +} + #else /* Py_GIL_DISABLED */ PyObject *CPyList_GetItem_(PyObject *list, CPyTagged index) { @@ -267,6 +291,14 @@ PyObject *CPyList_GetItemInt64Borrow(PyObject *list, int64_t index) { return PyList_GET_ITEM(list, index); } +PyObject *CPyList_GetItemUInt64Borrow(PyObject *list, uint64_t index) { + if (likely(index < (uint64_t)PyList_GET_SIZE(list))) { + return PyList_GET_ITEM(list, index); + } + PyErr_SetString(PyExc_IndexError, "list index out of range"); + return NULL; +} + // This function should only be used to fill in brand new lists. void CPyList_SetItemUnsafe(PyObject *list, Py_ssize_t index, PyObject *value) { PyList_SET_ITEM(list, index, value); diff --git a/mypyc/primitives/int_ops.py b/mypyc/primitives/int_ops.py index cd2049163d9a9..e166a9b1a2403 100644 --- a/mypyc/primitives/int_ops.py +++ b/mypyc/primitives/int_ops.py @@ -31,6 +31,7 @@ object_rprimitive, str_rprimitive, uint32_rprimitive, + uint64_rprimitive, void_rtype, ) from mypyc.primitives.registry import ( @@ -50,6 +51,7 @@ "mypy_extensions.i64", "mypy_extensions.i32", "mypy_extensions.i16", + "mypy_extensions.u64", "mypy_extensions.u32", "mypy_extensions.u16", "mypy_extensions.u8", @@ -296,6 +298,13 @@ def int_unary_op(name: str, c_function_name: str) -> PrimitiveDescription: error_kind=ERR_MAGIC, ) +uint64_to_int_op = custom_op( + arg_types=[uint64_rprimitive], + return_type=int_rprimitive, + c_function_name="CPyTagged_FromUInt64", + error_kind=ERR_MAGIC, +) + uint32_to_int_op = custom_op( arg_types=[uint32_rprimitive], return_type=int_rprimitive, @@ -303,6 +312,14 @@ def int_unary_op(name: str, c_function_name: str) -> PrimitiveDescription: error_kind=ERR_MAGIC, ) +# Convert tagged int (as PyObject *) to u64 +int_to_uint64_op = custom_op( + arg_types=[object_rprimitive], + return_type=uint64_rprimitive, + c_function_name="CPyLong_AsUInt64", + error_kind=ERR_MAGIC_OVERLAPPING, +) + # Convert tagged int (as PyObject *) to u32 int_to_uint32_op = custom_op( arg_types=[object_rprimitive], @@ -340,6 +357,13 @@ def int_unary_op(name: str, c_function_name: str) -> PrimitiveDescription: error_kind=ERR_ALWAYS, ) +uint64_overflow = custom_op( + arg_types=[], + return_type=void_rtype, + c_function_name="CPyUInt64_Overflow", + error_kind=ERR_ALWAYS, +) + uint16_overflow = custom_op( arg_types=[], return_type=void_rtype, diff --git a/mypyc/primitives/list_ops.py b/mypyc/primitives/list_ops.py index f5548e88592f1..65973d14bed6a 100644 --- a/mypyc/primitives/list_ops.py +++ b/mypyc/primitives/list_ops.py @@ -13,6 +13,7 @@ object_rprimitive, pointer_rprimitive, short_int_rprimitive, + uint64_rprimitive, void_rtype, ) from mypyc.primitives.registry import ( @@ -108,13 +109,23 @@ priority=2, ) -# Version with native int index +# Versions with native int index. A bool index matches every __getitem__ op, +# so all priorities must be distinct. i64 is preferred for bool indexes. list_get_item_int64_op = method_op( name="__getitem__", arg_types=[list_rprimitive, int64_rprimitive], return_type=object_rprimitive, c_function_name="CPyList_GetItemInt64", error_kind=ERR_MAGIC, + priority=6, +) + +method_op( + name="__getitem__", + arg_types=[list_rprimitive, uint64_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyList_GetItemUInt64", + error_kind=ERR_MAGIC, priority=5, ) @@ -143,7 +154,7 @@ priority=4, ) -# Version with native int index +# Versions with native int index (see above for why priorities are distinct) method_op( name="__getitem__", arg_types=[list_rprimitive, int64_rprimitive], @@ -152,7 +163,18 @@ is_borrowed=True, gil_only=True, error_kind=ERR_MAGIC, - priority=6, + priority=8, +) + +method_op( + name="__getitem__", + arg_types=[list_rprimitive, uint64_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyList_GetItemUInt64Borrow", + is_borrowed=True, + gil_only=True, + error_kind=ERR_MAGIC, + priority=7, ) # This is unsafe because it assumes that the index is a non-negative integer @@ -182,6 +204,17 @@ c_function_name="CPyList_SetItemInt64", error_kind=ERR_FALSE, steals=[False, False, True], + priority=3, +) + +# list[index_u64] = obj (lower priority than i64, since a bool index matches both) +method_op( + name="__setitem__", + arg_types=[list_rprimitive, uint64_rprimitive, object_rprimitive], + return_type=bit_rprimitive, + c_function_name="CPyList_SetItemUInt64", + error_kind=ERR_FALSE, + steals=[False, False, True], priority=2, ) diff --git a/mypyc/test-data/irbuild-u64.test b/mypyc/test-data/irbuild-u64.test new file mode 100644 index 0000000000000..bf47d2aedbc46 --- /dev/null +++ b/mypyc/test-data/irbuild-u64.test @@ -0,0 +1,444 @@ +# Test cases for u64 native ints. Focus on things that are different from u8; no need to +# duplicate all u8 test cases here. + +[case testU64BinaryOp] +from mypy_extensions import u64 + +def add_op(x: u64, y: u64) -> u64: + x = y + x + y = x + 5 + y += x + y += 7 + x = 5 + y + return x +def compare(x: u64, y: u64) -> None: + a = x == y + b = x == 5 + c = x < y + d = x < 5 + e = 5 == x + f = 5 < x +[out] +def add_op(x, y): + x, y, r0, r1, r2, r3, r4 :: u64 +L0: + r0 = y + x + x = r0 + r1 = x + 5 + y = r1 + r2 = y + x + y = r2 + r3 = y + 7 + y = r3 + r4 = 5 + y + x = r4 + return x +def compare(x, y): + x, y :: u64 + r0 :: bit + a :: bool + r1 :: bit + b :: bool + r2 :: bit + c :: bool + r3 :: bit + d :: bool + r4 :: bit + e :: bool + r5 :: bit + f :: bool +L0: + r0 = x == y + a = r0 + r1 = x == 5 + b = r1 + r2 = x < y :: unsigned + c = r2 + r3 = x < 5 :: unsigned + d = r3 + r4 = 5 == x + e = r4 + r5 = 5 < x :: unsigned + f = r5 + return 1 + +[case testU64DetectMoreOutOfRangeLiterals] +from mypy_extensions import u64 + +def out_of_range() -> None: + a: u64 = 18446744073709551616 + b: u64 = -1 + f(18446744073709551616) + # The following are ok + c: u64 = 0 + d: u64 = 18446744073709551615 + f(0) + f(18446744073709551615) + +def f(x: u64) -> None: pass +[out] +main:5: error: Value -1 is out of range for "u64" + +[case testU64BoxAndUnbox] +from typing import Any +from mypy_extensions import u64 + +def f(x: Any) -> Any: + y: u64 = x + return y +[out] +def f(x): + x :: object + r0, y :: u64 + r1 :: object +L0: + r0 = unbox(u64, x) + y = r0 + r1 = box(u64, y) + return r1 + +[case testU64ConvertToInt_64bit] +from mypy_extensions import u64 + +def u64_to_int(a: u64) -> int: + return a +[out] +def u64_to_int(a): + a :: u64 + r0 :: bit + r1, r2, r3 :: int +L0: + r0 = a <= 4611686018427387903 :: unsigned + if r0 goto L2 else goto L1 :: bool +L1: + r1 = CPyTagged_FromUInt64(a) + r2 = r1 + goto L3 +L2: + r3 = a << 1 + r2 = r3 +L3: + return r2 + +[case testU64ExplicitConversionFromNativeInt] +from mypy_extensions import i64, i32, i16, u8, u64 + +def from_u64(x: u64) -> u64: + return u64(x) + +def from_u8(x: u8) -> u64: + return u64(x) + +def from_i16(x: i16) -> u64: + return u64(x) + +def from_i32(x: i32) -> u64: + return u64(x) + +def from_i64(x: i64) -> u64: + return u64(x) +[out] +def from_u64(x): + x :: u64 +L0: + return x +def from_u8(x): + x :: u8 + r0 :: u64 +L0: + r0 = extend x: u8 to u64 + return r0 +def from_i16(x): + x :: i16 + r0 :: u64 +L0: + r0 = extend signed x: i16 to u64 + return r0 +def from_i32(x): + x :: i32 + r0 :: u64 +L0: + r0 = extend signed x: i32 to u64 + return r0 +def from_i64(x): + x :: i64 + r0 :: u64 +L0: + r0 = truncate x: i64 to u64 + return r0 + +[case testU64ExplicitConversionToNativeInt] +from mypy_extensions import i64, i32, i16, u8, u64 + +def to_u8(x: u64) -> u8: + return u8(x) + +def to_i16(x: u64) -> i16: + return i16(x) + +def to_i32(x: u64) -> i32: + return i32(x) + +def to_i64(x: u64) -> i64: + return i64(x) +[out] +def to_u8(x): + x :: u64 + r0 :: u8 +L0: + r0 = truncate x: u64 to u8 + return r0 +def to_i16(x): + x :: u64 + r0 :: i16 +L0: + r0 = truncate x: u64 to i16 + return r0 +def to_i32(x): + x :: u64 + r0 :: i32 +L0: + r0 = truncate x: u64 to i32 + return r0 +def to_i64(x): + x :: u64 + r0 :: i64 +L0: + r0 = truncate x: u64 to i64 + return r0 + +[case testU64ExplicitConversionFromInt_64bit] +from mypy_extensions import u64 + +def f(x: int) -> u64: + return u64(x) +[out] +def f(x): + x :: int + r0 :: native_int + r1, r2 :: bit + r3, r4 :: u64 + r5 :: ptr + r6 :: c_ptr + r7 :: u64 +L0: + r0 = x & 1 + r1 = r0 == 0 + if r1 goto L1 else goto L3 :: bool +L1: + r2 = x >= 0 :: signed + if r2 goto L2 else goto L4 :: bool +L2: + r3 = x >> 1 + r4 = r3 + goto L5 +L3: + r5 = x ^ 1 + r6 = r5 + r7 = CPyLong_AsUInt64(r6) + r4 = r7 + keep_alive x + goto L5 +L4: + CPyUInt64_Overflow() + unreachable +L5: + return r4 + +[case testU64ExplicitConversionFromInt_32bit] +from mypy_extensions import u64 + +def f(x: int) -> u64: + return u64(x) +[out] +def f(x): + x :: int + r0 :: native_int + r1, r2 :: bit + r3, r4, r5 :: u64 + r6 :: ptr + r7 :: c_ptr + r8 :: u64 +L0: + r0 = x & 1 + r1 = r0 == 0 + if r1 goto L1 else goto L3 :: bool +L1: + r2 = x >= 0 :: signed + if r2 goto L2 else goto L4 :: bool +L2: + r3 = extend signed x: builtins.int to u64 + r4 = r3 >> 1 + r5 = r4 + goto L5 +L3: + r6 = x ^ 1 + r7 = r6 + r8 = CPyLong_AsUInt64(r7) + r5 = r8 + keep_alive x + goto L5 +L4: + CPyUInt64_Overflow() + unreachable +L5: + return r5 + +[case testU64ExplicitConversionFromLiteral_64bit] +from mypy_extensions import u64 + +def f() -> None: + x = u64(0) + y = u64(11) + z = u64(-3) # Truncate + zz = u64(4294967298) # Truncate + a = u64(18446744073709551615) +[out] +def f(): + x, y, z, zz :: u64 + r0 :: int + r1 :: native_int + r2, r3 :: bit + r4, r5 :: u64 + r6 :: ptr + r7 :: c_ptr + r8, a :: u64 +L0: + x = 0 + y = 11 + z = 18446744073709551613 + zz = 4294967298 + r0 = object 18446744073709551615 + r1 = r0 & 1 + r2 = r1 == 0 + if r2 goto L1 else goto L3 :: bool +L1: + r3 = r0 >= 0 :: signed + if r3 goto L2 else goto L4 :: bool +L2: + r4 = r0 >> 1 + r5 = r4 + goto L5 +L3: + r6 = r0 ^ 1 + r7 = r6 + r8 = CPyLong_AsUInt64(r7) + r5 = r8 + keep_alive r0 + goto L5 +L4: + CPyUInt64_Overflow() + unreachable +L5: + a = r5 + return 1 + +[case testU64FromShortInt_64bit] +from mypy_extensions import u64 + +def g(a: list[int]) -> u64: + x: u64 = len(a) + return x +[out] +def g(a): + a :: list + r0 :: native_int + r1 :: short_int + r2 :: bit + r3, x :: u64 +L0: + r0 = var_object_size a + r1 = r0 << 1 + r2 = r1 >= 0 :: signed + if r2 goto L2 else goto L1 :: bool +L1: + CPyUInt64_Overflow() + unreachable +L2: + r3 = r1 >> 1 + x = r3 + return x + +[case testU64ListGetSetItem] +from typing import List +from mypy_extensions import u64 + +def get(a: List[int], i: u64) -> int: + return a[i] + +def set(a: List[int], i: u64, x: int) -> None: + a[i] = x +[out] +def get(a, i): + a :: list + i :: u64 + r0 :: object + r1 :: int +L0: + r0 = CPyList_GetItemUInt64(a, i) + r1 = unbox(int, r0) + return r1 +def set(a, i, x): + a :: list + i :: u64 + x :: int + r0 :: object + r1 :: bit +L0: + r0 = box(int, x) + r1 = CPyList_SetItemUInt64(a, i, r0) + return 1 + +[case testListGetSetItemBoolIndexNotAmbiguous] +# Bool matches both the i64 and u64 index ops; the i64 op must win +from typing import List + +class C: + s: str + +def get(a: List[int], b: bool) -> int: + return a[b] + +def get_borrow(a: List[C], b: bool) -> str: + return a[b].s + +def set(a: List[int], b: bool, x: int) -> None: + a[b] = x +[out] +def get(a, b): + a :: list + b :: bool + r0 :: i64 + r1 :: object + r2 :: int +L0: + r0 = extend b: builtins.bool to i64 + r1 = CPyList_GetItemInt64(a, r0) + r2 = unbox(int, r1) + return r2 +def get_borrow(a, b): + a :: list + b :: bool + r0 :: i64 + r1 :: object + r2 :: __main__.C + r3 :: str +L0: + r0 = extend b: builtins.bool to i64 + r1 = CPyList_GetItemInt64Borrow(a, r0) + r2 = borrow cast(__main__.C, r1) + r3 = r2.s + keep_alive a, r0, r1 + return r3 +def set(a, b, x): + a :: list + b :: bool + x :: int + r0 :: i64 + r1 :: object + r2 :: bit +L0: + r0 = extend b: builtins.bool to i64 + r1 = box(int, x) + r2 = CPyList_SetItemInt64(a, r0, r1) + return 1 diff --git a/mypyc/test-data/run-u64.test b/mypyc/test-data/run-u64.test new file mode 100644 index 0000000000000..209918eee29bf --- /dev/null +++ b/mypyc/test-data/run-u64.test @@ -0,0 +1,364 @@ +[case testU64BasicOps] +from typing import Any, Final, Tuple + +from mypy_extensions import u64, i16, i32, i64, u8 + +from testutil import assertRaises + +ERROR: Final = 239 + +def test_box_and_unbox() -> None: + for i in [0, 1, 255, 256, 1000, 32767, 65534, 18446744073709551615]: + o: Any = i + x: u64 = o + o2: Any = x + assert o == o2 + assert x == i + with assertRaises(ValueError, "int too large or small to convert to u64"): + o = 18446744073709551616 + x2: u64 = o + with assertRaises(ValueError, "int too large or small to convert to u64"): + o = -1 + x3: u64 = o + +def div_by_7(x: u64) -> u64: + return x // 7 + +def div(x: u64, y: u64) -> u64: + return x // y + +def test_divide_by_constant() -> None: + for i in [0, 1, 100, 1000, 18446744073709551615]: + assert div_by_7(i) == i // 7 + +def test_divide_by_variable() -> None: + for x in [0, 1, 255, 256, 1000, 18446744073709551615]: + for y in [0, 1, 7, 255, 256, 1000, 18446744073709551615]: + if y != 0: + assert div(x, y) == x // y + else: + with assertRaises(ZeroDivisionError, "integer division or modulo by zero"): + div(x, y) + +def mod_by_7(x: u64) -> u64: + return x % 7 + +def mod(x: u64, y: u64) -> u64: + return x % y + +def test_mod_by_constant() -> None: + for i in [0, 1, 100, 1000, 18446744073709551615]: + assert mod_by_7(i) == i % 7 + +def test_mod_by_variable() -> None: + for x in [0, 1, 255, 256, 1000, 18446744073709551615]: + for y in [0, 1, 7, 255, 256, 1000, 18446744073709551615]: + if y != 0: + assert mod(x, y) == x % y + else: + with assertRaises(ZeroDivisionError, "integer division or modulo by zero"): + mod(x, y) + +def test_simple_arithmetic_ops() -> None: + zero: u64 = int() + one: u64 = zero + 1 + two: u64 = one + 1 + neg_one: u64 = -one + assert neg_one == 18446744073709551615 + assert one + one == 2 + assert one + two == 3 + assert one + neg_one == 0 + assert one - one == 0 + assert one - two == 18446744073709551615 + assert one * one == 1 + assert one * two == 2 + assert two * two == 4 + assert two * neg_one == 18446744073709551614 + assert neg_one * one == 18446744073709551615 + assert neg_one * neg_one == 1 + assert two * 0 == 0 + assert 0 * two == 0 + assert -one == 18446744073709551615 + assert -two == 18446744073709551614 + assert -neg_one == 1 + assert -zero == 0 + +def test_bitwise_ops() -> None: + x: u64 = 47384 + int() + y: u64 = 20239 + int() + z: u64 = 28913 + int() + zero: u64 = int() + one: u64 = zero + 1 + two: u64 = zero + 2 + neg_one: u64 = -one + + assert x & y == 2312 + assert x & z == 12304 + assert z & z == z + assert x & zero == 0 + + assert x | y == 65311 + assert x | z == 63993 + assert z | z == z + assert x | 0 == x + + assert x ^ y == 62999 + assert x ^ z == 51689 + assert z ^ z == 0 + assert z ^ 0 == z + + assert x << one == 94768 + assert x << two == 189536 + assert z << two == 115652 + assert z << 0 == z + + assert x >> one == 23692 + assert x >> two == 11846 + assert z >> two == 7228 + assert z >> 0 == z + + for i in [0, 1, 255, 256, 1000, 32767, 18446744073709551615]: + t: u64 = i + assert ~t == (~(i + int()) & 0xffffffffffffffff) + +def eq(x: u64, y: u64) -> bool: + return x == y + +def test_eq() -> None: + assert eq(int(), int()) + assert eq(5 + int(), 5 + int()) + assert not eq(int(), 1 + int()) + assert not eq(5 + int(), 6 + int()) + +def test_comparisons() -> None: + one: u64 = 1 + int() + one2: u64 = 1 + int() + two: u64 = 2 + int() + assert one < two + assert not (one < one2) + assert not (two < one) + assert two > one + assert not (one > one2) + assert not (one > two) + assert one <= two + assert one <= one2 + assert not (two <= one) + assert two >= one + assert one >= one2 + assert not (one >= two) + assert one == one2 + assert not (one == two) + assert one != two + assert not (one != one2) + +def test_mixed_comparisons() -> None: + u64_3: u64 = int() + 3 + int_5 = int() + 5 + assert u64_3 < int_5 + assert int_5 > u64_3 + b = u64_3 > int_5 + assert not b + + int_largest = int() + 18446744073709551615 + assert int_largest > u64_3 + int_smallest = int() + assert u64_3 > int_smallest + + int_too_big = int() + 18446744073709551616 + int_too_small = int() -1 + with assertRaises(ValueError): + assert u64_3 < int_too_big + with assertRaises(ValueError): + assert int_too_big < u64_3 + with assertRaises(ValueError): + assert u64_3 > int_too_small + with assertRaises(ValueError): + assert int_too_small < u64_3 + +def test_mixed_arithmetic_and_bitwise_ops() -> None: + u64_3: u64 = int() + 3 + int_5 = int() + 5 + assert u64_3 + int_5 == 8 + assert int_5 - u64_3 == 2 + assert u64_3 << int_5 == 96 + assert int_5 << u64_3 == 40 + assert u64_3 ^ int_5 == 6 + assert int_5 | u64_3 == 7 + + int_largest = int() + 18446744073709551615 + assert int_largest - u64_3 == 18446744073709551612 + int_smallest = int() + assert int_smallest + u64_3 == 3 + + int_too_big = int() + 18446744073709551616 + int_too_small = int() - 1 + with assertRaises(ValueError): + assert u64_3 & int_too_big + with assertRaises(ValueError): + assert int_too_small & u64_3 + +def test_coerce_to_and_from_int() -> None: + for n in [0, 1, 255, 256, 1000, 32767, 18446744073709551615]: + x: u64 = n + m: int = x + assert m == n + +def test_coerce_from_len_and_negative_int() -> None: + a = [1, 2, 3] + x: u64 = len(a) + assert x == 3 + n = 0 + for i in range(-2, 2): + if i < 0: + with assertRaises(ValueError, "int too large or small to convert to u64"): + y: u64 = i + else: + y = i + assert y == i + n += 1 + assert n == 2 + +def test_explicit_conversion_to_u64() -> None: + x = u64(5) + assert x == 5 + y = int() + ERROR + x = u64(y) + assert x == ERROR + n64: i64 = 233 + x = u64(n64) + assert x == 233 + n32: i32 = 234 + x = u64(n32) + assert x == 234 + z = u64(x) + assert z == 234 + n16: i16 = 231 + x = u64(n16) + assert x == 231 + n8: u8 = 232 + x = u64(n8) + assert x == 232 + +def test_explicit_conversion_overflow() -> None: + max_u64 = int() + 18446744073709551615 + x = u64(max_u64) + assert x == 18446744073709551615 + assert int(x) == max_u64 + + min_u64 = int() + y = u64(min_u64) + assert y == 0 + assert int(y) == min_u64 + + too_big = int() + 18446744073709551616 + with assertRaises(ValueError): + x = u64(too_big) + + too_small = int() - 1 + with assertRaises(ValueError): + x = u64(too_small) + +def test_u64_from_large_small_literal() -> None: + x = u64(18446744073709551615) + assert x == 18446744073709551615 + x = u64(0) + assert x == 0 + +def test_u64_truncate_from_i64() -> None: + large = i64(2**62 + 157 + int()) + x = u64(large) + assert x == 2**62 + 157 + small = i64(-2**62 - 157 + int()) + x = u64(small) + assert x == 13835058055282163555 + large2 = i64(2**16 + int()) + x = u64(large2) + assert x == 65536 + small2 = i64(-2**16 - 1 - int()) + x = u64(small2) + assert x == 18446744073709486079 + +def test_u64_truncate_from_i32() -> None: + large = i32(2**20 + 2**16 + 5 + int()) + assert u64(large) == 1114117 + small = i32(-2**20 - 2**16 - 1 + int()) + assert u64(small) == 18446744073708437503 + +def from_float(x: float) -> u64: + return u64(x) + +def test_explicit_conversion_from_float() -> None: + assert from_float(0.0) == 0 + assert from_float(1.456) == 1 + assert from_float(234.567) == 234 + assert from_float(float(2**63)) == 2**63 + # Largest float below 2**64 + assert from_float(float(2**64 - 2048)) == 2**64 - 2048 + assert from_float(0) == 0 + assert from_float(-0.999) == 0 + # The error message could be better, but this is acceptable + with assertRaises(ValueError, "int too large or small to convert to u64"): + assert from_float(float(18446744073709551616)) + with assertRaises(ValueError, "int too large or small to convert to u64"): + from_float(float(-1.0)) + +def list_get(a: list[int], i: u64) -> int: + return a[i] + +def list_get_len(a: list[str], i: u64) -> int: + return len(a[i]) + +def list_set(a: list[int], i: u64, x: int) -> None: + a[i] = x + +def tuple_get(a: tuple[int, ...], i: u64) -> int: + return a[i] + +def str_get(s: str, i: u64) -> str: + return s[i] + +def test_index_with_u64() -> None: + a = [1, 2, 3] + assert list_get(a, 0) == 1 + assert list_get(a, 2) == 3 + assert list_get_len(["ab", "c"], 0) == 2 + list_set(a, 1, 5) + assert a == [1, 5, 3] + assert tuple_get((1, 2, 3), 2) == 3 + assert str_get("abc", 1) == "b" + for n in (3, 2**62, 2**63, 2**64 - 1): + with assertRaises(IndexError, "list index out of range"): + list_get(a, n) + with assertRaises(IndexError, "list index out of range"): + list_get_len(["x"], n) + with assertRaises(IndexError, "list assignment index out of range"): + list_set(a, n, 1) + assert a == [1, 5, 3] + with assertRaises(IndexError): + tuple_get((1, 2, 3), 3) + with assertRaises(IndexError): + str_get("abc", 3) + # Index too large for a short int takes the slow conversion path + with assertRaises(OverflowError): + tuple_get((1, 2, 3), 2**63) + with assertRaises(OverflowError): + str_get("abc", 2**64 - 1) + +def test_tuple_u64() -> None: + a: u64 = 1 + b: u64 = 2 + t = (a, b) + a, b = t + assert a == 1 + assert b == 2 + x: Any = t + tt: Tuple[u64, u64] = x + assert tt == (1, 2) + +def test_convert_u64_to_native_int() -> None: + for i in [0, 1, 255, 1000, 32767]: + x: u64 = i + assert u8(x) == (i & 0xff) + assert i16(x) == (i if i < 32768 else i - 18446744073709551616) + assert i32(x) == i + assert i64(x) == i diff --git a/mypyc/test/test_irbuild.py b/mypyc/test/test_irbuild.py index f442e3efb7136..07e0962e5d365 100644 --- a/mypyc/test/test_irbuild.py +++ b/mypyc/test/test_irbuild.py @@ -46,6 +46,7 @@ "irbuild-i32.test", "irbuild-i16.test", "irbuild-u8.test", + "irbuild-u64.test", "irbuild-u32.test", "irbuild-u16.test", "irbuild-vec-i64.test", diff --git a/mypyc/test/test_run.py b/mypyc/test/test_run.py index 63df8582d74fe..e9aca6ba5d7df 100644 --- a/mypyc/test/test_run.py +++ b/mypyc/test/test_run.py @@ -50,6 +50,7 @@ "run-i32.test", "run-i16.test", "run-u8.test", + "run-u64.test", "run-u32.test", "run-u16.test", "run-floats.test", diff --git a/mypyc/test/test_tuplename.py b/mypyc/test/test_tuplename.py index f577c7e2faaca..0fbc3994b011c 100644 --- a/mypyc/test/test_tuplename.py +++ b/mypyc/test/test_tuplename.py @@ -17,6 +17,7 @@ uint8_rprimitive, uint16_rprimitive, uint32_rprimitive, + uint64_rprimitive, ) @@ -29,6 +30,7 @@ def test_names(self) -> None: assert RTuple([int_rprimitive, int_rprimitive]).unique_id == "T2II" assert RTuple([int64_rprimitive, int32_rprimitive]).unique_id == "T284" assert RTuple([int32_rprimitive, uint32_rprimitive]).unique_id == "T24U4" + assert RTuple([int64_rprimitive, uint64_rprimitive]).unique_id == "T28U8" assert RTuple([int16_rprimitive, uint16_rprimitive]).unique_id == "T22U2" assert RTuple([uint8_rprimitive]).unique_id == "T1U1" assert RTuple([list_rprimitive, object_rprimitive, self.inst_a]).unique_id == "T3OOO" diff --git a/mypyc/test/test_typeops.py b/mypyc/test/test_typeops.py index 77e12f5a5adc0..6cd574d01f419 100644 --- a/mypyc/test/test_typeops.py +++ b/mypyc/test/test_typeops.py @@ -18,6 +18,7 @@ uint8_rprimitive, uint16_rprimitive, uint32_rprimitive, + uint64_rprimitive, ) from mypyc.rt_subtype import is_runtime_subtype from mypyc.subtype import is_subtype @@ -26,7 +27,7 @@ int64_rprimitive, int32_rprimitive, int16_rprimitive, - uint32_rprimitive, + uint64_rprimitive, uint32_rprimitive, uint16_rprimitive, uint8_rprimitive, @@ -69,6 +70,14 @@ def test_int16(self) -> None: assert not is_subtype(int16_rprimitive, int64_rprimitive) assert not is_subtype(int16_rprimitive, int32_rprimitive) + def test_uint64(self) -> None: + assert is_subtype(uint64_rprimitive, uint64_rprimitive) + assert is_subtype(uint64_rprimitive, int_rprimitive) + assert not is_subtype(uint64_rprimitive, short_int_rprimitive) + assert not is_subtype(uint64_rprimitive, int64_rprimitive) + assert not is_subtype(uint64_rprimitive, int32_rprimitive) + assert not is_subtype(uint64_rprimitive, uint32_rprimitive) + def test_uint32(self) -> None: assert is_subtype(uint32_rprimitive, uint32_rprimitive) assert is_subtype(uint32_rprimitive, int_rprimitive) diff --git a/test-data/unit/lib-stub/mypy_extensions.pyi b/test-data/unit/lib-stub/mypy_extensions.pyi index 6d0c03bbdd284..878b84651d960 100644 --- a/test-data/unit/lib-stub/mypy_extensions.pyi +++ b/test-data/unit/lib-stub/mypy_extensions.pyi @@ -50,7 +50,7 @@ class FlexibleAlias(Generic[_T, _U]): ... class __SupportsInt(Protocol[T_co]): def __int__(self) -> int: pass -_Int = Union[int, u8, u16, u32, i16, i32, i64] +_Int = Union[int, u8, u16, u32, u64, i16, i32, i64] class u8: def __init__(self, x: Union[_Int, str, bytes, SupportsInt], base: int = 10) -> None: ... @@ -142,6 +142,36 @@ class u32: def __ge__(self, x: u32) -> bool: ... def __gt__(self, x: u32) -> bool: ... +class u64: + def __init__(self, x: Union[_Int, str, bytes, SupportsInt], base: int = 10) -> None: ... + def __add__(self, x: u64) -> u64: ... + def __radd__(self, x: u64) -> u64: ... + def __sub__(self, x: u64) -> u64: ... + def __rsub__(self, x: u64) -> u64: ... + def __mul__(self, x: u64) -> u64: ... + def __rmul__(self, x: u64) -> u64: ... + def __floordiv__(self, x: u64) -> u64: ... + def __rfloordiv__(self, x: u64) -> u64: ... + def __mod__(self, x: u64) -> u64: ... + def __rmod__(self, x: u64) -> u64: ... + def __and__(self, x: u64) -> u64: ... + def __rand__(self, x: u64) -> u64: ... + def __or__(self, x: u64) -> u64: ... + def __ror__(self, x: u64) -> u64: ... + def __xor__(self, x: u64) -> u64: ... + def __rxor__(self, x: u64) -> u64: ... + def __lshift__(self, x: u64) -> u64: ... + def __rlshift__(self, x: u64) -> u64: ... + def __rshift__(self, x: u64) -> u64: ... + def __rrshift__(self, x: u64) -> u64: ... + def __neg__(self) -> u64: ... + def __invert__(self) -> u64: ... + def __pos__(self) -> u64: ... + def __lt__(self, x: u64) -> bool: ... + def __le__(self, x: u64) -> bool: ... + def __ge__(self, x: u64) -> bool: ... + def __gt__(self, x: u64) -> bool: ... + class i16: def __init__(self, x: Union[_Int, str, bytes, SupportsInt], base: int = 10) -> None: ... def __add__(self, x: i16) -> i16: ... From 33ae8b994a9ea39ac978c71c8e592917c597b6c4 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 9 Nov 2026 11:49:06 +0000 Subject: [PATCH 2/2] Improve large literal handling --- mypyc/irbuild/ll_builder.py | 29 ++++++++++--- mypyc/irbuild/specialize.py | 6 ++- mypyc/test-data/irbuild-i64.test | 73 ++++++++++++++++++++++++++++++++ mypyc/test-data/irbuild-u64.test | 42 ++++++------------ mypyc/test-data/run-i64.test | 10 +++++ mypyc/test-data/run-u64.test | 14 ++++++ 6 files changed, 137 insertions(+), 37 deletions(-) diff --git a/mypyc/irbuild/ll_builder.py b/mypyc/irbuild/ll_builder.py index 30c38e3a24a50..08bebbe8aab7c 100644 --- a/mypyc/irbuild/ll_builder.py +++ b/mypyc/irbuild/ll_builder.py @@ -262,6 +262,24 @@ BOOL_BINARY_OPS: Final = {"&", "&=", "|", "|=", "^", "^=", "==", "!=", "<", "<=", ">", ">="} +def int_literal_value(value: Value) -> int | None: + """Return the numeric value if value is an int literal, otherwise None. + + Recognize both short int literals (Integer) and literals that are too + large for a short int (LoadLiteral of a boxed int). + """ + if isinstance(value, Integer) and is_short_int_rprimitive(value.type): + return value.numeric_value() + if ( + isinstance(value, LoadLiteral) + and is_int_rprimitive(value.type) + and isinstance(value.value, int) + and not isinstance(value.value, bool) + ): + return value.value + return None + + class PendingKeepAlive: __slots__ = ("value", "scope", "seq") @@ -498,15 +516,12 @@ def coerce( if (src_type.is_unboxed and target_type.is_unboxed) and not is_runtime_subtype( src_type, target_type ): - if ( - isinstance(src, Integer) - and is_short_int_rprimitive(src_type) - and is_fixed_width_rtype(target_type) - ): - value = src.numeric_value() + if is_fixed_width_rtype(target_type) and (value := int_literal_value(src)) is not None: + # Integer literal (either a short int or a large one that needs a + # boxed int literal). if not check_native_int_range(target_type, value): self.error(f'Value {value} is out of range for "{target_type}"', line) - return Integer(src.value >> 1, target_type) + return Integer(value, target_type) elif is_int_rprimitive(src_type) and is_fixed_width_rtype(target_type): return self.coerce_int_to_fixed_width(src, target_type, line) elif is_fixed_width_rtype(src_type) and is_int_rprimitive(target_type): diff --git a/mypyc/irbuild/specialize.py b/mypyc/irbuild/specialize.py index 918e983140fef..16c0a6d46c12f 100644 --- a/mypyc/irbuild/specialize.py +++ b/mypyc/irbuild/specialize.py @@ -113,6 +113,7 @@ join_formatted_strings, tokenizer_format_call, ) +from mypyc.irbuild.ll_builder import int_literal_value from mypyc.irbuild.vec import ( supports_vec_to_sequence, vec_append, @@ -1198,6 +1199,7 @@ def translate_i64(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value return builder.add(Extend(val, int64_rprimitive, signed=False, line=expr.line)) elif is_int_rprimitive(arg_type) or is_bool_rprimitive(arg_type): val = builder.accept(arg) + val = truncate_literal(val, int64_rprimitive) return builder.coerce(val, int64_rprimitive, expr.line) return None @@ -1379,9 +1381,9 @@ def truncate_literal(value: Value, rtype: RPrimitive) -> Value: For example, truncate 256 into 0 if rtype is u8. """ - if not isinstance(value, Integer): + x = int_literal_value(value) + if x is None: return value # Not a literal, nothing to do - x = value.numeric_value() max_unsigned = (1 << (rtype.size * 8)) - 1 x = x & max_unsigned if rtype.is_signed and x >= (max_unsigned + 1) // 2: diff --git a/mypyc/test-data/irbuild-i64.test b/mypyc/test-data/irbuild-i64.test index b861406b43e78..38c6dd5240ed5 100644 --- a/mypyc/test-data/irbuild-i64.test +++ b/mypyc/test-data/irbuild-i64.test @@ -1653,6 +1653,79 @@ L0: z = -3 return 1 +[case testI64ExplicitConversionFromLargeLiteral_64bit] +from mypy_extensions import i64 + +def f() -> None: + a = i64(9223372036854775807) + b = i64(-9223372036854775808) + c = i64(9223372036854775808) # Truncate + d = i64(18446744073709551621) # Truncate +[out] +def f(): + r0 :: int + a :: i64 + r1 :: int + b :: i64 + r2 :: int + c :: i64 + r3 :: int + d :: i64 +L0: + r0 = object 9223372036854775807 + a = 9223372036854775807 + r1 = object -9223372036854775808 + b = -9223372036854775808 + r2 = object 9223372036854775808 + c = -9223372036854775808 + r3 = object 18446744073709551621 + d = 5 + return 1 + +[case testI64InitializeFromLargeLiteral_64bit] +from mypy_extensions import i64 + +def f() -> None: + a: i64 = 9223372036854775807 + b: i64 = -9223372036854775808 + g(9223372036854775807) + +def g(x: i64) -> None: pass +[out] +def f(): + r0 :: int + a :: i64 + r1 :: int + b :: i64 + r2 :: int + r3 :: None +L0: + r0 = object 9223372036854775807 + a = 9223372036854775807 + r1 = object -9223372036854775808 + b = -9223372036854775808 + r2 = object 9223372036854775807 + r3 = g(9223372036854775807) + return 1 +def g(x): + x :: i64 +L0: + return 1 + +[case testI64DetectOutOfRangeLiterals_64bit] +from mypy_extensions import i64 + +def out_of_range() -> None: + a: i64 = 9223372036854775808 + b: i64 = -9223372036854775809 + g(9223372036854775808) + +def g(x: i64) -> None: pass +[out] +main:4: error: Value 9223372036854775808 is out of range for "i64" +main:5: error: Value -9223372036854775809 is out of range for "i64" +main:6: error: Value 9223372036854775808 is out of range for "i64" + [case testI64ForLoopOverRange] from mypy_extensions import i64 diff --git a/mypyc/test-data/irbuild-u64.test b/mypyc/test-data/irbuild-u64.test index bf47d2aedbc46..765192e9390fd 100644 --- a/mypyc/test-data/irbuild-u64.test +++ b/mypyc/test-data/irbuild-u64.test @@ -77,7 +77,9 @@ def out_of_range() -> None: def f(x: u64) -> None: pass [out] +main:4: error: Value 18446744073709551616 is out of range for "u64" main:5: error: Value -1 is out of range for "u64" +main:6: error: Value 18446744073709551616 is out of range for "u64" [case testU64BoxAndUnbox] from typing import Any @@ -293,44 +295,28 @@ def f() -> None: z = u64(-3) # Truncate zz = u64(4294967298) # Truncate a = u64(18446744073709551615) + b = u64(18446744073709551621) # Truncate + c = u64(-18446744073709551615) # Truncate [out] def f(): x, y, z, zz :: u64 r0 :: int - r1 :: native_int - r2, r3 :: bit - r4, r5 :: u64 - r6 :: ptr - r7 :: c_ptr - r8, a :: u64 + a :: u64 + r1 :: int + b :: u64 + r2 :: int + c :: u64 L0: x = 0 y = 11 z = 18446744073709551613 zz = 4294967298 r0 = object 18446744073709551615 - r1 = r0 & 1 - r2 = r1 == 0 - if r2 goto L1 else goto L3 :: bool -L1: - r3 = r0 >= 0 :: signed - if r3 goto L2 else goto L4 :: bool -L2: - r4 = r0 >> 1 - r5 = r4 - goto L5 -L3: - r6 = r0 ^ 1 - r7 = r6 - r8 = CPyLong_AsUInt64(r7) - r5 = r8 - keep_alive r0 - goto L5 -L4: - CPyUInt64_Overflow() - unreachable -L5: - a = r5 + a = 18446744073709551615 + r1 = object 18446744073709551621 + b = 5 + r2 = object -18446744073709551615 + c = 1 return 1 [case testU64FromShortInt_64bit] diff --git a/mypyc/test-data/run-i64.test b/mypyc/test-data/run-i64.test index b548e4ad0472a..9ffb53e2be193 100644 --- a/mypyc/test-data/run-i64.test +++ b/mypyc/test-data/run-i64.test @@ -312,6 +312,16 @@ def test_i64_from_large_small_literal() -> None: assert x == 2**63 - 1 x = i64(-2**63) assert x == -2**63 + x = i64(9223372036854775807) + assert x == 2**63 - 1 + assert int(x) == 2**63 - 1 + x = i64(-9223372036854775808) + assert x == -2**63 + assert int(x) == -2**63 + y: i64 = 9223372036854775807 + assert y == 2**63 - 1 + y = -9223372036854775808 + assert y == -2**63 def from_float(x: float) -> i64: return i64(x) diff --git a/mypyc/test-data/run-u64.test b/mypyc/test-data/run-u64.test index 209918eee29bf..012b26815c47e 100644 --- a/mypyc/test-data/run-u64.test +++ b/mypyc/test-data/run-u64.test @@ -263,6 +263,20 @@ def test_u64_from_large_small_literal() -> None: assert x == 18446744073709551615 x = u64(0) assert x == 0 + x = u64(9223372036854775808) + assert x == 9223372036854775808 + +def test_u64_large_literal_implicit_coercion() -> None: + x: u64 = 18446744073709551615 + assert x == 18446744073709551615 + assert int(x) == 2**64 - 1 + x = 9223372036854775808 + assert x == 2**63 + assert int(x) == 2**63 + assert u64_identity(18446744073709551615) == 2**64 - 1 + +def u64_identity(x: u64) -> u64: + return x def test_u64_truncate_from_i64() -> None: large = i64(2**62 + 157 + int())