/src/cpython/Objects/iterobject.c
Line | Count | Source |
1 | | /* Iterator objects */ |
2 | | |
3 | | #include "Python.h" |
4 | | #include "pycore_abstract.h" // _PyObject_HasLen() |
5 | | #include "pycore_call.h" // _PyObject_CallNoArgs() |
6 | | #include "pycore_ceval.h" // _PyEval_GetBuiltin() |
7 | | #include "pycore_genobject.h" // _PyCoro_GetAwaitableIter() |
8 | | #include "pycore_iterobject.h" // _PyCallIter_NewEx() |
9 | | #include "pycore_object.h" // _PyObject_GC_TRACK() |
10 | | #include "pycore_pyatomic_ft_wrappers.h" // FT_ATOMIC_LOAD_SSIZE_RELAXED() |
11 | | #include "pycore_pyerrors.h" // _PyErr_FormatFromCause() |
12 | | #include "pycore_pystate.h" // _PyThreadState_GET() |
13 | | |
14 | | |
15 | | typedef struct { |
16 | | PyObject_HEAD |
17 | | Py_ssize_t it_index; /* -1 when iterator is exhausted */ |
18 | | PyObject *it_seq; /* Set to NULL when iterator is exhausted |
19 | | (in the default build) */ |
20 | | } seqiterobject; |
21 | | |
22 | | PyObject * |
23 | | PySeqIter_New(PyObject *seq) |
24 | 2.36M | { |
25 | 2.36M | seqiterobject *it; |
26 | | |
27 | 2.36M | if (!PySequence_Check(seq)) { |
28 | 0 | PyErr_BadInternalCall(); |
29 | 0 | return NULL; |
30 | 0 | } |
31 | 2.36M | it = PyObject_GC_New(seqiterobject, &PySeqIter_Type); |
32 | 2.36M | if (it == NULL) |
33 | 0 | return NULL; |
34 | 2.36M | it->it_index = 0; |
35 | 2.36M | it->it_seq = Py_NewRef(seq); |
36 | 2.36M | _PyObject_GC_TRACK(it); |
37 | 2.36M | return (PyObject *)it; |
38 | 2.36M | } |
39 | | |
40 | | static void |
41 | | iter_dealloc(PyObject *op) |
42 | 2.36M | { |
43 | 2.36M | seqiterobject *it = (seqiterobject*)op; |
44 | 2.36M | _PyObject_GC_UNTRACK(it); |
45 | 2.36M | Py_XDECREF(it->it_seq); |
46 | 2.36M | PyObject_GC_Del(it); |
47 | 2.36M | } |
48 | | |
49 | | static int |
50 | | iter_traverse(PyObject *op, visitproc visit, void *arg) |
51 | 6.86k | { |
52 | 6.86k | seqiterobject *it = (seqiterobject*)op; |
53 | 6.86k | Py_VISIT(it->it_seq); |
54 | 6.86k | return 0; |
55 | 6.86k | } |
56 | | |
57 | | static PyObject * |
58 | | iter_iternext(PyObject *iterator) |
59 | 9.85M | { |
60 | 9.85M | seqiterobject *it; |
61 | 9.85M | PyObject *seq; |
62 | 9.85M | PyObject *result; |
63 | | |
64 | 9.85M | assert(PySeqIter_Check(iterator)); |
65 | 9.85M | it = (seqiterobject *)iterator; |
66 | 9.85M | Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index); |
67 | 9.85M | if (index < 0) |
68 | 0 | return NULL; |
69 | 9.85M | seq = it->it_seq; |
70 | 9.85M | #ifndef Py_GIL_DISABLED |
71 | 9.85M | if (seq == NULL) |
72 | 0 | return NULL; |
73 | 9.85M | #endif |
74 | 9.85M | if (index == PY_SSIZE_T_MAX) { |
75 | 0 | PyErr_SetString(PyExc_OverflowError, |
76 | 0 | "iter index too large"); |
77 | 0 | return NULL; |
78 | 0 | } |
79 | | |
80 | 9.85M | result = PySequence_GetItem(seq, index); |
81 | 9.85M | if (result != NULL) { |
82 | | /* PySequence_GetItem() can exhaust the iterator re-entrantly. |
83 | | * Preserve the exhaustion sentinel if it is observed. Concurrent |
84 | | * exhaustion can still race with the store, but remains memory-safe |
85 | | * because the sequence stays alive. */ |
86 | 7.48M | if (FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index) >= 0) { |
87 | 7.48M | FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index + 1); |
88 | 7.48M | } |
89 | 7.48M | return result; |
90 | 7.48M | } |
91 | 2.36M | if (PyErr_ExceptionMatches(PyExc_IndexError) || |
92 | 0 | PyErr_ExceptionMatches(PyExc_StopIteration)) |
93 | 2.36M | { |
94 | | /* Mark the iterator exhausted before anything that can run |
95 | | * arbitrary code. */ |
96 | 2.36M | FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, -1); |
97 | 2.36M | #ifndef Py_GIL_DISABLED |
98 | 2.36M | Py_CLEAR(it->it_seq); |
99 | 2.36M | #endif |
100 | 2.36M | PyErr_Clear(); |
101 | 2.36M | } |
102 | 2.36M | return NULL; |
103 | 9.85M | } |
104 | | |
105 | | static PyObject * |
106 | | iter_len(PyObject *op, PyObject *Py_UNUSED(ignored)) |
107 | 6.55k | { |
108 | 6.55k | seqiterobject *it = (seqiterobject*)op; |
109 | 6.55k | Py_ssize_t seqsize, len; |
110 | | |
111 | 6.55k | Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index); |
112 | 6.55k | if (index >= 0 && it->it_seq != NULL) { |
113 | 6.55k | if (_PyObject_HasLen(it->it_seq)) { |
114 | 6.55k | seqsize = PySequence_Size(it->it_seq); |
115 | 6.55k | if (seqsize == -1) |
116 | 0 | return NULL; |
117 | 6.55k | } |
118 | 0 | else { |
119 | 0 | Py_RETURN_NOTIMPLEMENTED; |
120 | 0 | } |
121 | 6.55k | len = seqsize - index; |
122 | 6.55k | if (len >= 0) |
123 | 6.55k | return PyLong_FromSsize_t(len); |
124 | 6.55k | } |
125 | 0 | return PyLong_FromLong(0); |
126 | 6.55k | } |
127 | | |
128 | | PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); |
129 | | |
130 | | static PyObject * |
131 | | iter_reduce(PyObject *op, PyObject *Py_UNUSED(ignored)) |
132 | 0 | { |
133 | 0 | seqiterobject *it = (seqiterobject*)op; |
134 | 0 | PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter)); |
135 | | |
136 | | /* _PyEval_GetBuiltin can invoke arbitrary code, |
137 | | * call must be before access of iterator pointers. |
138 | | * see issue #101765 */ |
139 | |
|
140 | 0 | Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index); |
141 | 0 | if (index >= 0 && it->it_seq != NULL) |
142 | 0 | return Py_BuildValue("N(O)n", iter, it->it_seq, index); |
143 | 0 | else |
144 | 0 | return Py_BuildValue("N(())", iter); |
145 | 0 | } |
146 | | |
147 | | PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); |
148 | | |
149 | | static PyObject * |
150 | | iter_setstate(PyObject *op, PyObject *state) |
151 | 0 | { |
152 | 0 | seqiterobject *it = (seqiterobject*)op; |
153 | 0 | Py_ssize_t index = PyLong_AsSsize_t(state); |
154 | 0 | if (index == -1 && PyErr_Occurred()) |
155 | 0 | return NULL; |
156 | 0 | if (index < 0) |
157 | 0 | index = 0; |
158 | 0 | if (it->it_seq && FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index) >= 0) { |
159 | 0 | FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index); |
160 | 0 | } |
161 | 0 | Py_RETURN_NONE; |
162 | 0 | } |
163 | | |
164 | | PyDoc_STRVAR(setstate_doc, "Set state information for unpickling."); |
165 | | |
166 | | static PyMethodDef seqiter_methods[] = { |
167 | | {"__length_hint__", iter_len, METH_NOARGS, length_hint_doc}, |
168 | | {"__reduce__", iter_reduce, METH_NOARGS, reduce_doc}, |
169 | | {"__setstate__", iter_setstate, METH_O, setstate_doc}, |
170 | | {NULL, NULL} /* sentinel */ |
171 | | }; |
172 | | |
173 | | PyTypeObject PySeqIter_Type = { |
174 | | PyVarObject_HEAD_INIT(&PyType_Type, 0) |
175 | | "iterator", /* tp_name */ |
176 | | sizeof(seqiterobject), /* tp_basicsize */ |
177 | | 0, /* tp_itemsize */ |
178 | | /* methods */ |
179 | | iter_dealloc, /* tp_dealloc */ |
180 | | 0, /* tp_vectorcall_offset */ |
181 | | 0, /* tp_getattr */ |
182 | | 0, /* tp_setattr */ |
183 | | 0, /* tp_as_async */ |
184 | | 0, /* tp_repr */ |
185 | | 0, /* tp_as_number */ |
186 | | 0, /* tp_as_sequence */ |
187 | | 0, /* tp_as_mapping */ |
188 | | 0, /* tp_hash */ |
189 | | 0, /* tp_call */ |
190 | | 0, /* tp_str */ |
191 | | PyObject_GenericGetAttr, /* tp_getattro */ |
192 | | 0, /* tp_setattro */ |
193 | | 0, /* tp_as_buffer */ |
194 | | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ |
195 | | 0, /* tp_doc */ |
196 | | iter_traverse, /* tp_traverse */ |
197 | | 0, /* tp_clear */ |
198 | | 0, /* tp_richcompare */ |
199 | | 0, /* tp_weaklistoffset */ |
200 | | PyObject_SelfIter, /* tp_iter */ |
201 | | iter_iternext, /* tp_iternext */ |
202 | | seqiter_methods, /* tp_methods */ |
203 | | 0, /* tp_members */ |
204 | | }; |
205 | | |
206 | | /* -------------------------------------- */ |
207 | | |
208 | | typedef struct { |
209 | | PyObject_HEAD |
210 | | PyObject *it_callable; /* set to NULL when the iterator is exhausted */ |
211 | | PyObject *it_sentinel; /* can be NULL, and is when exhausted */ |
212 | | PyObject *it_stop_exc; /* never NULL */ |
213 | | } calliterobject; |
214 | | |
215 | | PyObject * |
216 | | _PyCallIter_NewEx(PyObject *callable, PyObject *sentinel, PyObject *stop_exc) |
217 | 427k | { |
218 | 427k | calliterobject *it; |
219 | 427k | if (stop_exc == NULL) { |
220 | 427k | stop_exc = PyExc_StopIteration; |
221 | 427k | } |
222 | 0 | else if (_PyEval_CheckExceptTypeValid(_PyThreadState_GET(), stop_exc) < 0) { |
223 | 0 | return NULL; |
224 | 0 | } |
225 | 427k | it = PyObject_GC_New(calliterobject, &PyCallIter_Type); |
226 | 427k | if (it == NULL) |
227 | 0 | return NULL; |
228 | 427k | it->it_callable = Py_NewRef(callable); |
229 | 427k | it->it_sentinel = Py_XNewRef(sentinel); |
230 | 427k | it->it_stop_exc = Py_NewRef(stop_exc); |
231 | 427k | _PyObject_GC_TRACK(it); |
232 | 427k | return (PyObject *)it; |
233 | 427k | } |
234 | | |
235 | | PyObject * |
236 | | PyCallIter_New(PyObject *callable, PyObject *sentinel) |
237 | 427k | { |
238 | 427k | return _PyCallIter_NewEx(callable, sentinel, NULL); |
239 | 427k | } |
240 | | |
241 | | // Sharing a callable iterator between threads, or calling __setstate__() |
242 | | // on an iterator that is in use, is not supported: the values produced are |
243 | | // unspecified, but the interpreter must not crash. |
244 | | |
245 | | static inline PyObject * |
246 | | calliter_swap(PyObject **field, PyObject *value) |
247 | 855k | { |
248 | | #ifdef Py_GIL_DISABLED |
249 | | return _Py_atomic_exchange_ptr(field, value); |
250 | | #else |
251 | 855k | PyObject *old = *field; |
252 | 855k | *field = value; |
253 | 855k | return old; |
254 | 855k | #endif |
255 | 855k | } |
256 | | |
257 | | static inline PyObject * |
258 | | calliter_load(PyObject **field) |
259 | 7.91M | { |
260 | 7.91M | return Py_XNewRef(FT_ATOMIC_LOAD_PTR_ACQUIRE(*field)); |
261 | 7.91M | } |
262 | | |
263 | | static void |
264 | | calliter_exhaust(calliterobject *it) |
265 | 427k | { |
266 | 427k | _PyObject_XDecRefDelayed(calliter_swap(&it->it_callable, NULL)); |
267 | 427k | _PyObject_XDecRefDelayed(calliter_swap(&it->it_sentinel, NULL)); |
268 | 427k | } |
269 | | |
270 | | static void |
271 | | calliter_dealloc(PyObject *op) |
272 | 427k | { |
273 | 427k | calliterobject *it = (calliterobject*)op; |
274 | 427k | _PyObject_GC_UNTRACK(it); |
275 | 427k | Py_XDECREF(it->it_callable); |
276 | 427k | Py_XDECREF(it->it_sentinel); |
277 | 427k | Py_XDECREF(it->it_stop_exc); |
278 | 427k | PyObject_GC_Del(it); |
279 | 427k | } |
280 | | |
281 | | static int |
282 | | calliter_traverse(PyObject *op, visitproc visit, void *arg) |
283 | 1.13k | { |
284 | 1.13k | calliterobject *it = (calliterobject*)op; |
285 | 1.13k | Py_VISIT(it->it_callable); |
286 | 1.13k | Py_VISIT(it->it_sentinel); |
287 | 1.13k | Py_VISIT(it->it_stop_exc); |
288 | 1.13k | return 0; |
289 | 1.13k | } |
290 | | |
291 | | static PyObject * |
292 | | calliter_iternext(PyObject *op) |
293 | 3.95M | { |
294 | 3.95M | calliterobject *it = (calliterobject*)op; |
295 | 3.95M | PyObject *callable, *sentinel, *stop_exc, *result; |
296 | | |
297 | 3.95M | callable = calliter_load(&it->it_callable); |
298 | 3.95M | if (callable == NULL) { |
299 | 0 | return NULL; |
300 | 0 | } |
301 | 3.95M | result = _PyObject_CallNoArgs(callable); |
302 | 3.95M | Py_DECREF(callable); |
303 | | |
304 | | /* The call can exhaust the iterator re-entrantly. */ |
305 | 3.95M | if (result != NULL && |
306 | 3.95M | FT_ATOMIC_LOAD_PTR_RELAXED(it->it_callable) != NULL) |
307 | 3.95M | { |
308 | 3.95M | sentinel = calliter_load(&it->it_sentinel); |
309 | 3.95M | if (sentinel == NULL) { |
310 | 0 | return result; /* Common case, fast path */ |
311 | 0 | } |
312 | | /* The comparison can run code that replaces the sentinel. */ |
313 | 3.95M | int ok = PyObject_RichCompareBool(sentinel, result, Py_EQ); |
314 | 3.95M | Py_DECREF(sentinel); |
315 | 3.95M | if (ok == 0) { |
316 | 3.53M | return result; /* Common case, fast path */ |
317 | 3.53M | } |
318 | | |
319 | 427k | if (ok > 0) { |
320 | 427k | calliter_exhaust(it); |
321 | 427k | } |
322 | 427k | } |
323 | 0 | else if (result == NULL) { |
324 | 0 | stop_exc = calliter_load(&it->it_stop_exc); |
325 | 0 | if (PyErr_ExceptionMatches(stop_exc)) { |
326 | 0 | PyErr_Clear(); |
327 | 0 | calliter_exhaust(it); |
328 | 0 | } |
329 | 0 | else if (PyErr_ExceptionMatches(PyExc_StopIteration)) { |
330 | | /* It would be mistaken for the end of the iteration (see |
331 | | PEP 479). */ |
332 | 0 | _PyErr_FormatFromCause(PyExc_RuntimeError, |
333 | 0 | "callable raised StopIteration"); |
334 | 0 | } |
335 | 0 | Py_DECREF(stop_exc); |
336 | 0 | } |
337 | 427k | Py_XDECREF(result); |
338 | 427k | return NULL; |
339 | 3.95M | } |
340 | | |
341 | | static PyObject * |
342 | | calliter_reduce(PyObject *op, PyObject *Py_UNUSED(ignored)) |
343 | 0 | { |
344 | 0 | calliterobject *it = (calliterobject*)op; |
345 | 0 | PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter)); |
346 | | |
347 | | /* _PyEval_GetBuiltin can invoke arbitrary code, |
348 | | * call must be before access of iterator pointers. |
349 | | * see issue #101765 */ |
350 | |
|
351 | 0 | PyObject *callable = calliter_load(&it->it_callable); |
352 | 0 | PyObject *sentinel = calliter_load(&it->it_sentinel); |
353 | 0 | PyObject *stop_exc = calliter_load(&it->it_stop_exc); |
354 | 0 | PyObject *res; |
355 | 0 | if (callable == NULL) { |
356 | 0 | res = Py_BuildValue("N(())", iter); |
357 | 0 | } |
358 | | /* Only the sentinel can be passed as an argument of iter(), so other |
359 | | attributes are restored from the state (see calliter_setstate()). */ |
360 | 0 | else if (sentinel == NULL) { |
361 | 0 | res = Py_BuildValue("N(OO)(()O)", iter, callable, Py_None, stop_exc); |
362 | 0 | } |
363 | 0 | else if (stop_exc == PyExc_StopIteration) { |
364 | 0 | res = Py_BuildValue("N(OO)", iter, callable, sentinel); |
365 | 0 | } |
366 | 0 | else { |
367 | 0 | res = Py_BuildValue("N(OO)((O)O)", iter, callable, Py_None, |
368 | 0 | sentinel, stop_exc); |
369 | 0 | } |
370 | 0 | Py_XDECREF(callable); |
371 | 0 | Py_XDECREF(sentinel); |
372 | 0 | Py_DECREF(stop_exc); |
373 | 0 | return res; |
374 | 0 | } |
375 | | |
376 | | static PyObject * |
377 | | calliter_setstate(PyObject *op, PyObject *state) |
378 | 0 | { |
379 | 0 | calliterobject *it = (calliterobject*)op; |
380 | 0 | PyObject *sentinel, *stop_exc; |
381 | |
|
382 | 0 | if (!PyTuple_Check(state) || PyTuple_GET_SIZE(state) != 2) { |
383 | 0 | goto error; |
384 | 0 | } |
385 | 0 | sentinel = PyTuple_GET_ITEM(state, 0); |
386 | 0 | stop_exc = PyTuple_GET_ITEM(state, 1); |
387 | 0 | if (!PyTuple_Check(sentinel) || PyTuple_GET_SIZE(sentinel) > 1) { |
388 | 0 | goto error; |
389 | 0 | } |
390 | 0 | if (_PyEval_CheckExceptTypeValid(_PyThreadState_GET(), stop_exc) < 0) { |
391 | 0 | return NULL; |
392 | 0 | } |
393 | 0 | if (FT_ATOMIC_LOAD_PTR_RELAXED(it->it_callable) != NULL) { |
394 | 0 | PyObject *value = PyTuple_GET_SIZE(sentinel) ? |
395 | 0 | Py_NewRef(PyTuple_GET_ITEM(sentinel, 0)) : NULL; |
396 | 0 | _PyObject_XDecRefDelayed(calliter_swap(&it->it_sentinel, value)); |
397 | 0 | _PyObject_XDecRefDelayed(calliter_swap(&it->it_stop_exc, |
398 | 0 | Py_NewRef(stop_exc))); |
399 | 0 | } |
400 | 0 | Py_RETURN_NONE; |
401 | | |
402 | 0 | error: |
403 | 0 | PyErr_SetString(PyExc_TypeError, "invalid state for callable_iterator"); |
404 | | return NULL; |
405 | 0 | } |
406 | | |
407 | | static PyMethodDef calliter_methods[] = { |
408 | | {"__reduce__", calliter_reduce, METH_NOARGS, reduce_doc}, |
409 | | {"__setstate__", calliter_setstate, METH_O, setstate_doc}, |
410 | | {NULL, NULL} /* sentinel */ |
411 | | }; |
412 | | |
413 | | PyTypeObject PyCallIter_Type = { |
414 | | PyVarObject_HEAD_INIT(&PyType_Type, 0) |
415 | | "callable_iterator", /* tp_name */ |
416 | | sizeof(calliterobject), /* tp_basicsize */ |
417 | | 0, /* tp_itemsize */ |
418 | | /* methods */ |
419 | | calliter_dealloc, /* tp_dealloc */ |
420 | | 0, /* tp_vectorcall_offset */ |
421 | | 0, /* tp_getattr */ |
422 | | 0, /* tp_setattr */ |
423 | | 0, /* tp_as_async */ |
424 | | 0, /* tp_repr */ |
425 | | 0, /* tp_as_number */ |
426 | | 0, /* tp_as_sequence */ |
427 | | 0, /* tp_as_mapping */ |
428 | | 0, /* tp_hash */ |
429 | | 0, /* tp_call */ |
430 | | 0, /* tp_str */ |
431 | | PyObject_GenericGetAttr, /* tp_getattro */ |
432 | | 0, /* tp_setattro */ |
433 | | 0, /* tp_as_buffer */ |
434 | | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ |
435 | | 0, /* tp_doc */ |
436 | | calliter_traverse, /* tp_traverse */ |
437 | | 0, /* tp_clear */ |
438 | | 0, /* tp_richcompare */ |
439 | | 0, /* tp_weaklistoffset */ |
440 | | PyObject_SelfIter, /* tp_iter */ |
441 | | calliter_iternext, /* tp_iternext */ |
442 | | calliter_methods, /* tp_methods */ |
443 | | }; |