From f35801e1972c49c46f4c943c0e17a18f53c6f161 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 12:07:09 +0500 Subject: [PATCH 1/3] [mypyc] Add primitive for chr Call PyUnicode_FromOrdinal directly for short ints in the valid range. Out-of-range values raise the same exceptions as CPython, which differ between Python versions: 3.13+ always raises ValueError, while older versions raise OverflowError for values that don't fit in a C int. Part of mypyc/mypyc#644. --- mypyc/doc/str_operations.rst | 1 + mypyc/lib-rt/CPy.h | 1 + mypyc/lib-rt/str_ops.c | 22 ++++++++++++++++++ mypyc/primitives/str_ops.py | 9 +++++++ mypyc/test-data/irbuild-str.test | 22 ++++++++++++++++++ mypyc/test-data/run-strings.test | 40 ++++++++++++++++++++++++++++++++ 6 files changed, 95 insertions(+) diff --git a/mypyc/doc/str_operations.rst b/mypyc/doc/str_operations.rst index 8f2daba02b72d..36fe303703744 100644 --- a/mypyc/doc/str_operations.rst +++ b/mypyc/doc/str_operations.rst @@ -92,6 +92,7 @@ A subset of these common string formatting expressions are optimized: Functions --------- +* ``chr(i: int)`` * ``len(s: str)`` * ``ord(s: str)`` diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index 65cc8f038e508..ae634513e5c63 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -1037,6 +1037,7 @@ PyObject *CPy_Encode(PyObject *obj, PyObject *encoding, PyObject *errors); Py_ssize_t CPyStr_Count(PyObject *unicode, PyObject *substring, CPyTagged start); Py_ssize_t CPyStr_CountFull(PyObject *unicode, PyObject *substring, CPyTagged start, CPyTagged end); CPyTagged CPyStr_Ord(PyObject *obj); +PyObject *CPyStr_Chr(CPyTagged n); PyObject *CPyStr_Multiply(PyObject *str, CPyTagged count); PyObject *CPyStr_Lower(PyObject *str); PyObject *CPyStr_Upper(PyObject *str); diff --git a/mypyc/lib-rt/str_ops.c b/mypyc/lib-rt/str_ops.c index 9e3d494868017..4d7fbf8069e34 100644 --- a/mypyc/lib-rt/str_ops.c +++ b/mypyc/lib-rt/str_ops.c @@ -640,6 +640,28 @@ CPyTagged CPyStr_Ord(PyObject *obj) { return CPY_INT_TAG; } +PyObject *CPyStr_Chr(CPyTagged n) { + if (likely(CPyTagged_CheckShort(n))) { + Py_ssize_t v = CPyTagged_ShortAsSsize_t(n); + if (likely(v >= 0 && v <= 0x10ffff)) { + return PyUnicode_FromOrdinal((int)v); + } +#if !CPY_3_13_FEATURES + if (v >= INT_MIN && v <= INT_MAX) { + return PyUnicode_FromOrdinal((int)v); + } +#endif + } +#if CPY_3_13_FEATURES + // Python 3.13+ raises ValueError for all out-of-range values + PyErr_SetString(PyExc_ValueError, "chr() arg not in range(0x110000)"); +#else + // Older Python versions convert the argument to a C int first + PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C int"); +#endif + return NULL; +} + PyObject *CPyStr_Multiply(PyObject *str, CPyTagged count) { Py_ssize_t temp_count = CPyTagged_AsSsize_t(count); if (temp_count == -1 && PyErr_Occurred()) { diff --git a/mypyc/primitives/str_ops.py b/mypyc/primitives/str_ops.py index 27cf79e62352d..58761aa77b7d7 100644 --- a/mypyc/primitives/str_ops.py +++ b/mypyc/primitives/str_ops.py @@ -554,6 +554,15 @@ error_kind=ERR_MAGIC, ) +# chr(int) +function_op( + name="builtins.chr", + arg_types=[int_rprimitive], + return_type=str_rprimitive, + c_function_name="CPyStr_Chr", + error_kind=ERR_MAGIC, +) + # Optimized str indexing for ord(s[i]) # str index adjustment - convert negative index to positive diff --git a/mypyc/test-data/irbuild-str.test b/mypyc/test-data/irbuild-str.test index bf2773196cdec..aa0191f6ae331 100644 --- a/mypyc/test-data/irbuild-str.test +++ b/mypyc/test-data/irbuild-str.test @@ -507,6 +507,28 @@ L0: r6 = unbox(int, r5) return r6 +[case testChr] +def f(x: int) -> str: + return chr(x) +def g(x: bool) -> str: + return chr(x) +[out] +def f(x): + x :: int + r0 :: str +L0: + r0 = CPyStr_Chr(x) + return r0 +def g(x): + x, r0 :: bool + r1 :: int + r2 :: str +L0: + r0 = x << 1 + r1 = extend r0: builtins.bool to builtins.int + r2 = CPyStr_Chr(r1) + return r2 + [case testOrdOfStrIndex_64bit] from mypy_extensions import i64, i32, i16, u8 def ord_str_index(s: str, i: int) -> int: diff --git a/mypyc/test-data/run-strings.test b/mypyc/test-data/run-strings.test index f26b160d816c1..0e18450b4a0b4 100644 --- a/mypyc/test-data/run-strings.test +++ b/mypyc/test-data/run-strings.test @@ -809,6 +809,10 @@ def test_format_method_python_doc() -> None: [case testChr] # Some test cases are from https://docs.python.org/3/howto/unicode.html +import sys +from typing import Any + +from testutil import assertRaises def try_invalid(x: int) -> bool: try: @@ -846,6 +850,42 @@ def test_chr() -> None: assert try_invalid(-1) assert try_invalid(1114112) +def test_chr_all_code_points() -> None: + f: Any = chr + for i in range(0x110000): + c = chr(i) + assert c == f(i) + assert ord(c) == i + # Latin-1 characters are cached singletons, like in CPython + assert chr(65 + int()) is chr(65 + int()) + assert chr(255 + int()) is chr(255 + int()) + +def test_chr_bool() -> None: + t = bool(int() + 1) + assert chr(t) == '\x01' + assert chr(not t) == '\x00' + +def test_chr_errors() -> None: + f: Any = chr + for n in [-1, 0x110000, 2**31 - 1, 2**31, -2**31, -2**31 - 1, 2**40, -2**40, + 2**62 - 1, 2**62, -2**62, -2**62 - 1, 2**70, -2**70]: + try: + f(n) + except Exception as e: + expected_type = type(e) + expected_msg = str(e) + else: + assert False + with assertRaises(expected_type, expected_msg): + chr(n + int()) + _, minor, _, _, _ = sys.version_info + if minor >= 13: + with assertRaises(ValueError, "chr() arg not in range(0x110000)"): + chr(2**70 + int()) + else: + with assertRaises(OverflowError, "Python int too large to convert to C int"): + chr(2**70 + int()) + [case testOrd] from testutil import assertRaises from mypy_extensions import i64, i32, i16, u8 From 7d773220ad242fda67f1a0d648a2344d1c930fca Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 13:35:26 +0500 Subject: [PATCH 2/3] Fix chr() error type for non-short ints that fit in a C int on 32-bit platforms --- mypyc/lib-rt/str_ops.c | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/mypyc/lib-rt/str_ops.c b/mypyc/lib-rt/str_ops.c index 4d7fbf8069e34..8d6ddf5c9cf78 100644 --- a/mypyc/lib-rt/str_ops.c +++ b/mypyc/lib-rt/str_ops.c @@ -646,20 +646,22 @@ PyObject *CPyStr_Chr(CPyTagged n) { if (likely(v >= 0 && v <= 0x10ffff)) { return PyUnicode_FromOrdinal((int)v); } -#if !CPY_3_13_FEATURES - if (v >= INT_MIN && v <= INT_MAX) { - return PyUnicode_FromOrdinal((int)v); - } -#endif } #if CPY_3_13_FEATURES // Python 3.13+ raises ValueError for all out-of-range values PyErr_SetString(PyExc_ValueError, "chr() arg not in range(0x110000)"); + return NULL; #else - // Older Python versions convert the argument to a C int first - PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C int"); + // Older Python versions convert the argument to a C int first. Note that on + // 32-bit platforms some values that fit in a C int aren't short ints. + Py_ssize_t v = CPyTagged_AsSsize_t(n); + if ((v == -1 && PyErr_Occurred()) || v < INT_MIN || v > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C int"); + return NULL; + } + // This raises ValueError, since the value is out of range + return PyUnicode_FromOrdinal((int)v); #endif - return NULL; } PyObject *CPyStr_Multiply(PyObject *str, CPyTagged count) { From 34db537e9cca89c2bbf19f1695f1eb1a6b1823a0 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Tue, 10 Nov 2026 23:31:39 +0500 Subject: [PATCH 3/3] Remove redundant chr() overflow test --- mypyc/test-data/run-strings.test | 8 -------- 1 file changed, 8 deletions(-) diff --git a/mypyc/test-data/run-strings.test b/mypyc/test-data/run-strings.test index 0e18450b4a0b4..c6312f62edb43 100644 --- a/mypyc/test-data/run-strings.test +++ b/mypyc/test-data/run-strings.test @@ -809,7 +809,6 @@ def test_format_method_python_doc() -> None: [case testChr] # Some test cases are from https://docs.python.org/3/howto/unicode.html -import sys from typing import Any from testutil import assertRaises @@ -878,13 +877,6 @@ def test_chr_errors() -> None: assert False with assertRaises(expected_type, expected_msg): chr(n + int()) - _, minor, _, _, _ = sys.version_info - if minor >= 13: - with assertRaises(ValueError, "chr() arg not in range(0x110000)"): - chr(2**70 + int()) - else: - with assertRaises(OverflowError, "Python int too large to convert to C int"): - chr(2**70 + int()) [case testOrd] from testutil import assertRaises