Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions mypyc/doc/float_operations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ Functions
* ``u16(f)`` (convert to 16-bit unsigned integer)
* ``u8(f)`` (convert to 8-bit unsigned integer)
* ``abs(f)``
* ``round(f)`` (with a single argument)
* ``math.sin(f)``
* ``math.cos(f)``
* ``math.tan(f)``
Expand Down
1 change: 1 addition & 0 deletions mypyc/doc/int_operations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,7 @@ Functions
---------

* ``abs(n)``
* ``round(n)`` (``int`` only, with a single argument)

Attributes
----------
Expand Down
29 changes: 29 additions & 0 deletions mypyc/irbuild/specialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,35 @@ def translate_abs(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value
return None


@specialize_function("builtins.round")
def translate_round(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
if len(expr.args) == 1 and expr.arg_kinds == [ARG_POS]:
arg_type = builder.node_type(expr.args[0])
if is_int_rprimitive(arg_type):
arg = builder.accept(expr.args[0])
# A long int can be an instance of an int subclass that overrides __round__.
arg_class = builder.primitive_op(type_of_int_op, [arg], expr.line)
int_class = builder.load_builtin("builtins.int", expr.line)
assert int_class is not None
is_exact_int = builder.translate_is_op(arg_class, int_class, "is", expr.line)
exact_block, subclass_block, next_block = BasicBlock(), BasicBlock(), BasicBlock()
result = Register(int_rprimitive)
builder.add_bool_branch(is_exact_int, exact_block, subclass_block)

builder.activate_block(exact_block)
builder.assign(result, arg, expr.line)
builder.goto(next_block)

builder.activate_block(subclass_block)
rounded = builder.call_refexpr_with_args(expr, callee, [arg])
builder.assign(result, builder.coerce(rounded, int_rprimitive, expr.line), expr.line)
builder.goto(next_block)

builder.activate_block(next_block)
return result
return None


@specialize_function("builtins.len")
def translate_len(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
if len(expr.args) == 1 and expr.arg_kinds == [ARG_POS]:
Expand Down
1 change: 1 addition & 0 deletions mypyc/lib-rt/CPy.h
Original file line number Diff line number Diff line change
Expand Up @@ -812,6 +812,7 @@ double CPyFloat_Exp(double x);
double CPyFloat_Log(double x);
CPyTagged CPyFloat_Floor(double x);
CPyTagged CPyFloat_Ceil(double x);
CPyTagged CPyFloat_Round(double x);
double CPyFloat_FromTagged(CPyTagged x);
bool CPyFloat_IsInf(double x);
bool CPyFloat_IsNaN(double x);
Expand Down
10 changes: 10 additions & 0 deletions mypyc/lib-rt/float_ops.c
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,16 @@ CPyTagged CPyFloat_Ceil(double x) {
return CPyTagged_FromFloat(v);
}

// Adapted from CPython 3.14, Objects/floatobject.c
CPyTagged CPyFloat_Round(double x) {
double rounded = round(x);
if (fabs(x - rounded) == 0.5) {
// Halfway case: round to even
rounded = 2.0 * round(x / 2.0);
}
return CPyTagged_FromFloat(rounded);
}

bool CPyFloat_IsInf(double x) {
return isinf(x) != 0;
}
Expand Down
9 changes: 9 additions & 0 deletions mypyc/primitives/float_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,15 @@
error_kind=ERR_NEVER,
)

# round(float)
function_op(
name="builtins.round",
arg_types=[float_rprimitive],
return_type=int_rprimitive,
c_function_name="CPyFloat_Round",
error_kind=ERR_MAGIC,
)

# math.sin(float)
function_op(
name="math.sin",
Expand Down
6 changes: 6 additions & 0 deletions mypyc/test-data/fixtures/ir.py
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,12 @@ def zip(x: Iterable[_T], y: Iterable[_S], z: Iterable[_V]) -> Iterator[Tuple[_T,
def eval(e: str) -> Any: ...
def abs(x: __SupportsAbs[_T]) -> _T: ...
@overload
def round(number: int, ndigits: int | None = None) -> int: ...
@overload
def round(number: float, ndigits: None = None) -> int: ...
@overload
def round(number: float, ndigits: int) -> float: ...
@overload
def divmod(x: __SupportsDivMod[T_contra, T_co], y: T_contra) -> T_co: ...
@overload
def divmod(x: T_contra, y: __SupportsRDivMod[T_contra, T_co]) -> T_co: ...
Expand Down
118 changes: 118 additions & 0 deletions mypyc/test-data/irbuild-float.test
Original file line number Diff line number Diff line change
Expand Up @@ -623,3 +623,121 @@ L0:
r3 = cast(union[int, float], r2)
r4 = (r1, r3)
return r4

[case testFloatRound]
def f(x: float) -> int:
return round(x)
def g(n: int) -> int:
return round(n)
def h(x: float) -> float:
return round(x, 2)
[out]
def f(x):
x :: float
r0 :: int
L0:
r0 = CPyFloat_Round(x)
return r0
def g(n):
n :: int
r0, r1 :: object
r2 :: bit
r3 :: int
r4 :: object
r5 :: str
r6, r7 :: object
r8 :: object[1]
r9 :: object_ptr
r10 :: object
r11 :: int
L0:
r0 = CPyTagged_Type(n)
r1 = load_address PyLong_Type
r2 = r0 == r1
if r2 goto L1 else goto L2 :: bool
L1:
r3 = n
goto L3
L2:
r4 = builtins :: module
r5 = 'round'
r6 = CPyObject_GetAttr(r4, r5)
r7 = box(int, n)
r8 = [r7]
r9 = load_address r8
r10 = PyObject_Vectorcall(r6, r9, 1, 0)
keep_alive r7
r11 = unbox(int, r10)
r3 = r11
L3:
return r3
def h(x):
x :: float
r0 :: object
r1 :: str
r2, r3, r4 :: object
r5 :: object[2]
r6 :: object_ptr
r7 :: object
r8 :: float
L0:
r0 = builtins :: module
r1 = 'round'
r2 = CPyObject_GetAttr(r0, r1)
r3 = box(float, x)
r4 = object 2
r5 = [r3, r4]
r6 = load_address r5
r7 = PyObject_Vectorcall(r2, r6, 2, 0)
keep_alive r3, r4
r8 = unbox(float, r7)
return r8

[case testIntRoundDigits]
def digits(n: int, ndigits: int) -> int:
return round(n, ndigits)
def optional_digits(n: int, ndigits: int | None) -> int:
return round(n, ndigits)
[out]
def digits(n, ndigits):
n, ndigits :: int
r0 :: object
r1 :: str
r2, r3, r4 :: object
r5 :: object[2]
r6 :: object_ptr
r7 :: object
r8 :: int
L0:
r0 = builtins :: module
r1 = 'round'
r2 = CPyObject_GetAttr(r0, r1)
r3 = box(int, n)
r4 = box(int, ndigits)
r5 = [r3, r4]
r6 = load_address r5
r7 = PyObject_Vectorcall(r2, r6, 2, 0)
keep_alive r3, r4
r8 = unbox(int, r7)
return r8
def optional_digits(n, ndigits):
n :: int
ndigits :: union[int, None]
r0 :: object
r1 :: str
r2, r3 :: object
r4 :: object[2]
r5 :: object_ptr
r6 :: object
r7 :: int
L0:
r0 = builtins :: module
r1 = 'round'
r2 = CPyObject_GetAttr(r0, r1)
r3 = box(int, n)
r4 = [r3, ndigits]
r5 = load_address r4
r6 = PyObject_Vectorcall(r2, r5, 2, 0)
keep_alive r3, ndigits
r7 = unbox(int, r6)
return r7
115 changes: 115 additions & 0 deletions mypyc/test-data/run-floats.test
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,80 @@ def test_explicit_conversion_from_int() -> None:
for x in a:
assert repr(float(x)) == repr(float_any(x))

def round_float(x: float) -> int:
return round(x)

def round_int(n: int) -> int:
return round(n)

def test_round_float() -> None:
# Use a dynamic reference to avoid specializing round().
round_any: Any = round

# Halfway cases round to even
assert round_float(0.5) == 0
assert round_float(1.5) == 2
assert round_float(2.5) == 2
assert round_float(3.5) == 4
assert round_float(-0.5) == 0
assert round_float(-1.5) == -2
assert round_float(-2.5) == -2
assert round_float(-3.5) == -4

assert round_float(0.49999999999999994) == 0
assert round_float(0.5000000000000001) == 1
assert round_float(-0.49999999999999994) == 0
assert round_float(-0.5000000000000001) == -1

assert round_float(-0.0) == 0
assert round_float(1.4) == 1
assert round_float(-1.6) == -2

assert round_float(2.0**51 + 0.5) == 2**51
assert round_float(2.0**51 + 1.5) == 2**51 + 2
assert round_float(-2.0**51 - 0.5) == -2**51
assert round_float(-2.0**51 - 1.5) == -2**51 - 2
assert round_float(2.0**52 - 0.5) == 2**52
assert round_float(2.0**52 + 1.0) == 2**52 + 1

# Short int limits on 32-bit platforms
assert round_float(2.0**30 - 1.0) == 2**30 - 1
assert round_float(2.0**30 - 0.5) == 2**30
assert round_float(-2.0**30 - 0.5) == -2**30
assert round_float(-2.0**30 - 1.0) == -2**30 - 1

assert round_float(2.0**62) == 2**62
assert round_float(-2.0**62) == -2**62
assert round_float(1e300) == int(1e300)
assert round_float(-1e300) == int(-1e300)

for x in float_vals:
if math.isinf(x):
with assertRaises(OverflowError, "cannot convert float infinity to integer"):
round_float(x)
elif math.isnan(x):
with assertRaises(ValueError, "cannot convert float NaN to integer"):
round_float(x)
else:
assert round_float(x) == round_any(x), x
assert type(round_float(x)) is int

for n in range(-1000, 1000):
x = n / 8
assert round_float(x) == round_any(x), x

# Two-argument round() still works (generic implementation)
y = identity(2.675)
assert round(y, 2) == 2.67
assert round(y, None) == 3

def test_round_int() -> None:
for n in [0, 1, -1, 2**62, -2**62, 2**63, -2**100, 10**400]:
assert round_int(n) == n
for b in (True, False):
assert round_int(b) == int(b)
assert type(round_int(b)) is int

def test_explicit_conversion_to_int() -> None:
int_any: Any = int
for x in float_vals:
Expand Down Expand Up @@ -726,3 +800,44 @@ class BadIntReal(int):
@property
def real(self) -> Any:
return "x"

[case testRoundIntSubclass]
def round_int(n: int) -> int:
return round(n)

def round_pop(values: list[int]) -> int:
return round(values.pop())

[file driver.py]
from native import round_int, round_pop
from testutil import assertRaises

class PlainInt(int):
pass

class OverrideRound(int):
def __round__(self):
return 42

def __getattribute__(self, name):
if name == "__round__":
raise AssertionError("round must use special method lookup")
return super().__getattribute__(name)

class RaisingRound(int):
def __round__(self):
raise ValueError("custom round failed")

# Large integer subclasses stay boxed and must retain their __round__ behavior.
big = 2**100
assert round_int(OverrideRound(big)) == 42
assert round_int(PlainInt(big)) == big
assert type(round_int(PlainInt(big))) is int
with assertRaises(ValueError, "custom round failed"):
round_int(RaisingRound(big))

# The argument is evaluated exactly once on both sides of the type guard.
for value, expected in [(3, 3), (big, big), (OverrideRound(big), 42)]:
values = [value]
assert round_pop(values) == expected
assert values == []
Loading