enumobject.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. /* enumerate object */
  2. #include "Python.h"
  3. #include "pycore_call.h" // _PyObject_CallNoArgs()
  4. #include "pycore_long.h" // _PyLong_GetOne()
  5. #include "pycore_object.h" // _PyObject_GC_TRACK()
  6. #include "clinic/enumobject.c.h"
  7. /*[clinic input]
  8. class enumerate "enumobject *" "&PyEnum_Type"
  9. class reversed "reversedobject *" "&PyReversed_Type"
  10. [clinic start generated code]*/
  11. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=d2dfdf1a88c88975]*/
  12. typedef struct {
  13. PyObject_HEAD
  14. Py_ssize_t en_index; /* current index of enumeration */
  15. PyObject* en_sit; /* secondary iterator of enumeration */
  16. PyObject* en_result; /* result tuple */
  17. PyObject* en_longindex; /* index for sequences >= PY_SSIZE_T_MAX */
  18. PyObject* one; /* borrowed reference */
  19. } enumobject;
  20. /*[clinic input]
  21. @classmethod
  22. enumerate.__new__ as enum_new
  23. iterable: object
  24. an object supporting iteration
  25. start: object = 0
  26. Return an enumerate object.
  27. The enumerate object yields pairs containing a count (from start, which
  28. defaults to zero) and a value yielded by the iterable argument.
  29. enumerate is useful for obtaining an indexed list:
  30. (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
  31. [clinic start generated code]*/
  32. static PyObject *
  33. enum_new_impl(PyTypeObject *type, PyObject *iterable, PyObject *start)
  34. /*[clinic end generated code: output=e95e6e439f812c10 input=782e4911efcb8acf]*/
  35. {
  36. enumobject *en;
  37. en = (enumobject *)type->tp_alloc(type, 0);
  38. if (en == NULL)
  39. return NULL;
  40. if (start != NULL) {
  41. start = PyNumber_Index(start);
  42. if (start == NULL) {
  43. Py_DECREF(en);
  44. return NULL;
  45. }
  46. assert(PyLong_Check(start));
  47. en->en_index = PyLong_AsSsize_t(start);
  48. if (en->en_index == -1 && PyErr_Occurred()) {
  49. PyErr_Clear();
  50. en->en_index = PY_SSIZE_T_MAX;
  51. en->en_longindex = start;
  52. } else {
  53. en->en_longindex = NULL;
  54. Py_DECREF(start);
  55. }
  56. } else {
  57. en->en_index = 0;
  58. en->en_longindex = NULL;
  59. }
  60. en->en_sit = PyObject_GetIter(iterable);
  61. if (en->en_sit == NULL) {
  62. Py_DECREF(en);
  63. return NULL;
  64. }
  65. en->en_result = PyTuple_Pack(2, Py_None, Py_None);
  66. if (en->en_result == NULL) {
  67. Py_DECREF(en);
  68. return NULL;
  69. }
  70. en->one = _PyLong_GetOne(); /* borrowed reference */
  71. return (PyObject *)en;
  72. }
  73. static int check_keyword(PyObject *kwnames, int index,
  74. const char *name)
  75. {
  76. PyObject *kw = PyTuple_GET_ITEM(kwnames, index);
  77. if (!_PyUnicode_EqualToASCIIString(kw, name)) {
  78. PyErr_Format(PyExc_TypeError,
  79. "'%S' is an invalid keyword argument for enumerate()", kw);
  80. return 0;
  81. }
  82. return 1;
  83. }
  84. // TODO: Use AC when bpo-43447 is supported
  85. static PyObject *
  86. enumerate_vectorcall(PyObject *type, PyObject *const *args,
  87. size_t nargsf, PyObject *kwnames)
  88. {
  89. PyTypeObject *tp = _PyType_CAST(type);
  90. Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
  91. Py_ssize_t nkwargs = 0;
  92. if (kwnames != NULL) {
  93. nkwargs = PyTuple_GET_SIZE(kwnames);
  94. }
  95. // Manually implement enumerate(iterable, start=...)
  96. if (nargs + nkwargs == 2) {
  97. if (nkwargs == 1) {
  98. if (!check_keyword(kwnames, 0, "start")) {
  99. return NULL;
  100. }
  101. } else if (nkwargs == 2) {
  102. PyObject *kw0 = PyTuple_GET_ITEM(kwnames, 0);
  103. if (_PyUnicode_EqualToASCIIString(kw0, "start")) {
  104. if (!check_keyword(kwnames, 1, "iterable")) {
  105. return NULL;
  106. }
  107. return enum_new_impl(tp, args[1], args[0]);
  108. }
  109. if (!check_keyword(kwnames, 0, "iterable") ||
  110. !check_keyword(kwnames, 1, "start")) {
  111. return NULL;
  112. }
  113. }
  114. return enum_new_impl(tp, args[0], args[1]);
  115. }
  116. if (nargs + nkwargs == 1) {
  117. if (nkwargs == 1 && !check_keyword(kwnames, 0, "iterable")) {
  118. return NULL;
  119. }
  120. return enum_new_impl(tp, args[0], NULL);
  121. }
  122. if (nargs == 0) {
  123. PyErr_SetString(PyExc_TypeError,
  124. "enumerate() missing required argument 'iterable'");
  125. return NULL;
  126. }
  127. PyErr_Format(PyExc_TypeError,
  128. "enumerate() takes at most 2 arguments (%d given)", nargs + nkwargs);
  129. return NULL;
  130. }
  131. static void
  132. enum_dealloc(enumobject *en)
  133. {
  134. PyObject_GC_UnTrack(en);
  135. Py_XDECREF(en->en_sit);
  136. Py_XDECREF(en->en_result);
  137. Py_XDECREF(en->en_longindex);
  138. Py_TYPE(en)->tp_free(en);
  139. }
  140. static int
  141. enum_traverse(enumobject *en, visitproc visit, void *arg)
  142. {
  143. Py_VISIT(en->en_sit);
  144. Py_VISIT(en->en_result);
  145. Py_VISIT(en->en_longindex);
  146. return 0;
  147. }
  148. static PyObject *
  149. enum_next_long(enumobject *en, PyObject* next_item)
  150. {
  151. PyObject *result = en->en_result;
  152. PyObject *next_index;
  153. PyObject *stepped_up;
  154. PyObject *old_index;
  155. PyObject *old_item;
  156. if (en->en_longindex == NULL) {
  157. en->en_longindex = PyLong_FromSsize_t(PY_SSIZE_T_MAX);
  158. if (en->en_longindex == NULL) {
  159. Py_DECREF(next_item);
  160. return NULL;
  161. }
  162. }
  163. next_index = en->en_longindex;
  164. assert(next_index != NULL);
  165. stepped_up = PyNumber_Add(next_index, en->one);
  166. if (stepped_up == NULL) {
  167. Py_DECREF(next_item);
  168. return NULL;
  169. }
  170. en->en_longindex = stepped_up;
  171. if (Py_REFCNT(result) == 1) {
  172. Py_INCREF(result);
  173. old_index = PyTuple_GET_ITEM(result, 0);
  174. old_item = PyTuple_GET_ITEM(result, 1);
  175. PyTuple_SET_ITEM(result, 0, next_index);
  176. PyTuple_SET_ITEM(result, 1, next_item);
  177. Py_DECREF(old_index);
  178. Py_DECREF(old_item);
  179. // bpo-42536: The GC may have untracked this result tuple. Since we're
  180. // recycling it, make sure it's tracked again:
  181. if (!_PyObject_GC_IS_TRACKED(result)) {
  182. _PyObject_GC_TRACK(result);
  183. }
  184. return result;
  185. }
  186. result = PyTuple_New(2);
  187. if (result == NULL) {
  188. Py_DECREF(next_index);
  189. Py_DECREF(next_item);
  190. return NULL;
  191. }
  192. PyTuple_SET_ITEM(result, 0, next_index);
  193. PyTuple_SET_ITEM(result, 1, next_item);
  194. return result;
  195. }
  196. static PyObject *
  197. enum_next(enumobject *en)
  198. {
  199. PyObject *next_index;
  200. PyObject *next_item;
  201. PyObject *result = en->en_result;
  202. PyObject *it = en->en_sit;
  203. PyObject *old_index;
  204. PyObject *old_item;
  205. next_item = (*Py_TYPE(it)->tp_iternext)(it);
  206. if (next_item == NULL)
  207. return NULL;
  208. if (en->en_index == PY_SSIZE_T_MAX)
  209. return enum_next_long(en, next_item);
  210. next_index = PyLong_FromSsize_t(en->en_index);
  211. if (next_index == NULL) {
  212. Py_DECREF(next_item);
  213. return NULL;
  214. }
  215. en->en_index++;
  216. if (Py_REFCNT(result) == 1) {
  217. Py_INCREF(result);
  218. old_index = PyTuple_GET_ITEM(result, 0);
  219. old_item = PyTuple_GET_ITEM(result, 1);
  220. PyTuple_SET_ITEM(result, 0, next_index);
  221. PyTuple_SET_ITEM(result, 1, next_item);
  222. Py_DECREF(old_index);
  223. Py_DECREF(old_item);
  224. // bpo-42536: The GC may have untracked this result tuple. Since we're
  225. // recycling it, make sure it's tracked again:
  226. if (!_PyObject_GC_IS_TRACKED(result)) {
  227. _PyObject_GC_TRACK(result);
  228. }
  229. return result;
  230. }
  231. result = PyTuple_New(2);
  232. if (result == NULL) {
  233. Py_DECREF(next_index);
  234. Py_DECREF(next_item);
  235. return NULL;
  236. }
  237. PyTuple_SET_ITEM(result, 0, next_index);
  238. PyTuple_SET_ITEM(result, 1, next_item);
  239. return result;
  240. }
  241. static PyObject *
  242. enum_reduce(enumobject *en, PyObject *Py_UNUSED(ignored))
  243. {
  244. if (en->en_longindex != NULL)
  245. return Py_BuildValue("O(OO)", Py_TYPE(en), en->en_sit, en->en_longindex);
  246. else
  247. return Py_BuildValue("O(On)", Py_TYPE(en), en->en_sit, en->en_index);
  248. }
  249. PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
  250. static PyMethodDef enum_methods[] = {
  251. {"__reduce__", (PyCFunction)enum_reduce, METH_NOARGS, reduce_doc},
  252. {"__class_getitem__", Py_GenericAlias,
  253. METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
  254. {NULL, NULL} /* sentinel */
  255. };
  256. PyTypeObject PyEnum_Type = {
  257. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  258. "enumerate", /* tp_name */
  259. sizeof(enumobject), /* tp_basicsize */
  260. 0, /* tp_itemsize */
  261. /* methods */
  262. (destructor)enum_dealloc, /* tp_dealloc */
  263. 0, /* tp_vectorcall_offset */
  264. 0, /* tp_getattr */
  265. 0, /* tp_setattr */
  266. 0, /* tp_as_async */
  267. 0, /* tp_repr */
  268. 0, /* tp_as_number */
  269. 0, /* tp_as_sequence */
  270. 0, /* tp_as_mapping */
  271. 0, /* tp_hash */
  272. 0, /* tp_call */
  273. 0, /* tp_str */
  274. PyObject_GenericGetAttr, /* tp_getattro */
  275. 0, /* tp_setattro */
  276. 0, /* tp_as_buffer */
  277. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  278. Py_TPFLAGS_BASETYPE, /* tp_flags */
  279. enum_new__doc__, /* tp_doc */
  280. (traverseproc)enum_traverse, /* tp_traverse */
  281. 0, /* tp_clear */
  282. 0, /* tp_richcompare */
  283. 0, /* tp_weaklistoffset */
  284. PyObject_SelfIter, /* tp_iter */
  285. (iternextfunc)enum_next, /* tp_iternext */
  286. enum_methods, /* tp_methods */
  287. 0, /* tp_members */
  288. 0, /* tp_getset */
  289. 0, /* tp_base */
  290. 0, /* tp_dict */
  291. 0, /* tp_descr_get */
  292. 0, /* tp_descr_set */
  293. 0, /* tp_dictoffset */
  294. 0, /* tp_init */
  295. PyType_GenericAlloc, /* tp_alloc */
  296. enum_new, /* tp_new */
  297. PyObject_GC_Del, /* tp_free */
  298. .tp_vectorcall = (vectorcallfunc)enumerate_vectorcall
  299. };
  300. /* Reversed Object ***************************************************************/
  301. typedef struct {
  302. PyObject_HEAD
  303. Py_ssize_t index;
  304. PyObject* seq;
  305. } reversedobject;
  306. /*[clinic input]
  307. @classmethod
  308. reversed.__new__ as reversed_new
  309. sequence as seq: object
  310. /
  311. Return a reverse iterator over the values of the given sequence.
  312. [clinic start generated code]*/
  313. static PyObject *
  314. reversed_new_impl(PyTypeObject *type, PyObject *seq)
  315. /*[clinic end generated code: output=f7854cc1df26f570 input=aeb720361e5e3f1d]*/
  316. {
  317. Py_ssize_t n;
  318. PyObject *reversed_meth;
  319. reversedobject *ro;
  320. reversed_meth = _PyObject_LookupSpecial(seq, &_Py_ID(__reversed__));
  321. if (reversed_meth == Py_None) {
  322. Py_DECREF(reversed_meth);
  323. PyErr_Format(PyExc_TypeError,
  324. "'%.200s' object is not reversible",
  325. Py_TYPE(seq)->tp_name);
  326. return NULL;
  327. }
  328. if (reversed_meth != NULL) {
  329. PyObject *res = _PyObject_CallNoArgs(reversed_meth);
  330. Py_DECREF(reversed_meth);
  331. return res;
  332. }
  333. else if (PyErr_Occurred())
  334. return NULL;
  335. if (!PySequence_Check(seq)) {
  336. PyErr_Format(PyExc_TypeError,
  337. "'%.200s' object is not reversible",
  338. Py_TYPE(seq)->tp_name);
  339. return NULL;
  340. }
  341. n = PySequence_Size(seq);
  342. if (n == -1)
  343. return NULL;
  344. ro = (reversedobject *)type->tp_alloc(type, 0);
  345. if (ro == NULL)
  346. return NULL;
  347. ro->index = n-1;
  348. ro->seq = Py_NewRef(seq);
  349. return (PyObject *)ro;
  350. }
  351. static PyObject *
  352. reversed_vectorcall(PyObject *type, PyObject * const*args,
  353. size_t nargsf, PyObject *kwnames)
  354. {
  355. if (!_PyArg_NoKwnames("reversed", kwnames)) {
  356. return NULL;
  357. }
  358. Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
  359. if (!_PyArg_CheckPositional("reversed", nargs, 1, 1)) {
  360. return NULL;
  361. }
  362. return reversed_new_impl(_PyType_CAST(type), args[0]);
  363. }
  364. static void
  365. reversed_dealloc(reversedobject *ro)
  366. {
  367. PyObject_GC_UnTrack(ro);
  368. Py_XDECREF(ro->seq);
  369. Py_TYPE(ro)->tp_free(ro);
  370. }
  371. static int
  372. reversed_traverse(reversedobject *ro, visitproc visit, void *arg)
  373. {
  374. Py_VISIT(ro->seq);
  375. return 0;
  376. }
  377. static PyObject *
  378. reversed_next(reversedobject *ro)
  379. {
  380. PyObject *item;
  381. Py_ssize_t index = ro->index;
  382. if (index >= 0) {
  383. item = PySequence_GetItem(ro->seq, index);
  384. if (item != NULL) {
  385. ro->index--;
  386. return item;
  387. }
  388. if (PyErr_ExceptionMatches(PyExc_IndexError) ||
  389. PyErr_ExceptionMatches(PyExc_StopIteration))
  390. PyErr_Clear();
  391. }
  392. ro->index = -1;
  393. Py_CLEAR(ro->seq);
  394. return NULL;
  395. }
  396. static PyObject *
  397. reversed_len(reversedobject *ro, PyObject *Py_UNUSED(ignored))
  398. {
  399. Py_ssize_t position, seqsize;
  400. if (ro->seq == NULL)
  401. return PyLong_FromLong(0);
  402. seqsize = PySequence_Size(ro->seq);
  403. if (seqsize == -1)
  404. return NULL;
  405. position = ro->index + 1;
  406. return PyLong_FromSsize_t((seqsize < position) ? 0 : position);
  407. }
  408. PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
  409. static PyObject *
  410. reversed_reduce(reversedobject *ro, PyObject *Py_UNUSED(ignored))
  411. {
  412. if (ro->seq)
  413. return Py_BuildValue("O(O)n", Py_TYPE(ro), ro->seq, ro->index);
  414. else
  415. return Py_BuildValue("O(())", Py_TYPE(ro));
  416. }
  417. static PyObject *
  418. reversed_setstate(reversedobject *ro, PyObject *state)
  419. {
  420. Py_ssize_t index = PyLong_AsSsize_t(state);
  421. if (index == -1 && PyErr_Occurred())
  422. return NULL;
  423. if (ro->seq != 0) {
  424. Py_ssize_t n = PySequence_Size(ro->seq);
  425. if (n < 0)
  426. return NULL;
  427. if (index < -1)
  428. index = -1;
  429. else if (index > n-1)
  430. index = n-1;
  431. ro->index = index;
  432. }
  433. Py_RETURN_NONE;
  434. }
  435. PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
  436. static PyMethodDef reversediter_methods[] = {
  437. {"__length_hint__", (PyCFunction)reversed_len, METH_NOARGS, length_hint_doc},
  438. {"__reduce__", (PyCFunction)reversed_reduce, METH_NOARGS, reduce_doc},
  439. {"__setstate__", (PyCFunction)reversed_setstate, METH_O, setstate_doc},
  440. {NULL, NULL} /* sentinel */
  441. };
  442. PyTypeObject PyReversed_Type = {
  443. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  444. "reversed", /* tp_name */
  445. sizeof(reversedobject), /* tp_basicsize */
  446. 0, /* tp_itemsize */
  447. /* methods */
  448. (destructor)reversed_dealloc, /* tp_dealloc */
  449. 0, /* tp_vectorcall_offset */
  450. 0, /* tp_getattr */
  451. 0, /* tp_setattr */
  452. 0, /* tp_as_async */
  453. 0, /* tp_repr */
  454. 0, /* tp_as_number */
  455. 0, /* tp_as_sequence */
  456. 0, /* tp_as_mapping */
  457. 0, /* tp_hash */
  458. 0, /* tp_call */
  459. 0, /* tp_str */
  460. PyObject_GenericGetAttr, /* tp_getattro */
  461. 0, /* tp_setattro */
  462. 0, /* tp_as_buffer */
  463. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  464. Py_TPFLAGS_BASETYPE, /* tp_flags */
  465. reversed_new__doc__, /* tp_doc */
  466. (traverseproc)reversed_traverse,/* tp_traverse */
  467. 0, /* tp_clear */
  468. 0, /* tp_richcompare */
  469. 0, /* tp_weaklistoffset */
  470. PyObject_SelfIter, /* tp_iter */
  471. (iternextfunc)reversed_next, /* tp_iternext */
  472. reversediter_methods, /* tp_methods */
  473. 0, /* tp_members */
  474. 0, /* tp_getset */
  475. 0, /* tp_base */
  476. 0, /* tp_dict */
  477. 0, /* tp_descr_get */
  478. 0, /* tp_descr_set */
  479. 0, /* tp_dictoffset */
  480. 0, /* tp_init */
  481. PyType_GenericAlloc, /* tp_alloc */
  482. reversed_new, /* tp_new */
  483. PyObject_GC_Del, /* tp_free */
  484. .tp_vectorcall = (vectorcallfunc)reversed_vectorcall,
  485. };