iterobject.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. /* Iterator objects */
  2. #include "Python.h"
  3. #include "pycore_call.h" // _PyObject_CallNoArgs()
  4. #include "pycore_object.h" // _PyObject_GC_TRACK()
  5. typedef struct {
  6. PyObject_HEAD
  7. Py_ssize_t it_index;
  8. PyObject *it_seq; /* Set to NULL when iterator is exhausted */
  9. } seqiterobject;
  10. PyObject *
  11. PySeqIter_New(PyObject *seq)
  12. {
  13. seqiterobject *it;
  14. if (!PySequence_Check(seq)) {
  15. PyErr_BadInternalCall();
  16. return NULL;
  17. }
  18. it = PyObject_GC_New(seqiterobject, &PySeqIter_Type);
  19. if (it == NULL)
  20. return NULL;
  21. it->it_index = 0;
  22. it->it_seq = Py_NewRef(seq);
  23. _PyObject_GC_TRACK(it);
  24. return (PyObject *)it;
  25. }
  26. static void
  27. iter_dealloc(seqiterobject *it)
  28. {
  29. _PyObject_GC_UNTRACK(it);
  30. Py_XDECREF(it->it_seq);
  31. PyObject_GC_Del(it);
  32. }
  33. static int
  34. iter_traverse(seqiterobject *it, visitproc visit, void *arg)
  35. {
  36. Py_VISIT(it->it_seq);
  37. return 0;
  38. }
  39. static PyObject *
  40. iter_iternext(PyObject *iterator)
  41. {
  42. seqiterobject *it;
  43. PyObject *seq;
  44. PyObject *result;
  45. assert(PySeqIter_Check(iterator));
  46. it = (seqiterobject *)iterator;
  47. seq = it->it_seq;
  48. if (seq == NULL)
  49. return NULL;
  50. if (it->it_index == PY_SSIZE_T_MAX) {
  51. PyErr_SetString(PyExc_OverflowError,
  52. "iter index too large");
  53. return NULL;
  54. }
  55. result = PySequence_GetItem(seq, it->it_index);
  56. if (result != NULL) {
  57. it->it_index++;
  58. return result;
  59. }
  60. if (PyErr_ExceptionMatches(PyExc_IndexError) ||
  61. PyErr_ExceptionMatches(PyExc_StopIteration))
  62. {
  63. PyErr_Clear();
  64. it->it_seq = NULL;
  65. Py_DECREF(seq);
  66. }
  67. return NULL;
  68. }
  69. static PyObject *
  70. iter_len(seqiterobject *it, PyObject *Py_UNUSED(ignored))
  71. {
  72. Py_ssize_t seqsize, len;
  73. if (it->it_seq) {
  74. if (_PyObject_HasLen(it->it_seq)) {
  75. seqsize = PySequence_Size(it->it_seq);
  76. if (seqsize == -1)
  77. return NULL;
  78. }
  79. else {
  80. Py_RETURN_NOTIMPLEMENTED;
  81. }
  82. len = seqsize - it->it_index;
  83. if (len >= 0)
  84. return PyLong_FromSsize_t(len);
  85. }
  86. return PyLong_FromLong(0);
  87. }
  88. PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
  89. static PyObject *
  90. iter_reduce(seqiterobject *it, PyObject *Py_UNUSED(ignored))
  91. {
  92. PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
  93. /* _PyEval_GetBuiltin can invoke arbitrary code,
  94. * call must be before access of iterator pointers.
  95. * see issue #101765 */
  96. if (it->it_seq != NULL)
  97. return Py_BuildValue("N(O)n", iter, it->it_seq, it->it_index);
  98. else
  99. return Py_BuildValue("N(())", iter);
  100. }
  101. PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
  102. static PyObject *
  103. iter_setstate(seqiterobject *it, PyObject *state)
  104. {
  105. Py_ssize_t index = PyLong_AsSsize_t(state);
  106. if (index == -1 && PyErr_Occurred())
  107. return NULL;
  108. if (it->it_seq != NULL) {
  109. if (index < 0)
  110. index = 0;
  111. it->it_index = index;
  112. }
  113. Py_RETURN_NONE;
  114. }
  115. PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
  116. static PyMethodDef seqiter_methods[] = {
  117. {"__length_hint__", (PyCFunction)iter_len, METH_NOARGS, length_hint_doc},
  118. {"__reduce__", (PyCFunction)iter_reduce, METH_NOARGS, reduce_doc},
  119. {"__setstate__", (PyCFunction)iter_setstate, METH_O, setstate_doc},
  120. {NULL, NULL} /* sentinel */
  121. };
  122. PyTypeObject PySeqIter_Type = {
  123. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  124. "iterator", /* tp_name */
  125. sizeof(seqiterobject), /* tp_basicsize */
  126. 0, /* tp_itemsize */
  127. /* methods */
  128. (destructor)iter_dealloc, /* tp_dealloc */
  129. 0, /* tp_vectorcall_offset */
  130. 0, /* tp_getattr */
  131. 0, /* tp_setattr */
  132. 0, /* tp_as_async */
  133. 0, /* tp_repr */
  134. 0, /* tp_as_number */
  135. 0, /* tp_as_sequence */
  136. 0, /* tp_as_mapping */
  137. 0, /* tp_hash */
  138. 0, /* tp_call */
  139. 0, /* tp_str */
  140. PyObject_GenericGetAttr, /* tp_getattro */
  141. 0, /* tp_setattro */
  142. 0, /* tp_as_buffer */
  143. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  144. 0, /* tp_doc */
  145. (traverseproc)iter_traverse, /* tp_traverse */
  146. 0, /* tp_clear */
  147. 0, /* tp_richcompare */
  148. 0, /* tp_weaklistoffset */
  149. PyObject_SelfIter, /* tp_iter */
  150. iter_iternext, /* tp_iternext */
  151. seqiter_methods, /* tp_methods */
  152. 0, /* tp_members */
  153. };
  154. /* -------------------------------------- */
  155. typedef struct {
  156. PyObject_HEAD
  157. PyObject *it_callable; /* Set to NULL when iterator is exhausted */
  158. PyObject *it_sentinel; /* Set to NULL when iterator is exhausted */
  159. } calliterobject;
  160. PyObject *
  161. PyCallIter_New(PyObject *callable, PyObject *sentinel)
  162. {
  163. calliterobject *it;
  164. it = PyObject_GC_New(calliterobject, &PyCallIter_Type);
  165. if (it == NULL)
  166. return NULL;
  167. it->it_callable = Py_NewRef(callable);
  168. it->it_sentinel = Py_NewRef(sentinel);
  169. _PyObject_GC_TRACK(it);
  170. return (PyObject *)it;
  171. }
  172. static void
  173. calliter_dealloc(calliterobject *it)
  174. {
  175. _PyObject_GC_UNTRACK(it);
  176. Py_XDECREF(it->it_callable);
  177. Py_XDECREF(it->it_sentinel);
  178. PyObject_GC_Del(it);
  179. }
  180. static int
  181. calliter_traverse(calliterobject *it, visitproc visit, void *arg)
  182. {
  183. Py_VISIT(it->it_callable);
  184. Py_VISIT(it->it_sentinel);
  185. return 0;
  186. }
  187. static PyObject *
  188. calliter_iternext(calliterobject *it)
  189. {
  190. PyObject *result;
  191. if (it->it_callable == NULL) {
  192. return NULL;
  193. }
  194. result = _PyObject_CallNoArgs(it->it_callable);
  195. if (result != NULL && it->it_sentinel != NULL){
  196. int ok;
  197. ok = PyObject_RichCompareBool(it->it_sentinel, result, Py_EQ);
  198. if (ok == 0) {
  199. return result; /* Common case, fast path */
  200. }
  201. if (ok > 0) {
  202. Py_CLEAR(it->it_callable);
  203. Py_CLEAR(it->it_sentinel);
  204. }
  205. }
  206. else if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
  207. PyErr_Clear();
  208. Py_CLEAR(it->it_callable);
  209. Py_CLEAR(it->it_sentinel);
  210. }
  211. Py_XDECREF(result);
  212. return NULL;
  213. }
  214. static PyObject *
  215. calliter_reduce(calliterobject *it, PyObject *Py_UNUSED(ignored))
  216. {
  217. PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
  218. /* _PyEval_GetBuiltin can invoke arbitrary code,
  219. * call must be before access of iterator pointers.
  220. * see issue #101765 */
  221. if (it->it_callable != NULL && it->it_sentinel != NULL)
  222. return Py_BuildValue("N(OO)", iter, it->it_callable, it->it_sentinel);
  223. else
  224. return Py_BuildValue("N(())", iter);
  225. }
  226. static PyMethodDef calliter_methods[] = {
  227. {"__reduce__", (PyCFunction)calliter_reduce, METH_NOARGS, reduce_doc},
  228. {NULL, NULL} /* sentinel */
  229. };
  230. PyTypeObject PyCallIter_Type = {
  231. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  232. "callable_iterator", /* tp_name */
  233. sizeof(calliterobject), /* tp_basicsize */
  234. 0, /* tp_itemsize */
  235. /* methods */
  236. (destructor)calliter_dealloc, /* tp_dealloc */
  237. 0, /* tp_vectorcall_offset */
  238. 0, /* tp_getattr */
  239. 0, /* tp_setattr */
  240. 0, /* tp_as_async */
  241. 0, /* tp_repr */
  242. 0, /* tp_as_number */
  243. 0, /* tp_as_sequence */
  244. 0, /* tp_as_mapping */
  245. 0, /* tp_hash */
  246. 0, /* tp_call */
  247. 0, /* tp_str */
  248. PyObject_GenericGetAttr, /* tp_getattro */
  249. 0, /* tp_setattro */
  250. 0, /* tp_as_buffer */
  251. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  252. 0, /* tp_doc */
  253. (traverseproc)calliter_traverse, /* tp_traverse */
  254. 0, /* tp_clear */
  255. 0, /* tp_richcompare */
  256. 0, /* tp_weaklistoffset */
  257. PyObject_SelfIter, /* tp_iter */
  258. (iternextfunc)calliter_iternext, /* tp_iternext */
  259. calliter_methods, /* tp_methods */
  260. };
  261. /* -------------------------------------- */
  262. typedef struct {
  263. PyObject_HEAD
  264. PyObject *wrapped;
  265. PyObject *default_value;
  266. } anextawaitableobject;
  267. static void
  268. anextawaitable_dealloc(anextawaitableobject *obj)
  269. {
  270. _PyObject_GC_UNTRACK(obj);
  271. Py_XDECREF(obj->wrapped);
  272. Py_XDECREF(obj->default_value);
  273. PyObject_GC_Del(obj);
  274. }
  275. static int
  276. anextawaitable_traverse(anextawaitableobject *obj, visitproc visit, void *arg)
  277. {
  278. Py_VISIT(obj->wrapped);
  279. Py_VISIT(obj->default_value);
  280. return 0;
  281. }
  282. static PyObject *
  283. anextawaitable_getiter(anextawaitableobject *obj)
  284. {
  285. assert(obj->wrapped != NULL);
  286. PyObject *awaitable = _PyCoro_GetAwaitableIter(obj->wrapped);
  287. if (awaitable == NULL) {
  288. return NULL;
  289. }
  290. if (Py_TYPE(awaitable)->tp_iternext == NULL) {
  291. /* _PyCoro_GetAwaitableIter returns a Coroutine, a Generator,
  292. * or an iterator. Of these, only coroutines lack tp_iternext.
  293. */
  294. assert(PyCoro_CheckExact(awaitable));
  295. unaryfunc getter = Py_TYPE(awaitable)->tp_as_async->am_await;
  296. PyObject *new_awaitable = getter(awaitable);
  297. if (new_awaitable == NULL) {
  298. Py_DECREF(awaitable);
  299. return NULL;
  300. }
  301. Py_SETREF(awaitable, new_awaitable);
  302. if (!PyIter_Check(awaitable)) {
  303. PyErr_SetString(PyExc_TypeError,
  304. "__await__ returned a non-iterable");
  305. Py_DECREF(awaitable);
  306. return NULL;
  307. }
  308. }
  309. return awaitable;
  310. }
  311. static PyObject *
  312. anextawaitable_iternext(anextawaitableobject *obj)
  313. {
  314. /* Consider the following class:
  315. *
  316. * class A:
  317. * async def __anext__(self):
  318. * ...
  319. * a = A()
  320. *
  321. * Then `await anext(a)` should call
  322. * a.__anext__().__await__().__next__()
  323. *
  324. * On the other hand, given
  325. *
  326. * async def agen():
  327. * yield 1
  328. * yield 2
  329. * gen = agen()
  330. *
  331. * Then `await anext(gen)` can just call
  332. * gen.__anext__().__next__()
  333. */
  334. PyObject *awaitable = anextawaitable_getiter(obj);
  335. if (awaitable == NULL) {
  336. return NULL;
  337. }
  338. PyObject *result = (*Py_TYPE(awaitable)->tp_iternext)(awaitable);
  339. Py_DECREF(awaitable);
  340. if (result != NULL) {
  341. return result;
  342. }
  343. if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)) {
  344. _PyGen_SetStopIterationValue(obj->default_value);
  345. }
  346. return NULL;
  347. }
  348. static PyObject *
  349. anextawaitable_proxy(anextawaitableobject *obj, char *meth, PyObject *arg) {
  350. PyObject *awaitable = anextawaitable_getiter(obj);
  351. if (awaitable == NULL) {
  352. return NULL;
  353. }
  354. PyObject *ret = PyObject_CallMethod(awaitable, meth, "O", arg);
  355. Py_DECREF(awaitable);
  356. if (ret != NULL) {
  357. return ret;
  358. }
  359. if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)) {
  360. /* `anextawaitableobject` is only used by `anext()` when
  361. * a default value is provided. So when we have a StopAsyncIteration
  362. * exception we replace it with a `StopIteration(default)`, as if
  363. * it was the return value of `__anext__()` coroutine.
  364. */
  365. _PyGen_SetStopIterationValue(obj->default_value);
  366. }
  367. return NULL;
  368. }
  369. static PyObject *
  370. anextawaitable_send(anextawaitableobject *obj, PyObject *arg) {
  371. return anextawaitable_proxy(obj, "send", arg);
  372. }
  373. static PyObject *
  374. anextawaitable_throw(anextawaitableobject *obj, PyObject *arg) {
  375. return anextawaitable_proxy(obj, "throw", arg);
  376. }
  377. static PyObject *
  378. anextawaitable_close(anextawaitableobject *obj, PyObject *arg) {
  379. return anextawaitable_proxy(obj, "close", arg);
  380. }
  381. PyDoc_STRVAR(send_doc,
  382. "send(arg) -> send 'arg' into the wrapped iterator,\n\
  383. return next yielded value or raise StopIteration.");
  384. PyDoc_STRVAR(throw_doc,
  385. "throw(value)\n\
  386. throw(typ[,val[,tb]])\n\
  387. \n\
  388. raise exception in the wrapped iterator, return next yielded value\n\
  389. or raise StopIteration.\n\
  390. the (type, val, tb) signature is deprecated, \n\
  391. and may be removed in a future version of Python.");
  392. PyDoc_STRVAR(close_doc,
  393. "close() -> raise GeneratorExit inside generator.");
  394. static PyMethodDef anextawaitable_methods[] = {
  395. {"send",(PyCFunction)anextawaitable_send, METH_O, send_doc},
  396. {"throw",(PyCFunction)anextawaitable_throw, METH_VARARGS, throw_doc},
  397. {"close",(PyCFunction)anextawaitable_close, METH_VARARGS, close_doc},
  398. {NULL, NULL} /* Sentinel */
  399. };
  400. static PyAsyncMethods anextawaitable_as_async = {
  401. PyObject_SelfIter, /* am_await */
  402. 0, /* am_aiter */
  403. 0, /* am_anext */
  404. 0, /* am_send */
  405. };
  406. PyTypeObject _PyAnextAwaitable_Type = {
  407. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  408. "anext_awaitable", /* tp_name */
  409. sizeof(anextawaitableobject), /* tp_basicsize */
  410. 0, /* tp_itemsize */
  411. /* methods */
  412. (destructor)anextawaitable_dealloc, /* tp_dealloc */
  413. 0, /* tp_vectorcall_offset */
  414. 0, /* tp_getattr */
  415. 0, /* tp_setattr */
  416. &anextawaitable_as_async, /* tp_as_async */
  417. 0, /* tp_repr */
  418. 0, /* tp_as_number */
  419. 0, /* tp_as_sequence */
  420. 0, /* tp_as_mapping */
  421. 0, /* tp_hash */
  422. 0, /* tp_call */
  423. 0, /* tp_str */
  424. PyObject_GenericGetAttr, /* tp_getattro */
  425. 0, /* tp_setattro */
  426. 0, /* tp_as_buffer */
  427. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  428. 0, /* tp_doc */
  429. (traverseproc)anextawaitable_traverse, /* tp_traverse */
  430. 0, /* tp_clear */
  431. 0, /* tp_richcompare */
  432. 0, /* tp_weaklistoffset */
  433. PyObject_SelfIter, /* tp_iter */
  434. (unaryfunc)anextawaitable_iternext, /* tp_iternext */
  435. anextawaitable_methods, /* tp_methods */
  436. };
  437. PyObject *
  438. PyAnextAwaitable_New(PyObject *awaitable, PyObject *default_value)
  439. {
  440. anextawaitableobject *anext = PyObject_GC_New(
  441. anextawaitableobject, &_PyAnextAwaitable_Type);
  442. if (anext == NULL) {
  443. return NULL;
  444. }
  445. anext->wrapped = Py_NewRef(awaitable);
  446. anext->default_value = Py_NewRef(default_value);
  447. _PyObject_GC_TRACK(anext);
  448. return (PyObject *)anext;
  449. }