Coverage Report

Created: 2026-10-17 06:15

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