Coverage Report

Created: 2025-07-11 06:24

/src/cpython/Objects/abstract.c
Line
Count
Source (jump to first uncovered line)
1
/* Abstract Object Interface (many thanks to Jim Fulton) */
2
3
#include "Python.h"
4
#include "pycore_abstract.h"      // _PyIndex_Check()
5
#include "pycore_call.h"          // _PyObject_CallNoArgs()
6
#include "pycore_ceval.h"         // _Py_EnterRecursiveCallTstate()
7
#include "pycore_crossinterp.h"   // _Py_CallInInterpreter()
8
#include "pycore_genobject.h"     // _PyGen_FetchStopIterationValue()
9
#include "pycore_list.h"          // _PyList_AppendTakeRef()
10
#include "pycore_long.h"          // _PyLong_IsNegative()
11
#include "pycore_object.h"        // _Py_CheckSlotResult()
12
#include "pycore_pybuffer.h"      // _PyBuffer_ReleaseInInterpreterAndRawFree()
13
#include "pycore_pyerrors.h"      // _PyErr_Occurred()
14
#include "pycore_pystate.h"       // _PyThreadState_GET()
15
#include "pycore_tuple.h"         // _PyTuple_FromArraySteal()
16
#include "pycore_unionobject.h"   // _PyUnion_Check()
17
18
#include <stddef.h>               // offsetof()
19
20
21
/* Shorthands to return certain errors */
22
23
static PyObject *
24
type_error(const char *msg, PyObject *obj)
25
0
{
26
0
    PyErr_Format(PyExc_TypeError, msg, Py_TYPE(obj)->tp_name);
27
0
    return NULL;
28
0
}
29
30
static PyObject *
31
null_error(void)
32
0
{
33
0
    PyThreadState *tstate = _PyThreadState_GET();
34
0
    if (!_PyErr_Occurred(tstate)) {
35
0
        _PyErr_SetString(tstate, PyExc_SystemError,
36
0
                         "null argument to internal routine");
37
0
    }
38
0
    return NULL;
39
0
}
40
41
/* Operations on any object */
42
43
PyObject *
44
PyObject_Type(PyObject *o)
45
92
{
46
92
    PyObject *v;
47
48
92
    if (o == NULL) {
49
0
        return null_error();
50
0
    }
51
52
92
    v = (PyObject *)Py_TYPE(o);
53
92
    return Py_NewRef(v);
54
92
}
55
56
Py_ssize_t
57
PyObject_Size(PyObject *o)
58
80.3M
{
59
80.3M
    if (o == NULL) {
60
0
        null_error();
61
0
        return -1;
62
0
    }
63
64
80.3M
    PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
65
80.3M
    if (m && m->sq_length) {
66
80.3M
        Py_ssize_t len = m->sq_length(o);
67
80.3M
        assert(_Py_CheckSlotResult(o, "__len__", len >= 0));
68
80.3M
        return len;
69
80.3M
    }
70
71
424
    return PyMapping_Size(o);
72
80.3M
}
73
74
#undef PyObject_Length
75
Py_ssize_t
76
PyObject_Length(PyObject *o)
77
0
{
78
0
    return PyObject_Size(o);
79
0
}
80
301k
#define PyObject_Length PyObject_Size
81
82
int
83
5.18M
_PyObject_HasLen(PyObject *o) {
84
5.18M
    return (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) ||
85
5.18M
        (Py_TYPE(o)->tp_as_mapping && Py_TYPE(o)->tp_as_mapping->mp_length);
86
5.18M
}
87
88
/* The length hint function returns a non-negative value from o.__len__()
89
   or o.__length_hint__(). If those methods aren't found the defaultvalue is
90
   returned.  If one of the calls fails with an exception other than TypeError
91
   this function returns -1.
92
*/
93
94
Py_ssize_t
95
PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
96
5.18M
{
97
5.18M
    PyObject *hint, *result;
98
5.18M
    Py_ssize_t res;
99
5.18M
    if (_PyObject_HasLen(o)) {
100
301k
        res = PyObject_Length(o);
101
301k
        if (res < 0) {
102
0
            PyThreadState *tstate = _PyThreadState_GET();
103
0
            assert(_PyErr_Occurred(tstate));
104
0
            if (!_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
105
0
                return -1;
106
0
            }
107
0
            _PyErr_Clear(tstate);
108
0
        }
109
301k
        else {
110
301k
            return res;
111
301k
        }
112
301k
    }
113
4.88M
    hint = _PyObject_LookupSpecial(o, &_Py_ID(__length_hint__));
114
4.88M
    if (hint == NULL) {
115
3.43M
        if (PyErr_Occurred()) {
116
0
            return -1;
117
0
        }
118
3.43M
        return defaultvalue;
119
3.43M
    }
120
1.44M
    result = _PyObject_CallNoArgs(hint);
121
1.44M
    Py_DECREF(hint);
122
1.44M
    if (result == NULL) {
123
0
        PyThreadState *tstate = _PyThreadState_GET();
124
0
        if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
125
0
            _PyErr_Clear(tstate);
126
0
            return defaultvalue;
127
0
        }
128
0
        return -1;
129
0
    }
130
1.44M
    else if (result == Py_NotImplemented) {
131
0
        Py_DECREF(result);
132
0
        return defaultvalue;
133
0
    }
134
1.44M
    if (!PyLong_Check(result)) {
135
0
        PyErr_Format(PyExc_TypeError, "__length_hint__ must be an integer, not %.100s",
136
0
            Py_TYPE(result)->tp_name);
137
0
        Py_DECREF(result);
138
0
        return -1;
139
0
    }
140
1.44M
    res = PyLong_AsSsize_t(result);
141
1.44M
    Py_DECREF(result);
142
1.44M
    if (res < 0 && PyErr_Occurred()) {
143
0
        return -1;
144
0
    }
145
1.44M
    if (res < 0) {
146
0
        PyErr_Format(PyExc_ValueError, "__length_hint__() should return >= 0");
147
0
        return -1;
148
0
    }
149
1.44M
    return res;
150
1.44M
}
151
152
PyObject *
153
PyObject_GetItem(PyObject *o, PyObject *key)
154
143M
{
155
143M
    if (o == NULL || key == NULL) {
156
0
        return null_error();
157
0
    }
158
159
143M
    PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
160
143M
    if (m && m->mp_subscript) {
161
143M
        PyObject *item = m->mp_subscript(o, key);
162
143M
        assert(_Py_CheckSlotResult(o, "__getitem__", item != NULL));
163
143M
        return item;
164
143M
    }
165
166
42
    PySequenceMethods *ms = Py_TYPE(o)->tp_as_sequence;
167
42
    if (ms && ms->sq_item) {
168
0
        if (_PyIndex_Check(key)) {
169
0
            Py_ssize_t key_value;
170
0
            key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
171
0
            if (key_value == -1 && PyErr_Occurred())
172
0
                return NULL;
173
0
            return PySequence_GetItem(o, key_value);
174
0
        }
175
0
        else {
176
0
            return type_error("sequence index must "
177
0
                              "be integer, not '%.200s'", key);
178
0
        }
179
0
    }
180
181
42
    if (PyType_Check(o)) {
182
42
        PyObject *meth, *result;
183
184
        // Special case type[int], but disallow other types so str[int] fails
185
42
        if ((PyTypeObject*)o == &PyType_Type) {
186
0
            return Py_GenericAlias(o, key);
187
0
        }
188
189
42
        if (PyObject_GetOptionalAttr(o, &_Py_ID(__class_getitem__), &meth) < 0) {
190
0
            return NULL;
191
0
        }
192
42
        if (meth && meth != Py_None) {
193
42
            result = PyObject_CallOneArg(meth, key);
194
42
            Py_DECREF(meth);
195
42
            return result;
196
42
        }
197
0
        Py_XDECREF(meth);
198
0
        PyErr_Format(PyExc_TypeError, "type '%.200s' is not subscriptable",
199
0
                     ((PyTypeObject *)o)->tp_name);
200
0
        return NULL;
201
42
    }
202
203
0
    return type_error("'%.200s' object is not subscriptable", o);
204
42
}
205
206
int
207
PyMapping_GetOptionalItem(PyObject *obj, PyObject *key, PyObject **result)
208
97.7k
{
209
97.7k
    if (PyDict_CheckExact(obj)) {
210
97.4k
        return PyDict_GetItemRef(obj, key, result);
211
97.4k
    }
212
213
279
    *result = PyObject_GetItem(obj, key);
214
279
    if (*result) {
215
44
        return 1;
216
44
    }
217
235
    assert(PyErr_Occurred());
218
235
    if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
219
0
        return -1;
220
0
    }
221
235
    PyErr_Clear();
222
235
    return 0;
223
235
}
224
225
int
226
PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
227
197k
{
228
197k
    if (o == NULL || key == NULL || value == NULL) {
229
0
        null_error();
230
0
        return -1;
231
0
    }
232
233
197k
    PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
234
197k
    if (m && m->mp_ass_subscript) {
235
197k
        int res = m->mp_ass_subscript(o, key, value);
236
197k
        assert(_Py_CheckSlotResult(o, "__setitem__", res >= 0));
237
197k
        return res;
238
197k
    }
239
240
0
    if (Py_TYPE(o)->tp_as_sequence) {
241
0
        if (_PyIndex_Check(key)) {
242
0
            Py_ssize_t key_value;
243
0
            key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
244
0
            if (key_value == -1 && PyErr_Occurred())
245
0
                return -1;
246
0
            return PySequence_SetItem(o, key_value, value);
247
0
        }
248
0
        else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
249
0
            type_error("sequence index must be "
250
0
                       "integer, not '%.200s'", key);
251
0
            return -1;
252
0
        }
253
0
    }
254
255
0
    type_error("'%.200s' object does not support item assignment", o);
256
0
    return -1;
257
0
}
258
259
int
260
PyObject_DelItem(PyObject *o, PyObject *key)
261
383k
{
262
383k
    if (o == NULL || key == NULL) {
263
0
        null_error();
264
0
        return -1;
265
0
    }
266
267
383k
    PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
268
383k
    if (m && m->mp_ass_subscript) {
269
383k
        int res = m->mp_ass_subscript(o, key, (PyObject*)NULL);
270
383k
        assert(_Py_CheckSlotResult(o, "__delitem__", res >= 0));
271
383k
        return res;
272
383k
    }
273
274
0
    if (Py_TYPE(o)->tp_as_sequence) {
275
0
        if (_PyIndex_Check(key)) {
276
0
            Py_ssize_t key_value;
277
0
            key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
278
0
            if (key_value == -1 && PyErr_Occurred())
279
0
                return -1;
280
0
            return PySequence_DelItem(o, key_value);
281
0
        }
282
0
        else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
283
0
            type_error("sequence index must be "
284
0
                       "integer, not '%.200s'", key);
285
0
            return -1;
286
0
        }
287
0
    }
288
289
0
    type_error("'%.200s' object does not support item deletion", o);
290
0
    return -1;
291
0
}
292
293
int
294
PyObject_DelItemString(PyObject *o, const char *key)
295
0
{
296
0
    PyObject *okey;
297
0
    int ret;
298
299
0
    if (o == NULL || key == NULL) {
300
0
        null_error();
301
0
        return -1;
302
0
    }
303
0
    okey = PyUnicode_FromString(key);
304
0
    if (okey == NULL)
305
0
        return -1;
306
0
    ret = PyObject_DelItem(o, okey);
307
0
    Py_DECREF(okey);
308
0
    return ret;
309
0
}
310
311
312
/* Return 1 if the getbuffer function is available, otherwise return 0. */
313
int
314
PyObject_CheckBuffer(PyObject *obj)
315
8.53M
{
316
8.53M
    PyBufferProcs *tp_as_buffer = Py_TYPE(obj)->tp_as_buffer;
317
8.53M
    return (tp_as_buffer != NULL && tp_as_buffer->bf_getbuffer != NULL);
318
8.53M
}
319
320
// Old buffer protocols (deprecated, abi only)
321
322
/* Checks whether an arbitrary object supports the (character, single segment)
323
   buffer interface.
324
325
   Returns 1 on success, 0 on failure.
326
327
   We release the buffer right after use of this function which could
328
   cause issues later on.  Don't use these functions in new code.
329
 */
330
PyAPI_FUNC(int) /* abi_only */
331
PyObject_CheckReadBuffer(PyObject *obj)
332
0
{
333
0
    PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
334
0
    Py_buffer view;
335
336
0
    if (pb == NULL ||
337
0
        pb->bf_getbuffer == NULL)
338
0
        return 0;
339
0
    if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) {
340
0
        PyErr_Clear();
341
0
        return 0;
342
0
    }
343
0
    PyBuffer_Release(&view);
344
0
    return 1;
345
0
}
346
347
static int
348
as_read_buffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len)
349
0
{
350
0
    Py_buffer view;
351
352
0
    if (obj == NULL || buffer == NULL || buffer_len == NULL) {
353
0
        null_error();
354
0
        return -1;
355
0
    }
356
0
    if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0)
357
0
        return -1;
358
359
0
    *buffer = view.buf;
360
0
    *buffer_len = view.len;
361
0
    PyBuffer_Release(&view);
362
0
    return 0;
363
0
}
364
365
/* Takes an arbitrary object which must support the (character, single segment)
366
   buffer interface and returns a pointer to a read-only memory location
367
   usable as character based input for subsequent processing.
368
369
   Return 0 on success.  buffer and buffer_len are only set in case no error
370
   occurs. Otherwise, -1 is returned and an exception set. */
371
PyAPI_FUNC(int) /* abi_only */
372
PyObject_AsCharBuffer(PyObject *obj,
373
                      const char **buffer,
374
                      Py_ssize_t *buffer_len)
375
0
{
376
0
    return as_read_buffer(obj, (const void **)buffer, buffer_len);
377
0
}
378
379
/* Same as PyObject_AsCharBuffer() except that this API expects (readable,
380
   single segment) buffer interface and returns a pointer to a read-only memory
381
   location which can contain arbitrary data.
382
383
   0 is returned on success.  buffer and buffer_len are only set in case no
384
   error occurs.  Otherwise, -1 is returned and an exception set. */
385
PyAPI_FUNC(int) /* abi_only */
386
PyObject_AsReadBuffer(PyObject *obj,
387
                      const void **buffer,
388
                      Py_ssize_t *buffer_len)
389
0
{
390
0
    return as_read_buffer(obj, buffer, buffer_len);
391
0
}
392
393
/* Takes an arbitrary object which must support the (writable, single segment)
394
   buffer interface and returns a pointer to a writable memory location in
395
   buffer of size 'buffer_len'.
396
397
   Return 0 on success.  buffer and buffer_len are only set in case no error
398
   occurs. Otherwise, -1 is returned and an exception set. */
399
PyAPI_FUNC(int) /* abi_only */
400
PyObject_AsWriteBuffer(PyObject *obj,
401
                       void **buffer,
402
                       Py_ssize_t *buffer_len)
403
0
{
404
0
    PyBufferProcs *pb;
405
0
    Py_buffer view;
406
407
0
    if (obj == NULL || buffer == NULL || buffer_len == NULL) {
408
0
        null_error();
409
0
        return -1;
410
0
    }
411
0
    pb = Py_TYPE(obj)->tp_as_buffer;
412
0
    if (pb == NULL ||
413
0
        pb->bf_getbuffer == NULL ||
414
0
        ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) {
415
0
        PyErr_SetString(PyExc_TypeError,
416
0
                        "expected a writable bytes-like object");
417
0
        return -1;
418
0
    }
419
420
0
    *buffer = view.buf;
421
0
    *buffer_len = view.len;
422
0
    PyBuffer_Release(&view);
423
0
    return 0;
424
0
}
425
426
/* Buffer C-API for Python 3.0 */
427
428
int
429
PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
430
11.3M
{
431
11.3M
    if (flags != PyBUF_SIMPLE) {  /* fast path */
432
813k
        if (flags == PyBUF_READ || flags == PyBUF_WRITE) {
433
0
            PyErr_BadInternalCall();
434
0
            return -1;
435
0
        }
436
813k
    }
437
11.3M
    PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
438
439
11.3M
    if (pb == NULL || pb->bf_getbuffer == NULL) {
440
0
        PyErr_Format(PyExc_TypeError,
441
0
                     "a bytes-like object is required, not '%.100s'",
442
0
                     Py_TYPE(obj)->tp_name);
443
0
        return -1;
444
0
    }
445
11.3M
    int res = (*pb->bf_getbuffer)(obj, view, flags);
446
11.3M
    assert(_Py_CheckSlotResult(obj, "getbuffer", res >= 0));
447
11.3M
    return res;
448
11.3M
}
449
450
static int
451
_IsFortranContiguous(const Py_buffer *view)
452
0
{
453
0
    Py_ssize_t sd, dim;
454
0
    int i;
455
456
    /* 1) len = product(shape) * itemsize
457
       2) itemsize > 0
458
       3) len = 0 <==> exists i: shape[i] = 0 */
459
0
    if (view->len == 0) return 1;
460
0
    if (view->strides == NULL) {  /* C-contiguous by definition */
461
        /* Trivially F-contiguous */
462
0
        if (view->ndim <= 1) return 1;
463
464
        /* ndim > 1 implies shape != NULL */
465
0
        assert(view->shape != NULL);
466
467
        /* Effectively 1-d */
468
0
        sd = 0;
469
0
        for (i=0; i<view->ndim; i++) {
470
0
            if (view->shape[i] > 1) sd += 1;
471
0
        }
472
0
        return sd <= 1;
473
0
    }
474
475
    /* strides != NULL implies both of these */
476
0
    assert(view->ndim > 0);
477
0
    assert(view->shape != NULL);
478
479
0
    sd = view->itemsize;
480
0
    for (i=0; i<view->ndim; i++) {
481
0
        dim = view->shape[i];
482
0
        if (dim > 1 && view->strides[i] != sd) {
483
0
            return 0;
484
0
        }
485
0
        sd *= dim;
486
0
    }
487
0
    return 1;
488
0
}
489
490
static int
491
_IsCContiguous(const Py_buffer *view)
492
812k
{
493
812k
    Py_ssize_t sd, dim;
494
812k
    int i;
495
496
    /* 1) len = product(shape) * itemsize
497
       2) itemsize > 0
498
       3) len = 0 <==> exists i: shape[i] = 0 */
499
812k
    if (view->len == 0) return 1;
500
702k
    if (view->strides == NULL) return 1; /* C-contiguous by definition */
501
502
    /* strides != NULL implies both of these */
503
702k
    assert(view->ndim > 0);
504
702k
    assert(view->shape != NULL);
505
506
702k
    sd = view->itemsize;
507
1.40M
    for (i=view->ndim-1; i>=0; i--) {
508
702k
        dim = view->shape[i];
509
702k
        if (dim > 1 && view->strides[i] != sd) {
510
0
            return 0;
511
0
        }
512
702k
        sd *= dim;
513
702k
    }
514
702k
    return 1;
515
702k
}
516
517
int
518
PyBuffer_IsContiguous(const Py_buffer *view, char order)
519
812k
{
520
521
812k
    if (view->suboffsets != NULL) return 0;
522
523
812k
    if (order == 'C')
524
812k
        return _IsCContiguous(view);
525
0
    else if (order == 'F')
526
0
        return _IsFortranContiguous(view);
527
0
    else if (order == 'A')
528
0
        return (_IsCContiguous(view) || _IsFortranContiguous(view));
529
0
    return 0;
530
812k
}
531
532
533
void*
534
PyBuffer_GetPointer(const Py_buffer *view, const Py_ssize_t *indices)
535
0
{
536
0
    char* pointer;
537
0
    int i;
538
0
    pointer = (char *)view->buf;
539
0
    for (i = 0; i < view->ndim; i++) {
540
0
        pointer += view->strides[i]*indices[i];
541
0
        if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
542
0
            pointer = *((char**)pointer) + view->suboffsets[i];
543
0
        }
544
0
    }
545
0
    return (void*)pointer;
546
0
}
547
548
549
static void
550
_Py_add_one_to_index_F(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
551
0
{
552
0
    int k;
553
554
0
    for (k=0; k<nd; k++) {
555
0
        if (index[k] < shape[k]-1) {
556
0
            index[k]++;
557
0
            break;
558
0
        }
559
0
        else {
560
0
            index[k] = 0;
561
0
        }
562
0
    }
563
0
}
564
565
static void
566
_Py_add_one_to_index_C(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
567
0
{
568
0
    int k;
569
570
0
    for (k=nd-1; k>=0; k--) {
571
0
        if (index[k] < shape[k]-1) {
572
0
            index[k]++;
573
0
            break;
574
0
        }
575
0
        else {
576
0
            index[k] = 0;
577
0
        }
578
0
    }
579
0
}
580
581
Py_ssize_t
582
PyBuffer_SizeFromFormat(const char *format)
583
0
{
584
0
    PyObject *calcsize = NULL;
585
0
    PyObject *res = NULL;
586
0
    PyObject *fmt = NULL;
587
0
    Py_ssize_t itemsize = -1;
588
589
0
    calcsize = PyImport_ImportModuleAttrString("struct", "calcsize");
590
0
    if (calcsize == NULL) {
591
0
        goto done;
592
0
    }
593
594
0
    fmt = PyUnicode_FromString(format);
595
0
    if (fmt == NULL) {
596
0
        goto done;
597
0
    }
598
599
0
    res = PyObject_CallFunctionObjArgs(calcsize, fmt, NULL);
600
0
    if (res == NULL) {
601
0
        goto done;
602
0
    }
603
604
0
    itemsize = PyLong_AsSsize_t(res);
605
0
    if (itemsize < 0) {
606
0
        goto done;
607
0
    }
608
609
0
done:
610
0
    Py_XDECREF(calcsize);
611
0
    Py_XDECREF(fmt);
612
0
    Py_XDECREF(res);
613
0
    return itemsize;
614
0
}
615
616
int
617
PyBuffer_FromContiguous(const Py_buffer *view, const void *buf, Py_ssize_t len, char fort)
618
0
{
619
0
    int k;
620
0
    void (*addone)(int, Py_ssize_t *, const Py_ssize_t *);
621
0
    Py_ssize_t *indices, elements;
622
0
    char *ptr;
623
0
    const char *src;
624
625
0
    if (len > view->len) {
626
0
        len = view->len;
627
0
    }
628
629
0
    if (PyBuffer_IsContiguous(view, fort)) {
630
        /* simplest copy is all that is needed */
631
0
        memcpy(view->buf, buf, len);
632
0
        return 0;
633
0
    }
634
635
    /* Otherwise a more elaborate scheme is needed */
636
637
    /* view->ndim <= 64 */
638
0
    indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
639
0
    if (indices == NULL) {
640
0
        PyErr_NoMemory();
641
0
        return -1;
642
0
    }
643
0
    for (k=0; k<view->ndim;k++) {
644
0
        indices[k] = 0;
645
0
    }
646
647
0
    if (fort == 'F') {
648
0
        addone = _Py_add_one_to_index_F;
649
0
    }
650
0
    else {
651
0
        addone = _Py_add_one_to_index_C;
652
0
    }
653
0
    src = buf;
654
    /* XXX : This is not going to be the fastest code in the world
655
             several optimizations are possible.
656
     */
657
0
    elements = len / view->itemsize;
658
0
    while (elements--) {
659
0
        ptr = PyBuffer_GetPointer(view, indices);
660
0
        memcpy(ptr, src, view->itemsize);
661
0
        src += view->itemsize;
662
0
        addone(view->ndim, indices, view->shape);
663
0
    }
664
665
0
    PyMem_Free(indices);
666
0
    return 0;
667
0
}
668
669
int PyObject_CopyData(PyObject *dest, PyObject *src)
670
0
{
671
0
    Py_buffer view_dest, view_src;
672
0
    int k;
673
0
    Py_ssize_t *indices, elements;
674
0
    char *dptr, *sptr;
675
676
0
    if (!PyObject_CheckBuffer(dest) ||
677
0
        !PyObject_CheckBuffer(src)) {
678
0
        PyErr_SetString(PyExc_TypeError,
679
0
                        "both destination and source must be "\
680
0
                        "bytes-like objects");
681
0
        return -1;
682
0
    }
683
684
0
    if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
685
0
    if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
686
0
        PyBuffer_Release(&view_dest);
687
0
        return -1;
688
0
    }
689
690
0
    if (view_dest.len < view_src.len) {
691
0
        PyErr_SetString(PyExc_BufferError,
692
0
                        "destination is too small to receive data from source");
693
0
        PyBuffer_Release(&view_dest);
694
0
        PyBuffer_Release(&view_src);
695
0
        return -1;
696
0
    }
697
698
0
    if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
699
0
         PyBuffer_IsContiguous(&view_src, 'C')) ||
700
0
        (PyBuffer_IsContiguous(&view_dest, 'F') &&
701
0
         PyBuffer_IsContiguous(&view_src, 'F'))) {
702
        /* simplest copy is all that is needed */
703
0
        memcpy(view_dest.buf, view_src.buf, view_src.len);
704
0
        PyBuffer_Release(&view_dest);
705
0
        PyBuffer_Release(&view_src);
706
0
        return 0;
707
0
    }
708
709
    /* Otherwise a more elaborate copy scheme is needed */
710
711
    /* XXX(nnorwitz): need to check for overflow! */
712
0
    indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
713
0
    if (indices == NULL) {
714
0
        PyErr_NoMemory();
715
0
        PyBuffer_Release(&view_dest);
716
0
        PyBuffer_Release(&view_src);
717
0
        return -1;
718
0
    }
719
0
    for (k=0; k<view_src.ndim;k++) {
720
0
        indices[k] = 0;
721
0
    }
722
0
    elements = 1;
723
0
    for (k=0; k<view_src.ndim; k++) {
724
        /* XXX(nnorwitz): can this overflow? */
725
0
        elements *= view_src.shape[k];
726
0
    }
727
0
    while (elements--) {
728
0
        _Py_add_one_to_index_C(view_src.ndim, indices, view_src.shape);
729
0
        dptr = PyBuffer_GetPointer(&view_dest, indices);
730
0
        sptr = PyBuffer_GetPointer(&view_src, indices);
731
0
        memcpy(dptr, sptr, view_src.itemsize);
732
0
    }
733
0
    PyMem_Free(indices);
734
0
    PyBuffer_Release(&view_dest);
735
0
    PyBuffer_Release(&view_src);
736
0
    return 0;
737
0
}
738
739
void
740
PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
741
                               Py_ssize_t *strides, int itemsize,
742
                               char fort)
743
0
{
744
0
    int k;
745
0
    Py_ssize_t sd;
746
747
0
    sd = itemsize;
748
0
    if (fort == 'F') {
749
0
        for (k=0; k<nd; k++) {
750
0
            strides[k] = sd;
751
0
            sd *= shape[k];
752
0
        }
753
0
    }
754
0
    else {
755
0
        for (k=nd-1; k>=0; k--) {
756
0
            strides[k] = sd;
757
0
            sd *= shape[k];
758
0
        }
759
0
    }
760
0
    return;
761
0
}
762
763
int
764
PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
765
                  int readonly, int flags)
766
11.4M
{
767
11.4M
    if (view == NULL) {
768
0
        PyErr_SetString(PyExc_BufferError,
769
0
                        "PyBuffer_FillInfo: view==NULL argument is obsolete");
770
0
        return -1;
771
0
    }
772
773
11.4M
    if (flags != PyBUF_SIMPLE) {  /* fast path */
774
1.08M
        if (flags == PyBUF_READ || flags == PyBUF_WRITE) {
775
0
            PyErr_BadInternalCall();
776
0
            return -1;
777
0
        }
778
1.08M
        if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
779
1.08M
            (readonly == 1)) {
780
0
            PyErr_SetString(PyExc_BufferError,
781
0
                            "Object is not writable.");
782
0
            return -1;
783
0
        }
784
1.08M
    }
785
786
11.4M
    view->obj = Py_XNewRef(obj);
787
11.4M
    view->buf = buf;
788
11.4M
    view->len = len;
789
11.4M
    view->readonly = readonly;
790
11.4M
    view->itemsize = 1;
791
11.4M
    view->format = NULL;
792
11.4M
    if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
793
1.08M
        view->format = "B";
794
11.4M
    view->ndim = 1;
795
11.4M
    view->shape = NULL;
796
11.4M
    if ((flags & PyBUF_ND) == PyBUF_ND)
797
1.08M
        view->shape = &(view->len);
798
11.4M
    view->strides = NULL;
799
11.4M
    if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
800
1.08M
        view->strides = &(view->itemsize);
801
11.4M
    view->suboffsets = NULL;
802
11.4M
    view->internal = NULL;
803
11.4M
    return 0;
804
11.4M
}
805
806
void
807
PyBuffer_Release(Py_buffer *view)
808
12.8M
{
809
12.8M
    PyObject *obj = view->obj;
810
12.8M
    PyBufferProcs *pb;
811
12.8M
    if (obj == NULL)
812
1.35M
        return;
813
11.4M
    pb = Py_TYPE(obj)->tp_as_buffer;
814
11.4M
    if (pb && pb->bf_releasebuffer) {
815
973k
        pb->bf_releasebuffer(obj, view);
816
973k
    }
817
11.4M
    view->obj = NULL;
818
11.4M
    Py_DECREF(obj);
819
11.4M
}
820
821
static int
822
_buffer_release_call(void *arg)
823
0
{
824
0
    PyBuffer_Release((Py_buffer *)arg);
825
0
    return 0;
826
0
}
827
828
int
829
_PyBuffer_ReleaseInInterpreter(PyInterpreterState *interp,
830
                               Py_buffer *view)
831
0
{
832
0
    return _Py_CallInInterpreter(interp, _buffer_release_call, view);
833
0
}
834
835
int
836
_PyBuffer_ReleaseInInterpreterAndRawFree(PyInterpreterState *interp,
837
                                         Py_buffer *view)
838
0
{
839
0
    return _Py_CallInInterpreterAndRawFree(interp, _buffer_release_call, view);
840
0
}
841
842
PyObject *
843
PyObject_Format(PyObject *obj, PyObject *format_spec)
844
191k
{
845
191k
    PyObject *meth;
846
191k
    PyObject *empty = NULL;
847
191k
    PyObject *result = NULL;
848
849
191k
    if (format_spec != NULL && !PyUnicode_Check(format_spec)) {
850
0
        PyErr_Format(PyExc_SystemError,
851
0
                     "Format specifier must be a string, not %.200s",
852
0
                     Py_TYPE(format_spec)->tp_name);
853
0
        return NULL;
854
0
    }
855
856
    /* Fast path for common types. */
857
191k
    if (format_spec == NULL || PyUnicode_GET_LENGTH(format_spec) == 0) {
858
190k
        if (PyUnicode_CheckExact(obj)) {
859
0
            return Py_NewRef(obj);
860
0
        }
861
190k
        if (PyLong_CheckExact(obj)) {
862
832
            return PyObject_Str(obj);
863
832
        }
864
190k
    }
865
866
    /* If no format_spec is provided, use an empty string */
867
190k
    if (format_spec == NULL) {
868
0
        empty = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
869
0
        format_spec = empty;
870
0
    }
871
872
    /* Find the (unbound!) __format__ method */
873
190k
    meth = _PyObject_LookupSpecial(obj, &_Py_ID(__format__));
874
190k
    if (meth == NULL) {
875
0
        PyThreadState *tstate = _PyThreadState_GET();
876
0
        if (!_PyErr_Occurred(tstate)) {
877
0
            _PyErr_Format(tstate, PyExc_TypeError,
878
0
                          "Type %.100s doesn't define __format__",
879
0
                          Py_TYPE(obj)->tp_name);
880
0
        }
881
0
        goto done;
882
0
    }
883
884
    /* And call it. */
885
190k
    result = PyObject_CallOneArg(meth, format_spec);
886
190k
    Py_DECREF(meth);
887
888
190k
    if (result && !PyUnicode_Check(result)) {
889
0
        PyErr_Format(PyExc_TypeError,
890
0
                     "__format__ must return a str, not %.200s",
891
0
                     Py_TYPE(result)->tp_name);
892
0
        Py_SETREF(result, NULL);
893
0
        goto done;
894
0
    }
895
896
190k
done:
897
190k
    Py_XDECREF(empty);
898
190k
    return result;
899
190k
}
900
/* Operations on numbers */
901
902
int
903
PyNumber_Check(PyObject *o)
904
11.2M
{
905
11.2M
    if (o == NULL)
906
0
        return 0;
907
11.2M
    PyNumberMethods *nb = Py_TYPE(o)->tp_as_number;
908
11.2M
    return nb && (nb->nb_index || nb->nb_int || nb->nb_float || PyComplex_Check(o));
909
11.2M
}
910
911
/* Binary operators */
912
913
28.7M
#define NB_SLOT(x) offsetof(PyNumberMethods, x)
914
#define NB_BINOP(nb_methods, slot) \
915
36.3M
        (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
916
#define NB_TERNOP(nb_methods, slot) \
917
49
        (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
918
919
/*
920
  Calling scheme used for binary operations:
921
922
  Order operations are tried until either a valid result or error:
923
    w.op(v,w)[*], v.op(v,w), w.op(v,w)
924
925
  [*] only when Py_TYPE(v) != Py_TYPE(w) && Py_TYPE(w) is a subclass of
926
      Py_TYPE(v)
927
 */
928
929
static PyObject *
930
binary_op1(PyObject *v, PyObject *w, const int op_slot
931
#ifndef NDEBUG
932
           , const char *op_name
933
#endif
934
           )
935
48.0M
{
936
48.0M
    binaryfunc slotv;
937
48.0M
    if (Py_TYPE(v)->tp_as_number != NULL) {
938
28.8M
        slotv = NB_BINOP(Py_TYPE(v)->tp_as_number, op_slot);
939
28.8M
    }
940
19.2M
    else {
941
19.2M
        slotv = NULL;
942
19.2M
    }
943
944
48.0M
    binaryfunc slotw;
945
48.0M
    if (!Py_IS_TYPE(w, Py_TYPE(v)) && Py_TYPE(w)->tp_as_number != NULL) {
946
6.96M
        slotw = NB_BINOP(Py_TYPE(w)->tp_as_number, op_slot);
947
6.96M
        if (slotw == slotv) {
948
47.1k
            slotw = NULL;
949
47.1k
        }
950
6.96M
    }
951
41.0M
    else {
952
41.0M
        slotw = NULL;
953
41.0M
    }
954
955
48.0M
    if (slotv) {
956
28.3M
        PyObject *x;
957
28.3M
        if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
958
190
            x = slotw(v, w);
959
190
            if (x != Py_NotImplemented)
960
190
                return x;
961
0
            Py_DECREF(x); /* can't do it */
962
0
            slotw = NULL;
963
0
        }
964
28.3M
        x = slotv(v, w);
965
28.3M
        assert(_Py_CheckSlotResult(v, op_name, x != NULL));
966
28.3M
        if (x != Py_NotImplemented) {
967
28.3M
            return x;
968
28.3M
        }
969
9
        Py_DECREF(x); /* can't do it */
970
9
    }
971
19.6M
    if (slotw) {
972
351k
        PyObject *x = slotw(v, w);
973
351k
        assert(_Py_CheckSlotResult(w, op_name, x != NULL));
974
351k
        if (x != Py_NotImplemented) {
975
2
            return x;
976
2
        }
977
351k
        Py_DECREF(x); /* can't do it */
978
351k
    }
979
19.6M
    Py_RETURN_NOTIMPLEMENTED;
980
19.6M
}
981
982
#ifdef NDEBUG
983
47.4M
#  define BINARY_OP1(v, w, op_slot, op_name) binary_op1(v, w, op_slot)
984
#else
985
#  define BINARY_OP1(v, w, op_slot, op_name) binary_op1(v, w, op_slot, op_name)
986
#endif
987
988
static PyObject *
989
binop_type_error(PyObject *v, PyObject *w, const char *op_name)
990
0
{
991
0
    PyErr_Format(PyExc_TypeError,
992
0
                 "unsupported operand type(s) for %.100s: "
993
0
                 "'%.100s' and '%.100s'",
994
0
                 op_name,
995
0
                 Py_TYPE(v)->tp_name,
996
0
                 Py_TYPE(w)->tp_name);
997
0
    return NULL;
998
0
}
999
1000
static PyObject *
1001
binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
1002
27.6M
{
1003
27.6M
    PyObject *result = BINARY_OP1(v, w, op_slot, op_name);
1004
27.6M
    if (result == Py_NotImplemented) {
1005
0
        Py_DECREF(result);
1006
0
        return binop_type_error(v, w, op_name);
1007
0
    }
1008
27.6M
    return result;
1009
27.6M
}
1010
1011
1012
/*
1013
  Calling scheme used for ternary operations:
1014
1015
  Order operations are tried until either a valid result or error:
1016
    v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
1017
 */
1018
1019
static PyObject *
1020
ternary_op(PyObject *v,
1021
           PyObject *w,
1022
           PyObject *z,
1023
           const int op_slot,
1024
           const char *op_name
1025
           )
1026
49
{
1027
49
    PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
1028
49
    PyNumberMethods *mw = Py_TYPE(w)->tp_as_number;
1029
1030
49
    ternaryfunc slotv;
1031
49
    if (mv != NULL) {
1032
49
        slotv = NB_TERNOP(mv, op_slot);
1033
49
    }
1034
0
    else {
1035
0
        slotv = NULL;
1036
0
    }
1037
1038
49
    ternaryfunc slotw;
1039
49
    if (!Py_IS_TYPE(w, Py_TYPE(v)) && mw != NULL) {
1040
0
        slotw = NB_TERNOP(mw, op_slot);
1041
0
        if (slotw == slotv) {
1042
0
            slotw = NULL;
1043
0
        }
1044
0
    }
1045
49
    else {
1046
49
        slotw = NULL;
1047
49
    }
1048
1049
49
    if (slotv) {
1050
49
        PyObject *x;
1051
49
        if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
1052
0
            x = slotw(v, w, z);
1053
0
            if (x != Py_NotImplemented) {
1054
0
                return x;
1055
0
            }
1056
0
            Py_DECREF(x); /* can't do it */
1057
0
            slotw = NULL;
1058
0
        }
1059
49
        x = slotv(v, w, z);
1060
49
        assert(_Py_CheckSlotResult(v, op_name, x != NULL));
1061
49
        if (x != Py_NotImplemented) {
1062
49
            return x;
1063
49
        }
1064
0
        Py_DECREF(x); /* can't do it */
1065
0
    }
1066
0
    if (slotw) {
1067
0
        PyObject *x = slotw(v, w, z);
1068
0
        assert(_Py_CheckSlotResult(w, op_name, x != NULL));
1069
0
        if (x != Py_NotImplemented) {
1070
0
            return x;
1071
0
        }
1072
0
        Py_DECREF(x); /* can't do it */
1073
0
    }
1074
1075
0
    PyNumberMethods *mz = Py_TYPE(z)->tp_as_number;
1076
0
    if (mz != NULL) {
1077
0
        ternaryfunc slotz = NB_TERNOP(mz, op_slot);
1078
0
        if (slotz == slotv || slotz == slotw) {
1079
0
            slotz = NULL;
1080
0
        }
1081
0
        if (slotz) {
1082
0
            PyObject *x = slotz(v, w, z);
1083
0
            assert(_Py_CheckSlotResult(z, op_name, x != NULL));
1084
0
            if (x != Py_NotImplemented) {
1085
0
                return x;
1086
0
            }
1087
0
            Py_DECREF(x); /* can't do it */
1088
0
        }
1089
0
    }
1090
1091
0
    if (z == Py_None) {
1092
0
        PyErr_Format(
1093
0
            PyExc_TypeError,
1094
0
            "unsupported operand type(s) for %.100s: "
1095
0
            "'%.100s' and '%.100s'",
1096
0
            op_name,
1097
0
            Py_TYPE(v)->tp_name,
1098
0
            Py_TYPE(w)->tp_name);
1099
0
    }
1100
0
    else {
1101
0
        PyErr_Format(
1102
0
            PyExc_TypeError,
1103
0
            "unsupported operand type(s) for %.100s: "
1104
0
            "'%.100s', '%.100s', '%.100s'",
1105
0
            op_name,
1106
0
            Py_TYPE(v)->tp_name,
1107
0
            Py_TYPE(w)->tp_name,
1108
0
            Py_TYPE(z)->tp_name);
1109
0
    }
1110
0
    return NULL;
1111
0
}
1112
1113
#define BINARY_FUNC(func, op, op_name) \
1114
    PyObject * \
1115
27.6M
    func(PyObject *v, PyObject *w) { \
1116
27.6M
        return binary_op(v, w, NB_SLOT(op), op_name); \
1117
27.6M
    }
PyNumber_Or
Line
Count
Source
1115
361k
    func(PyObject *v, PyObject *w) { \
1116
361k
        return binary_op(v, w, NB_SLOT(op), op_name); \
1117
361k
    }
PyNumber_Xor
Line
Count
Source
1115
172
    func(PyObject *v, PyObject *w) { \
1116
172
        return binary_op(v, w, NB_SLOT(op), op_name); \
1117
172
    }
PyNumber_And
Line
Count
Source
1115
2.88k
    func(PyObject *v, PyObject *w) { \
1116
2.88k
        return binary_op(v, w, NB_SLOT(op), op_name); \
1117
2.88k
    }
PyNumber_Lshift
Line
Count
Source
1115
35
    func(PyObject *v, PyObject *w) { \
1116
35
        return binary_op(v, w, NB_SLOT(op), op_name); \
1117
35
    }
PyNumber_Rshift
Line
Count
Source
1115
156
    func(PyObject *v, PyObject *w) { \
1116
156
        return binary_op(v, w, NB_SLOT(op), op_name); \
1117
156
    }
PyNumber_Subtract
Line
Count
Source
1115
724
    func(PyObject *v, PyObject *w) { \
1116
724
        return binary_op(v, w, NB_SLOT(op), op_name); \
1117
724
    }
Unexecuted instantiation: PyNumber_Divmod
Unexecuted instantiation: PyNumber_MatrixMultiply
PyNumber_FloorDivide
Line
Count
Source
1115
1.25M
    func(PyObject *v, PyObject *w) { \
1116
1.25M
        return binary_op(v, w, NB_SLOT(op), op_name); \
1117
1.25M
    }
PyNumber_TrueDivide
Line
Count
Source
1115
11.6k
    func(PyObject *v, PyObject *w) { \
1116
11.6k
        return binary_op(v, w, NB_SLOT(op), op_name); \
1117
11.6k
    }
PyNumber_Remainder
Line
Count
Source
1115
26.0M
    func(PyObject *v, PyObject *w) { \
1116
26.0M
        return binary_op(v, w, NB_SLOT(op), op_name); \
1117
26.0M
    }
1118
1119
BINARY_FUNC(PyNumber_Or, nb_or, "|")
1120
BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
1121
BINARY_FUNC(PyNumber_And, nb_and, "&")
1122
BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
1123
BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
1124
BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
1125
BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
1126
1127
PyObject *
1128
PyNumber_Add(PyObject *v, PyObject *w)
1129
19.3M
{
1130
19.3M
    PyObject *result = BINARY_OP1(v, w, NB_SLOT(nb_add), "+");
1131
19.3M
    if (result != Py_NotImplemented) {
1132
63.2k
        return result;
1133
63.2k
    }
1134
19.2M
    Py_DECREF(result);
1135
1136
19.2M
    PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
1137
19.2M
    if (m && m->sq_concat) {
1138
19.2M
        result = (*m->sq_concat)(v, w);
1139
19.2M
        assert(_Py_CheckSlotResult(v, "+", result != NULL));
1140
19.2M
        return result;
1141
19.2M
    }
1142
1143
0
    return binop_type_error(v, w, "+");
1144
19.2M
}
1145
1146
static PyObject *
1147
sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
1148
351k
{
1149
351k
    Py_ssize_t count;
1150
351k
    if (_PyIndex_Check(n)) {
1151
351k
        count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
1152
351k
        if (count == -1 && PyErr_Occurred()) {
1153
0
            return NULL;
1154
0
        }
1155
351k
    }
1156
0
    else {
1157
0
        return type_error("can't multiply sequence by "
1158
0
                          "non-int of type '%.200s'", n);
1159
0
    }
1160
351k
    PyObject *res = (*repeatfunc)(seq, count);
1161
351k
    assert(_Py_CheckSlotResult(seq, "*", res != NULL));
1162
351k
    return res;
1163
351k
}
1164
1165
PyObject *
1166
PyNumber_Multiply(PyObject *v, PyObject *w)
1167
492k
{
1168
492k
    PyObject *result = BINARY_OP1(v, w, NB_SLOT(nb_multiply), "*");
1169
492k
    if (result == Py_NotImplemented) {
1170
351k
        PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
1171
351k
        PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
1172
351k
        Py_DECREF(result);
1173
351k
        if  (mv && mv->sq_repeat) {
1174
351k
            return sequence_repeat(mv->sq_repeat, v, w);
1175
351k
        }
1176
7
        else if (mw && mw->sq_repeat) {
1177
7
            return sequence_repeat(mw->sq_repeat, w, v);
1178
7
        }
1179
0
        result = binop_type_error(v, w, "*");
1180
0
    }
1181
140k
    return result;
1182
492k
}
1183
1184
BINARY_FUNC(PyNumber_MatrixMultiply, nb_matrix_multiply, "@")
1185
BINARY_FUNC(PyNumber_FloorDivide, nb_floor_divide, "//")
1186
BINARY_FUNC(PyNumber_TrueDivide, nb_true_divide, "/")
1187
BINARY_FUNC(PyNumber_Remainder, nb_remainder, "%")
1188
1189
PyObject *
1190
PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
1191
49
{
1192
49
    return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
1193
49
}
1194
1195
PyObject *
1196
_PyNumber_PowerNoMod(PyObject *lhs, PyObject *rhs)
1197
41
{
1198
41
    return PyNumber_Power(lhs, rhs, Py_None);
1199
41
}
1200
1201
/* Binary in-place operators */
1202
1203
/* The in-place operators are defined to fall back to the 'normal',
1204
   non in-place operations, if the in-place methods are not in place.
1205
1206
   - If the left hand object has the appropriate struct members, and
1207
     they are filled, call the appropriate function and return the
1208
     result.  No coercion is done on the arguments; the left-hand object
1209
     is the one the operation is performed on, and it's up to the
1210
     function to deal with the right-hand object.
1211
1212
   - Otherwise, in-place modification is not supported. Handle it exactly as
1213
     a non in-place operation of the same kind.
1214
1215
   */
1216
1217
static PyObject *
1218
binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot
1219
#ifndef NDEBUG
1220
            , const char *op_name
1221
#endif
1222
            )
1223
600k
{
1224
600k
    PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
1225
600k
    if (mv != NULL) {
1226
600k
        binaryfunc slot = NB_BINOP(mv, iop_slot);
1227
600k
        if (slot) {
1228
47.4k
            PyObject *x = (slot)(v, w);
1229
47.4k
            assert(_Py_CheckSlotResult(v, op_name, x != NULL));
1230
47.4k
            if (x != Py_NotImplemented) {
1231
47.4k
                return x;
1232
47.4k
            }
1233
0
            Py_DECREF(x);
1234
0
        }
1235
600k
    }
1236
553k
#ifdef NDEBUG
1237
553k
    return binary_op1(v, w, op_slot);
1238
#else
1239
    return binary_op1(v, w, op_slot, op_name);
1240
#endif
1241
600k
}
1242
1243
#ifdef NDEBUG
1244
600k
#  define BINARY_IOP1(v, w, iop_slot, op_slot, op_name) binary_iop1(v, w, iop_slot, op_slot)
1245
#else
1246
#  define BINARY_IOP1(v, w, iop_slot, op_slot, op_name) binary_iop1(v, w, iop_slot, op_slot, op_name)
1247
#endif
1248
1249
static PyObject *
1250
binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
1251
                const char *op_name)
1252
536k
{
1253
536k
    PyObject *result = BINARY_IOP1(v, w, iop_slot, op_slot, op_name);
1254
536k
    if (result == Py_NotImplemented) {
1255
0
        Py_DECREF(result);
1256
0
        return binop_type_error(v, w, op_name);
1257
0
    }
1258
536k
    return result;
1259
536k
}
1260
1261
static PyObject *
1262
ternary_iop(PyObject *v, PyObject *w, PyObject *z, const int iop_slot, const int op_slot,
1263
                const char *op_name)
1264
0
{
1265
0
    PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
1266
0
    if (mv != NULL) {
1267
0
        ternaryfunc slot = NB_TERNOP(mv, iop_slot);
1268
0
        if (slot) {
1269
0
            PyObject *x = (slot)(v, w, z);
1270
0
            if (x != Py_NotImplemented) {
1271
0
                return x;
1272
0
            }
1273
0
            Py_DECREF(x);
1274
0
        }
1275
0
    }
1276
0
    return ternary_op(v, w, z, op_slot, op_name);
1277
0
}
1278
1279
#define INPLACE_BINOP(func, iop, op, op_name) \
1280
    PyObject * \
1281
536k
    func(PyObject *v, PyObject *w) { \
1282
536k
        return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1283
536k
    }
PyNumber_InPlaceOr
Line
Count
Source
1281
47.5k
    func(PyObject *v, PyObject *w) { \
1282
47.5k
        return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1283
47.5k
    }
PyNumber_InPlaceXor
Line
Count
Source
1281
8
    func(PyObject *v, PyObject *w) { \
1282
8
        return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1283
8
    }
PyNumber_InPlaceAnd
Line
Count
Source
1281
23
    func(PyObject *v, PyObject *w) { \
1282
23
        return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1283
23
    }
PyNumber_InPlaceLshift
Line
Count
Source
1281
492
    func(PyObject *v, PyObject *w) { \
1282
492
        return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1283
492
    }
Unexecuted instantiation: PyNumber_InPlaceRshift
PyNumber_InPlaceSubtract
Line
Count
Source
1281
18
    func(PyObject *v, PyObject *w) { \
1282
18
        return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1283
18
    }
Unexecuted instantiation: PyNumber_InPlaceMatrixMultiply
PyNumber_InPlaceFloorDivide
Line
Count
Source
1281
487k
    func(PyObject *v, PyObject *w) { \
1282
487k
        return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1283
487k
    }
Unexecuted instantiation: PyNumber_InPlaceTrueDivide
Unexecuted instantiation: PyNumber_InPlaceRemainder
1284
1285
INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1286
INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1287
INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1288
INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1289
INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1290
INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
1291
INPLACE_BINOP(PyNumber_InPlaceMatrixMultiply, nb_inplace_matrix_multiply, nb_matrix_multiply, "@=")
1292
INPLACE_BINOP(PyNumber_InPlaceFloorDivide, nb_inplace_floor_divide, nb_floor_divide, "//=")
1293
INPLACE_BINOP(PyNumber_InPlaceTrueDivide, nb_inplace_true_divide, nb_true_divide,  "/=")
1294
INPLACE_BINOP(PyNumber_InPlaceRemainder, nb_inplace_remainder, nb_remainder, "%=")
1295
1296
PyObject *
1297
PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1298
64.7k
{
1299
64.7k
    PyObject *result = BINARY_IOP1(v, w, NB_SLOT(nb_inplace_add),
1300
64.7k
                                   NB_SLOT(nb_add), "+=");
1301
64.7k
    if (result == Py_NotImplemented) {
1302
476
        PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
1303
476
        Py_DECREF(result);
1304
476
        if (m != NULL) {
1305
476
            binaryfunc func = m->sq_inplace_concat;
1306
476
            if (func == NULL)
1307
86
                func = m->sq_concat;
1308
476
            if (func != NULL) {
1309
476
                result = func(v, w);
1310
476
                assert(_Py_CheckSlotResult(v, "+=", result != NULL));
1311
476
                return result;
1312
476
            }
1313
476
        }
1314
0
        result = binop_type_error(v, w, "+=");
1315
0
    }
1316
64.3k
    return result;
1317
64.7k
}
1318
1319
PyObject *
1320
PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1321
0
{
1322
0
    PyObject *result = BINARY_IOP1(v, w, NB_SLOT(nb_inplace_multiply),
1323
0
                                   NB_SLOT(nb_multiply), "*=");
1324
0
    if (result == Py_NotImplemented) {
1325
0
        ssizeargfunc f = NULL;
1326
0
        PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
1327
0
        PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
1328
0
        Py_DECREF(result);
1329
0
        if (mv != NULL) {
1330
0
            f = mv->sq_inplace_repeat;
1331
0
            if (f == NULL)
1332
0
                f = mv->sq_repeat;
1333
0
            if (f != NULL)
1334
0
                return sequence_repeat(f, v, w);
1335
0
        }
1336
0
        else if (mw != NULL) {
1337
            /* Note that the right hand operand should not be
1338
             * mutated in this case so sq_inplace_repeat is not
1339
             * used. */
1340
0
            if (mw->sq_repeat)
1341
0
                return sequence_repeat(mw->sq_repeat, w, v);
1342
0
        }
1343
0
        result = binop_type_error(v, w, "*=");
1344
0
    }
1345
0
    return result;
1346
0
}
1347
1348
PyObject *
1349
PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1350
0
{
1351
0
    return ternary_iop(v, w, z, NB_SLOT(nb_inplace_power),
1352
0
                                NB_SLOT(nb_power), "**=");
1353
0
}
1354
1355
PyObject *
1356
_PyNumber_InPlacePowerNoMod(PyObject *lhs, PyObject *rhs)
1357
0
{
1358
0
    return PyNumber_InPlacePower(lhs, rhs, Py_None);
1359
0
}
1360
1361
1362
/* Unary operators and functions */
1363
1364
#define UNARY_FUNC(func, op, meth_name, descr)                           \
1365
    PyObject *                                                           \
1366
11.3k
    func(PyObject *o) {                                                  \
1367
11.3k
        if (o == NULL) {                                                 \
1368
0
            return null_error();                                         \
1369
0
        }                                                                \
1370
11.3k
                                                                         \
1371
11.3k
        PyNumberMethods *m = Py_TYPE(o)->tp_as_number;                   \
1372
11.3k
        if (m && m->op) {                                                \
1373
11.3k
            PyObject *res = (*m->op)(o);                                 \
1374
11.3k
            assert(_Py_CheckSlotResult(o, #meth_name, res != NULL));     \
1375
11.3k
            return res;                                                  \
1376
11.3k
        }                                                                \
1377
11.3k
                                                                         \
1378
11.3k
        return type_error("bad operand type for "descr": '%.200s'", o);  \
1379
11.3k
    }
PyNumber_Negative
Line
Count
Source
1366
11.1k
    func(PyObject *o) {                                                  \
1367
11.1k
        if (o == NULL) {                                                 \
1368
0
            return null_error();                                         \
1369
0
        }                                                                \
1370
11.1k
                                                                         \
1371
11.1k
        PyNumberMethods *m = Py_TYPE(o)->tp_as_number;                   \
1372
11.1k
        if (m && m->op) {                                                \
1373
11.1k
            PyObject *res = (*m->op)(o);                                 \
1374
11.1k
            assert(_Py_CheckSlotResult(o, #meth_name, res != NULL));     \
1375
11.1k
            return res;                                                  \
1376
11.1k
        }                                                                \
1377
11.1k
                                                                         \
1378
11.1k
        return type_error("bad operand type for "descr": '%.200s'", o);  \
1379
11.1k
    }
Unexecuted instantiation: PyNumber_Positive
PyNumber_Invert
Line
Count
Source
1366
270
    func(PyObject *o) {                                                  \
1367
270
        if (o == NULL) {                                                 \
1368
0
            return null_error();                                         \
1369
0
        }                                                                \
1370
270
                                                                         \
1371
270
        PyNumberMethods *m = Py_TYPE(o)->tp_as_number;                   \
1372
270
        if (m && m->op) {                                                \
1373
270
            PyObject *res = (*m->op)(o);                                 \
1374
270
            assert(_Py_CheckSlotResult(o, #meth_name, res != NULL));     \
1375
270
            return res;                                                  \
1376
270
        }                                                                \
1377
270
                                                                         \
1378
270
        return type_error("bad operand type for "descr": '%.200s'", o);  \
1379
270
    }
Unexecuted instantiation: PyNumber_Absolute
1380
1381
UNARY_FUNC(PyNumber_Negative, nb_negative, __neg__, "unary -")
1382
UNARY_FUNC(PyNumber_Positive, nb_positive, __pos__, "unary +")
1383
UNARY_FUNC(PyNumber_Invert, nb_invert, __invert__, "unary ~")
1384
UNARY_FUNC(PyNumber_Absolute, nb_absolute, __abs__, "abs()")
1385
1386
1387
int
1388
PyIndex_Check(PyObject *obj)
1389
134M
{
1390
134M
    return _PyIndex_Check(obj);
1391
134M
}
1392
1393
1394
/* Return a Python int from the object item.
1395
   Can return an instance of int subclass.
1396
   Raise TypeError if the result is not an int
1397
   or if the object cannot be interpreted as an index.
1398
*/
1399
PyObject *
1400
_PyNumber_Index(PyObject *item)
1401
417M
{
1402
417M
    if (item == NULL) {
1403
0
        return null_error();
1404
0
    }
1405
1406
417M
    if (PyLong_Check(item)) {
1407
417M
        return Py_NewRef(item);
1408
417M
    }
1409
3.77k
    if (!_PyIndex_Check(item)) {
1410
3.77k
        PyErr_Format(PyExc_TypeError,
1411
3.77k
                     "'%.200s' object cannot be interpreted "
1412
3.77k
                     "as an integer", Py_TYPE(item)->tp_name);
1413
3.77k
        return NULL;
1414
3.77k
    }
1415
1416
0
    PyObject *result = Py_TYPE(item)->tp_as_number->nb_index(item);
1417
0
    assert(_Py_CheckSlotResult(item, "__index__", result != NULL));
1418
0
    if (!result || PyLong_CheckExact(result)) {
1419
0
        return result;
1420
0
    }
1421
1422
0
    if (!PyLong_Check(result)) {
1423
0
        PyErr_Format(PyExc_TypeError,
1424
0
                     "__index__ returned non-int (type %.200s)",
1425
0
                     Py_TYPE(result)->tp_name);
1426
0
        Py_DECREF(result);
1427
0
        return NULL;
1428
0
    }
1429
    /* Issue #17576: warn if 'result' not of exact type int. */
1430
0
    if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1431
0
            "__index__ returned non-int (type %.200s).  "
1432
0
            "The ability to return an instance of a strict subclass of int "
1433
0
            "is deprecated, and may be removed in a future version of Python.",
1434
0
            Py_TYPE(result)->tp_name)) {
1435
0
        Py_DECREF(result);
1436
0
        return NULL;
1437
0
    }
1438
0
    return result;
1439
0
}
1440
1441
/* Return an exact Python int from the object item.
1442
   Raise TypeError if the result is not an int
1443
   or if the object cannot be interpreted as an index.
1444
*/
1445
PyObject *
1446
PyNumber_Index(PyObject *item)
1447
16.5M
{
1448
16.5M
    PyObject *result = _PyNumber_Index(item);
1449
16.5M
    if (result != NULL && !PyLong_CheckExact(result)) {
1450
0
        Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1451
0
    }
1452
16.5M
    return result;
1453
16.5M
}
1454
1455
/* Return an error on Overflow only if err is not NULL*/
1456
1457
Py_ssize_t
1458
PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1459
319M
{
1460
319M
    Py_ssize_t result;
1461
319M
    PyObject *runerr;
1462
319M
    PyObject *value = _PyNumber_Index(item);
1463
319M
    if (value == NULL)
1464
2.82k
        return -1;
1465
1466
    /* We're done if PyLong_AsSsize_t() returns without error. */
1467
319M
    result = PyLong_AsSsize_t(value);
1468
319M
    if (result != -1)
1469
300M
        goto finish;
1470
1471
18.2M
    PyThreadState *tstate = _PyThreadState_GET();
1472
18.2M
    runerr = _PyErr_Occurred(tstate);
1473
18.2M
    if (!runerr) {
1474
18.2M
        goto finish;
1475
18.2M
    }
1476
1477
    /* Error handling code -- only manage OverflowError differently */
1478
0
    if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) {
1479
0
        goto finish;
1480
0
    }
1481
0
    _PyErr_Clear(tstate);
1482
1483
    /* If no error-handling desired then the default clipping
1484
       is sufficient. */
1485
0
    if (!err) {
1486
0
        assert(PyLong_Check(value));
1487
        /* Whether or not it is less than or equal to
1488
           zero is determined by the sign of ob_size
1489
        */
1490
0
        if (_PyLong_IsNegative((PyLongObject *)value))
1491
0
            result = PY_SSIZE_T_MIN;
1492
0
        else
1493
0
            result = PY_SSIZE_T_MAX;
1494
0
    }
1495
0
    else {
1496
        /* Otherwise replace the error with caller's error object. */
1497
0
        _PyErr_Format(tstate, err,
1498
0
                      "cannot fit '%.200s' into an index-sized integer",
1499
0
                      Py_TYPE(item)->tp_name);
1500
0
    }
1501
1502
319M
 finish:
1503
319M
    Py_DECREF(value);
1504
319M
    return result;
1505
0
}
1506
1507
1508
PyObject *
1509
PyNumber_Long(PyObject *o)
1510
2.79M
{
1511
2.79M
    PyObject *result;
1512
2.79M
    PyNumberMethods *m;
1513
2.79M
    Py_buffer view;
1514
1515
2.79M
    if (o == NULL) {
1516
0
        return null_error();
1517
0
    }
1518
1519
2.79M
    if (PyLong_CheckExact(o)) {
1520
2.75k
        return Py_NewRef(o);
1521
2.75k
    }
1522
2.79M
    m = Py_TYPE(o)->tp_as_number;
1523
2.79M
    if (m && m->nb_int) { /* This should include subclasses of int */
1524
        /* Convert using the nb_int slot, which should return something
1525
           of exact type int. */
1526
13.0k
        result = m->nb_int(o);
1527
13.0k
        assert(_Py_CheckSlotResult(o, "__int__", result != NULL));
1528
13.0k
        if (!result || PyLong_CheckExact(result)) {
1529
13.0k
            return result;
1530
13.0k
        }
1531
1532
0
        if (!PyLong_Check(result)) {
1533
0
            PyErr_Format(PyExc_TypeError,
1534
0
                         "__int__ returned non-int (type %.200s)",
1535
0
                         Py_TYPE(result)->tp_name);
1536
0
            Py_DECREF(result);
1537
0
            return NULL;
1538
0
        }
1539
        /* Issue #17576: warn if 'result' not of exact type int. */
1540
0
        if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1541
0
                "__int__ returned non-int (type %.200s).  "
1542
0
                "The ability to return an instance of a strict subclass of int "
1543
0
                "is deprecated, and may be removed in a future version of Python.",
1544
0
                Py_TYPE(result)->tp_name)) {
1545
0
            Py_DECREF(result);
1546
0
            return NULL;
1547
0
        }
1548
0
        Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1549
0
        return result;
1550
0
    }
1551
2.78M
    if (m && m->nb_index) {
1552
0
        return PyNumber_Index(o);
1553
0
    }
1554
1555
2.78M
    if (PyUnicode_Check(o))
1556
        /* The below check is done in PyLong_FromUnicodeObject(). */
1557
2.78M
        return PyLong_FromUnicodeObject(o, 10);
1558
1559
0
    if (PyBytes_Check(o))
1560
        /* need to do extra error checking that PyLong_FromString()
1561
         * doesn't do.  In particular int('9\x005') must raise an
1562
         * exception, not truncate at the null.
1563
         */
1564
0
        return _PyLong_FromBytes(PyBytes_AS_STRING(o),
1565
0
                                 PyBytes_GET_SIZE(o), 10);
1566
1567
0
    if (PyByteArray_Check(o))
1568
0
        return _PyLong_FromBytes(PyByteArray_AS_STRING(o),
1569
0
                                 PyByteArray_GET_SIZE(o), 10);
1570
1571
0
    if (PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) == 0) {
1572
0
        PyObject *bytes;
1573
1574
        /* Copy to NUL-terminated buffer. */
1575
0
        bytes = PyBytes_FromStringAndSize((const char *)view.buf, view.len);
1576
0
        if (bytes == NULL) {
1577
0
            PyBuffer_Release(&view);
1578
0
            return NULL;
1579
0
        }
1580
0
        result = _PyLong_FromBytes(PyBytes_AS_STRING(bytes),
1581
0
                                   PyBytes_GET_SIZE(bytes), 10);
1582
0
        Py_DECREF(bytes);
1583
0
        PyBuffer_Release(&view);
1584
0
        return result;
1585
0
    }
1586
1587
0
    return type_error("int() argument must be a string, a bytes-like object "
1588
0
                      "or a real number, not '%.200s'", o);
1589
0
}
1590
1591
PyObject *
1592
PyNumber_Float(PyObject *o)
1593
0
{
1594
0
    if (o == NULL) {
1595
0
        return null_error();
1596
0
    }
1597
1598
0
    if (PyFloat_CheckExact(o)) {
1599
0
        return Py_NewRef(o);
1600
0
    }
1601
1602
0
    PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
1603
0
    if (m && m->nb_float) { /* This should include subclasses of float */
1604
0
        PyObject *res = m->nb_float(o);
1605
0
        assert(_Py_CheckSlotResult(o, "__float__", res != NULL));
1606
0
        if (!res || PyFloat_CheckExact(res)) {
1607
0
            return res;
1608
0
        }
1609
1610
0
        if (!PyFloat_Check(res)) {
1611
0
            PyErr_Format(PyExc_TypeError,
1612
0
                         "%.50s.__float__ returned non-float (type %.50s)",
1613
0
                         Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name);
1614
0
            Py_DECREF(res);
1615
0
            return NULL;
1616
0
        }
1617
        /* Issue #26983: warn if 'res' not of exact type float. */
1618
0
        if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1619
0
                "%.50s.__float__ returned non-float (type %.50s).  "
1620
0
                "The ability to return an instance of a strict subclass of float "
1621
0
                "is deprecated, and may be removed in a future version of Python.",
1622
0
                Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name)) {
1623
0
            Py_DECREF(res);
1624
0
            return NULL;
1625
0
        }
1626
0
        double val = PyFloat_AS_DOUBLE(res);
1627
0
        Py_DECREF(res);
1628
0
        return PyFloat_FromDouble(val);
1629
0
    }
1630
1631
0
    if (m && m->nb_index) {
1632
0
        PyObject *res = _PyNumber_Index(o);
1633
0
        if (!res) {
1634
0
            return NULL;
1635
0
        }
1636
0
        double val = PyLong_AsDouble(res);
1637
0
        Py_DECREF(res);
1638
0
        if (val == -1.0 && PyErr_Occurred()) {
1639
0
            return NULL;
1640
0
        }
1641
0
        return PyFloat_FromDouble(val);
1642
0
    }
1643
1644
    /* A float subclass with nb_float == NULL */
1645
0
    if (PyFloat_Check(o)) {
1646
0
        return PyFloat_FromDouble(PyFloat_AS_DOUBLE(o));
1647
0
    }
1648
0
    return PyFloat_FromString(o);
1649
0
}
1650
1651
1652
PyObject *
1653
PyNumber_ToBase(PyObject *n, int base)
1654
1.53k
{
1655
1.53k
    if (!(base == 2 || base == 8 || base == 10 || base == 16)) {
1656
0
        PyErr_SetString(PyExc_SystemError,
1657
0
                        "PyNumber_ToBase: base must be 2, 8, 10 or 16");
1658
0
        return NULL;
1659
0
    }
1660
1.53k
    PyObject *index = _PyNumber_Index(n);
1661
1.53k
    if (!index)
1662
0
        return NULL;
1663
1.53k
    PyObject *res = _PyLong_Format(index, base);
1664
1.53k
    Py_DECREF(index);
1665
1.53k
    return res;
1666
1.53k
}
1667
1668
1669
/* Operations on sequences */
1670
1671
int
1672
PySequence_Check(PyObject *s)
1673
1.19k
{
1674
1.19k
    if (PyDict_Check(s))
1675
0
        return 0;
1676
1.19k
    return Py_TYPE(s)->tp_as_sequence &&
1677
1.19k
        Py_TYPE(s)->tp_as_sequence->sq_item != NULL;
1678
1.19k
}
1679
1680
Py_ssize_t
1681
PySequence_Size(PyObject *s)
1682
10
{
1683
10
    if (s == NULL) {
1684
0
        null_error();
1685
0
        return -1;
1686
0
    }
1687
1688
10
    PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1689
10
    if (m && m->sq_length) {
1690
10
        Py_ssize_t len = m->sq_length(s);
1691
10
        assert(_Py_CheckSlotResult(s, "__len__", len >= 0));
1692
10
        return len;
1693
10
    }
1694
1695
0
    if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_length) {
1696
0
        type_error("%.200s is not a sequence", s);
1697
0
        return -1;
1698
0
    }
1699
0
    type_error("object of type '%.200s' has no len()", s);
1700
0
    return -1;
1701
0
}
1702
1703
#undef PySequence_Length
1704
Py_ssize_t
1705
PySequence_Length(PyObject *s)
1706
0
{
1707
0
    return PySequence_Size(s);
1708
0
}
1709
#define PySequence_Length PySequence_Size
1710
1711
PyObject *
1712
PySequence_Concat(PyObject *s, PyObject *o)
1713
0
{
1714
0
    if (s == NULL || o == NULL) {
1715
0
        return null_error();
1716
0
    }
1717
1718
0
    PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1719
0
    if (m && m->sq_concat) {
1720
0
        PyObject *res = m->sq_concat(s, o);
1721
0
        assert(_Py_CheckSlotResult(s, "+", res != NULL));
1722
0
        return res;
1723
0
    }
1724
1725
    /* Instances of user classes defining an __add__() method only
1726
       have an nb_add slot, not an sq_concat slot.      So we fall back
1727
       to nb_add if both arguments appear to be sequences. */
1728
0
    if (PySequence_Check(s) && PySequence_Check(o)) {
1729
0
        PyObject *result = BINARY_OP1(s, o, NB_SLOT(nb_add), "+");
1730
0
        if (result != Py_NotImplemented)
1731
0
            return result;
1732
0
        Py_DECREF(result);
1733
0
    }
1734
0
    return type_error("'%.200s' object can't be concatenated", s);
1735
0
}
1736
1737
PyObject *
1738
PySequence_Repeat(PyObject *o, Py_ssize_t count)
1739
0
{
1740
0
    if (o == NULL) {
1741
0
        return null_error();
1742
0
    }
1743
1744
0
    PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
1745
0
    if (m && m->sq_repeat) {
1746
0
        PyObject *res = m->sq_repeat(o, count);
1747
0
        assert(_Py_CheckSlotResult(o, "*", res != NULL));
1748
0
        return res;
1749
0
    }
1750
1751
    /* Instances of user classes defining a __mul__() method only
1752
       have an nb_multiply slot, not an sq_repeat slot. so we fall back
1753
       to nb_multiply if o appears to be a sequence. */
1754
0
    if (PySequence_Check(o)) {
1755
0
        PyObject *n, *result;
1756
0
        n = PyLong_FromSsize_t(count);
1757
0
        if (n == NULL)
1758
0
            return NULL;
1759
0
        result = BINARY_OP1(o, n, NB_SLOT(nb_multiply), "*");
1760
0
        Py_DECREF(n);
1761
0
        if (result != Py_NotImplemented)
1762
0
            return result;
1763
0
        Py_DECREF(result);
1764
0
    }
1765
0
    return type_error("'%.200s' object can't be repeated", o);
1766
0
}
1767
1768
PyObject *
1769
PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1770
0
{
1771
0
    if (s == NULL || o == NULL) {
1772
0
        return null_error();
1773
0
    }
1774
1775
0
    PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1776
0
    if (m && m->sq_inplace_concat) {
1777
0
        PyObject *res = m->sq_inplace_concat(s, o);
1778
0
        assert(_Py_CheckSlotResult(s, "+=", res != NULL));
1779
0
        return res;
1780
0
    }
1781
0
    if (m && m->sq_concat) {
1782
0
        PyObject *res = m->sq_concat(s, o);
1783
0
        assert(_Py_CheckSlotResult(s, "+", res != NULL));
1784
0
        return res;
1785
0
    }
1786
1787
0
    if (PySequence_Check(s) && PySequence_Check(o)) {
1788
0
        PyObject *result = BINARY_IOP1(s, o, NB_SLOT(nb_inplace_add),
1789
0
                                       NB_SLOT(nb_add), "+=");
1790
0
        if (result != Py_NotImplemented)
1791
0
            return result;
1792
0
        Py_DECREF(result);
1793
0
    }
1794
0
    return type_error("'%.200s' object can't be concatenated", s);
1795
0
}
1796
1797
PyObject *
1798
PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
1799
0
{
1800
0
    if (o == NULL) {
1801
0
        return null_error();
1802
0
    }
1803
1804
0
    PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
1805
0
    if (m && m->sq_inplace_repeat) {
1806
0
        PyObject *res = m->sq_inplace_repeat(o, count);
1807
0
        assert(_Py_CheckSlotResult(o, "*=", res != NULL));
1808
0
        return res;
1809
0
    }
1810
0
    if (m && m->sq_repeat) {
1811
0
        PyObject *res = m->sq_repeat(o, count);
1812
0
        assert(_Py_CheckSlotResult(o, "*", res != NULL));
1813
0
        return res;
1814
0
    }
1815
1816
0
    if (PySequence_Check(o)) {
1817
0
        PyObject *n, *result;
1818
0
        n = PyLong_FromSsize_t(count);
1819
0
        if (n == NULL)
1820
0
            return NULL;
1821
0
        result = BINARY_IOP1(o, n, NB_SLOT(nb_inplace_multiply),
1822
0
                             NB_SLOT(nb_multiply), "*=");
1823
0
        Py_DECREF(n);
1824
0
        if (result != Py_NotImplemented)
1825
0
            return result;
1826
0
        Py_DECREF(result);
1827
0
    }
1828
0
    return type_error("'%.200s' object can't be repeated", o);
1829
0
}
1830
1831
PyObject *
1832
PySequence_GetItem(PyObject *s, Py_ssize_t i)
1833
16.3M
{
1834
16.3M
    if (s == NULL) {
1835
0
        return null_error();
1836
0
    }
1837
1838
16.3M
    PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1839
16.3M
    if (m && m->sq_item) {
1840
16.3M
        if (i < 0) {
1841
0
            if (m->sq_length) {
1842
0
                Py_ssize_t l = (*m->sq_length)(s);
1843
0
                assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
1844
0
                if (l < 0) {
1845
0
                    return NULL;
1846
0
                }
1847
0
                i += l;
1848
0
            }
1849
0
        }
1850
16.3M
        PyObject *res = m->sq_item(s, i);
1851
16.3M
        assert(_Py_CheckSlotResult(s, "__getitem__", res != NULL));
1852
16.3M
        return res;
1853
16.3M
    }
1854
1855
0
    if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_subscript) {
1856
0
        return type_error("%.200s is not a sequence", s);
1857
0
    }
1858
0
    return type_error("'%.200s' object does not support indexing", s);
1859
0
}
1860
1861
PyObject *
1862
PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
1863
0
{
1864
0
    if (!s) {
1865
0
        return null_error();
1866
0
    }
1867
1868
0
    PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping;
1869
0
    if (mp && mp->mp_subscript) {
1870
0
        PyObject *slice = _PySlice_FromIndices(i1, i2);
1871
0
        if (!slice) {
1872
0
            return NULL;
1873
0
        }
1874
0
        PyObject *res = mp->mp_subscript(s, slice);
1875
0
        assert(_Py_CheckSlotResult(s, "__getitem__", res != NULL));
1876
0
        Py_DECREF(slice);
1877
0
        return res;
1878
0
    }
1879
1880
0
    return type_error("'%.200s' object is unsliceable", s);
1881
0
}
1882
1883
int
1884
PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
1885
0
{
1886
0
    if (s == NULL) {
1887
0
        null_error();
1888
0
        return -1;
1889
0
    }
1890
1891
0
    PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1892
0
    if (m && m->sq_ass_item) {
1893
0
        if (i < 0) {
1894
0
            if (m->sq_length) {
1895
0
                Py_ssize_t l = (*m->sq_length)(s);
1896
0
                assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
1897
0
                if (l < 0) {
1898
0
                    return -1;
1899
0
                }
1900
0
                i += l;
1901
0
            }
1902
0
        }
1903
0
        int res = m->sq_ass_item(s, i, o);
1904
0
        assert(_Py_CheckSlotResult(s, "__setitem__", res >= 0));
1905
0
        return res;
1906
0
    }
1907
1908
0
    if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
1909
0
        type_error("%.200s is not a sequence", s);
1910
0
        return -1;
1911
0
    }
1912
0
    type_error("'%.200s' object does not support item assignment", s);
1913
0
    return -1;
1914
0
}
1915
1916
int
1917
PySequence_DelItem(PyObject *s, Py_ssize_t i)
1918
5.40k
{
1919
5.40k
    if (s == NULL) {
1920
0
        null_error();
1921
0
        return -1;
1922
0
    }
1923
1924
5.40k
    PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1925
5.40k
    if (m && m->sq_ass_item) {
1926
5.40k
        if (i < 0) {
1927
0
            if (m->sq_length) {
1928
0
                Py_ssize_t l = (*m->sq_length)(s);
1929
0
                assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
1930
0
                if (l < 0) {
1931
0
                    return -1;
1932
0
                }
1933
0
                i += l;
1934
0
            }
1935
0
        }
1936
5.40k
        int res = m->sq_ass_item(s, i, (PyObject *)NULL);
1937
5.40k
        assert(_Py_CheckSlotResult(s, "__delitem__", res >= 0));
1938
5.40k
        return res;
1939
5.40k
    }
1940
1941
0
    if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
1942
0
        type_error("%.200s is not a sequence", s);
1943
0
        return -1;
1944
0
    }
1945
0
    type_error("'%.200s' object doesn't support item deletion", s);
1946
0
    return -1;
1947
0
}
1948
1949
int
1950
PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
1951
0
{
1952
0
    if (s == NULL) {
1953
0
        null_error();
1954
0
        return -1;
1955
0
    }
1956
1957
0
    PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping;
1958
0
    if (mp && mp->mp_ass_subscript) {
1959
0
        PyObject *slice = _PySlice_FromIndices(i1, i2);
1960
0
        if (!slice)
1961
0
            return -1;
1962
0
        int res = mp->mp_ass_subscript(s, slice, o);
1963
0
        assert(_Py_CheckSlotResult(s, "__setitem__", res >= 0));
1964
0
        Py_DECREF(slice);
1965
0
        return res;
1966
0
    }
1967
1968
0
    type_error("'%.200s' object doesn't support slice assignment", s);
1969
0
    return -1;
1970
0
}
1971
1972
int
1973
PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
1974
0
{
1975
0
    if (s == NULL) {
1976
0
        null_error();
1977
0
        return -1;
1978
0
    }
1979
1980
0
    PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping;
1981
0
    if (mp && mp->mp_ass_subscript) {
1982
0
        PyObject *slice = _PySlice_FromIndices(i1, i2);
1983
0
        if (!slice) {
1984
0
            return -1;
1985
0
        }
1986
0
        int res = mp->mp_ass_subscript(s, slice, NULL);
1987
0
        assert(_Py_CheckSlotResult(s, "__delitem__", res >= 0));
1988
0
        Py_DECREF(slice);
1989
0
        return res;
1990
0
    }
1991
0
    type_error("'%.200s' object doesn't support slice deletion", s);
1992
0
    return -1;
1993
0
}
1994
1995
PyObject *
1996
PySequence_Tuple(PyObject *v)
1997
1.79M
{
1998
1.79M
    PyObject *it;  /* iter(v) */
1999
2000
1.79M
    if (v == NULL) {
2001
0
        return null_error();
2002
0
    }
2003
2004
    /* Special-case the common tuple and list cases, for efficiency. */
2005
1.79M
    if (PyTuple_CheckExact(v)) {
2006
        /* Note that we can't know whether it's safe to return
2007
           a tuple *subclass* instance as-is, hence the restriction
2008
           to exact tuples here.  In contrast, lists always make
2009
           a copy, so there's no need for exactness below. */
2010
1.55M
        return Py_NewRef(v);
2011
1.55M
    }
2012
242k
    if (PyList_CheckExact(v))
2013
242k
        return PyList_AsTuple(v);
2014
2015
    /* Get iterator. */
2016
195
    it = PyObject_GetIter(v);
2017
195
    if (it == NULL)
2018
0
        return NULL;
2019
2020
195
    Py_ssize_t n;
2021
195
    PyObject *buffer[8];
2022
939
    for (n = 0; n < 8; n++) {
2023
939
        PyObject *item = PyIter_Next(it);
2024
939
        if (item == NULL) {
2025
195
            if (PyErr_Occurred()) {
2026
0
                goto fail;
2027
0
            }
2028
195
            Py_DECREF(it);
2029
195
            return _PyTuple_FromArraySteal(buffer, n);
2030
195
        }
2031
744
        buffer[n] = item;
2032
744
    }
2033
0
    PyListObject *list = (PyListObject *)PyList_New(16);
2034
0
    if (list == NULL) {
2035
0
        goto fail;
2036
0
    }
2037
0
    assert(n == 8);
2038
0
    Py_SET_SIZE(list, n);
2039
0
    for (Py_ssize_t j = 0; j < n; j++) {
2040
0
        PyList_SET_ITEM(list, j, buffer[j]);
2041
0
    }
2042
0
    for (;;) {
2043
0
        PyObject *item = PyIter_Next(it);
2044
0
        if (item == NULL) {
2045
0
            if (PyErr_Occurred()) {
2046
0
                Py_DECREF(list);
2047
0
                Py_DECREF(it);
2048
0
                return NULL;
2049
0
            }
2050
0
            break;
2051
0
        }
2052
0
        if (_PyList_AppendTakeRef(list, item) < 0) {
2053
0
            Py_DECREF(list);
2054
0
            Py_DECREF(it);
2055
0
            return NULL;
2056
0
        }
2057
0
    }
2058
0
    Py_DECREF(it);
2059
0
    PyObject *res = _PyList_AsTupleAndClear(list);
2060
0
    Py_DECREF(list);
2061
0
    return res;
2062
0
fail:
2063
0
    Py_DECREF(it);
2064
0
    while (n > 0) {
2065
0
        n--;
2066
0
        Py_DECREF(buffer[n]);
2067
0
    }
2068
0
    return NULL;
2069
0
}
2070
2071
PyObject *
2072
PySequence_List(PyObject *v)
2073
4.97M
{
2074
4.97M
    PyObject *result;  /* result list */
2075
4.97M
    PyObject *rv;          /* return value from PyList_Extend */
2076
2077
4.97M
    if (v == NULL) {
2078
0
        return null_error();
2079
0
    }
2080
2081
4.97M
    result = PyList_New(0);
2082
4.97M
    if (result == NULL)
2083
0
        return NULL;
2084
2085
4.97M
    rv = _PyList_Extend((PyListObject *)result, v);
2086
4.97M
    if (rv == NULL) {
2087
691
        Py_DECREF(result);
2088
691
        return NULL;
2089
691
    }
2090
4.96M
    Py_DECREF(rv);
2091
4.96M
    return result;
2092
4.97M
}
2093
2094
PyObject *
2095
PySequence_Fast(PyObject *v, const char *m)
2096
42.6M
{
2097
42.6M
    PyObject *it;
2098
2099
42.6M
    if (v == NULL) {
2100
0
        return null_error();
2101
0
    }
2102
2103
42.6M
    if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
2104
39.4M
        return Py_NewRef(v);
2105
39.4M
    }
2106
2107
3.24M
    it = PyObject_GetIter(v);
2108
3.24M
    if (it == NULL) {
2109
0
        PyThreadState *tstate = _PyThreadState_GET();
2110
0
        if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
2111
0
            _PyErr_SetString(tstate, PyExc_TypeError, m);
2112
0
        }
2113
0
        return NULL;
2114
0
    }
2115
2116
3.24M
    v = PySequence_List(it);
2117
3.24M
    Py_DECREF(it);
2118
2119
3.24M
    return v;
2120
3.24M
}
2121
2122
/* Iterate over seq.  Result depends on the operation:
2123
   PY_ITERSEARCH_COUNT:  -1 if error, else # of times obj appears in seq.
2124
   PY_ITERSEARCH_INDEX:  0-based index of first occurrence of obj in seq;
2125
    set ValueError and return -1 if none found; also return -1 on error.
2126
   PY_ITERSEARCH_CONTAINS:  return 1 if obj in seq, else 0; -1 on error.
2127
*/
2128
Py_ssize_t
2129
_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
2130
0
{
2131
0
    Py_ssize_t n;
2132
0
    int wrapped;  /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2133
0
    PyObject *it;  /* iter(seq) */
2134
2135
0
    if (seq == NULL || obj == NULL) {
2136
0
        null_error();
2137
0
        return -1;
2138
0
    }
2139
2140
0
    it = PyObject_GetIter(seq);
2141
0
    if (it == NULL) {
2142
0
        if (PyErr_ExceptionMatches(PyExc_TypeError)) {
2143
0
            if (operation == PY_ITERSEARCH_CONTAINS) {
2144
0
                type_error(
2145
0
                    "argument of type '%.200s' is not a container or iterable",
2146
0
                    seq
2147
0
                    );
2148
0
            }
2149
0
            else {
2150
0
                type_error("argument of type '%.200s' is not iterable", seq);
2151
0
            }
2152
0
        }
2153
0
        return -1;
2154
0
    }
2155
2156
0
    n = wrapped = 0;
2157
0
    for (;;) {
2158
0
        int cmp;
2159
0
        PyObject *item = PyIter_Next(it);
2160
0
        if (item == NULL) {
2161
0
            if (PyErr_Occurred())
2162
0
                goto Fail;
2163
0
            break;
2164
0
        }
2165
2166
0
        cmp = PyObject_RichCompareBool(item, obj, Py_EQ);
2167
0
        Py_DECREF(item);
2168
0
        if (cmp < 0)
2169
0
            goto Fail;
2170
0
        if (cmp > 0) {
2171
0
            switch (operation) {
2172
0
            case PY_ITERSEARCH_COUNT:
2173
0
                if (n == PY_SSIZE_T_MAX) {
2174
0
                    PyErr_SetString(PyExc_OverflowError,
2175
0
                           "count exceeds C integer size");
2176
0
                    goto Fail;
2177
0
                }
2178
0
                ++n;
2179
0
                break;
2180
2181
0
            case PY_ITERSEARCH_INDEX:
2182
0
                if (wrapped) {
2183
0
                    PyErr_SetString(PyExc_OverflowError,
2184
0
                           "index exceeds C integer size");
2185
0
                    goto Fail;
2186
0
                }
2187
0
                goto Done;
2188
2189
0
            case PY_ITERSEARCH_CONTAINS:
2190
0
                n = 1;
2191
0
                goto Done;
2192
2193
0
            default:
2194
0
                Py_UNREACHABLE();
2195
0
            }
2196
0
        }
2197
2198
0
        if (operation == PY_ITERSEARCH_INDEX) {
2199
0
            if (n == PY_SSIZE_T_MAX)
2200
0
                wrapped = 1;
2201
0
            ++n;
2202
0
        }
2203
0
    }
2204
2205
0
    if (operation != PY_ITERSEARCH_INDEX)
2206
0
        goto Done;
2207
2208
0
    PyErr_SetString(PyExc_ValueError,
2209
0
                    "sequence.index(x): x not in sequence");
2210
    /* fall into failure code */
2211
0
Fail:
2212
0
    n = -1;
2213
    /* fall through */
2214
0
Done:
2215
0
    Py_DECREF(it);
2216
0
    return n;
2217
2218
0
}
2219
2220
/* Return # of times o appears in s. */
2221
Py_ssize_t
2222
PySequence_Count(PyObject *s, PyObject *o)
2223
0
{
2224
0
    return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
2225
0
}
2226
2227
/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
2228
 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
2229
 */
2230
int
2231
PySequence_Contains(PyObject *seq, PyObject *ob)
2232
96.4M
{
2233
96.4M
    PySequenceMethods *sqm = Py_TYPE(seq)->tp_as_sequence;
2234
96.4M
    if (sqm != NULL && sqm->sq_contains != NULL) {
2235
96.4M
        int res = (*sqm->sq_contains)(seq, ob);
2236
96.4M
        assert(_Py_CheckSlotResult(seq, "__contains__", res >= 0));
2237
96.4M
        return res;
2238
96.4M
    }
2239
0
    Py_ssize_t result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
2240
0
    return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
2241
96.4M
}
2242
2243
/* Backwards compatibility */
2244
#undef PySequence_In
2245
int
2246
PySequence_In(PyObject *w, PyObject *v)
2247
0
{
2248
0
    return PySequence_Contains(w, v);
2249
0
}
2250
2251
Py_ssize_t
2252
PySequence_Index(PyObject *s, PyObject *o)
2253
0
{
2254
0
    return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
2255
0
}
2256
2257
/* Operations on mappings */
2258
2259
int
2260
PyMapping_Check(PyObject *o)
2261
22.5M
{
2262
22.5M
    return o && Py_TYPE(o)->tp_as_mapping &&
2263
22.5M
        Py_TYPE(o)->tp_as_mapping->mp_subscript;
2264
22.5M
}
2265
2266
Py_ssize_t
2267
PyMapping_Size(PyObject *o)
2268
424
{
2269
424
    if (o == NULL) {
2270
0
        null_error();
2271
0
        return -1;
2272
0
    }
2273
2274
424
    PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
2275
424
    if (m && m->mp_length) {
2276
424
        Py_ssize_t len = m->mp_length(o);
2277
424
        assert(_Py_CheckSlotResult(o, "__len__", len >= 0));
2278
424
        return len;
2279
424
    }
2280
2281
0
    if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) {
2282
0
        type_error("%.200s is not a mapping", o);
2283
0
        return -1;
2284
0
    }
2285
    /* PyMapping_Size() can be called from PyObject_Size(). */
2286
0
    type_error("object of type '%.200s' has no len()", o);
2287
0
    return -1;
2288
0
}
2289
2290
#undef PyMapping_Length
2291
Py_ssize_t
2292
PyMapping_Length(PyObject *o)
2293
0
{
2294
0
    return PyMapping_Size(o);
2295
0
}
2296
#define PyMapping_Length PyMapping_Size
2297
2298
PyObject *
2299
PyMapping_GetItemString(PyObject *o, const char *key)
2300
80
{
2301
80
    PyObject *okey, *r;
2302
2303
80
    if (key == NULL) {
2304
0
        return null_error();
2305
0
    }
2306
2307
80
    okey = PyUnicode_FromString(key);
2308
80
    if (okey == NULL)
2309
0
        return NULL;
2310
80
    r = PyObject_GetItem(o, okey);
2311
80
    Py_DECREF(okey);
2312
80
    return r;
2313
80
}
2314
2315
int
2316
PyMapping_GetOptionalItemString(PyObject *obj, const char *key, PyObject **result)
2317
0
{
2318
0
    if (key == NULL) {
2319
0
        *result = NULL;
2320
0
        null_error();
2321
0
        return -1;
2322
0
    }
2323
0
    PyObject *okey = PyUnicode_FromString(key);
2324
0
    if (okey == NULL) {
2325
0
        *result = NULL;
2326
0
        return -1;
2327
0
    }
2328
0
    int rc = PyMapping_GetOptionalItem(obj, okey, result);
2329
0
    Py_DECREF(okey);
2330
0
    return rc;
2331
0
}
2332
2333
int
2334
PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value)
2335
16
{
2336
16
    PyObject *okey;
2337
16
    int r;
2338
2339
16
    if (key == NULL) {
2340
0
        null_error();
2341
0
        return -1;
2342
0
    }
2343
2344
16
    okey = PyUnicode_FromString(key);
2345
16
    if (okey == NULL)
2346
0
        return -1;
2347
16
    r = PyObject_SetItem(o, okey, value);
2348
16
    Py_DECREF(okey);
2349
16
    return r;
2350
16
}
2351
2352
int
2353
PyMapping_HasKeyStringWithError(PyObject *obj, const char *key)
2354
0
{
2355
0
    PyObject *res;
2356
0
    int rc = PyMapping_GetOptionalItemString(obj, key, &res);
2357
0
    Py_XDECREF(res);
2358
0
    return rc;
2359
0
}
2360
2361
int
2362
PyMapping_HasKeyWithError(PyObject *obj, PyObject *key)
2363
0
{
2364
0
    PyObject *res;
2365
0
    int rc = PyMapping_GetOptionalItem(obj, key, &res);
2366
0
    Py_XDECREF(res);
2367
0
    return rc;
2368
0
}
2369
2370
int
2371
PyMapping_HasKeyString(PyObject *obj, const char *key)
2372
0
{
2373
0
    PyObject *value;
2374
0
    int rc;
2375
0
    if (obj == NULL) {
2376
        // For backward compatibility.
2377
        // PyMapping_GetOptionalItemString() crashes if obj is NULL.
2378
0
        null_error();
2379
0
        rc = -1;
2380
0
    }
2381
0
    else {
2382
0
        rc = PyMapping_GetOptionalItemString(obj, key, &value);
2383
0
    }
2384
0
    if (rc < 0) {
2385
0
        PyErr_FormatUnraisable(
2386
0
            "Exception ignored in PyMapping_HasKeyString(); consider using "
2387
0
            "PyMapping_HasKeyStringWithError(), "
2388
0
            "PyMapping_GetOptionalItemString() or PyMapping_GetItemString()");
2389
0
        return 0;
2390
0
    }
2391
0
    Py_XDECREF(value);
2392
0
    return rc;
2393
0
}
2394
2395
int
2396
PyMapping_HasKey(PyObject *obj, PyObject *key)
2397
0
{
2398
0
    PyObject *value;
2399
0
    int rc;
2400
0
    if (obj == NULL || key == NULL) {
2401
        // For backward compatibility.
2402
        // PyMapping_GetOptionalItem() crashes if any of them is NULL.
2403
0
        null_error();
2404
0
        rc = -1;
2405
0
    }
2406
0
    else {
2407
0
        rc = PyMapping_GetOptionalItem(obj, key, &value);
2408
0
    }
2409
0
    if (rc < 0) {
2410
0
        PyErr_FormatUnraisable(
2411
0
            "Exception ignored in PyMapping_HasKey(); consider using "
2412
0
            "PyMapping_HasKeyWithError(), "
2413
0
            "PyMapping_GetOptionalItem() or PyObject_GetItem()");
2414
0
        return 0;
2415
0
    }
2416
0
    Py_XDECREF(value);
2417
0
    return rc;
2418
0
}
2419
2420
/* This function is quite similar to PySequence_Fast(), but specialized to be
2421
   a helper for PyMapping_Keys(), PyMapping_Items() and PyMapping_Values().
2422
 */
2423
static PyObject *
2424
method_output_as_list(PyObject *o, PyObject *meth)
2425
810
{
2426
810
    PyObject *it, *result, *meth_output;
2427
2428
810
    assert(o != NULL);
2429
810
    meth_output = PyObject_CallMethodNoArgs(o, meth);
2430
810
    if (meth_output == NULL || PyList_CheckExact(meth_output)) {
2431
0
        return meth_output;
2432
0
    }
2433
810
    it = PyObject_GetIter(meth_output);
2434
810
    if (it == NULL) {
2435
0
        PyThreadState *tstate = _PyThreadState_GET();
2436
0
        if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
2437
0
            _PyErr_Format(tstate, PyExc_TypeError,
2438
0
                          "%.200s.%U() returned a non-iterable (type %.200s)",
2439
0
                          Py_TYPE(o)->tp_name,
2440
0
                          meth,
2441
0
                          Py_TYPE(meth_output)->tp_name);
2442
0
        }
2443
0
        Py_DECREF(meth_output);
2444
0
        return NULL;
2445
0
    }
2446
810
    Py_DECREF(meth_output);
2447
810
    result = PySequence_List(it);
2448
810
    Py_DECREF(it);
2449
810
    return result;
2450
810
}
2451
2452
PyObject *
2453
PyMapping_Keys(PyObject *o)
2454
256
{
2455
256
    if (o == NULL) {
2456
0
        return null_error();
2457
0
    }
2458
256
    if (PyDict_CheckExact(o)) {
2459
120
        return PyDict_Keys(o);
2460
120
    }
2461
136
    return method_output_as_list(o, &_Py_ID(keys));
2462
256
}
2463
2464
PyObject *
2465
PyMapping_Items(PyObject *o)
2466
674
{
2467
674
    if (o == NULL) {
2468
0
        return null_error();
2469
0
    }
2470
674
    if (PyDict_CheckExact(o)) {
2471
0
        return PyDict_Items(o);
2472
0
    }
2473
674
    return method_output_as_list(o, &_Py_ID(items));
2474
674
}
2475
2476
PyObject *
2477
PyMapping_Values(PyObject *o)
2478
0
{
2479
0
    if (o == NULL) {
2480
0
        return null_error();
2481
0
    }
2482
0
    if (PyDict_CheckExact(o)) {
2483
0
        return PyDict_Values(o);
2484
0
    }
2485
0
    return method_output_as_list(o, &_Py_ID(values));
2486
0
}
2487
2488
/* isinstance(), issubclass() */
2489
2490
/* abstract_get_bases() has logically 4 return states:
2491
 *
2492
 * 1. getattr(cls, '__bases__') could raise an AttributeError
2493
 * 2. getattr(cls, '__bases__') could raise some other exception
2494
 * 3. getattr(cls, '__bases__') could return a tuple
2495
 * 4. getattr(cls, '__bases__') could return something other than a tuple
2496
 *
2497
 * Only state #3 is a non-error state and only it returns a non-NULL object
2498
 * (it returns the retrieved tuple).
2499
 *
2500
 * Any raised AttributeErrors are masked by clearing the exception and
2501
 * returning NULL.  If an object other than a tuple comes out of __bases__,
2502
 * then again, the return value is NULL.  So yes, these two situations
2503
 * produce exactly the same results: NULL is returned and no error is set.
2504
 *
2505
 * If some exception other than AttributeError is raised, then NULL is also
2506
 * returned, but the exception is not cleared.  That's because we want the
2507
 * exception to be propagated along.
2508
 *
2509
 * Callers are expected to test for PyErr_Occurred() when the return value
2510
 * is NULL to decide whether a valid exception should be propagated or not.
2511
 * When there's no exception to propagate, it's customary for the caller to
2512
 * set a TypeError.
2513
 */
2514
static PyObject *
2515
abstract_get_bases(PyObject *cls)
2516
0
{
2517
0
    PyObject *bases;
2518
2519
0
    (void)PyObject_GetOptionalAttr(cls, &_Py_ID(__bases__), &bases);
2520
0
    if (bases != NULL && !PyTuple_Check(bases)) {
2521
0
        Py_DECREF(bases);
2522
0
        return NULL;
2523
0
    }
2524
0
    return bases;
2525
0
}
2526
2527
2528
static int
2529
abstract_issubclass(PyObject *derived, PyObject *cls)
2530
0
{
2531
0
    PyObject *bases = NULL;
2532
0
    Py_ssize_t i, n;
2533
0
    int r = 0;
2534
2535
0
    while (1) {
2536
0
        if (derived == cls) {
2537
0
            Py_XDECREF(bases); /* See below comment */
2538
0
            return 1;
2539
0
        }
2540
        /* Use XSETREF to drop bases reference *after* finishing with
2541
           derived; bases might be the only reference to it.
2542
           XSETREF is used instead of SETREF, because bases is NULL on the
2543
           first iteration of the loop.
2544
        */
2545
0
        Py_XSETREF(bases, abstract_get_bases(derived));
2546
0
        if (bases == NULL) {
2547
0
            if (PyErr_Occurred())
2548
0
                return -1;
2549
0
            return 0;
2550
0
        }
2551
0
        n = PyTuple_GET_SIZE(bases);
2552
0
        if (n == 0) {
2553
0
            Py_DECREF(bases);
2554
0
            return 0;
2555
0
        }
2556
        /* Avoid recursivity in the single inheritance case */
2557
0
        if (n == 1) {
2558
0
            derived = PyTuple_GET_ITEM(bases, 0);
2559
0
            continue;
2560
0
        }
2561
0
        break;
2562
0
    }
2563
0
    assert(n >= 2);
2564
0
    if (_Py_EnterRecursiveCall(" in __issubclass__")) {
2565
0
        Py_DECREF(bases);
2566
0
        return -1;
2567
0
    }
2568
0
    for (i = 0; i < n; i++) {
2569
0
        r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2570
0
        if (r != 0) {
2571
0
            break;
2572
0
        }
2573
0
    }
2574
0
    _Py_LeaveRecursiveCall();
2575
0
    Py_DECREF(bases);
2576
0
    return r;
2577
0
}
2578
2579
static int
2580
check_class(PyObject *cls, const char *error)
2581
0
{
2582
0
    PyObject *bases = abstract_get_bases(cls);
2583
0
    if (bases == NULL) {
2584
        /* Do not mask errors. */
2585
0
        PyThreadState *tstate = _PyThreadState_GET();
2586
0
        if (!_PyErr_Occurred(tstate)) {
2587
0
            _PyErr_SetString(tstate, PyExc_TypeError, error);
2588
0
        }
2589
0
        return 0;
2590
0
    }
2591
0
    Py_DECREF(bases);
2592
0
    return -1;
2593
0
}
2594
2595
static int
2596
object_isinstance(PyObject *inst, PyObject *cls)
2597
1.24M
{
2598
1.24M
    PyObject *icls;
2599
1.24M
    int retval;
2600
1.24M
    if (PyType_Check(cls)) {
2601
1.24M
        retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2602
1.24M
        if (retval == 0) {
2603
1.16M
            retval = PyObject_GetOptionalAttr(inst, &_Py_ID(__class__), &icls);
2604
1.16M
            if (icls != NULL) {
2605
1.16M
                if (icls != (PyObject *)(Py_TYPE(inst)) && PyType_Check(icls)) {
2606
0
                    retval = PyType_IsSubtype(
2607
0
                        (PyTypeObject *)icls,
2608
0
                        (PyTypeObject *)cls);
2609
0
                }
2610
1.16M
                else {
2611
1.16M
                    retval = 0;
2612
1.16M
                }
2613
1.16M
                Py_DECREF(icls);
2614
1.16M
            }
2615
1.16M
        }
2616
1.24M
    }
2617
0
    else {
2618
0
        if (!check_class(cls,
2619
0
            "isinstance() arg 2 must be a type, a tuple of types, or a union"))
2620
0
            return -1;
2621
0
        retval = PyObject_GetOptionalAttr(inst, &_Py_ID(__class__), &icls);
2622
0
        if (icls != NULL) {
2623
0
            retval = abstract_issubclass(icls, cls);
2624
0
            Py_DECREF(icls);
2625
0
        }
2626
0
    }
2627
2628
1.24M
    return retval;
2629
1.24M
}
2630
2631
static int
2632
object_recursive_isinstance(PyThreadState *tstate, PyObject *inst, PyObject *cls)
2633
12.3M
{
2634
    /* Quick test for an exact match */
2635
12.3M
    if (Py_IS_TYPE(inst, (PyTypeObject *)cls)) {
2636
10.9M
        return 1;
2637
10.9M
    }
2638
2639
    /* We know what type's __instancecheck__ does. */
2640
1.38M
    if (PyType_CheckExact(cls)) {
2641
1.23M
        return object_isinstance(inst, cls);
2642
1.23M
    }
2643
2644
144k
    if (_PyUnion_Check(cls)) {
2645
0
        cls = _Py_union_args(cls);
2646
0
    }
2647
2648
144k
    if (PyTuple_Check(cls)) {
2649
        /* Not a general sequence -- that opens up the road to
2650
           recursion and stack overflow. */
2651
136k
        if (_Py_EnterRecursiveCallTstate(tstate, " in __instancecheck__")) {
2652
0
            return -1;
2653
0
        }
2654
136k
        Py_ssize_t n = PyTuple_GET_SIZE(cls);
2655
136k
        int r = 0;
2656
233k
        for (Py_ssize_t i = 0; i < n; ++i) {
2657
200k
            PyObject *item = PyTuple_GET_ITEM(cls, i);
2658
200k
            r = object_recursive_isinstance(tstate, inst, item);
2659
200k
            if (r != 0) {
2660
                /* either found it, or got an error */
2661
103k
                break;
2662
103k
            }
2663
200k
        }
2664
136k
        _Py_LeaveRecursiveCallTstate(tstate);
2665
136k
        return r;
2666
136k
    }
2667
2668
8.50k
    PyObject *checker = _PyObject_LookupSpecial(cls, &_Py_ID(__instancecheck__));
2669
8.50k
    if (checker != NULL) {
2670
8.50k
        if (_Py_EnterRecursiveCallTstate(tstate, " in __instancecheck__")) {
2671
0
            Py_DECREF(checker);
2672
0
            return -1;
2673
0
        }
2674
2675
8.50k
        PyObject *res = PyObject_CallOneArg(checker, inst);
2676
8.50k
        _Py_LeaveRecursiveCallTstate(tstate);
2677
8.50k
        Py_DECREF(checker);
2678
2679
8.50k
        if (res == NULL) {
2680
0
            return -1;
2681
0
        }
2682
8.50k
        int ok = PyObject_IsTrue(res);
2683
8.50k
        Py_DECREF(res);
2684
2685
8.50k
        return ok;
2686
8.50k
    }
2687
0
    else if (_PyErr_Occurred(tstate)) {
2688
0
        return -1;
2689
0
    }
2690
2691
    /* cls has no __instancecheck__() method */
2692
0
    return object_isinstance(inst, cls);
2693
8.50k
}
2694
2695
2696
int
2697
PyObject_IsInstance(PyObject *inst, PyObject *cls)
2698
12.1M
{
2699
12.1M
    PyThreadState *tstate = _PyThreadState_GET();
2700
12.1M
    return object_recursive_isinstance(tstate, inst, cls);
2701
12.1M
}
2702
2703
2704
static  int
2705
recursive_issubclass(PyObject *derived, PyObject *cls)
2706
13.6M
{
2707
13.6M
    if (PyType_Check(cls) && PyType_Check(derived)) {
2708
        /* Fast path (non-recursive) */
2709
13.6M
        return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls);
2710
13.6M
    }
2711
0
    if (!check_class(derived,
2712
0
                     "issubclass() arg 1 must be a class"))
2713
0
        return -1;
2714
2715
0
    if (!_PyUnion_Check(cls) && !check_class(cls,
2716
0
                            "issubclass() arg 2 must be a class,"
2717
0
                            " a tuple of classes, or a union")) {
2718
0
        return -1;
2719
0
    }
2720
2721
0
    return abstract_issubclass(derived, cls);
2722
0
}
2723
2724
static int
2725
object_issubclass(PyThreadState *tstate, PyObject *derived, PyObject *cls)
2726
14.0M
{
2727
14.0M
    PyObject *checker;
2728
2729
    /* We know what type's __subclasscheck__ does. */
2730
14.0M
    if (PyType_CheckExact(cls)) {
2731
        /* Quick test for an exact match */
2732
14.0M
        if (derived == cls)
2733
14.0M
            return 1;
2734
18.2k
        return recursive_issubclass(derived, cls);
2735
14.0M
    }
2736
2737
2.51k
    if (_PyUnion_Check(cls)) {
2738
0
        cls = _Py_union_args(cls);
2739
0
    }
2740
2741
2.51k
    if (PyTuple_Check(cls)) {
2742
2743
0
        if (_Py_EnterRecursiveCallTstate(tstate, " in __subclasscheck__")) {
2744
0
            return -1;
2745
0
        }
2746
0
        Py_ssize_t n = PyTuple_GET_SIZE(cls);
2747
0
        int r = 0;
2748
0
        for (Py_ssize_t i = 0; i < n; ++i) {
2749
0
            PyObject *item = PyTuple_GET_ITEM(cls, i);
2750
0
            r = object_issubclass(tstate, derived, item);
2751
0
            if (r != 0)
2752
                /* either found it, or got an error */
2753
0
                break;
2754
0
        }
2755
0
        _Py_LeaveRecursiveCallTstate(tstate);
2756
0
        return r;
2757
0
    }
2758
2759
2.51k
    checker = _PyObject_LookupSpecial(cls, &_Py_ID(__subclasscheck__));
2760
2.51k
    if (checker != NULL) {
2761
2.51k
        int ok = -1;
2762
2.51k
        if (_Py_EnterRecursiveCallTstate(tstate, " in __subclasscheck__")) {
2763
0
            Py_DECREF(checker);
2764
0
            return ok;
2765
0
        }
2766
2.51k
        PyObject *res = PyObject_CallOneArg(checker, derived);
2767
2.51k
        _Py_LeaveRecursiveCallTstate(tstate);
2768
2.51k
        Py_DECREF(checker);
2769
2.51k
        if (res != NULL) {
2770
2.51k
            ok = PyObject_IsTrue(res);
2771
2.51k
            Py_DECREF(res);
2772
2.51k
        }
2773
2.51k
        return ok;
2774
2.51k
    }
2775
0
    else if (_PyErr_Occurred(tstate)) {
2776
0
        return -1;
2777
0
    }
2778
2779
    /* Can be reached when infinite recursion happens. */
2780
0
    return recursive_issubclass(derived, cls);
2781
2.51k
}
2782
2783
2784
int
2785
PyObject_IsSubclass(PyObject *derived, PyObject *cls)
2786
14.0M
{
2787
14.0M
    PyThreadState *tstate = _PyThreadState_GET();
2788
14.0M
    return object_issubclass(tstate, derived, cls);
2789
14.0M
}
2790
2791
2792
int
2793
_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
2794
8.50k
{
2795
8.50k
    return object_isinstance(inst, cls);
2796
8.50k
}
2797
2798
int
2799
_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
2800
13.6M
{
2801
13.6M
    return recursive_issubclass(derived, cls);
2802
13.6M
}
2803
2804
2805
PyObject *
2806
PyObject_GetIter(PyObject *o)
2807
114M
{
2808
114M
    PyTypeObject *t = Py_TYPE(o);
2809
114M
    getiterfunc f;
2810
2811
114M
    f = t->tp_iter;
2812
114M
    if (f == NULL) {
2813
595
        if (PySequence_Check(o))
2814
595
            return PySeqIter_New(o);
2815
0
        return type_error("'%.200s' object is not iterable", o);
2816
595
    }
2817
114M
    else {
2818
114M
        PyObject *res = (*f)(o);
2819
114M
        if (res != NULL && !PyIter_Check(res)) {
2820
0
            PyErr_Format(PyExc_TypeError,
2821
0
                         "iter() returned non-iterator "
2822
0
                         "of type '%.100s'",
2823
0
                         Py_TYPE(res)->tp_name);
2824
0
            Py_SETREF(res, NULL);
2825
0
        }
2826
114M
        return res;
2827
114M
    }
2828
114M
}
2829
2830
PyObject *
2831
0
PyObject_GetAIter(PyObject *o) {
2832
0
    PyTypeObject *t = Py_TYPE(o);
2833
0
    unaryfunc f;
2834
2835
0
    if (t->tp_as_async == NULL || t->tp_as_async->am_aiter == NULL) {
2836
0
        return type_error("'%.200s' object is not an async iterable", o);
2837
0
    }
2838
0
    f = t->tp_as_async->am_aiter;
2839
0
    PyObject *it = (*f)(o);
2840
0
    if (it != NULL && !PyAIter_Check(it)) {
2841
0
        PyErr_Format(PyExc_TypeError,
2842
0
                     "aiter() returned not an async iterator of type '%.100s'",
2843
0
                     Py_TYPE(it)->tp_name);
2844
0
        Py_SETREF(it, NULL);
2845
0
    }
2846
0
    return it;
2847
0
}
2848
2849
int
2850
PyIter_Check(PyObject *obj)
2851
131M
{
2852
131M
    PyTypeObject *tp = Py_TYPE(obj);
2853
131M
    return (tp->tp_iternext != NULL &&
2854
131M
            tp->tp_iternext != &_PyObject_NextNotImplemented);
2855
131M
}
2856
2857
int
2858
PyAIter_Check(PyObject *obj)
2859
0
{
2860
0
    PyTypeObject *tp = Py_TYPE(obj);
2861
0
    return (tp->tp_as_async != NULL &&
2862
0
            tp->tp_as_async->am_anext != NULL &&
2863
0
            tp->tp_as_async->am_anext != &_PyObject_NextNotImplemented);
2864
0
}
2865
2866
static int
2867
iternext(PyObject *iter, PyObject **item)
2868
80.3M
{
2869
80.3M
    iternextfunc tp_iternext = Py_TYPE(iter)->tp_iternext;
2870
80.3M
    if ((*item = tp_iternext(iter))) {
2871
60.9M
        return 1;
2872
60.9M
    }
2873
2874
19.3M
    PyThreadState *tstate = _PyThreadState_GET();
2875
    /* When the iterator is exhausted it must return NULL;
2876
     * a StopIteration exception may or may not be set. */
2877
19.3M
    if (!_PyErr_Occurred(tstate)) {
2878
19.3M
        return 0;
2879
19.3M
    }
2880
22.7k
    if (_PyErr_ExceptionMatches(tstate, PyExc_StopIteration)) {
2881
0
        _PyErr_Clear(tstate);
2882
0
        return 0;
2883
0
    }
2884
2885
    /* Error case: an exception (different than StopIteration) is set. */
2886
22.7k
    return -1;
2887
22.7k
}
2888
2889
/* Return 1 and set 'item' to the next item of 'iter' on success.
2890
 * Return 0 and set 'item' to NULL when there are no remaining values.
2891
 * Return -1, set 'item' to NULL and set an exception on error.
2892
 */
2893
int
2894
PyIter_NextItem(PyObject *iter, PyObject **item)
2895
0
{
2896
0
    assert(iter != NULL);
2897
0
    assert(item != NULL);
2898
2899
0
    if (Py_TYPE(iter)->tp_iternext == NULL) {
2900
0
        *item = NULL;
2901
0
        PyErr_Format(PyExc_TypeError, "expected an iterator, got '%T'", iter);
2902
0
        return -1;
2903
0
    }
2904
2905
0
    return iternext(iter, item);
2906
0
}
2907
2908
/* Return next item.
2909
 *
2910
 * If an error occurs, return NULL.  PyErr_Occurred() will be true.
2911
 * If the iteration terminates normally, return NULL and clear the
2912
 * PyExc_StopIteration exception (if it was set).  PyErr_Occurred()
2913
 * will be false.
2914
 * Else return the next object.  PyErr_Occurred() will be false.
2915
 */
2916
PyObject *
2917
PyIter_Next(PyObject *iter)
2918
80.3M
{
2919
80.3M
    PyObject *item;
2920
80.3M
    (void)iternext(iter, &item);
2921
80.3M
    return item;
2922
80.3M
}
2923
2924
PySendResult
2925
PyIter_Send(PyObject *iter, PyObject *arg, PyObject **result)
2926
0
{
2927
0
    assert(arg != NULL);
2928
0
    assert(result != NULL);
2929
0
    if (Py_TYPE(iter)->tp_as_async && Py_TYPE(iter)->tp_as_async->am_send) {
2930
0
        PySendResult res = Py_TYPE(iter)->tp_as_async->am_send(iter, arg, result);
2931
0
        assert(_Py_CheckSlotResult(iter, "am_send", res != PYGEN_ERROR));
2932
0
        return res;
2933
0
    }
2934
0
    if (arg == Py_None && PyIter_Check(iter)) {
2935
0
        *result = Py_TYPE(iter)->tp_iternext(iter);
2936
0
    }
2937
0
    else {
2938
0
        *result = PyObject_CallMethodOneArg(iter, &_Py_ID(send), arg);
2939
0
    }
2940
0
    if (*result != NULL) {
2941
0
        return PYGEN_NEXT;
2942
0
    }
2943
0
    if (_PyGen_FetchStopIterationValue(result) == 0) {
2944
0
        return PYGEN_RETURN;
2945
0
    }
2946
0
    return PYGEN_ERROR;
2947
0
}