diff --git a/mypyc/doc/bytearray_operations.rst b/mypyc/doc/bytearray_operations.rst index 3ee242b5648b..3947aaf56759 100644 --- a/mypyc/doc/bytearray_operations.rst +++ b/mypyc/doc/bytearray_operations.rst @@ -11,3 +11,21 @@ Construction * ``bytearray()`` * ``bytearray(x)`` + +Operators +--------- + +* Indexing (``b[n]``) +* Slicing (``b[n:m]``, ``b[n:]``, ``b[:m]``) + +Statements +---------- + +Set item by integer index: + +* ``b[n] = x`` + +Functions +--------- + +* ``len(b: bytearray)`` diff --git a/mypyc/irbuild/expression.py b/mypyc/irbuild/expression.py index e2ae96e6f161..e99a9e6dca6b 100644 --- a/mypyc/irbuild/expression.py +++ b/mypyc/irbuild/expression.py @@ -146,6 +146,7 @@ vec_item_type, vec_slice, ) +from mypyc.primitives.bytearray_ops import bytearray_slice_op from mypyc.primitives.bytes_ops import bytes_slice_op from mypyc.primitives.dict_ops import dict_get_item_op, dict_new_op, exact_dict_set_item_op from mypyc.primitives.float_ops import ( @@ -1084,6 +1085,8 @@ def try_gen_slice_op(builder: IRBuilder, base: Value, index: SliceExpr) -> Value end = builder.load_int(MAX_SHORT_INT) if isinstance(base.type, RVec): return vec_slice(builder.builder, base, begin, end, index.line) + if is_bytearray_rprimitive(base.type): + return builder.primitive_op(bytearray_slice_op, [base, begin, end], index.line) candidates = [list_slice_op, tuple_slice_op, str_slice_op, bytes_slice_op] return builder.builder.matching_call_c(candidates, [base, begin, end], index.line) diff --git a/mypyc/irbuild/ll_builder.py b/mypyc/irbuild/ll_builder.py index 08bebbe8aab7..0eab3061f553 100644 --- a/mypyc/irbuild/ll_builder.py +++ b/mypyc/irbuild/ll_builder.py @@ -102,6 +102,7 @@ int64_rprimitive, int_rprimitive, is_bool_or_bit_rprimitive, + is_bytearray_rprimitive, is_bytes_rprimitive, is_c_py_ssize_t_rprimitive, is_dict_rprimitive, @@ -2925,7 +2926,12 @@ def builtin_len(self, val: Value, line: int, use_pyssize_t: bool = False) -> Val """ typ = val.type size_value = None - if is_list_rprimitive(typ) or is_tuple_rprimitive(typ) or is_bytes_rprimitive(typ): + if ( + is_list_rprimitive(typ) + or is_tuple_rprimitive(typ) + or is_bytes_rprimitive(typ) + or is_bytearray_rprimitive(typ) + ): size_value = self.primitive_op(var_object_size, [val], line) elif is_set_rprimitive(typ) or is_frozenset_rprimitive(typ): elem_address = self.add(GetElementPtr(val, PySetObject, "used")) diff --git a/mypyc/lib-rt/bytearray_extra_ops.c b/mypyc/lib-rt/bytearray_extra_ops.c index fe734ed73159..3c49522b2f93 100644 --- a/mypyc/lib-rt/bytearray_extra_ops.c +++ b/mypyc/lib-rt/bytearray_extra_ops.c @@ -31,3 +31,125 @@ PyObject *CPyByteArray_FromBytesSlice(PyObject *obj, CPyTagged start, CPyTagged Py_DECREF(slice); return result; } + +// On free-threaded builds, the item array of a bytearray may be resized or freed +// concurrently, so it must only be accessed in a critical section. On other builds, +// the critical section macros don't do anything. + +CPyTagged CPyByteArray_GetItem(PyObject *obj, CPyTagged index) { + if (likely(PyByteArray_CheckExact(obj) && CPyTagged_CheckShort(index))) { + Py_ssize_t n = CPyTagged_ShortAsSsize_t(index); + CPyTagged result = CPY_INT_TAG; + Py_BEGIN_CRITICAL_SECTION(obj); + Py_ssize_t size = PyByteArray_GET_SIZE(obj); + if (n < 0) { + n += size; + } + if (n < 0 || n >= size) { + PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); + } else { + result = (CPyTagged)(unsigned char)PyByteArray_AS_STRING(obj)[n] << 1; + } + Py_END_CRITICAL_SECTION(); + return result; + } + + // Generic path for subclasses and large indexes + PyObject *index_obj = CPyTagged_AsObject(index); + if (index_obj == NULL) { + return CPY_INT_TAG; + } + PyObject *item = PyObject_GetItem(obj, index_obj); + Py_DECREF(index_obj); + if (item == NULL) { + return CPY_INT_TAG; + } + if (unlikely(!PyLong_Check(item))) { + CPy_TypeError("int", item); + Py_DECREF(item); + return CPY_INT_TAG; + } + return CPyTagged_StealFromObject(item); +} + +bool CPyByteArray_SetItem(PyObject *obj, CPyTagged index, CPyTagged value) { + if (likely(PyByteArray_CheckExact(obj) && CPyTagged_CheckShort(index))) { + Py_ssize_t n = CPyTagged_ShortAsSsize_t(index); + // Like CPython, check the value before the index + Py_ssize_t v = CPyTagged_CheckShort(value) ? CPyTagged_ShortAsSsize_t(value) : -1; + if (v < 0 || v > 255) { + PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); + return false; + } + bool ok = false; + Py_BEGIN_CRITICAL_SECTION(obj); + Py_ssize_t size = PyByteArray_GET_SIZE(obj); + if (n < 0) { + n += size; + } + if (n < 0 || n >= size) { + PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); + } else { + PyByteArray_AS_STRING(obj)[n] = (char)v; + ok = true; + } + Py_END_CRITICAL_SECTION(); + return ok; + } + + // Generic path for subclasses and large indexes + PyObject *index_obj = CPyTagged_AsObject(index); + if (index_obj == NULL) { + return false; + } + PyObject *value_obj = CPyTagged_AsObject(value); + if (value_obj == NULL) { + Py_DECREF(index_obj); + return false; + } + int res = PyObject_SetItem(obj, index_obj, value_obj); + Py_DECREF(index_obj); + Py_DECREF(value_obj); + return res >= 0; +} + +PyObject *CPyByteArray_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) { + if (likely(PyByteArray_CheckExact(obj) + && CPyTagged_CheckShort(start) && CPyTagged_CheckShort(end))) { + Py_ssize_t startn = CPyTagged_ShortAsSsize_t(start); + Py_ssize_t endn = CPyTagged_ShortAsSsize_t(end); + PyObject *result; + Py_BEGIN_CRITICAL_SECTION(obj); + Py_ssize_t size = PyByteArray_GET_SIZE(obj); + if (startn < 0) { + startn += size; + if (startn < 0) { + startn = 0; + } + } else if (startn > size) { + startn = size; + } + if (endn < 0) { + endn += size; + if (endn < 0) { + endn = 0; + } + } else if (endn > size) { + endn = size; + } + Py_ssize_t len = endn > startn ? endn - startn : 0; + result = PyByteArray_FromStringAndSize(PyByteArray_AS_STRING(obj) + startn, len); + Py_END_CRITICAL_SECTION(); + return result; + } + + // Generic path for subclasses and large indexes + PyObject *result = CPyObject_GetSlice(obj, start, end); + if (result != NULL && unlikely(!PyByteArray_Check(result))) { + // A subclass may override __getitem__ to return anything + CPy_TypeError("bytearray", result); + Py_DECREF(result); + return NULL; + } + return result; +} diff --git a/mypyc/lib-rt/bytearray_extra_ops.h b/mypyc/lib-rt/bytearray_extra_ops.h index 3fe973d23011..05e7eb96e38d 100644 --- a/mypyc/lib-rt/bytearray_extra_ops.h +++ b/mypyc/lib-rt/bytearray_extra_ops.h @@ -11,4 +11,13 @@ PyObject *CPyByteArray_New(void); // An omitted bound is represented by CPY_INT_TAG. PyObject *CPyByteArray_FromBytesSlice(PyObject *obj, CPyTagged start, CPyTagged end); +// bytearray[index] +CPyTagged CPyByteArray_GetItem(PyObject *obj, CPyTagged index); + +// bytearray[index] = value +bool CPyByteArray_SetItem(PyObject *obj, CPyTagged index, CPyTagged value); + +// bytearray[start:end] +PyObject *CPyByteArray_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end); + #endif diff --git a/mypyc/primitives/bytearray_ops.py b/mypyc/primitives/bytearray_ops.py index c02b3ee1c2a7..f8ea3db584b2 100644 --- a/mypyc/primitives/bytearray_ops.py +++ b/mypyc/primitives/bytearray_ops.py @@ -8,7 +8,7 @@ from __future__ import annotations from mypyc.ir.deps import BYTEARRAY_EXTRA_OPS -from mypyc.ir.ops import ERR_MAGIC, ERR_NEVER +from mypyc.ir.ops import ERR_FALSE, ERR_MAGIC, ERR_NEVER from mypyc.ir.rtypes import ( bit_rprimitive, bytearray_rprimitive, @@ -16,7 +16,7 @@ int_rprimitive, object_rprimitive, ) -from mypyc.primitives.registry import custom_primitive_op, function_op, load_address_op +from mypyc.primitives.registry import custom_primitive_op, function_op, load_address_op, method_op # Get the 'bytearray' type object. load_address_op(name="builtins.bytearray", type=object_rprimitive, src="PyByteArray_Type") @@ -59,3 +59,33 @@ c_function_name="PyByteArray_Check", error_kind=ERR_NEVER, ) + +# bytearray[index] +method_op( + name="__getitem__", + arg_types=[bytearray_rprimitive, int_rprimitive], + return_type=int_rprimitive, + c_function_name="CPyByteArray_GetItem", + error_kind=ERR_MAGIC, + dependencies=[BYTEARRAY_EXTRA_OPS], +) + +# bytearray[index] = value +method_op( + name="__setitem__", + arg_types=[bytearray_rprimitive, int_rprimitive, int_rprimitive], + return_type=bit_rprimitive, + c_function_name="CPyByteArray_SetItem", + error_kind=ERR_FALSE, + dependencies=[BYTEARRAY_EXTRA_OPS], +) + +# bytearray[begin:end] +bytearray_slice_op = custom_primitive_op( + name="bytearray_slice", + arg_types=[bytearray_rprimitive, int_rprimitive, int_rprimitive], + return_type=bytearray_rprimitive, + c_function_name="CPyByteArray_GetSlice", + error_kind=ERR_MAGIC, + dependencies=[BYTEARRAY_EXTRA_OPS], +) diff --git a/mypyc/primitives/bytes_ops.py b/mypyc/primitives/bytes_ops.py index 3b1b08613a25..9efeb108afb6 100644 --- a/mypyc/primitives/bytes_ops.py +++ b/mypyc/primitives/bytes_ops.py @@ -93,7 +93,6 @@ ) # bytes[index] -# bytearray[index] method_op( name="__getitem__", arg_types=[bytes_rprimitive, int_rprimitive], diff --git a/mypyc/test-data/fixtures/ir.py b/mypyc/test-data/fixtures/ir.py index 423bfcdb4c7b..035bae6c19b4 100644 --- a/mypyc/test-data/fixtures/ir.py +++ b/mypyc/test-data/fixtures/ir.py @@ -222,6 +222,7 @@ def endswith(self, t: bytes) -> bool: ... def append(self, x: int) -> None: ... def clear(self) -> None: ... def __iter__(self) -> Iterator[int]: ... + def __len__(self) -> int: ... class memoryview: def __init__(self, x: object) -> None: pass diff --git a/mypyc/test-data/irbuild-bytes.test b/mypyc/test-data/irbuild-bytes.test index 28acade030ae..9dea9d9dd647 100644 --- a/mypyc/test-data/irbuild-bytes.test +++ b/mypyc/test-data/irbuild-bytes.test @@ -257,6 +257,69 @@ L0: r1 = r0 << 1 return r1 +[case testBytearrayLen] +def f(b: bytearray) -> int: + return len(b) +[out] +def f(b): + b :: bytearray + r0 :: native_int + r1 :: short_int +L0: + r0 = var_object_size b + r1 = r0 << 1 + return r1 + +[case testBytearrayGetItem] +def f(b: bytearray, i: int) -> int: + return b[i] +[out] +def f(b, i): + b :: bytearray + i, r0 :: int +L0: + r0 = CPyByteArray_GetItem(b, i) + return r0 + +[case testBytearraySetItem] +def f(b: bytearray, i: int, x: int) -> None: + b[i] = x +[out] +def f(b, i, x): + b :: bytearray + i, x :: int + r0 :: bit +L0: + r0 = CPyByteArray_SetItem(b, i, x) + return 1 + +[case testBytearraySlice] +def f(b: bytearray, i: int, j: int) -> bytearray: + return b[i:j] +def g(b: bytearray, i: int, j: int, k: int) -> bytearray: + return b[i:j:k] +[out] +def f(b, i, j): + b :: bytearray + i, j :: int + r0 :: bytearray +L0: + r0 = CPyByteArray_GetSlice(b, i, j) + return r0 +def g(b, i, j, k): + b :: bytearray + i, j, k :: int + r0, r1, r2, r3, r4 :: object + r5 :: bytearray +L0: + r0 = box(int, i) + r1 = box(int, j) + r2 = box(int, k) + r3 = PySlice_New(r0, r1, r2) + r4 = PyObject_GetItem(b, r3) + r5 = cast(bytearray, r4) + return r5 + [case testBytesFormatting] def f(var: bytes, num: int) -> None: b1 = b'aaaa%bbbbb%s' % (var, var) diff --git a/mypyc/test-data/run-bytes.test b/mypyc/test-data/run-bytes.test index ebd666f3a11e..a847fa5f7ecb 100644 --- a/mypyc/test-data/run-bytes.test +++ b/mypyc/test-data/run-bytes.test @@ -692,6 +692,147 @@ class ByteArrayIterOverride(bytearray): def __iter__(self) -> Iterator[int]: yield 42 +[case testBytearrayPrimitivesMatchGeneric] +from typing import Any, Callable + +from testutil import assertRaises + +from basubclass import ByteArraySubclass, ByteArrayOverrides, WrongSliceType + +BIG_INTS = [2**31, 2**62 - 1, 2**62, 2**63, 2**70] + +def outcome(f: Callable[[], object]) -> object: + try: + return f() + except Exception as e: + return (type(e), str(e)) + +def test_len() -> None: + b = bytearray() + a: Any = b + for i in range(20): + assert len(b) == len(a) == i + a.append(i) + del a[3:7] + assert len(b) == len(a) == 16 + a.extend(b"xyz") + assert len(b) == len(a) == 19 + a.clear() + assert len(b) == len(a) == 0 + +def test_get_item() -> None: + b = bytearray(b"\x00\x7f\x80\xfe\xff") + a: Any = b + n = len(b) + for i in list(range(-n - 2, n + 2)) + BIG_INTS + [-x for x in BIG_INTS]: + assert outcome(lambda: b[i]) == outcome(lambda: a[i]), i + with assertRaises(IndexError, "bytearray index out of range"): + b[n + int()] + with assertRaises(IndexError, "bytearray index out of range"): + bytearray()[int()] + +def test_set_item() -> None: + values = [-1, 0, 1, 127, 128, 255, 256] + BIG_INTS + [-x for x in BIG_INTS] + n = 4 + for i in list(range(-n - 2, n + 2)) + BIG_INTS + [-x for x in BIG_INTS]: + for v in values: + b = bytearray(b"abcd") + a: Any = bytearray(b"abcd") + + def set_native() -> None: + b[i] = v + + def set_generic() -> None: + a[i] = v + + assert outcome(set_native) == outcome(set_generic), (i, v) + assert b == a, (i, v) + b = bytearray(b"abcd") + # The value is checked before the index, like in CPython + with assertRaises(ValueError, "byte must be in range(0, 256)"): + b[10 + int()] = 256 + with assertRaises(IndexError, "bytearray index out of range"): + b[10 + int()] = 255 + b[1] += 1 + b[-1] -= 2 + assert b == b"accb" + +def test_slice() -> None: + b = bytearray(b"abcdefg") + a: Any = b + n = len(b) + bounds = list(range(-n - 2, n + 3)) + BIG_INTS + [-x for x in BIG_INTS] + for i in bounds: + assert b[i:] == a[i:], i + assert b[:i] == a[:i], i + for j in bounds: + assert b[i:j] == a[i:j], (i, j) + assert type(b[i:j]) is bytearray + c = b[:] + assert c == b and c is not b + c[0] = ord("z") + assert b == b"abcdefg" + assert bytearray()[1:2] == bytearray() + +def test_subclass() -> None: + # Use bytearray as the static type, so that the primitives are used + s: bytearray = ByteArraySubclass(b"abc") + assert len(s) == 3 + assert s[1] == ord("b") + assert s[-1] == ord("c") + s[0] = ord("x") + assert s == b"xbc" + t = s[1:] + assert t == b"bc" + assert type(t) is bytearray + with assertRaises(IndexError, "bytearray index out of range"): + s[3 + int()] + + overrides = ByteArrayOverrides(b"abc") + o: bytearray = overrides + assert o[0] == 42 + assert o[-1] == 42 + o[1] = 5 + assert overrides.last_set == (1, 5) + assert o == b"abc" + assert o[0:2] == b"slice" + + wrong = WrongSliceType(b"abc") + w: bytearray = wrong + wrong.result = 1.5 + with assertRaises(TypeError, "bytearray object expected; got float"): + w[0:2] + wrong.result = b"bc" + with assertRaises(TypeError, "bytearray object expected; got bytes"): + w[1:] + wrong.result = ByteArraySubclass(b"bc") + assert w[1:] == b"bc" + +[file basubclass.py] +from typing import Any + +class ByteArraySubclass(bytearray): + pass + +class ByteArrayOverrides(bytearray): + last_set: Any = None + + def __getitem__(self, i: Any) -> Any: + if isinstance(i, slice): + return bytearray(b"slice") + return 42 + + def __setitem__(self, i: Any, v: Any) -> None: + self.last_set = (i, v) + +class WrongSliceType(bytearray): + result: Any = None + + def __getitem__(self, i: Any) -> Any: + if isinstance(i, slice): + return self.result + return super().__getitem__(i) + [case testBytesJoin] from typing import Any from testutil import assertRaises