diff --git a/mypyc/doc/str_operations.rst b/mypyc/doc/str_operations.rst index b5d488486e37..04209aec4ba6 100644 --- a/mypyc/doc/str_operations.rst +++ b/mypyc/doc/str_operations.rst @@ -49,9 +49,12 @@ Methods * ``s.isascii()`` * ``s.isdecimal()`` * ``s.isdigit()`` +* ``s.islower()`` * ``s.isnumeric()`` * ``s.isprintable()`` * ``s.isspace()`` +* ``s.istitle()`` +* ``s.isupper()`` * ``s.lower()`` * ``s.join(x: Iterable)`` * ``s.lstrip()`` diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index 0518ab034df3..2a1150988180 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -1116,6 +1116,9 @@ static inline bool CPyStr_IsAscii(PyObject *str) { bool CPyStr_IsDecimal(PyObject *str); bool CPyStr_IsNumeric(PyObject *str); bool CPyStr_IsPrintable(PyObject *str); +bool CPyStr_IsLower(PyObject *str); +bool CPyStr_IsTitle(PyObject *str); +bool CPyStr_IsUpper(PyObject *str); // Bytes operations diff --git a/mypyc/lib-rt/str_ops.c b/mypyc/lib-rt/str_ops.c index 0fcdac6a3815..8d3965644f6a 100644 --- a/mypyc/lib-rt/str_ops.c +++ b/mypyc/lib-rt/str_ops.c @@ -890,3 +890,98 @@ bool CPyStr_IsPrintable(PyObject *str) { #undef CPY_ASCII_ISPRINTABLE #undef CPY_STR_RETURN_ALL_CHARS #undef CPY_STR_CHECK_CHARS + +// Shared implementation of str.islower() and str.isupper(), mirroring CPython. There +// must be at least one cased character, and no character may be titlecase or have +// the opposite case. +static inline bool CPyStr_IsCase(PyObject *str, bool lower) { + Py_ssize_t len = PyUnicode_GET_LENGTH(str); + bool cased = false; + + // ASCII fast path (there are no titlecase characters in ASCII) + if (PyUnicode_IS_ASCII(str)) { + const Py_UCS1 *data = PyUnicode_1BYTE_DATA(str); + for (Py_ssize_t i = 0; i < len; i++) { + Py_UCS1 ch = data[i]; + if (lower ? Py_ISUPPER(ch) : Py_ISLOWER(ch)) + return false; + if (lower ? Py_ISLOWER(ch) : Py_ISUPPER(ch)) + cased = true; + } + return cased; + } + + int kind = PyUnicode_KIND(str); + const void *data = PyUnicode_DATA(str); + if (len == 1) { + Py_UCS4 ch = PyUnicode_READ(kind, data, 0); + return lower ? Py_UNICODE_ISLOWER(ch) : Py_UNICODE_ISUPPER(ch); + } + for (Py_ssize_t i = 0; i < len; i++) { + Py_UCS4 ch = PyUnicode_READ(kind, data, i); + if (Py_UNICODE_ISTITLE(ch) || (lower ? Py_UNICODE_ISUPPER(ch) : Py_UNICODE_ISLOWER(ch))) + return false; + if (!cased && (lower ? Py_UNICODE_ISLOWER(ch) : Py_UNICODE_ISUPPER(ch))) + cased = true; + } + return cased; +} + +bool CPyStr_IsLower(PyObject *str) { + return CPyStr_IsCase(str, true); +} + +bool CPyStr_IsUpper(PyObject *str) { + return CPyStr_IsCase(str, false); +} + +// Mirrors CPython's str.istitle(). Uppercase and titlecase characters may only follow +// uncased characters, lowercase characters may only follow cased characters, and +// there must be at least one cased character. +bool CPyStr_IsTitle(PyObject *str) { + Py_ssize_t len = PyUnicode_GET_LENGTH(str); + bool cased = false; + bool previous_is_cased = false; + + // ASCII fast path (there are no titlecase characters in ASCII) + if (PyUnicode_IS_ASCII(str)) { + const Py_UCS1 *data = PyUnicode_1BYTE_DATA(str); + for (Py_ssize_t i = 0; i < len; i++) { + Py_UCS1 ch = data[i]; + if (Py_ISUPPER(ch)) { + if (previous_is_cased) + return false; + previous_is_cased = cased = true; + } else if (Py_ISLOWER(ch)) { + if (!previous_is_cased) + return false; + previous_is_cased = cased = true; + } else { + previous_is_cased = false; + } + } + return cased; + } + + int kind = PyUnicode_KIND(str); + const void *data = PyUnicode_DATA(str); + if (len == 1) { + Py_UCS4 ch = PyUnicode_READ(kind, data, 0); + return Py_UNICODE_ISTITLE(ch) || Py_UNICODE_ISUPPER(ch); + } + for (Py_ssize_t i = 0; i < len; i++) { + Py_UCS4 ch = PyUnicode_READ(kind, data, i); + if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) { + if (previous_is_cased) + return false; + previous_is_cased = cased = true; + } else if (Py_UNICODE_ISLOWER(ch)) { + if (!previous_is_cased) + return false; + previous_is_cased = cased = true; + } else { + previous_is_cased = false; + } + } + return cased; +} diff --git a/mypyc/primitives/str_ops.py b/mypyc/primitives/str_ops.py index ea968cd2837f..3ea676785bf8 100644 --- a/mypyc/primitives/str_ops.py +++ b/mypyc/primitives/str_ops.py @@ -484,6 +484,33 @@ error_kind=ERR_NEVER, ) +# str.islower() +method_op( + name="islower", + arg_types=[str_rprimitive], + return_type=bool_rprimitive, + c_function_name="CPyStr_IsLower", + error_kind=ERR_NEVER, +) + +# str.istitle() +method_op( + name="istitle", + arg_types=[str_rprimitive], + return_type=bool_rprimitive, + c_function_name="CPyStr_IsTitle", + error_kind=ERR_NEVER, +) + +# str.isupper() +method_op( + name="isupper", + arg_types=[str_rprimitive], + return_type=bool_rprimitive, + c_function_name="CPyStr_IsUpper", + error_kind=ERR_NEVER, +) + # obj.decode() method_op( diff --git a/mypyc/test-data/annotate-basic.test b/mypyc/test-data/annotate-basic.test index c9e1c4b64a32..f5eea8f2f6fa 100644 --- a/mypyc/test-data/annotate-basic.test +++ b/mypyc/test-data/annotate-basic.test @@ -185,8 +185,8 @@ def dict_set_item(d: Dict[str, str]) -> None: def startswith(x: str) -> bool: return x.startswith('foo') -def islower(x: str) -> bool: - return x.islower() # A: Call non-native method "islower" (it may be defined in a non-native class, or decorated). +def expandtabs(x: str) -> str: + return x.expandtabs() # A: Call non-native method "expandtabs" (it may be defined in a non-native class, or decorated). [case testAnnotateSpecificStdlibFeatures] import functools diff --git a/mypyc/test-data/fixtures/ir.py b/mypyc/test-data/fixtures/ir.py index 8e2d63ae317a..87fa42cede77 100644 --- a/mypyc/test-data/fixtures/ir.py +++ b/mypyc/test-data/fixtures/ir.py @@ -127,6 +127,7 @@ def join(self, x: Iterable[str]) -> str: pass def format(self, *args: Any, **kwargs: Any) -> str: ... def lower(self) -> str: ... def upper(self) -> str: ... + def expandtabs(self) -> str: ... def startswith(self, x: Union[str, Tuple[str, ...]], start: int=..., end: int=...) -> bool: ... def endswith(self, x: Union[str, Tuple[str, ...]], start: int=..., end: int=...) -> bool: ... def replace(self, old: str, new: str, maxcount: int=...) -> str: ... @@ -145,6 +146,8 @@ def isascii(self) -> bool: ... def isdecimal(self) -> bool: ... def isnumeric(self) -> bool: ... def isprintable(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... class float: def __init__(self, x: object) -> None: pass diff --git a/mypyc/test-data/irbuild-str.test b/mypyc/test-data/irbuild-str.test index 1a9580af54f3..951aa11e00f0 100644 --- a/mypyc/test-data/irbuild-str.test +++ b/mypyc/test-data/irbuild-str.test @@ -1103,6 +1103,39 @@ L0: r0 = CPyStr_IsPrintable(x) return r0 +[case testStrIsLower] +def is_lower(x: str) -> bool: + return x.islower() +[out] +def is_lower(x): + x :: str + r0 :: bool +L0: + r0 = CPyStr_IsLower(x) + return r0 + +[case testStrIsTitle] +def is_title(x: str) -> bool: + return x.istitle() +[out] +def is_title(x): + x :: str + r0 :: bool +L0: + r0 = CPyStr_IsTitle(x) + return r0 + +[case testStrIsUpper] +def is_upper(x: str) -> bool: + return x.isupper() +[out] +def is_upper(x): + x :: str + r0 :: bool +L0: + r0 = CPyStr_IsUpper(x) + return r0 + [case testStrIndexEqLiteral_64bit] def is_comma(s: str, i: int) -> bool: return s[i] == "," diff --git a/mypyc/test-data/run-strings.test b/mypyc/test-data/run-strings.test index 46baca6341bd..2e99a01e7ac3 100644 --- a/mypyc/test-data/run-strings.test +++ b/mypyc/test-data/run-strings.test @@ -1567,6 +1567,103 @@ def test_str_subclass() -> None: class S(str): pass +[case testStrIsCased] +from typing import Any + +def check(s: str) -> None: + # Any forces generic dispatch, so we compare our primitives against CPython's + a: Any = s + assert s.islower() == a.islower(), f"islower mismatch for {s!r}" + assert s.isupper() == a.isupper(), f"isupper mismatch for {s!r}" + assert s.istitle() == a.istitle(), f"istitle mismatch for {s!r}" + +def test_all_code_points() -> None: + # Covers the ASCII, UCS-1, UCS-2 and UCS-4 string kinds. Check all BMP code points, + # and a sample of the others (checking all of them is slow). + for i in [*range(0x10000), *range(0x10000, 0x110000, 97), 0x10FFFF]: + c = chr(i) + check(c) + check(c + "a") + check("A" + c) + +def test_strings() -> None: + samples = [ + "", " ", "a", "A", "abc", "ABC", "Abc", "aBC", "abC", "123", "abc 123!", "ABC 123!", + "Hello World", "Hello world", "hello World", "HEllo", "Hello-World", "Hello World 123!", + "été", "Été", "ÉTÉ", "ÉtÉ", + "абв", "АБВ", "Абв Гд", + "DŽ", "Dž", "dž", "Dža", "DžA", "DŽDž", "aDž", + "中文", "abc中", "ABC中", "Abc中", + "\U00010400", "\U00010428", "abc\U00010428", "ABC\U00010400", "abc\U00010400", + "\U00010400\U00010428", "\U0001f600", "A\U0001f600", + ] + for s in samples: + check(s) + check(s + " " + s) + +def test_islower() -> None: + assert "abc".islower() + assert "abc 123!".islower() + assert not "".islower() + assert not "123".islower() + assert not "Abc".islower() + assert not "abC".islower() + assert "été".islower() + assert not "Été".islower() + assert "абв".islower() + assert not "Dža".islower() # Titlecase character + assert "abc\U00010428".islower() + assert not "abc\U00010400".islower() + assert not "中文".islower() + +def test_isupper() -> None: + assert "ABC".isupper() + assert "ABC 123!".isupper() + assert not "".isupper() + assert not "123".isupper() + assert not "aBC".isupper() + assert not "ABc".isupper() + assert "ÉTÉ".isupper() + assert not "ÉtÉ".isupper() + assert "АБВ".isupper() + assert not "DžA".isupper() # Titlecase character + assert "ABC\U00010400".isupper() + assert not "ABC\U00010428".isupper() + assert not "中文".isupper() + +def test_istitle() -> None: + assert "Hello".istitle() + assert "Hello World".istitle() + assert "Hello World 123!".istitle() + assert "A".istitle() + assert "Hello-World".istitle() + assert not "".istitle() + assert not "123".istitle() + assert not "hello".istitle() + assert not "Hello world".istitle() + assert not "HEllo".istitle() + assert not "HELLO".istitle() + assert "Été".istitle() + assert not "été".istitle() + assert "Абв Гд".istitle() + assert "Dž".istitle() # Titlecase character + assert "Dža".istitle() + assert not "DŽDž".istitle() + assert "\U00010400\U00010428".istitle() + assert not "\U00010428".istitle() + assert not "中文".istitle() + +def test_str_subclass() -> None: + from strsubclass import S + assert S("abc").islower() + assert not S("abc").isupper() + assert not S("abc").istitle() + assert S("Abc").istitle() + +[file strsubclass.py] +class S(str): + pass + [case testStrIndexEqLiteralSpecialize] from testutil import assertRaises