Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions mypyc/lib-rt/CPy.h
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,8 @@ PyObject *CPyList_Extend(PyObject *o1, PyObject *o2);
int CPyList_Remove(PyObject *list, PyObject *obj);
CPyTagged CPyList_Index(PyObject *list, PyObject *obj);
PyObject *CPySequence_Sort(PyObject *seq);
PyObject *CPySequence_Concat(PyObject *seq, PyObject *other);
PyObject *CPySequence_InPlaceConcat(PyObject *seq, PyObject *other);
PyObject *CPySequence_Multiply(PyObject *seq, CPyTagged t_size);
PyObject *CPySequence_RMultiply(CPyTagged t_size, PyObject *seq);
PyObject *CPySequence_InPlaceMultiply(PyObject *seq, CPyTagged t_size);
Expand Down
9 changes: 8 additions & 1 deletion mypyc/lib-rt/dict_ops.c
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,14 @@ PyObject *CPyDict_Copy(PyObject *dict) {
if (PyDict_CheckExact(dict)) {
return PyDict_Copy(dict);
}
return PyObject_CallMethodNoArgs(dict, mypyc_interned_str.copy);
PyObject *res = PyObject_CallMethodNoArgs(dict, mypyc_interned_str.copy);
// An overriding method in a subclass can return an arbitrary object
if (res != NULL && !PyDict_Check(res)) {
CPy_TypeError("dict", res);
Py_DECREF(res);
return NULL;
}
return res;
}

PyObject *CPyDict_GetKeysIter(PyObject *dict) {
Expand Down
47 changes: 43 additions & 4 deletions mypyc/lib-rt/list_ops.c
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,35 @@ char CPyList_Clear(PyObject *list) {
return 1;
}

// Operations on list and tuple subclasses may call an overriding method that returns an
// arbitrary object. Check that the result is a list if seq is a list, or a tuple otherwise
// (only lists and tuples are supported), since callers rely on the result type.
static PyObject *CPySequence_CheckResult(PyObject *seq, PyObject *res) {
if (res == NULL) {
return NULL;
}
const char *expected;
if (PyList_Check(seq)) {
if (PyList_Check(res)) {
return res;
}
expected = "list";
} else {
if (PyTuple_Check(res)) {
return res;
}
expected = "tuple";
}
CPy_TypeError(expected, res);
Py_DECREF(res);
return NULL;
}

PyObject *CPyList_Copy(PyObject *list) {
if(PyList_CheckExact(list)) {
return PyList_GetSlice(list, 0, PyList_GET_SIZE(list));
}
return PyObject_CallMethodNoArgs(list, mypyc_interned_str.copy);
return CPySequence_CheckResult(list, PyObject_CallMethodNoArgs(list, mypyc_interned_str.copy));
}

#ifndef Py_GIL_DISABLED
Expand Down Expand Up @@ -424,24 +448,39 @@ PyObject *CPySequence_Sort(PyObject *seq) {
return newlist;
}

PyObject *CPySequence_Concat(PyObject *seq, PyObject *other) {
return CPySequence_CheckResult(seq, PySequence_Concat(seq, other));
}

PyObject *CPySequence_InPlaceConcat(PyObject *seq, PyObject *other) {
return CPySequence_CheckResult(seq, PySequence_InPlaceConcat(seq, other));
}

PyObject *CPySequence_Multiply(PyObject *seq, CPyTagged t_size) {
Py_ssize_t size = CPyTagged_AsSsize_t(t_size);
if (size == -1 && PyErr_Occurred()) {
return NULL;
}
return PySequence_Repeat(seq, size);
return CPySequence_CheckResult(seq, PySequence_Repeat(seq, size));
}

PyObject *CPySequence_RMultiply(CPyTagged t_size, PyObject *seq) {
return CPySequence_Multiply(seq, t_size);
if (PyList_CheckExact(seq) || PyTuple_CheckExact(seq)) {
return CPySequence_Multiply(seq, t_size);
}
// Use the generic operation so that __rmul__ is called on subclasses
PyObject *size = CPyTagged_AsObject(t_size);
PyObject *res = PyNumber_Multiply(size, seq);
Py_DECREF(size);
return CPySequence_CheckResult(seq, res);
}

PyObject *CPySequence_InPlaceMultiply(PyObject *seq, CPyTagged t_size) {
Py_ssize_t size = CPyTagged_AsSsize_t(t_size);
if (size == -1 && PyErr_Occurred()) {
return NULL;
}
return PySequence_InPlaceRepeat(seq, size);
return CPySequence_CheckResult(seq, PySequence_InPlaceRepeat(seq, size));
}

PyObject *CPyList_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) {
Expand Down
8 changes: 6 additions & 2 deletions mypyc/lib-rt/str_ops.c
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,9 @@ PyObject *CPyStr_Multiply(PyObject *str, CPyTagged count) {
PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);
return NULL;
}
return PySequence_Repeat(str, temp_count);
// Use the str implementation directly (like PyUnicode_Concat does for str + str), so
// that the result is always an exact str even if a subclass overrides __mul__.
return PyUnicode_Type.tp_as_sequence->sq_repeat(str, temp_count);
}


Expand Down Expand Up @@ -728,7 +730,9 @@ static inline PyObject *CPyStr_ChangeCase(PyObject *self,
#if CPY_3_13_FEATURES
// On 3.13+, _PyUnicode_ToLowerFull/ToUpperFull are no longer exported,
// so fall back to CPython's method implementation for non-ASCII strings.
return PyObject_CallMethodNoArgs(self, method_name);
// The method is looked up on str (not on the type of self), so that the
// result is always an exact str even if a subclass overrides it.
return PyObject_CallMethodOneArg((PyObject *)&PyUnicode_Type, method_name, self);
#else
// General Unicode: unicode_func handles 1-to-N expansion.
// Worst case: each codepoint expands to 3 (per Unicode standard).
Expand Down
4 changes: 2 additions & 2 deletions mypyc/primitives/list_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@
name="+",
arg_types=[list_rprimitive, list_rprimitive],
return_type=list_rprimitive,
c_function_name="PySequence_Concat",
c_function_name="CPySequence_Concat",
error_kind=ERR_MAGIC,
)

Expand All @@ -317,7 +317,7 @@
name="+=",
arg_types=[list_rprimitive, object_rprimitive],
return_type=list_rprimitive,
c_function_name="PySequence_InPlaceConcat",
c_function_name="CPySequence_InPlaceConcat",
error_kind=ERR_MAGIC,
)

Expand Down
2 changes: 1 addition & 1 deletion mypyc/primitives/tuple_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@
name="+",
arg_types=[tuple_rprimitive, tuple_rprimitive],
return_type=tuple_rprimitive,
c_function_name="PySequence_Concat",
c_function_name="CPySequence_Concat",
error_kind=ERR_MAGIC,
)

Expand Down
4 changes: 2 additions & 2 deletions mypyc/test-data/irbuild-lists.test
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def f(a: List[int], b: List[int]) -> None:
def f(a, b):
a, b, r0, c :: list
L0:
r0 = PySequence_Concat(a, b)
r0 = CPySequence_Concat(a, b)
c = r0
return 1

Expand All @@ -185,7 +185,7 @@ def f(a, b):
b :: object
r0 :: list
L0:
r0 = PySequence_InPlaceConcat(a, b)
r0 = CPySequence_InPlaceConcat(a, b)
a = r0
return 1

Expand Down
6 changes: 3 additions & 3 deletions mypyc/test-data/irbuild-tuple.test
Original file line number Diff line number Diff line change
Expand Up @@ -1101,11 +1101,11 @@ def f(a, b):
r2 :: object
r3, d :: tuple
L0:
r0 = PySequence_Concat(a, b)
r0 = CPySequence_Concat(a, b)
c = r0
r1 = (2, 4)
r2 = box(tuple[int, int], r1)
r3 = PySequence_Concat(a, r2)
r3 = CPySequence_Concat(a, r2)
d = r3
return 1
def g(a, b):
Expand All @@ -1116,7 +1116,7 @@ def g(a, b):
L0:
r0 = box(tuple[int, int], a)
r1 = box(tuple[int, int], b)
r2 = PySequence_Concat(r0, r1)
r2 = CPySequence_Concat(r0, r1)
r3 = unbox(tuple[int, int, int, int], r2)
c = r3
return 1
Expand Down
29 changes: 29 additions & 0 deletions mypyc/test-data/run-dicts.test
Original file line number Diff line number Diff line change
Expand Up @@ -630,3 +630,32 @@ for convert in (keys, values, items):
gc.collect()
assert all(ref() is None for ref in refs)
assert convert(CustomDict(iter([1, 2]))) == [1, 2]

[case testDictCopyOverridingSubclass]
from typing import Dict
from testutil import assertRaises
from dictsub import BadDict, GoodDict

def copy(d: Dict[int, int]) -> Dict[int, int]:
return d.copy()

def test_bad_result_type() -> None:
d: Dict[int, int] = BadDict({1: 2})
with assertRaises(TypeError, "dict object expected; got int"):
copy(d)

def test_override_called() -> None:
d: Dict[int, int] = GoodDict({1: 2})
assert copy(d) == {1: 2, 3: 4}
assert type(copy(d)) is GoodDict

[file dictsub.py]
from typing import Any

class BadDict(dict):
def copy(self) -> Any:
return 1

class GoodDict(dict):
def copy(self) -> Any:
return GoodDict({**self, 3: 4})
83 changes: 83 additions & 0 deletions mypyc/test-data/run-lists.test
Original file line number Diff line number Diff line change
Expand Up @@ -731,3 +731,86 @@ for index in (0, -1):
items = [Reentrant()]
assign(items, index, None)
assert items == []

[case testListOpsOverridingSubclass]
from typing import List
from testutil import assertRaises
from listsub import BadList, GoodList

def add(a: List[int], b: List[int]) -> List[int]:
return a + b

def iadd(a: List[int], b: List[int]) -> List[int]:
a += b
return a

def mul(a: List[int], n: int) -> List[int]:
return a * n

def rmul(a: List[int], n: int) -> List[int]:
return n * a

def imul(a: List[int], n: int) -> List[int]:
a *= n
return a

def copy(a: List[int]) -> List[int]:
return a.copy()

def test_bad_result_type() -> None:
a: List[int] = BadList([1])
with assertRaises(TypeError, "list object expected; got int"):
add(a, [2])
with assertRaises(TypeError, "list object expected; got int"):
iadd(a, [2])
with assertRaises(TypeError, "list object expected; got int"):
mul(a, 2)
with assertRaises(TypeError, "list object expected; got int"):
rmul(a, 2)
with assertRaises(TypeError, "list object expected; got int"):
imul(a, 2)
with assertRaises(TypeError, "list object expected; got int"):
copy(a)

def test_overrides_called() -> None:
a: List[int] = GoodList([1])
assert add(a, [2]) == [1, 2, 0]
assert iadd(a, [2]) == [1, 2, 1]
assert mul(a, 2) == [1, 1, 2]
assert rmul(a, 2) == [1, 1, 3]
assert imul(a, 2) == [1, 1, 4]
assert copy(a) == [1, 5]
assert type(copy(a)) is GoodList
assert a == [1]
assert rmul([1], 2) == [1, 1]

[file listsub.py]
from typing import Any

class BadList(list):
def __add__(self, other: Any) -> Any:
return 1
def __iadd__(self, other: Any) -> Any:
return 2
def __mul__(self, n: Any) -> Any:
return 3
def __rmul__(self, n: Any) -> Any:
return 4
def __imul__(self, n: Any) -> Any:
return 5
def copy(self) -> Any:
return 6

class GoodList(list):
def __add__(self, other: Any) -> Any:
return GoodList(list(self) + other + [0])
def __iadd__(self, other: Any) -> Any:
return GoodList(list(self) + other + [1])
def __mul__(self, n: Any) -> Any:
return GoodList(list(self) * n + [2])
def __rmul__(self, n: Any) -> Any:
return GoodList(list(self) * n + [3])
def __imul__(self, n: Any) -> Any:
return GoodList(list(self) * n + [4])
def copy(self) -> Any:
return GoodList(list(self) + [5])
48 changes: 48 additions & 0 deletions mypyc/test-data/run-strings.test
Original file line number Diff line number Diff line change
Expand Up @@ -1470,3 +1470,51 @@ def test_out_of_range_raises_indexerror() -> None:
eq_comma(s, 3)
with assertRaises(IndexError):
eq_comma(s, -4)

[case testStrOpsOverridingSubclass]
from strsub import StrOverride

def mul(s: str, n: int) -> str:
return s * n

def rmul(s: str, n: int) -> str:
return n * s

def lower(s: str) -> str:
return s.lower()

def upper(s: str) -> str:
return s.upper()

def test_multiply() -> None:
# Overrides aren't used, and the result is always an exact str
for s in ["", "a", "ab\xe9"]:
sub: str = StrOverride(s)
for n in [-1, 0, 1, 3]:
for res in [mul(sub, n), rmul(sub, n)]:
assert type(res) is str
assert res == s * n
assert len(res) == len(s * n)

def test_lower_upper() -> None:
for s in ["Hello", "\xc9cole Σ", "İ", "\xdf"]:
sub: str = StrOverride(s)
assert type(lower(sub)) is str
assert lower(sub) == s.lower()
assert len(lower(sub)) == len(s.lower())
assert type(upper(sub)) is str
assert upper(sub) == s.upper()
assert len(upper(sub)) == len(s.upper())

[file strsub.py]
from typing import Any

class StrOverride(str):
def __mul__(self, n: Any) -> Any:
return 12345678901234567890
def __rmul__(self, n: Any) -> Any:
return 12345678901234567891
def lower(self) -> Any:
return 12345678901234567892
def upper(self) -> Any:
return 12345678901234567893
Loading
Loading