diff --git a/mypyc/lib-rt/dict_ops.c b/mypyc/lib-rt/dict_ops.c index 5c1d0c7a48e98..1ece9517f3fbd 100644 --- a/mypyc/lib-rt/dict_ops.c +++ b/mypyc/lib-rt/dict_ops.c @@ -72,8 +72,10 @@ PyObject *CPyDict_GetWithNone(PyObject *dict, PyObject *key) { PyObject *CPyDict_SetDefault(PyObject *dict, PyObject *key, PyObject *value) { if (PyDict_CheckExact(dict)) { - PyObject* ret = PyDict_SetDefault(dict, key, value); - Py_XINCREF(ret); + PyObject *ret; + if (PyDict_SetDefaultRef(dict, key, value, &ret) < 0) { + return NULL; + } return ret; } return PyObject_CallMethodObjArgs(dict, mypyc_interned_str.setdefault, key, value, NULL); @@ -85,42 +87,31 @@ PyObject *CPyDict_SetDefaultWithNone(PyObject *dict, PyObject *key) { PyObject *CPyDict_SetDefaultWithEmptyDatatype(PyObject *dict, PyObject *key, int data_type) { - PyObject *res; if (PyDict_CheckExact(dict)) { + // Fast path: avoid creating the empty collection if the key exists + PyObject *res; int found = PyDict_GetItemRef(dict, key, &res); - if (found < 0) { - return NULL; + if (found != 0) { + return res; } + } + PyObject *new_obj; + if (data_type == 1) { + new_obj = PyList_New(0); + } else if (data_type == 2) { + new_obj = PyDict_New(); + } else if (data_type == 3) { + new_obj = PySet_New(NULL); } else { - res = PyObject_GetItem(dict, key); - if (!res) { - if (!PyErr_ExceptionMatches(PyExc_KeyError)) { - return NULL; - } - PyErr_Clear(); - } + new_obj = NULL; } - if (!res) { - PyObject *new_obj; - if (data_type == 1) { - new_obj = PyList_New(0); - } else if (data_type == 2) { - new_obj = PyDict_New(); - } else if (data_type == 3) { - new_obj = PySet_New(NULL); - } else { - new_obj = NULL; - } - - if (new_obj == NULL) { - res = NULL; - } else if (CPyDict_SetItem(dict, key, new_obj) == -1) { - Py_DECREF(new_obj); - res = NULL; - } else { - res = new_obj; - } + if (new_obj == NULL) { + return NULL; } + // Use setdefault (not get + set) so that this is atomic for exact dicts + // on free-threaded builds and respects overridden methods in subclasses + PyObject *res = CPyDict_SetDefault(dict, key, new_obj); + Py_DECREF(new_obj); return res; } diff --git a/mypyc/lib-rt/pythonsupport.h b/mypyc/lib-rt/pythonsupport.h index 2d3eef3bd740c..631d77cf33e83 100644 --- a/mypyc/lib-rt/pythonsupport.h +++ b/mypyc/lib-rt/pythonsupport.h @@ -448,7 +448,11 @@ list_count(PyListObject *self, PyObject *value) } #else for (i = 0; i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ); + PyObject *item = self->ob_item[i]; + // The comparison may mutate the list, so keep the item alive. + Py_INCREF(item); + int cmp = PyObject_RichCompareBool(item, value, Py_EQ); + Py_DECREF(item); if (cmp > 0) count++; else if (cmp < 0) diff --git a/mypyc/primitives/list_ops.py b/mypyc/primitives/list_ops.py index f5548e88592f1..bbe33c6100cd4 100644 --- a/mypyc/primitives/list_ops.py +++ b/mypyc/primitives/list_ops.py @@ -367,7 +367,7 @@ arg_types=[object_rprimitive, c_pyssize_t_rprimitive], return_type=object_rprimitive, c_function_name="PySequence_GetItem", - error_kind=ERR_NEVER, + error_kind=ERR_MAGIC, ) sequence_get_slice = custom_op( diff --git a/mypyc/test-data/run-dicts.test b/mypyc/test-data/run-dicts.test index 609c21bbcf21a..8d5248de7899a 100644 --- a/mypyc/test-data/run-dicts.test +++ b/mypyc/test-data/run-dicts.test @@ -365,6 +365,44 @@ def test_lookup_error_propagation() -> None: assert d == {} assert default(d, "present") is default(d, "present") +def test_empty_collection_setdefault_subclass() -> None: + from collections import Counter + from dictsubclasses import MissingDict, SetDefaultDict + + for default, empty in ((default_list, []), (default_dict, {}), (default_set, set())): + # Counter.__missing__ returns 0, but setdefault must still insert + d: Dict[Any, Any] = Counter() + assert default(d, "x") == empty + assert d == {"x": empty} + assert default(d, "x") is d["x"] + + # __missing__ isn't used by setdefault + d = MissingDict() + assert default(d, "x") == empty + assert d == {"x": empty} + + sd = SetDefaultDict() + assert default(sd, "x") == empty + assert sd.calls == [("x", empty)] + assert sd == {} + + d = defaultdict(int) + assert default(d, "x") == empty + assert d == {"x": empty} + +[file dictsubclasses.py] +class MissingDict(dict): + def __missing__(self, key): + return "missing" + +class SetDefaultDict(dict): + def __init__(self): + self.calls = [] + + def setdefault(self, key, default=None): + self.calls.append((key, default)) + return default + [case testDictToBool] from typing import Dict, List diff --git a/mypyc/test-data/run-lists.test b/mypyc/test-data/run-lists.test index ccb24de3514f9..df9e0dd37931f 100644 --- a/mypyc/test-data/run-lists.test +++ b/mypyc/test-data/run-lists.test @@ -364,6 +364,43 @@ def test_index() -> None: else: assert False +[case testListCountEqMutatesList] +from typing import Any + +from listcounthelper import X, Y + +def count(a: list[Any], x: Any) -> int: + return a.count(x) + +def test_count_eq_clears_list() -> None: + lst: list[Any] = [] + lst.append(X(lst)) + y = Y() + assert count(lst, y) == 0 + assert lst == [] + assert y.seen == ["X"] + +[file listcounthelper.py] +from typing import Any + +class X: + def __init__(self, lst: list[Any]) -> None: + self.lst = lst + + def __eq__(self, other: object) -> bool: + # Drop the list's (only) reference to self, then force the reflected + # comparison, which receives self as the argument + self.lst.clear() + return NotImplemented + +class Y: + def __init__(self) -> None: + self.seen: list[str] = [] + + def __eq__(self, other: object) -> bool: + self.seen.append(type(other).__name__) + return False + [case testListOfUserDefinedClass] class C: x: int diff --git a/mypyc/test-data/run-match.test b/mypyc/test-data/run-match.test index b24552072a655..94d1d17cf769a 100644 --- a/mypyc/test-data/run-match.test +++ b/mypyc/test-data/run-match.test @@ -302,3 +302,38 @@ f(sequence) [out] {'some': 'data'} [3] + +[case testSequencePatternGetItemRaises_python3_10] +def f(x: object) -> object: + match x: + case [a, b]: + return a + return None + +def g(x: object) -> object: + match x: + case [1, *rest, b]: + return b + return None + +[file driver.py] +from collections.abc import Sequence + +from native import f, g + +class BadSequence(Sequence): + def __len__(self) -> int: + return 2 + + def __getitem__(self, index: int) -> None: + raise RuntimeError("boom") + +for fn in (f, g): + try: + fn(BadSequence()) + except RuntimeError as e: + print(type(e).__name__, e) + +[out] +RuntimeError boom +RuntimeError boom