diff --git a/mypyc/irbuild/specialize.py b/mypyc/irbuild/specialize.py index 69cb21a00213..4b582d98be4d 100644 --- a/mypyc/irbuild/specialize.py +++ b/mypyc/irbuild/specialize.py @@ -164,6 +164,7 @@ isinstance_slice, isinstance_type, slow_isinstance_op, + type_of_int_op, ) from mypyc.primitives.set_ops import isinstance_frozenset, isinstance_set from mypyc.primitives.str_ops import ( @@ -1429,6 +1430,35 @@ def translate_float(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Valu return None +@specialize_function("builtins.type") +def translate_type(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None: + """Get the type of an unboxed int, float or bool without boxing it. + + Only these exact types are handled. A union such as 'bool | int' is boxed + already, and unboxing it as an int would lose the type of a bool. + """ + 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_int_rprimitive(arg_type): + # A long int can be an instance of a subclass of int + return builder.primitive_op(type_of_int_op, [builder.accept(arg)], expr.line) + if is_bool_rprimitive(arg_type): + type_name = "builtins.bool" + elif is_float_rprimitive(arg_type): + type_name = "builtins.float" + elif is_fixed_width_rtype(arg_type): + type_name = "builtins.int" + else: + return None + # The type doesn't depend on the value, but the argument can have side effects + builder.accept(arg) + type_obj = builder.load_builtin(type_name, expr.line) + assert type_obj is not None + return type_obj + + @specialize_function("builtins.ord") def translate_ord(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None: if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS: diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index d4bd2d8938ce..7de0585f553d 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -1260,6 +1260,17 @@ static inline PyObject *CPy_TYPE(PyObject *obj) { return result; } +// type() of an int, without boxing it +static inline PyObject *CPyTagged_Type(CPyTagged x) { + // A short int boxes to an exact int, but a long int is an object that can + // be an instance of a subclass of int + if (likely(CPyTagged_CheckShort(x))) { + Py_INCREF(&PyLong_Type); + return (PyObject *)&PyLong_Type; + } + return CPy_TYPE(CPyTagged_LongAsObject(x)); +} + PyObject *CPy_CalculateMetaclass(PyObject *type, PyObject *o); PyObject *CPyType_ResolveBases(PyObject *bases); PyObject *CPy_GetCoro(PyObject *obj); diff --git a/mypyc/primitives/misc_ops.py b/mypyc/primitives/misc_ops.py index b620b137f153..a0c5089e6610 100644 --- a/mypyc/primitives/misc_ops.py +++ b/mypyc/primitives/misc_ops.py @@ -344,6 +344,17 @@ error_kind=ERR_NEVER, ) +# type(x) for an int, without boxing x first. This is used by translate_type() in +# irbuild/specialize.py, which checks for the exact type. As a function op it would +# also match a union such as 'bool | int' and unbox it, so that type(True) would give int. +type_of_int_op = custom_primitive_op( + name="builtins.type", + arg_types=[int_rprimitive], + c_function_name="CPyTagged_Type", + return_type=object_rprimitive, + error_kind=ERR_NEVER, +) + # Get 'builtins.type' (base class of all classes) type_object_op = load_address_op(name="builtins.type", type=object_rprimitive, src="PyType_Type") diff --git a/mypyc/test-data/irbuild-classes.test b/mypyc/test-data/irbuild-classes.test index b4424cfa9e88..0a7068538587 100644 --- a/mypyc/test-data/irbuild-classes.test +++ b/mypyc/test-data/irbuild-classes.test @@ -2519,6 +2519,97 @@ L0: r0 = CPy_TYPE(x) return r0 +[case testTypeOfUnboxedValue] +from typing import Union + +from mypy_extensions import u16 + +def type_of_int(x: int) -> type: + return type(x) + +def type_of_float(x: float) -> type: + return type(x) + +def type_of_bool(x: bool) -> type: + return type(x) + +def type_of_u16(x: u16) -> type: + return type(x) + +def type_of_bool_or_int(x: Union[bool, int]) -> type: + return type(x) + +def is_exact_int(x: int) -> bool: + return type(x) is int + +def is_exact_float(x: float) -> bool: + return type(x) is float + +def get_float() -> float: + return 1.5 + +def type_of_call() -> type: + return type(get_float()) +[out] +def type_of_int(x): + x :: int + r0 :: object +L0: + r0 = CPyTagged_Type(x) + return r0 +def type_of_float(x): + x :: float + r0 :: object +L0: + r0 = load_address PyFloat_Type + return r0 +def type_of_bool(x): + x :: bool + r0 :: object +L0: + r0 = load_address PyBool_Type + return r0 +def type_of_u16(x): + x :: u16 + r0 :: object +L0: + r0 = load_address PyLong_Type + return r0 +def type_of_bool_or_int(x): + x :: union[bool, int] + r0 :: object +L0: + r0 = CPy_TYPE(x) + return r0 +def is_exact_int(x): + x :: int + r0, r1 :: object + r2 :: bit +L0: + r0 = CPyTagged_Type(x) + r1 = load_address PyLong_Type + r2 = r0 == r1 + return r2 +def is_exact_float(x): + x :: float + r0, r1 :: object + r2 :: bit +L0: + r0 = load_address PyFloat_Type + r1 = load_address PyFloat_Type + r2 = r0 == r1 + return r2 +def get_float(): +L0: + return 1.5 +def type_of_call(): + r0 :: float + r1 :: object +L0: + r0 = get_float() + r1 = load_address PyFloat_Type + return r1 + [case testDunderNew] from __future__ import annotations from typing import Any diff --git a/mypyc/test-data/run-misc.test b/mypyc/test-data/run-misc.test index 3467a2427eaf..9b29b43fb830 100644 --- a/mypyc/test-data/run-misc.test +++ b/mypyc/test-data/run-misc.test @@ -1403,6 +1403,88 @@ def test_range_slice_memoryview() -> None: assert is_memoryview(memoryview(b"x")) is True assert is_memoryview(b"x") is False +[case testTypeOfUnboxedValue] +from typing import Any, Union + +from mypy_extensions import i64, u16, u32, u64 +from testutil import assertRaises + +def type_of_int(x: int) -> type: + return type(x) +def type_of_float(x: float) -> type: + return type(x) +def type_of_bool(x: bool) -> type: + return type(x) +def type_of_i64(x: i64) -> type: + return type(x) +def type_of_u16(x: u16) -> type: + return type(x) +def type_of_u32(x: u32) -> type: + return type(x) +def type_of_u64(x: u64) -> type: + return type(x) +def type_of_bool_or_int(x: Union[bool, int]) -> type: + return type(x) +def is_exact_int(x: int) -> bool: + return type(x) is int + +def float_arg(log: list[str]) -> float: + log.append("float") + return 1.5 +def bool_arg(log: list[str]) -> bool: + log.append("bool") + return True +def u16_arg(log: list[str]) -> u16: + log.append("u16") + return 5 +def float_error() -> float: + raise ValueError("float") +def u16_error() -> u16: + raise ValueError("u16") + +type_: Any = type +MyInt: Any = type_("MyInt", (int,), {}) + +def test_type_of_unboxed_value() -> None: + big = MyInt(2**100) + assert type_of_int(5) is int + assert type_of_int(-(2**100)) is int + # A long int keeps its object, which can be an instance of a subclass + assert type_of_int(big) is MyInt + assert is_exact_int(5) and is_exact_int(2**100) + assert not is_exact_int(big) + assert type_of_float(1.5) is float + assert type_of_bool(True) is bool + assert type_of_bool(1 > 2) is bool + assert type_of_i64(-5) is int + assert type_of_i64(-(2**63)) is int + assert type_of_u16(2**16 - 1) is int + assert type_of_u32(2**32 - 1) is int + assert type_of_u64(2**64 - 1) is int + n = 2**70 + assert type(n + 1) is int + assert type(n > 1) is bool + assert type(n / 2) is float + +def test_type_of_union() -> None: + # A union is boxed, so a bool or an instance of an int subclass keeps its type + small = MyInt(5) + assert type_of_bool_or_int(True) is bool + assert type_of_bool_or_int(small) is MyInt + assert type_of_bool_or_int(5) is int + +def test_argument_is_evaluated() -> None: + # The value isn't needed for the type of a float, bool or u16, but it's evaluated + log: list[str] = [] + assert type(float_arg(log)) is float + assert type(bool_arg(log)) is bool + assert type(u16_arg(log)) is int + assert log == ["float", "bool", "u16"] + with assertRaises(ValueError, "float"): + type(float_error()) + with assertRaises(ValueError, "u16"): + type(u16_error()) + [case testIsInstanceMixedTuple] from typing import Any from mypy_extensions import mypyc_attr