Coverage Report

Created: 2026-12-01 06:09

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