diff --git a/mypyc/doc/float_operations.rst b/mypyc/doc/float_operations.rst index f1da294f3c2f..d9755e5e5a3f 100644 --- a/mypyc/doc/float_operations.rst +++ b/mypyc/doc/float_operations.rst @@ -47,7 +47,7 @@ Functions * ``i8(f)`` (convert to 8-bit signed integer) * ``u16(f)`` (convert to 16-bit unsigned integer) * ``u8(f)`` (convert to 8-bit unsigned integer) -* ``abs(f)`` +* ``abs(f)`` (also for ``complex`` values and unions such as ``float | complex``) * ``math.sin(f)`` * ``math.cos(f)`` * ``math.tan(f)`` diff --git a/mypyc/irbuild/expression.py b/mypyc/irbuild/expression.py index e99a9e6dca6b..d304ab5a0da7 100644 --- a/mypyc/irbuild/expression.py +++ b/mypyc/irbuild/expression.py @@ -54,10 +54,8 @@ Instance, ProperType, TupleType, - Type, TypeOfAny, TypeType, - UnionType, get_proper_type, ) from mypyc.common import KEEP_ALIVE_SHORT_LIVED, KEEP_ALIVE_WHOLE_EXPRESSION, MAX_SHORT_INT @@ -133,6 +131,7 @@ apply_dunder_specialization, apply_function_specialization, apply_method_specialization, + is_builtin_number_type, translate_getitem_with_bounds_check, translate_object_new, translate_object_setattr, @@ -371,19 +370,6 @@ def transform_member_expr(builder: IRBuilder, expr: MemberExpr) -> Value: ) -def is_builtin_number_type(typ: Type | None) -> bool: - """Is typ int, bool, float, complex or a union of them (and not a subclass)?""" - typ = get_proper_type(typ) - if isinstance(typ, UnionType): - return all(is_builtin_number_type(item) for item in typ.items) - return isinstance(typ, Instance) and typ.type.fullname in ( - "builtins.int", - "builtins.bool", - "builtins.float", - "builtins.complex", - ) - - def transform_real_imag( builder: IRBuilder, obj: Value, is_real: bool, rtype: RType, line: int ) -> Value: diff --git a/mypyc/irbuild/specialize.py b/mypyc/irbuild/specialize.py index d33f15a68bee..f5204eb7ef79 100644 --- a/mypyc/irbuild/specialize.py +++ b/mypyc/irbuild/specialize.py @@ -37,7 +37,7 @@ TupleExpr, Var, ) -from mypy.types import AnyType, TypeOfAny +from mypy.types import AnyType, Instance, Type, TypeOfAny, UnionType, get_proper_type from mypyc.ir.class_ir import ClassIR from mypyc.ir.ops import ( ERR_FALSE, @@ -144,7 +144,7 @@ dict_values_op, isinstance_dict, ) -from mypyc.primitives.float_ops import isinstance_float +from mypyc.primitives.float_ops import complex_abs_op, isinstance_float from mypyc.primitives.generic_ops import generic_setattr, setup_object from mypyc.primitives.int_ops import ( int_to_big_endian_op, @@ -414,6 +414,37 @@ def translate_builtins_with_unary_dunder( return None +def is_builtin_number_type(typ: Type | None) -> bool: + """Is typ int, bool, float, complex or a union of them (and not a subclass)?""" + typ = get_proper_type(typ) + if isinstance(typ, UnionType): + return all(is_builtin_number_type(item) for item in typ.items) + return isinstance(typ, Instance) and typ.type.fullname in ( + "builtins.int", + "builtins.bool", + "builtins.float", + "builtins.complex", + ) + + +@specialize_function("builtins.abs") +def translate_complex_abs(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None: + """Specialize abs() of a complex (or a float | complex), which is a float. + + The argument is a boxed object, and the generic abs() would return a float object + that is unboxed right away. abs() of an unboxed float or int has a primitive. + """ + if len(expr.args) == 1 and expr.arg_kinds == [ARG_POS]: + arg = expr.args[0] + if ( + is_float_rprimitive(builder.node_type(expr)) + and not builder.node_type(arg).is_unboxed + and is_builtin_number_type(builder.types.get(arg)) + ): + return builder.primitive_op(complex_abs_op, [builder.accept(arg)], expr.line) + 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]: diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index 5151bb7cd745..b3fbc25f4f5b 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -814,6 +814,7 @@ bool CPyFloat_IsInf(double x); bool CPyFloat_IsNaN(double x); double CPyComplex_GetPartSlow(PyObject *o, PyObject *name); double CPyLong_AsDouble(PyObject *o); +double CPyComplex_Abs(PyObject *o); // o.real, where the static type of o is float or complex. Other types, // including subclasses that might override the property, use getattr. diff --git a/mypyc/lib-rt/float_ops.c b/mypyc/lib-rt/float_ops.c index 4210b84f33a9..f264502f3451 100644 --- a/mypyc/lib-rt/float_ops.c +++ b/mypyc/lib-rt/float_ops.c @@ -264,3 +264,51 @@ double CPyLong_AsDouble(PyObject *o) { } return result; } + +// abs(o), where the static type of o is complex (or float | complex). An int or a +// float can be used where a complex is expected. Anything else, including subclasses +// that might override __abs__, calls __abs__, and the result is converted to a C +// double like unboxing it to a float would. +double CPyComplex_Abs(PyObject *o) { + if (PyComplex_CheckExact(o)) { + // The same as complex.__abs__ (see _Py_c_abs in Objects/complexobject.c) + Py_complex z = ((PyComplexObject *)o)->cval; + if (!isfinite(z.real) || !isfinite(z.imag)) { + // C99 rules: if either part is infinite, the result is infinity, even if + // the other part is a NaN + if (isinf(z.real)) { + return fabs(z.real); + } + if (isinf(z.imag)) { + return fabs(z.imag); + } + return Py_NAN; + } + double result = hypot(z.real, z.imag); + if (!isfinite(result)) { + PyErr_SetString(PyExc_OverflowError, "absolute value too large"); + return CPY_FLOAT_ERROR; + } + return result; + } else if (PyFloat_CheckExact(o)) { + return fabs(PyFloat_AS_DOUBLE(o)); + } else if (PyLong_CheckExact(o)) { + double result = CPyLong_AsDouble(o); + if (result == CPY_FLOAT_ERROR && PyErr_Occurred()) { + return CPY_FLOAT_ERROR; + } + return fabs(result); + } + PyObject *abs = PyNumber_Absolute(o); + if (abs == NULL) { + return CPY_FLOAT_ERROR; + } + double result = PyFloat_AsDouble(abs); + if (result == -1.0 && PyErr_Occurred()) { + // Same error as unboxing the result would produce + CPy_TypeError("float", abs); + result = CPY_FLOAT_ERROR; + } + Py_DECREF(abs); + return result; +} diff --git a/mypyc/primitives/float_ops.py b/mypyc/primitives/float_ops.py index 26d7127fe28f..dea444aa4f94 100644 --- a/mypyc/primitives/float_ops.py +++ b/mypyc/primitives/float_ops.py @@ -212,3 +212,12 @@ c_function_name="CPyNumber_Imag", error_kind=ERR_MAGIC, ) + +# abs(obj), where obj is a complex or a float | complex +complex_abs_op = custom_primitive_op( + name="builtins.abs", + arg_types=[object_rprimitive], + return_type=float_rprimitive, + c_function_name="CPyComplex_Abs", + error_kind=ERR_MAGIC_OVERLAPPING, +) diff --git a/mypyc/test-data/fixtures/ir.py b/mypyc/test-data/fixtures/ir.py index 9f83160038e9..d2189d2d804b 100644 --- a/mypyc/test-data/fixtures/ir.py +++ b/mypyc/test-data/fixtures/ir.py @@ -184,6 +184,7 @@ def __rsub__(self, n: float) -> complex: pass def __mul__(self, n: complex) -> complex: pass def __truediv__(self, n: complex) -> complex: pass def __neg__(self) -> complex: pass + def __abs__(self) -> float: pass @property def real(self) -> float: ... @property diff --git a/mypyc/test-data/irbuild-float.test b/mypyc/test-data/irbuild-float.test index eda91504a2c6..e4c375c44445 100644 --- a/mypyc/test-data/irbuild-float.test +++ b/mypyc/test-data/irbuild-float.test @@ -623,3 +623,40 @@ L0: r3 = cast(union[int, float], r2) r4 = (r1, r3) return r4 + +[case testComplexAbs] +from typing import Any + +def complex_abs(z: complex) -> float: + return abs(z) +def union_abs(x: float | complex) -> float: + return abs(x) +def float_abs(x: float) -> float: + return abs(x) +def any_abs(x: Any) -> float: + return abs(x) +[out] +def complex_abs(z): + z :: object + r0 :: float +L0: + r0 = CPyComplex_Abs(z) + return r0 +def union_abs(x): + x :: union[float, object] + r0 :: float +L0: + r0 = CPyComplex_Abs(x) + return r0 +def float_abs(x): + x, r0 :: float +L0: + r0 = fabs(x) + return r0 +def any_abs(x): + x, r0 :: object + r1 :: float +L0: + r0 = PyNumber_Absolute(x) + r1 = unbox(float, r0) + return r1 diff --git a/mypyc/test-data/run-floats.test b/mypyc/test-data/run-floats.test index 11e23770a0f9..913af001e9fd 100644 --- a/mypyc/test-data/run-floats.test +++ b/mypyc/test-data/run-floats.test @@ -726,3 +726,109 @@ class BadIntReal(int): @property def real(self) -> Any: return "x" + +[case testComplexAbs] +from typing import Any +from testutil import assertRaises, float_vals, FLOAT_MAGIC +from complexabs import ( + OverrideAbs, OverrideFloatAbs, PlainComplex, IntAbs, MagicAbs, BadAbs, RaisingAbs, +) + +def complex_abs(z: complex) -> float: + return abs(z) + +def union_abs(x: float | complex) -> float: + return abs(x) + +def number_abs(x: int | complex) -> float: + return abs(x) + +def generic_abs(x: Any) -> Any: + return abs(x) + +def same(a: object, b: object) -> bool: + # Unlike ==, this distinguishes -0.0 from 0.0 and treats nan as equal to itself + return repr(a) == repr(b) + +def test_complex() -> None: + for re in float_vals: + for im in float_vals: + z = complex(re, im) + try: + expected = generic_abs(z) + except OverflowError: + for f in (complex_abs, union_abs, number_abs): + with assertRaises(OverflowError, "absolute value too large"): + f(z) + else: + assert same(complex_abs(z), expected) + assert same(union_abs(z), expected) + assert same(number_abs(z), expected) + assert complex_abs(3 - 4j) + 1.0 == 6.0 + for z in [complex(1.5e308, 1.5e308), complex(-1.7e308, 1e308)]: + with assertRaises(OverflowError, "absolute value too large"): + complex_abs(z) + with assertRaises(OverflowError, "absolute value too large"): + union_abs(z) + +def test_float() -> None: + for x in float_vals: + assert same(complex_abs(x), generic_abs(x)) + assert same(union_abs(x), generic_abs(x)) + +def test_int() -> None: + # An int can be used where a complex is expected + for n in [0, 1, -1, -113, -(2**62), 2**100]: + assert complex_abs(n) == abs(n) + assert union_abs(n) == abs(n) + assert number_abs(n) == abs(n) + assert complex_abs(True) == 1 + +def test_subclasses() -> None: + # Subclasses could override __abs__, so they call it + for f in (complex_abs, union_abs, number_abs): + assert same(f(OverrideAbs(1, 2)), 42.0) + assert same(f(PlainComplex(3, 4)), 5.0) + assert same(f(OverrideFloatAbs(-2.0)), 7.5) + assert f(IntAbs(1, 1)) == 3 + # This result is the same as the error value of a C double + assert same(f(MagicAbs(1, 1)), FLOAT_MAGIC) + +def test_errors() -> None: + with assertRaises(ValueError, "no abs"): + complex_abs(RaisingAbs(1, 1)) + # The result is converted to a float like when unboxing it + with assertRaises(TypeError, "float object expected; got str"): + complex_abs(BadAbs(1, 1)) + with assertRaises(TypeError, "float object expected; got int"): + complex_abs(10**400) + +[file complexabs.py] +from typing import Any + +class OverrideAbs(complex): + def __abs__(self) -> float: + return 42.0 + +class OverrideFloatAbs(float): + def __abs__(self) -> float: + return 7.5 + +class PlainComplex(complex): + pass + +class IntAbs(complex): + def __abs__(self) -> Any: + return 3 + +class MagicAbs(complex): + def __abs__(self) -> float: + return -113.0 + +class BadAbs(complex): + def __abs__(self) -> Any: + return "x" + +class RaisingAbs(complex): + def __abs__(self) -> float: + raise ValueError("no abs")