Coverage Report

Created: 2026-10-31 06:21

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