Coverage Report

Created: 2026-05-16 06:46

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