Coverage Report

Created: 2025-11-24 06:11

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