From 3f83f6840a3f44ab6400a8231fb3e26ef82489ae Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 15:41:12 +0500 Subject: [PATCH 1/4] [mypyc] Fix crashes with big int subclass values that override dunders Unboxing an int keeps the original object when the value doesn't fit in a short int, so a long tagged int can refer to an instance of an int subclass. The slow paths of int operations used the generic PyNumber_* and rich comparison APIs, which call any dunder methods the subclass overrides. A non-int result was then read as an int object (crash or garbage), and an exception in an operation that can't fail aborted the process with "fatal: out of memory". Convert operands to exact int objects in the slow paths, using int's own nb_int slot so that no overrides are called. This matches the behavior for small values, which never call the overrides. Also check for errors from PyFloat_AsDouble in CPyTagged_TrueDivide. --- mypyc/lib-rt/int_ops.c | 78 +++++++++++++++++++------------ mypyc/test-data/run-integers.test | 69 +++++++++++++++++++++++++++ 2 files changed, 118 insertions(+), 29 deletions(-) diff --git a/mypyc/lib-rt/int_ops.c b/mypyc/lib-rt/int_ops.c index edf2fc2f1b967..3fe136b849964 100644 --- a/mypyc/lib-rt/int_ops.c +++ b/mypyc/lib-rt/int_ops.c @@ -98,6 +98,25 @@ PyObject *CPyTagged_StealAsObject(CPyTagged x) { return value; } +// Like CPyTagged_AsObject, but always return an exact int object. A long tagged int +// can refer to an instance of an int subclass, since unboxing doesn't copy the object. +// The slow paths below use this so that the generic PyNumber_* and rich comparison +// APIs don't call any dunder methods overridden in the subclass, which could return +// arbitrary objects or raise exceptions that can't be propagated. +static PyObject *CPyTagged_AsExactObject(CPyTagged x) { + PyObject *value = CPyTagged_AsObject(x); + if (unlikely(!PyLong_CheckExact(value))) { + // int.__int__ returns an exact copy without calling any overrides + PyObject *copy = PyLong_Type.tp_as_number->nb_int(value); + Py_DECREF(value); + if (copy == NULL) { + CPyError_OutOfMemory(); + } + value = copy; + } + return value; +} + Py_ssize_t CPyTagged_AsSsize_t(CPyTagged x) { if (likely(CPyTagged_CheckShort(x))) { return CPyTagged_ShortAsSsize_t(x); @@ -129,7 +148,7 @@ void CPyTagged_XDecRef(CPyTagged x) { // Tagged int negation slow path, where the result may be a long integer CPyTagged CPyTagged_Negate_(CPyTagged num) { - PyObject *num_obj = CPyTagged_AsObject(num); + PyObject *num_obj = CPyTagged_AsExactObject(num); PyObject *result = PyNumber_Negative(num_obj); if (result == NULL) { CPyError_OutOfMemory(); @@ -140,7 +159,7 @@ CPyTagged CPyTagged_Negate_(CPyTagged num) { // Tagged int absolute value slow path, where the result may be a long integer CPyTagged CPyTagged_Absolute_(CPyTagged num) { - PyObject *num_obj = CPyTagged_AsObject(num); + PyObject *num_obj = CPyTagged_AsExactObject(num); PyObject *result = PyNumber_Absolute(num_obj); if (result == NULL) { CPyError_OutOfMemory(); @@ -151,8 +170,8 @@ CPyTagged CPyTagged_Absolute_(CPyTagged num) { // Tagged int addition slow path, where the result may be a long integer CPyTagged CPyTagged_Add_(CPyTagged left, CPyTagged right) { - PyObject *left_obj = CPyTagged_AsObject(left); - PyObject *right_obj = CPyTagged_AsObject(right); + PyObject *left_obj = CPyTagged_AsExactObject(left); + PyObject *right_obj = CPyTagged_AsExactObject(right); PyObject *result = PyNumber_Add(left_obj, right_obj); if (result == NULL) { CPyError_OutOfMemory(); @@ -164,8 +183,8 @@ CPyTagged CPyTagged_Add_(CPyTagged left, CPyTagged right) { // Tagged int subtraction slow path, where the result may be a long integer CPyTagged CPyTagged_Subtract_(CPyTagged left, CPyTagged right) { - PyObject *left_obj = CPyTagged_AsObject(left); - PyObject *right_obj = CPyTagged_AsObject(right); + PyObject *left_obj = CPyTagged_AsExactObject(left); + PyObject *right_obj = CPyTagged_AsExactObject(right); PyObject *result = PyNumber_Subtract(left_obj, right_obj); if (result == NULL) { CPyError_OutOfMemory(); @@ -177,8 +196,8 @@ CPyTagged CPyTagged_Subtract_(CPyTagged left, CPyTagged right) { // Tagged int multiplication slow path, where the result may be a long integer CPyTagged CPyTagged_Multiply_(CPyTagged left, CPyTagged right) { - PyObject *left_obj = CPyTagged_AsObject(left); - PyObject *right_obj = CPyTagged_AsObject(right); + PyObject *left_obj = CPyTagged_AsExactObject(left); + PyObject *right_obj = CPyTagged_AsExactObject(right); PyObject *result = PyNumber_Multiply(left_obj, right_obj); if (result == NULL) { CPyError_OutOfMemory(); @@ -190,8 +209,8 @@ CPyTagged CPyTagged_Multiply_(CPyTagged left, CPyTagged right) { // Tagged int // slow path, where the result may be a long integer (or raise) CPyTagged CPyTagged_FloorDivide_(CPyTagged left, CPyTagged right) { - PyObject *left_obj = CPyTagged_AsObject(left); - PyObject *right_obj = CPyTagged_AsObject(right); + PyObject *left_obj = CPyTagged_AsExactObject(left); + PyObject *right_obj = CPyTagged_AsExactObject(right); PyObject *result = PyNumber_FloorDivide(left_obj, right_obj); Py_DECREF(left_obj); Py_DECREF(right_obj); @@ -205,8 +224,8 @@ CPyTagged CPyTagged_FloorDivide_(CPyTagged left, CPyTagged right) { // Tagged int % slow path, where the result may be a long integer (or raise) CPyTagged CPyTagged_Remainder_(CPyTagged left, CPyTagged right) { - PyObject *left_obj = CPyTagged_AsObject(left); - PyObject *right_obj = CPyTagged_AsObject(right); + PyObject *left_obj = CPyTagged_AsExactObject(left); + PyObject *right_obj = CPyTagged_AsExactObject(right); PyObject *result = PyNumber_Remainder(left_obj, right_obj); Py_DECREF(left_obj); Py_DECREF(right_obj); @@ -222,8 +241,8 @@ bool CPyTagged_IsEq_(CPyTagged left, CPyTagged right) { if (CPyTagged_CheckShort(right)) { return false; } else { - PyObject *left_obj = CPyTagged_AsObject(left); - PyObject *right_obj = CPyTagged_AsObject(right); + PyObject *left_obj = CPyTagged_AsExactObject(left); + PyObject *right_obj = CPyTagged_AsExactObject(right); int result = PyObject_RichCompareBool(left_obj, right_obj, Py_EQ); Py_DECREF(left_obj); Py_DECREF(right_obj); @@ -235,8 +254,8 @@ bool CPyTagged_IsEq_(CPyTagged left, CPyTagged right) { } bool CPyTagged_IsLt_(CPyTagged left, CPyTagged right) { - PyObject *left_obj = CPyTagged_AsObject(left); - PyObject *right_obj = CPyTagged_AsObject(right); + PyObject *left_obj = CPyTagged_AsExactObject(left); + PyObject *right_obj = CPyTagged_AsExactObject(right); int result = PyObject_RichCompareBool(left_obj, right_obj, Py_LT); Py_DECREF(left_obj); Py_DECREF(right_obj); @@ -275,8 +294,8 @@ PyObject *CPyBool_Str(bool b) { // Bitwise op '&', '|' or '^' using the generic (slow) API static CPyTagged GenericBitwiseOp(CPyTagged a, CPyTagged b, char op) { - PyObject *aobj = CPyTagged_AsObject(a); - PyObject *bobj = CPyTagged_AsObject(b); + PyObject *aobj = CPyTagged_AsExactObject(a); + PyObject *bobj = CPyTagged_AsExactObject(b); PyObject *r; if (op == '&') { r = PyNumber_And(aobj, bobj); @@ -379,7 +398,7 @@ CPyTagged CPyTagged_BitwiseLongOp_(CPyTagged a, CPyTagged b, char op) { // Bitwise '~' slow path CPyTagged CPyTagged_Invert_(CPyTagged num) { - PyObject *obj = CPyTagged_AsObject(num); + PyObject *obj = CPyTagged_AsExactObject(num); PyObject *result = PyNumber_Invert(obj); if (unlikely(result == NULL)) { CPyError_OutOfMemory(); @@ -391,8 +410,8 @@ CPyTagged CPyTagged_Invert_(CPyTagged num) { // Bitwise '>>' slow path CPyTagged CPyTagged_Rshift_(CPyTagged left, CPyTagged right) { // Long integer or negative shift -- use generic op - PyObject *lobj = CPyTagged_AsObject(left); - PyObject *robj = CPyTagged_AsObject(right); + PyObject *lobj = CPyTagged_AsExactObject(left); + PyObject *robj = CPyTagged_AsExactObject(right); PyObject *result = PyNumber_Rshift(lobj, robj); Py_DECREF(lobj); Py_DECREF(robj); @@ -406,8 +425,8 @@ CPyTagged CPyTagged_Rshift_(CPyTagged left, CPyTagged right) { // Bitwise '<<' slow path CPyTagged CPyTagged_Lshift_(CPyTagged left, CPyTagged right) { // Long integer or out of range shift -- use generic op - PyObject *lobj = CPyTagged_AsObject(left); - PyObject *robj = CPyTagged_AsObject(right); + PyObject *lobj = CPyTagged_AsExactObject(left); + PyObject *robj = CPyTagged_AsExactObject(right); PyObject *result = PyNumber_Lshift(lobj, robj); Py_DECREF(lobj); Py_DECREF(robj); @@ -656,18 +675,19 @@ double CPyTagged_TrueDivide(CPyTagged x, CPyTagged y) { if (likely(!CPyTagged_CheckLong(x) && !CPyTagged_CheckLong(y))) { return (double)((Py_ssize_t)x >> 1) / (double)((Py_ssize_t)y >> 1); } else { - PyObject *xo = CPyTagged_AsObject(x); - PyObject *yo = CPyTagged_AsObject(y); + PyObject *xo = CPyTagged_AsExactObject(x); + PyObject *yo = CPyTagged_AsExactObject(y); PyObject *result = PyNumber_TrueDivide(xo, yo); + Py_DECREF(xo); + Py_DECREF(yo); if (result == NULL) { - Py_DECREF(xo); - Py_DECREF(yo); return CPY_FLOAT_ERROR; } double value = PyFloat_AsDouble(result); - Py_DECREF(xo); - Py_DECREF(yo); Py_DECREF(result); + if (unlikely(value == -1.0) && PyErr_Occurred()) { + return CPY_FLOAT_ERROR; + } return value; } return 1.0; diff --git a/mypyc/test-data/run-integers.test b/mypyc/test-data/run-integers.test index 524bd283d24f7..e2a0cfe13e22f 100644 --- a/mypyc/test-data/run-integers.test +++ b/mypyc/test-data/run-integers.test @@ -646,3 +646,72 @@ def test_bit_length() -> None: i -= 1 assert bit_length(i) == bit_length_python(i) assert bit_length(-(i)) == bit_length_python(-(i)) + +[case testIntSubclassOverridesNotCalled] +# Unboxing keeps a large int subclass instance as is, but int operations +# shouldn't call the overridden dunders (like they don't for small values). +from typing import Any +from intsub import WrongType, Raising + +def int_ops(x: int, y: int) -> list[object]: + return [ + x + y, x - y, x * y, x // y, x % y, x / y, -x, abs(x), ~x, x & y, x | y, x ^ y, + x << 3, x >> 3, x == y, x != y, x < y, x <= y, x > y, x >= y, + ] + +def test_int_subclass_overrides_not_called() -> None: + vals = [5, -3, 2**70, -(2**70) - 1, 2**64 + 2**63] + f: Any = int_ops + for cls in WrongType, Raising: + for n in vals: + for m in vals: + expected = int_ops(n, m) + assert int_ops(cls(n), m) == expected + assert int_ops(n, cls(m)) == expected + assert int_ops(cls(n), cls(m)) == expected + # Through the wrapper function (unboxing borrows the argument) + assert f(cls(n), m) == expected + assert f(n, cls(m)) == expected + assert f(cls(n), cls(m)) == expected + +[file intsub.py] +class WrongType(int): + def __add__(self, o): return "x" + def __radd__(self, o): return "x" + def __sub__(self, o): return 1.5 + def __rsub__(self, o): return 1.5 + def __mul__(self, o): return [] + def __rmul__(self, o): return [] + def __floordiv__(self, o): return "x" + def __rfloordiv__(self, o): return "x" + def __mod__(self, o): return "x" + def __rmod__(self, o): return "x" + def __truediv__(self, o): return "x" + def __rtruediv__(self, o): return "x" + def __neg__(self): return [1, 2] + def __abs__(self): return "x" + def __invert__(self): return "x" + def __and__(self, o): return "x" + def __rand__(self, o): return "x" + def __or__(self, o): return "x" + def __ror__(self, o): return "x" + def __xor__(self, o): return "x" + def __rxor__(self, o): return "x" + def __lshift__(self, o): return "x" + def __rshift__(self, o): return "x" + def __eq__(self, o): return "x" + def __ne__(self, o): return "x" + def __lt__(self, o): return "x" + def __le__(self, o): return "x" + def __gt__(self, o): return "x" + def __ge__(self, o): return "x" + +def _fail(*args): + raise RuntimeError("should not be called") + +class Raising(int): + __add__ = __radd__ = __sub__ = __rsub__ = __mul__ = __rmul__ = _fail + __floordiv__ = __rfloordiv__ = __mod__ = __rmod__ = __truediv__ = __rtruediv__ = _fail + __neg__ = __abs__ = __invert__ = _fail + __and__ = __rand__ = __or__ = __ror__ = __xor__ = __rxor__ = __lshift__ = __rshift__ = _fail + __eq__ = __ne__ = __lt__ = __le__ = __gt__ = __ge__ = _fail From 674082537a53092438dc1e416ff0d83250d49f22 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 15:42:28 +0500 Subject: [PATCH 2/4] [mypyc] Fix rounding of int / int with operands larger than 2**53 The fast path of int true division converted short int operands to doubles before dividing, which rounds twice if an operand can't be represented exactly as a double. For example, (2**53 + 1) / 3 returned 3002399751580330.5 instead of 3002399751580331.0. Only use the fast path if the absolute values of both operands are at most 2**53 (like CPython), and otherwise fall back to the int object implementation, which is correctly rounded. --- mypyc/lib-rt/CPy.h | 10 ++++++++++ mypyc/lib-rt/int_ops.c | 4 +++- mypyc/test-data/run-integers.test | 9 +++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index 65cc8f038e508..5be64d0a3aac4 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -298,6 +298,16 @@ static inline CPyTagged CPyTagged_BorrowFromObject(PyObject *object) { } } +// Can x be converted to a double exactly? This is true for short ints with an +// absolute value of at most 2**53 (always true on 32-bit platforms). +static inline bool CPyTagged_FitsInDouble(CPyTagged x) { + if (CPyTagged_CheckLong(x)) { + return false; + } + int64_t value = CPyTagged_ShortAsSsize_t(x); + return value >= -((int64_t)1 << 53) && value <= ((int64_t)1 << 53); +} + static inline bool CPyTagged_TooBig(Py_ssize_t value) { // Micro-optimized for the common case where it fits. return (size_t)value > CPY_TAGGED_MAX diff --git a/mypyc/lib-rt/int_ops.c b/mypyc/lib-rt/int_ops.c index 3fe136b849964..867f068d17094 100644 --- a/mypyc/lib-rt/int_ops.c +++ b/mypyc/lib-rt/int_ops.c @@ -672,7 +672,9 @@ double CPyTagged_TrueDivide(CPyTagged x, CPyTagged y) { PyErr_SetString(PyExc_ZeroDivisionError, "division by zero"); return CPY_FLOAT_ERROR; } - if (likely(!CPyTagged_CheckLong(x) && !CPyTagged_CheckLong(y))) { + // Dividing as doubles is only correctly rounded if both operands can be + // represented exactly as doubles (CPython uses the same fast path) + if (likely(CPyTagged_FitsInDouble(x) && CPyTagged_FitsInDouble(y))) { return (double)((Py_ssize_t)x >> 1) / (double)((Py_ssize_t)y >> 1); } else { PyObject *xo = CPyTagged_AsExactObject(x); diff --git a/mypyc/test-data/run-integers.test b/mypyc/test-data/run-integers.test index e2a0cfe13e22f..fdfe68d45a5f0 100644 --- a/mypyc/test-data/run-integers.test +++ b/mypyc/test-data/run-integers.test @@ -499,6 +499,15 @@ def test_true_divide() -> None: assert large1 / -2 == getattr(large1, "__truediv__")(-2) assert 17 / large2 == getattr(17, "__truediv__")(large2) + # Short ints that can't be represented exactly as floats + assert (2**53 + 1 + int()) / 3 == 3002399751580331.0 + vals = [1, 3, 7, 10**9 + 7, 2**53 - 1, 2**53, 2**53 + 1, 2**53 + 3, 2**60 + 1, 2**62 - 1] + for x in vals: + for y in vals: + for xs in x, -x: + for ys in y, -y: + assert xs / ys == getattr(xs, "__truediv__")(ys), (xs, ys) + huge = 10**1000 + int() with assertRaises(OverflowError, "integer division result too large for a float"): huge / 2 From d611f8acb5f81dba57663f25b01c7c0f6ee6eba8 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 15:50:29 +0500 Subject: [PATCH 3/4] [mypyc] Fix float vs int comparisons with ints not exact as floats Comparisons between float and int converted the int to a double first, which loses precision for ints with an absolute value larger than 2**53 and raises OverflowError for very large ints. For example, 2.0**53 == 2**53 + 1 was True, and 1.0 < 2**1100 raised OverflowError. CPython compares the values exactly. Use a new primitive CPyFloat_CompareTagged for these comparisons. It compares as doubles if the int is a short int that fits in 53 bits, and otherwise falls back to a rich comparison of the boxed values. Int literals are still converted to float at compile time if the conversion is exact. Arithmetic operations are unchanged. --- mypyc/irbuild/ll_builder.py | 39 ++++++++++++++++- mypyc/lib-rt/CPy.h | 1 + mypyc/lib-rt/float_ops.c | 29 +++++++++++++ mypyc/primitives/float_ops.py | 10 +++++ mypyc/test-data/irbuild-float.test | 68 ++++++++++++++++++++---------- mypyc/test-data/run-floats.test | 27 ++++++++++++ 6 files changed, 151 insertions(+), 23 deletions(-) diff --git a/mypyc/irbuild/ll_builder.py b/mypyc/irbuild/ll_builder.py index 01ee6dc6442d9..f3a7519919f53 100644 --- a/mypyc/irbuild/ll_builder.py +++ b/mypyc/irbuild/ll_builder.py @@ -145,7 +145,7 @@ dict_update_in_display_op, ) from mypyc.primitives.exc_ops import err_occurred_op, keep_propagating_op -from mypyc.primitives.float_ops import copysign_op, int_to_float_op +from mypyc.primitives.float_ops import copysign_op, float_int_compare_op, int_to_float_op from mypyc.primitives.generic_ops import ( call_fastcall_wrapper_op, call_legacy_wrapper_op, @@ -257,6 +257,19 @@ # Binary operations on bools that are specialized and don't just promote operands to int BOOL_BINARY_OPS: Final = {"&", "&=", "|", "|=", "^", "^=", "==", "!=", "<", "<=", ">", ">="} +# Py_LT etc. values of comparison operators +py_comparison_op_ids: Final = {"<": 0, "<=": 1, "==": 2, "!=": 3, ">": 4, ">=": 5} + +# Comparison operators with swapped operands (x < y is the same as y > x) +swapped_comparison_ops: Final = { + "<": ">", + "<=": ">=", + "==": "==", + "!=": "!=", + ">": "<", + ">=": "<=", +} + class PendingKeepAlive: __slots__ = ("value", "scope", "seq") @@ -1845,6 +1858,13 @@ def binary_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value: return self.comparison_op(lreg, rreg, op_id, line) if is_float_rprimitive(ltype) or is_float_rprimitive(rtype): + if op in float_comparison_op_to_id: + # Like in CPython, comparisons are exact, so an int can only be converted + # to float if this doesn't lose precision (which may require a runtime check) + if self.needs_exact_float_compare(lreg): + return self.compare_float_and_int(rreg, lreg, swapped_comparison_ops[op], line) + if self.needs_exact_float_compare(rreg): + return self.compare_float_and_int(lreg, rreg, op, line) if isinstance(lreg, Integer): lreg = Float(float(lreg.numeric_value())) elif isinstance(rreg, Integer): @@ -2728,6 +2748,23 @@ def float_mod(self, lhs: Value, rhs: Value, line: int) -> Value: def compare_floats(self, lhs: Value, rhs: Value, op: int, line: int) -> Value: return self.add(FloatComparisonOp(lhs, rhs, op, line)) + def needs_exact_float_compare(self, value: Value) -> bool: + """Is value an int that may not be exactly representable as a float?""" + if isinstance(value, Integer): + n = value.numeric_value() + return float(n) != n + return is_int_rprimitive(value.type) + + def compare_float_and_int(self, lhs: Value, rhs: Value, op: str, line: int) -> Value: + """Compare float and int exactly, like CPython.""" + if isinstance(rhs, Integer): + rhs = self.load_int(rhs.numeric_value()) + return self.primitive_op( + float_int_compare_op, + [lhs, rhs, Integer(py_comparison_op_ids[op], c_int_rprimitive)], + line, + ) + def int_add(self, lhs: Value, rhs: Value | int) -> Value: """Helper to add two native integers. diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index 5be64d0a3aac4..ce9942d5749dc 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -746,6 +746,7 @@ double CPyFloat_Log(double x); CPyTagged CPyFloat_Floor(double x); CPyTagged CPyFloat_Ceil(double x); double CPyFloat_FromTagged(CPyTagged x); +char CPyFloat_CompareTagged(double x, CPyTagged y, int op); bool CPyFloat_IsInf(double x); bool CPyFloat_IsNaN(double x); double CPyComplex_GetPartSlow(PyObject *o, PyObject *name); diff --git a/mypyc/lib-rt/float_ops.c b/mypyc/lib-rt/float_ops.c index 4210b84f33a98..543da568eac5a 100644 --- a/mypyc/lib-rt/float_ops.c +++ b/mypyc/lib-rt/float_ops.c @@ -54,6 +54,35 @@ double CPyFloat_FromTagged(CPyTagged x) { return result; } +// Compare a float and an int (op is Py_LT etc.). Like in CPython, the comparison is +// exact, so the int can only be converted to a double if this doesn't lose precision. +// Return 2 on error. +char CPyFloat_CompareTagged(double x, CPyTagged y, int op) { + if (likely(CPyTagged_FitsInDouble(y))) { + double yf = (double)CPyTagged_ShortAsSsize_t(y); + switch (op) { + case Py_LT: return x < yf; + case Py_LE: return x <= yf; + case Py_EQ: return x == yf; + case Py_NE: return x != yf; + case Py_GT: return x > yf; + default: return x >= yf; + } + } + PyObject *xo = PyFloat_FromDouble(x); + if (xo == NULL) { + return 2; + } + PyObject *yo = CPyTagged_AsObject(y); + int result = PyObject_RichCompareBool(xo, yo, op); + Py_DECREF(xo); + Py_DECREF(yo); + if (result < 0) { + return 2; + } + return result; +} + double CPyFloat_Sin(double x) { double v = sin(x); if (unlikely(isnan(v)) && !isnan(x)) { diff --git a/mypyc/primitives/float_ops.py b/mypyc/primitives/float_ops.py index 26d7127fe28fe..8c6acc0f872cf 100644 --- a/mypyc/primitives/float_ops.py +++ b/mypyc/primitives/float_ops.py @@ -6,6 +6,7 @@ from mypyc.ir.rtypes import ( bit_rprimitive, bool_rprimitive, + c_int_rprimitive, float_rprimitive, int_rprimitive, object_rprimitive, @@ -33,6 +34,15 @@ error_kind=ERR_MAGIC_OVERLAPPING, ) +# Exact comparison of float and int (the last argument is Py_LT etc.) +float_int_compare_op = custom_primitive_op( + name="float_int_compare", + arg_types=[float_rprimitive, int_rprimitive, c_int_rprimitive], + return_type=bool_rprimitive, + c_function_name="CPyFloat_CompareTagged", + error_kind=ERR_MAGIC, +) + # float(str) function_op( name="builtins.float", diff --git a/mypyc/test-data/irbuild-float.test b/mypyc/test-data/irbuild-float.test index eda91504a2c6b..63589335f10f6 100644 --- a/mypyc/test-data/irbuild-float.test +++ b/mypyc/test-data/irbuild-float.test @@ -264,35 +264,59 @@ def f(x: float, y: int) -> None: def f(x, y): x :: float y :: int - r0 :: float - r1 :: bit - r2, r3, z, r4, r5, r6, r7, r8 :: float - r9 :: bit - r10 :: float + r0 :: bool + r1, r2, z, r3, r4, r5, r6 :: float + r7 :: bool + r8 :: float L0: - r0 = CPyFloat_FromTagged(y) - r1 = x < r0 - if r1 goto L1 else goto L2 :: bool + r0 = CPyFloat_CompareTagged(x, y, 0) + if r0 goto L1 else goto L2 :: bool L1: - r2 = CPyFloat_FromTagged(y) - r3 = x + r2 - z = r3 - r4 = CPyFloat_FromTagged(y) - r5 = x - r4 - x = r5 - r6 = CPyFloat_FromTagged(y) - r7 = r6 + z - z = r7 + r1 = CPyFloat_FromTagged(y) + r2 = x + r1 + z = r2 + r3 = CPyFloat_FromTagged(y) + r4 = x - r3 + x = r4 + r5 = CPyFloat_FromTagged(y) + r6 = r5 + z + z = r6 L2: - r8 = CPyFloat_FromTagged(y) - r9 = r8 == x - if r9 goto L3 else goto L4 :: bool + r7 = CPyFloat_CompareTagged(x, y, 2) + if r7 goto L3 else goto L4 :: bool L3: - r10 = x - 1.0 - x = r10 + r8 = x - 1.0 + x = r8 L4: return 1 +[case testFloatIntComparisons] +def f(x: float, n: int) -> None: + b = x >= n + b = n < x + b = x == 9007199254740992 + b = x == 9007199254740993 + b = 9007199254740993 <= x +[out] +def f(x, n): + x :: float + n :: int + r0, b, r1 :: bool + r2 :: bit + r3, r4 :: bool +L0: + r0 = CPyFloat_CompareTagged(x, n, 5) + b = r0 + r1 = CPyFloat_CompareTagged(x, n, 4) + b = r1 + r2 = x == 9007199254740992.0 + b = r2 + r3 = CPyFloat_CompareTagged(x, 18014398509481986, 2) + b = r3 + r4 = CPyFloat_CompareTagged(x, 18014398509481986, 5) + b = r4 + return 1 + [case testFloatDivideSimple] def f(x: float, y: float) -> float: z = x / y diff --git a/mypyc/test-data/run-floats.test b/mypyc/test-data/run-floats.test index 11e23770a0f90..7306e12e8d612 100644 --- a/mypyc/test-data/run-floats.test +++ b/mypyc/test-data/run-floats.test @@ -102,6 +102,33 @@ def test_mixed_comparisons() -> None: assert not (zf + 0.9) > (zn + 1) assert (zn + 1) < (zf + 1.1) +def test_mixed_comparisons_are_exact() -> None: + ints = [0, 1, -1, 2**53 - 1, 2**53, 2**53 + 1, -(2**53) - 1, 2**62 - 1, -(2**62), + 2**63 + 1, 2**1100, -(2**1100)] + floats = [0.0, -0.0, 1.0, -1.5, 2.0**53, 2.0**53 + 2, -(2.0**53), 2.0**63, 1e300, -1e300, + math.inf, -math.inf, math.nan] + for n in ints: + for x in floats: + assert (x == n) == getattr(x, "__eq__")(n), (x, n) + assert (x != n) == getattr(x, "__ne__")(n), (x, n) + assert (x < n) == getattr(x, "__lt__")(n), (x, n) + assert (x <= n) == getattr(x, "__le__")(n), (x, n) + assert (x > n) == getattr(x, "__gt__")(n), (x, n) + assert (x >= n) == getattr(x, "__ge__")(n), (x, n) + assert (n == x) == getattr(x, "__eq__")(n), (x, n) + assert (n != x) == getattr(x, "__ne__")(n), (x, n) + assert (n < x) == getattr(x, "__gt__")(n), (x, n) + assert (n <= x) == getattr(x, "__ge__")(n), (x, n) + assert (n > x) == getattr(x, "__lt__")(n), (x, n) + assert (n >= x) == getattr(x, "__le__")(n), (x, n) + x = 2.0**53 + float(0.0) + assert x != 9007199254740993 + assert not (x == 9007199254740993) + assert x < 9007199254740993 + assert 9007199254740993 > x + assert x == 9007199254740992 + assert x <= 9007199254740992 + def test_boxing_and_unboxing() -> None: x = 1.5 boxed: Any = x From a60e9358dec417bc37887cea4e52225c123ab6ff Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 18:29:41 +0500 Subject: [PATCH 4/4] Only run float/int comparison IR test on 64-bit platforms Int literals such as 2**53 don't fit in a short int on 32-bit platforms, so the generated IR is different. --- mypyc/test-data/irbuild-float.test | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mypyc/test-data/irbuild-float.test b/mypyc/test-data/irbuild-float.test index 63589335f10f6..4c26e12ef4d31 100644 --- a/mypyc/test-data/irbuild-float.test +++ b/mypyc/test-data/irbuild-float.test @@ -290,7 +290,7 @@ L3: L4: return 1 -[case testFloatIntComparisons] +[case testFloatIntComparisons_64bit] def f(x: float, n: int) -> None: b = x >= n b = n < x