ยปCore Development>Code coverage>Objects/abstract.c

Python code coverage for Objects/abstract.c

#countcontent
1n/a/* Abstract Object Interface (many thanks to Jim Fulton) */
2n/a
3n/a#include "Python.h"
4n/a#include <ctype.h>
5n/a#include "structmember.h" /* we need the offsetof() macro from there */
6n/a#include "longintrepr.h"
7n/a
8n/a
9n/a
10n/a/* Shorthands to return certain errors */
11n/a
12n/astatic PyObject *
13n/atype_error(const char *msg, PyObject *obj)
14n/a{
15n/a PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name);
16n/a return NULL;
17n/a}
18n/a
19n/astatic PyObject *
20n/anull_error(void)
21n/a{
22n/a if (!PyErr_Occurred())
23n/a PyErr_SetString(PyExc_SystemError,
24n/a "null argument to internal routine");
25n/a return NULL;
26n/a}
27n/a
28n/a/* Operations on any object */
29n/a
30n/aPyObject *
31n/aPyObject_Type(PyObject *o)
32n/a{
33n/a PyObject *v;
34n/a
35n/a if (o == NULL) {
36n/a return null_error();
37n/a }
38n/a
39n/a v = (PyObject *)o->ob_type;
40n/a Py_INCREF(v);
41n/a return v;
42n/a}
43n/a
44n/aPy_ssize_t
45n/aPyObject_Size(PyObject *o)
46n/a{
47n/a PySequenceMethods *m;
48n/a
49n/a if (o == NULL) {
50n/a null_error();
51n/a return -1;
52n/a }
53n/a
54n/a m = o->ob_type->tp_as_sequence;
55n/a if (m && m->sq_length)
56n/a return m->sq_length(o);
57n/a
58n/a return PyMapping_Size(o);
59n/a}
60n/a
61n/a#undef PyObject_Length
62n/aPy_ssize_t
63n/aPyObject_Length(PyObject *o)
64n/a{
65n/a return PyObject_Size(o);
66n/a}
67n/a#define PyObject_Length PyObject_Size
68n/a
69n/aint
70n/a_PyObject_HasLen(PyObject *o) {
71n/a return (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) ||
72n/a (Py_TYPE(o)->tp_as_mapping && Py_TYPE(o)->tp_as_mapping->mp_length);
73n/a}
74n/a
75n/a/* The length hint function returns a non-negative value from o.__len__()
76n/a or o.__length_hint__(). If those methods aren't found the defaultvalue is
77n/a returned. If one of the calls fails with an exception other than TypeError
78n/a this function returns -1.
79n/a*/
80n/a
81n/aPy_ssize_t
82n/aPyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
83n/a{
84n/a PyObject *hint, *result;
85n/a Py_ssize_t res;
86n/a _Py_IDENTIFIER(__length_hint__);
87n/a if (_PyObject_HasLen(o)) {
88n/a res = PyObject_Length(o);
89n/a if (res < 0 && PyErr_Occurred()) {
90n/a if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
91n/a return -1;
92n/a }
93n/a PyErr_Clear();
94n/a }
95n/a else {
96n/a return res;
97n/a }
98n/a }
99n/a hint = _PyObject_LookupSpecial(o, &PyId___length_hint__);
100n/a if (hint == NULL) {
101n/a if (PyErr_Occurred()) {
102n/a return -1;
103n/a }
104n/a return defaultvalue;
105n/a }
106n/a result = _PyObject_CallNoArg(hint);
107n/a Py_DECREF(hint);
108n/a if (result == NULL) {
109n/a if (PyErr_ExceptionMatches(PyExc_TypeError)) {
110n/a PyErr_Clear();
111n/a return defaultvalue;
112n/a }
113n/a return -1;
114n/a }
115n/a else if (result == Py_NotImplemented) {
116n/a Py_DECREF(result);
117n/a return defaultvalue;
118n/a }
119n/a if (!PyLong_Check(result)) {
120n/a PyErr_Format(PyExc_TypeError, "__length_hint__ must be an integer, not %.100s",
121n/a Py_TYPE(result)->tp_name);
122n/a Py_DECREF(result);
123n/a return -1;
124n/a }
125n/a res = PyLong_AsSsize_t(result);
126n/a Py_DECREF(result);
127n/a if (res < 0 && PyErr_Occurred()) {
128n/a return -1;
129n/a }
130n/a if (res < 0) {
131n/a PyErr_Format(PyExc_ValueError, "__length_hint__() should return >= 0");
132n/a return -1;
133n/a }
134n/a return res;
135n/a}
136n/a
137n/aPyObject *
138n/aPyObject_GetItem(PyObject *o, PyObject *key)
139n/a{
140n/a PyMappingMethods *m;
141n/a
142n/a if (o == NULL || key == NULL) {
143n/a return null_error();
144n/a }
145n/a
146n/a m = o->ob_type->tp_as_mapping;
147n/a if (m && m->mp_subscript) {
148n/a PyObject *item = m->mp_subscript(o, key);
149n/a assert((item != NULL) ^ (PyErr_Occurred() != NULL));
150n/a return item;
151n/a }
152n/a
153n/a if (o->ob_type->tp_as_sequence) {
154n/a if (PyIndex_Check(key)) {
155n/a Py_ssize_t key_value;
156n/a key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
157n/a if (key_value == -1 && PyErr_Occurred())
158n/a return NULL;
159n/a return PySequence_GetItem(o, key_value);
160n/a }
161n/a else if (o->ob_type->tp_as_sequence->sq_item)
162n/a return type_error("sequence index must "
163n/a "be integer, not '%.200s'", key);
164n/a }
165n/a
166n/a return type_error("'%.200s' object is not subscriptable", o);
167n/a}
168n/a
169n/aint
170n/aPyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
171n/a{
172n/a PyMappingMethods *m;
173n/a
174n/a if (o == NULL || key == NULL || value == NULL) {
175n/a null_error();
176n/a return -1;
177n/a }
178n/a m = o->ob_type->tp_as_mapping;
179n/a if (m && m->mp_ass_subscript)
180n/a return m->mp_ass_subscript(o, key, value);
181n/a
182n/a if (o->ob_type->tp_as_sequence) {
183n/a if (PyIndex_Check(key)) {
184n/a Py_ssize_t key_value;
185n/a key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
186n/a if (key_value == -1 && PyErr_Occurred())
187n/a return -1;
188n/a return PySequence_SetItem(o, key_value, value);
189n/a }
190n/a else if (o->ob_type->tp_as_sequence->sq_ass_item) {
191n/a type_error("sequence index must be "
192n/a "integer, not '%.200s'", key);
193n/a return -1;
194n/a }
195n/a }
196n/a
197n/a type_error("'%.200s' object does not support item assignment", o);
198n/a return -1;
199n/a}
200n/a
201n/aint
202n/aPyObject_DelItem(PyObject *o, PyObject *key)
203n/a{
204n/a PyMappingMethods *m;
205n/a
206n/a if (o == NULL || key == NULL) {
207n/a null_error();
208n/a return -1;
209n/a }
210n/a m = o->ob_type->tp_as_mapping;
211n/a if (m && m->mp_ass_subscript)
212n/a return m->mp_ass_subscript(o, key, (PyObject*)NULL);
213n/a
214n/a if (o->ob_type->tp_as_sequence) {
215n/a if (PyIndex_Check(key)) {
216n/a Py_ssize_t key_value;
217n/a key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
218n/a if (key_value == -1 && PyErr_Occurred())
219n/a return -1;
220n/a return PySequence_DelItem(o, key_value);
221n/a }
222n/a else if (o->ob_type->tp_as_sequence->sq_ass_item) {
223n/a type_error("sequence index must be "
224n/a "integer, not '%.200s'", key);
225n/a return -1;
226n/a }
227n/a }
228n/a
229n/a type_error("'%.200s' object does not support item deletion", o);
230n/a return -1;
231n/a}
232n/a
233n/aint
234n/aPyObject_DelItemString(PyObject *o, const char *key)
235n/a{
236n/a PyObject *okey;
237n/a int ret;
238n/a
239n/a if (o == NULL || key == NULL) {
240n/a null_error();
241n/a return -1;
242n/a }
243n/a okey = PyUnicode_FromString(key);
244n/a if (okey == NULL)
245n/a return -1;
246n/a ret = PyObject_DelItem(o, okey);
247n/a Py_DECREF(okey);
248n/a return ret;
249n/a}
250n/a
251n/a/* We release the buffer right after use of this function which could
252n/a cause issues later on. Don't use these functions in new code.
253n/a */
254n/aint
255n/aPyObject_CheckReadBuffer(PyObject *obj)
256n/a{
257n/a PyBufferProcs *pb = obj->ob_type->tp_as_buffer;
258n/a Py_buffer view;
259n/a
260n/a if (pb == NULL ||
261n/a pb->bf_getbuffer == NULL)
262n/a return 0;
263n/a if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) {
264n/a PyErr_Clear();
265n/a return 0;
266n/a }
267n/a PyBuffer_Release(&view);
268n/a return 1;
269n/a}
270n/a
271n/astatic int
272n/aas_read_buffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len)
273n/a{
274n/a Py_buffer view;
275n/a
276n/a if (obj == NULL || buffer == NULL || buffer_len == NULL) {
277n/a null_error();
278n/a return -1;
279n/a }
280n/a if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0)
281n/a return -1;
282n/a
283n/a *buffer = view.buf;
284n/a *buffer_len = view.len;
285n/a PyBuffer_Release(&view);
286n/a return 0;
287n/a}
288n/a
289n/aint
290n/aPyObject_AsCharBuffer(PyObject *obj,
291n/a const char **buffer,
292n/a Py_ssize_t *buffer_len)
293n/a{
294n/a return as_read_buffer(obj, (const void **)buffer, buffer_len);
295n/a}
296n/a
297n/aint PyObject_AsReadBuffer(PyObject *obj,
298n/a const void **buffer,
299n/a Py_ssize_t *buffer_len)
300n/a{
301n/a return as_read_buffer(obj, buffer, buffer_len);
302n/a}
303n/a
304n/aint PyObject_AsWriteBuffer(PyObject *obj,
305n/a void **buffer,
306n/a Py_ssize_t *buffer_len)
307n/a{
308n/a PyBufferProcs *pb;
309n/a Py_buffer view;
310n/a
311n/a if (obj == NULL || buffer == NULL || buffer_len == NULL) {
312n/a null_error();
313n/a return -1;
314n/a }
315n/a pb = obj->ob_type->tp_as_buffer;
316n/a if (pb == NULL ||
317n/a pb->bf_getbuffer == NULL ||
318n/a ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) {
319n/a PyErr_SetString(PyExc_TypeError,
320n/a "expected a writable bytes-like object");
321n/a return -1;
322n/a }
323n/a
324n/a *buffer = view.buf;
325n/a *buffer_len = view.len;
326n/a PyBuffer_Release(&view);
327n/a return 0;
328n/a}
329n/a
330n/a/* Buffer C-API for Python 3.0 */
331n/a
332n/aint
333n/aPyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
334n/a{
335n/a PyBufferProcs *pb = obj->ob_type->tp_as_buffer;
336n/a
337n/a if (pb == NULL || pb->bf_getbuffer == NULL) {
338n/a PyErr_Format(PyExc_TypeError,
339n/a "a bytes-like object is required, not '%.100s'",
340n/a Py_TYPE(obj)->tp_name);
341n/a return -1;
342n/a }
343n/a return (*pb->bf_getbuffer)(obj, view, flags);
344n/a}
345n/a
346n/astatic int
347n/a_IsFortranContiguous(const Py_buffer *view)
348n/a{
349n/a Py_ssize_t sd, dim;
350n/a int i;
351n/a
352n/a /* 1) len = product(shape) * itemsize
353n/a 2) itemsize > 0
354n/a 3) len = 0 <==> exists i: shape[i] = 0 */
355n/a if (view->len == 0) return 1;
356n/a if (view->strides == NULL) { /* C-contiguous by definition */
357n/a /* Trivially F-contiguous */
358n/a if (view->ndim <= 1) return 1;
359n/a
360n/a /* ndim > 1 implies shape != NULL */
361n/a assert(view->shape != NULL);
362n/a
363n/a /* Effectively 1-d */
364n/a sd = 0;
365n/a for (i=0; i<view->ndim; i++) {
366n/a if (view->shape[i] > 1) sd += 1;
367n/a }
368n/a return sd <= 1;
369n/a }
370n/a
371n/a /* strides != NULL implies both of these */
372n/a assert(view->ndim > 0);
373n/a assert(view->shape != NULL);
374n/a
375n/a sd = view->itemsize;
376n/a for (i=0; i<view->ndim; i++) {
377n/a dim = view->shape[i];
378n/a if (dim > 1 && view->strides[i] != sd) {
379n/a return 0;
380n/a }
381n/a sd *= dim;
382n/a }
383n/a return 1;
384n/a}
385n/a
386n/astatic int
387n/a_IsCContiguous(const Py_buffer *view)
388n/a{
389n/a Py_ssize_t sd, dim;
390n/a int i;
391n/a
392n/a /* 1) len = product(shape) * itemsize
393n/a 2) itemsize > 0
394n/a 3) len = 0 <==> exists i: shape[i] = 0 */
395n/a if (view->len == 0) return 1;
396n/a if (view->strides == NULL) return 1; /* C-contiguous by definition */
397n/a
398n/a /* strides != NULL implies both of these */
399n/a assert(view->ndim > 0);
400n/a assert(view->shape != NULL);
401n/a
402n/a sd = view->itemsize;
403n/a for (i=view->ndim-1; i>=0; i--) {
404n/a dim = view->shape[i];
405n/a if (dim > 1 && view->strides[i] != sd) {
406n/a return 0;
407n/a }
408n/a sd *= dim;
409n/a }
410n/a return 1;
411n/a}
412n/a
413n/aint
414n/aPyBuffer_IsContiguous(const Py_buffer *view, char order)
415n/a{
416n/a
417n/a if (view->suboffsets != NULL) return 0;
418n/a
419n/a if (order == 'C')
420n/a return _IsCContiguous(view);
421n/a else if (order == 'F')
422n/a return _IsFortranContiguous(view);
423n/a else if (order == 'A')
424n/a return (_IsCContiguous(view) || _IsFortranContiguous(view));
425n/a return 0;
426n/a}
427n/a
428n/a
429n/avoid*
430n/aPyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)
431n/a{
432n/a char* pointer;
433n/a int i;
434n/a pointer = (char *)view->buf;
435n/a for (i = 0; i < view->ndim; i++) {
436n/a pointer += view->strides[i]*indices[i];
437n/a if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
438n/a pointer = *((char**)pointer) + view->suboffsets[i];
439n/a }
440n/a }
441n/a return (void*)pointer;
442n/a}
443n/a
444n/a
445n/avoid
446n/a_Py_add_one_to_index_F(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
447n/a{
448n/a int k;
449n/a
450n/a for (k=0; k<nd; k++) {
451n/a if (index[k] < shape[k]-1) {
452n/a index[k]++;
453n/a break;
454n/a }
455n/a else {
456n/a index[k] = 0;
457n/a }
458n/a }
459n/a}
460n/a
461n/avoid
462n/a_Py_add_one_to_index_C(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
463n/a{
464n/a int k;
465n/a
466n/a for (k=nd-1; k>=0; k--) {
467n/a if (index[k] < shape[k]-1) {
468n/a index[k]++;
469n/a break;
470n/a }
471n/a else {
472n/a index[k] = 0;
473n/a }
474n/a }
475n/a}
476n/a
477n/aint
478n/aPyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
479n/a{
480n/a int k;
481n/a void (*addone)(int, Py_ssize_t *, const Py_ssize_t *);
482n/a Py_ssize_t *indices, elements;
483n/a char *src, *ptr;
484n/a
485n/a if (len > view->len) {
486n/a len = view->len;
487n/a }
488n/a
489n/a if (PyBuffer_IsContiguous(view, fort)) {
490n/a /* simplest copy is all that is needed */
491n/a memcpy(view->buf, buf, len);
492n/a return 0;
493n/a }
494n/a
495n/a /* Otherwise a more elaborate scheme is needed */
496n/a
497n/a /* view->ndim <= 64 */
498n/a indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
499n/a if (indices == NULL) {
500n/a PyErr_NoMemory();
501n/a return -1;
502n/a }
503n/a for (k=0; k<view->ndim;k++) {
504n/a indices[k] = 0;
505n/a }
506n/a
507n/a if (fort == 'F') {
508n/a addone = _Py_add_one_to_index_F;
509n/a }
510n/a else {
511n/a addone = _Py_add_one_to_index_C;
512n/a }
513n/a src = buf;
514n/a /* XXX : This is not going to be the fastest code in the world
515n/a several optimizations are possible.
516n/a */
517n/a elements = len / view->itemsize;
518n/a while (elements--) {
519n/a ptr = PyBuffer_GetPointer(view, indices);
520n/a memcpy(ptr, src, view->itemsize);
521n/a src += view->itemsize;
522n/a addone(view->ndim, indices, view->shape);
523n/a }
524n/a
525n/a PyMem_Free(indices);
526n/a return 0;
527n/a}
528n/a
529n/aint PyObject_CopyData(PyObject *dest, PyObject *src)
530n/a{
531n/a Py_buffer view_dest, view_src;
532n/a int k;
533n/a Py_ssize_t *indices, elements;
534n/a char *dptr, *sptr;
535n/a
536n/a if (!PyObject_CheckBuffer(dest) ||
537n/a !PyObject_CheckBuffer(src)) {
538n/a PyErr_SetString(PyExc_TypeError,
539n/a "both destination and source must be "\
540n/a "bytes-like objects");
541n/a return -1;
542n/a }
543n/a
544n/a if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
545n/a if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
546n/a PyBuffer_Release(&view_dest);
547n/a return -1;
548n/a }
549n/a
550n/a if (view_dest.len < view_src.len) {
551n/a PyErr_SetString(PyExc_BufferError,
552n/a "destination is too small to receive data from source");
553n/a PyBuffer_Release(&view_dest);
554n/a PyBuffer_Release(&view_src);
555n/a return -1;
556n/a }
557n/a
558n/a if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
559n/a PyBuffer_IsContiguous(&view_src, 'C')) ||
560n/a (PyBuffer_IsContiguous(&view_dest, 'F') &&
561n/a PyBuffer_IsContiguous(&view_src, 'F'))) {
562n/a /* simplest copy is all that is needed */
563n/a memcpy(view_dest.buf, view_src.buf, view_src.len);
564n/a PyBuffer_Release(&view_dest);
565n/a PyBuffer_Release(&view_src);
566n/a return 0;
567n/a }
568n/a
569n/a /* Otherwise a more elaborate copy scheme is needed */
570n/a
571n/a /* XXX(nnorwitz): need to check for overflow! */
572n/a indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
573n/a if (indices == NULL) {
574n/a PyErr_NoMemory();
575n/a PyBuffer_Release(&view_dest);
576n/a PyBuffer_Release(&view_src);
577n/a return -1;
578n/a }
579n/a for (k=0; k<view_src.ndim;k++) {
580n/a indices[k] = 0;
581n/a }
582n/a elements = 1;
583n/a for (k=0; k<view_src.ndim; k++) {
584n/a /* XXX(nnorwitz): can this overflow? */
585n/a elements *= view_src.shape[k];
586n/a }
587n/a while (elements--) {
588n/a _Py_add_one_to_index_C(view_src.ndim, indices, view_src.shape);
589n/a dptr = PyBuffer_GetPointer(&view_dest, indices);
590n/a sptr = PyBuffer_GetPointer(&view_src, indices);
591n/a memcpy(dptr, sptr, view_src.itemsize);
592n/a }
593n/a PyMem_Free(indices);
594n/a PyBuffer_Release(&view_dest);
595n/a PyBuffer_Release(&view_src);
596n/a return 0;
597n/a}
598n/a
599n/avoid
600n/aPyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
601n/a Py_ssize_t *strides, int itemsize,
602n/a char fort)
603n/a{
604n/a int k;
605n/a Py_ssize_t sd;
606n/a
607n/a sd = itemsize;
608n/a if (fort == 'F') {
609n/a for (k=0; k<nd; k++) {
610n/a strides[k] = sd;
611n/a sd *= shape[k];
612n/a }
613n/a }
614n/a else {
615n/a for (k=nd-1; k>=0; k--) {
616n/a strides[k] = sd;
617n/a sd *= shape[k];
618n/a }
619n/a }
620n/a return;
621n/a}
622n/a
623n/aint
624n/aPyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
625n/a int readonly, int flags)
626n/a{
627n/a if (view == NULL) {
628n/a PyErr_SetString(PyExc_BufferError,
629n/a "PyBuffer_FillInfo: view==NULL argument is obsolete");
630n/a return -1;
631n/a }
632n/a
633n/a if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
634n/a (readonly == 1)) {
635n/a PyErr_SetString(PyExc_BufferError,
636n/a "Object is not writable.");
637n/a return -1;
638n/a }
639n/a
640n/a view->obj = obj;
641n/a if (obj)
642n/a Py_INCREF(obj);
643n/a view->buf = buf;
644n/a view->len = len;
645n/a view->readonly = readonly;
646n/a view->itemsize = 1;
647n/a view->format = NULL;
648n/a if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
649n/a view->format = "B";
650n/a view->ndim = 1;
651n/a view->shape = NULL;
652n/a if ((flags & PyBUF_ND) == PyBUF_ND)
653n/a view->shape = &(view->len);
654n/a view->strides = NULL;
655n/a if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
656n/a view->strides = &(view->itemsize);
657n/a view->suboffsets = NULL;
658n/a view->internal = NULL;
659n/a return 0;
660n/a}
661n/a
662n/avoid
663n/aPyBuffer_Release(Py_buffer *view)
664n/a{
665n/a PyObject *obj = view->obj;
666n/a PyBufferProcs *pb;
667n/a if (obj == NULL)
668n/a return;
669n/a pb = Py_TYPE(obj)->tp_as_buffer;
670n/a if (pb && pb->bf_releasebuffer)
671n/a pb->bf_releasebuffer(obj, view);
672n/a view->obj = NULL;
673n/a Py_DECREF(obj);
674n/a}
675n/a
676n/aPyObject *
677n/aPyObject_Format(PyObject *obj, PyObject *format_spec)
678n/a{
679n/a PyObject *meth;
680n/a PyObject *empty = NULL;
681n/a PyObject *result = NULL;
682n/a _Py_IDENTIFIER(__format__);
683n/a
684n/a if (format_spec != NULL && !PyUnicode_Check(format_spec)) {
685n/a PyErr_Format(PyExc_SystemError,
686n/a "Format specifier must be a string, not %.200s",
687n/a Py_TYPE(format_spec)->tp_name);
688n/a return NULL;
689n/a }
690n/a
691n/a /* Fast path for common types. */
692n/a if (format_spec == NULL || PyUnicode_GET_LENGTH(format_spec) == 0) {
693n/a if (PyUnicode_CheckExact(obj)) {
694n/a Py_INCREF(obj);
695n/a return obj;
696n/a }
697n/a if (PyLong_CheckExact(obj)) {
698n/a return PyObject_Str(obj);
699n/a }
700n/a }
701n/a
702n/a /* If no format_spec is provided, use an empty string */
703n/a if (format_spec == NULL) {
704n/a empty = PyUnicode_New(0, 0);
705n/a format_spec = empty;
706n/a }
707n/a
708n/a /* Find the (unbound!) __format__ method */
709n/a meth = _PyObject_LookupSpecial(obj, &PyId___format__);
710n/a if (meth == NULL) {
711n/a if (!PyErr_Occurred())
712n/a PyErr_Format(PyExc_TypeError,
713n/a "Type %.100s doesn't define __format__",
714n/a Py_TYPE(obj)->tp_name);
715n/a goto done;
716n/a }
717n/a
718n/a /* And call it. */
719n/a result = PyObject_CallFunctionObjArgs(meth, format_spec, NULL);
720n/a Py_DECREF(meth);
721n/a
722n/a if (result && !PyUnicode_Check(result)) {
723n/a PyErr_Format(PyExc_TypeError,
724n/a "__format__ must return a str, not %.200s",
725n/a Py_TYPE(result)->tp_name);
726n/a Py_DECREF(result);
727n/a result = NULL;
728n/a goto done;
729n/a }
730n/a
731n/adone:
732n/a Py_XDECREF(empty);
733n/a return result;
734n/a}
735n/a/* Operations on numbers */
736n/a
737n/aint
738n/aPyNumber_Check(PyObject *o)
739n/a{
740n/a return o && o->ob_type->tp_as_number &&
741n/a (o->ob_type->tp_as_number->nb_int ||
742n/a o->ob_type->tp_as_number->nb_float);
743n/a}
744n/a
745n/a/* Binary operators */
746n/a
747n/a#define NB_SLOT(x) offsetof(PyNumberMethods, x)
748n/a#define NB_BINOP(nb_methods, slot) \
749n/a (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
750n/a#define NB_TERNOP(nb_methods, slot) \
751n/a (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
752n/a
753n/a/*
754n/a Calling scheme used for binary operations:
755n/a
756n/a Order operations are tried until either a valid result or error:
757n/a w.op(v,w)[*], v.op(v,w), w.op(v,w)
758n/a
759n/a [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
760n/a v->ob_type
761n/a */
762n/a
763n/astatic PyObject *
764n/abinary_op1(PyObject *v, PyObject *w, const int op_slot)
765n/a{
766n/a PyObject *x;
767n/a binaryfunc slotv = NULL;
768n/a binaryfunc slotw = NULL;
769n/a
770n/a if (v->ob_type->tp_as_number != NULL)
771n/a slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot);
772n/a if (w->ob_type != v->ob_type &&
773n/a w->ob_type->tp_as_number != NULL) {
774n/a slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot);
775n/a if (slotw == slotv)
776n/a slotw = NULL;
777n/a }
778n/a if (slotv) {
779n/a if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
780n/a x = slotw(v, w);
781n/a if (x != Py_NotImplemented)
782n/a return x;
783n/a Py_DECREF(x); /* can't do it */
784n/a slotw = NULL;
785n/a }
786n/a x = slotv(v, w);
787n/a if (x != Py_NotImplemented)
788n/a return x;
789n/a Py_DECREF(x); /* can't do it */
790n/a }
791n/a if (slotw) {
792n/a x = slotw(v, w);
793n/a if (x != Py_NotImplemented)
794n/a return x;
795n/a Py_DECREF(x); /* can't do it */
796n/a }
797n/a Py_RETURN_NOTIMPLEMENTED;
798n/a}
799n/a
800n/astatic PyObject *
801n/abinop_type_error(PyObject *v, PyObject *w, const char *op_name)
802n/a{
803n/a PyErr_Format(PyExc_TypeError,
804n/a "unsupported operand type(s) for %.100s: "
805n/a "'%.100s' and '%.100s'",
806n/a op_name,
807n/a v->ob_type->tp_name,
808n/a w->ob_type->tp_name);
809n/a return NULL;
810n/a}
811n/a
812n/astatic PyObject *
813n/abinary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
814n/a{
815n/a PyObject *result = binary_op1(v, w, op_slot);
816n/a if (result == Py_NotImplemented) {
817n/a Py_DECREF(result);
818n/a return binop_type_error(v, w, op_name);
819n/a }
820n/a return result;
821n/a}
822n/a
823n/a
824n/a/*
825n/a Calling scheme used for ternary operations:
826n/a
827n/a Order operations are tried until either a valid result or error:
828n/a v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
829n/a */
830n/a
831n/astatic PyObject *
832n/aternary_op(PyObject *v,
833n/a PyObject *w,
834n/a PyObject *z,
835n/a const int op_slot,
836n/a const char *op_name)
837n/a{
838n/a PyNumberMethods *mv, *mw, *mz;
839n/a PyObject *x = NULL;
840n/a ternaryfunc slotv = NULL;
841n/a ternaryfunc slotw = NULL;
842n/a ternaryfunc slotz = NULL;
843n/a
844n/a mv = v->ob_type->tp_as_number;
845n/a mw = w->ob_type->tp_as_number;
846n/a if (mv != NULL)
847n/a slotv = NB_TERNOP(mv, op_slot);
848n/a if (w->ob_type != v->ob_type &&
849n/a mw != NULL) {
850n/a slotw = NB_TERNOP(mw, op_slot);
851n/a if (slotw == slotv)
852n/a slotw = NULL;
853n/a }
854n/a if (slotv) {
855n/a if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
856n/a x = slotw(v, w, z);
857n/a if (x != Py_NotImplemented)
858n/a return x;
859n/a Py_DECREF(x); /* can't do it */
860n/a slotw = NULL;
861n/a }
862n/a x = slotv(v, w, z);
863n/a if (x != Py_NotImplemented)
864n/a return x;
865n/a Py_DECREF(x); /* can't do it */
866n/a }
867n/a if (slotw) {
868n/a x = slotw(v, w, z);
869n/a if (x != Py_NotImplemented)
870n/a return x;
871n/a Py_DECREF(x); /* can't do it */
872n/a }
873n/a mz = z->ob_type->tp_as_number;
874n/a if (mz != NULL) {
875n/a slotz = NB_TERNOP(mz, op_slot);
876n/a if (slotz == slotv || slotz == slotw)
877n/a slotz = NULL;
878n/a if (slotz) {
879n/a x = slotz(v, w, z);
880n/a if (x != Py_NotImplemented)
881n/a return x;
882n/a Py_DECREF(x); /* can't do it */
883n/a }
884n/a }
885n/a
886n/a if (z == Py_None)
887n/a PyErr_Format(
888n/a PyExc_TypeError,
889n/a "unsupported operand type(s) for ** or pow(): "
890n/a "'%.100s' and '%.100s'",
891n/a v->ob_type->tp_name,
892n/a w->ob_type->tp_name);
893n/a else
894n/a PyErr_Format(
895n/a PyExc_TypeError,
896n/a "unsupported operand type(s) for pow(): "
897n/a "'%.100s', '%.100s', '%.100s'",
898n/a v->ob_type->tp_name,
899n/a w->ob_type->tp_name,
900n/a z->ob_type->tp_name);
901n/a return NULL;
902n/a}
903n/a
904n/a#define BINARY_FUNC(func, op, op_name) \
905n/a PyObject * \
906n/a func(PyObject *v, PyObject *w) { \
907n/a return binary_op(v, w, NB_SLOT(op), op_name); \
908n/a }
909n/a
910n/aBINARY_FUNC(PyNumber_Or, nb_or, "|")
911n/aBINARY_FUNC(PyNumber_Xor, nb_xor, "^")
912n/aBINARY_FUNC(PyNumber_And, nb_and, "&")
913n/aBINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
914n/aBINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
915n/aBINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
916n/aBINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
917n/a
918n/aPyObject *
919n/aPyNumber_Add(PyObject *v, PyObject *w)
920n/a{
921n/a PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
922n/a if (result == Py_NotImplemented) {
923n/a PySequenceMethods *m = v->ob_type->tp_as_sequence;
924n/a Py_DECREF(result);
925n/a if (m && m->sq_concat) {
926n/a return (*m->sq_concat)(v, w);
927n/a }
928n/a result = binop_type_error(v, w, "+");
929n/a }
930n/a return result;
931n/a}
932n/a
933n/astatic PyObject *
934n/asequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
935n/a{
936n/a Py_ssize_t count;
937n/a if (PyIndex_Check(n)) {
938n/a count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
939n/a if (count == -1 && PyErr_Occurred())
940n/a return NULL;
941n/a }
942n/a else {
943n/a return type_error("can't multiply sequence by "
944n/a "non-int of type '%.200s'", n);
945n/a }
946n/a return (*repeatfunc)(seq, count);
947n/a}
948n/a
949n/aPyObject *
950n/aPyNumber_Multiply(PyObject *v, PyObject *w)
951n/a{
952n/a PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
953n/a if (result == Py_NotImplemented) {
954n/a PySequenceMethods *mv = v->ob_type->tp_as_sequence;
955n/a PySequenceMethods *mw = w->ob_type->tp_as_sequence;
956n/a Py_DECREF(result);
957n/a if (mv && mv->sq_repeat) {
958n/a return sequence_repeat(mv->sq_repeat, v, w);
959n/a }
960n/a else if (mw && mw->sq_repeat) {
961n/a return sequence_repeat(mw->sq_repeat, w, v);
962n/a }
963n/a result = binop_type_error(v, w, "*");
964n/a }
965n/a return result;
966n/a}
967n/a
968n/aPyObject *
969n/aPyNumber_MatrixMultiply(PyObject *v, PyObject *w)
970n/a{
971n/a return binary_op(v, w, NB_SLOT(nb_matrix_multiply), "@");
972n/a}
973n/a
974n/aPyObject *
975n/aPyNumber_FloorDivide(PyObject *v, PyObject *w)
976n/a{
977n/a return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
978n/a}
979n/a
980n/aPyObject *
981n/aPyNumber_TrueDivide(PyObject *v, PyObject *w)
982n/a{
983n/a return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
984n/a}
985n/a
986n/aPyObject *
987n/aPyNumber_Remainder(PyObject *v, PyObject *w)
988n/a{
989n/a return binary_op(v, w, NB_SLOT(nb_remainder), "%");
990n/a}
991n/a
992n/aPyObject *
993n/aPyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
994n/a{
995n/a return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
996n/a}
997n/a
998n/a/* Binary in-place operators */
999n/a
1000n/a/* The in-place operators are defined to fall back to the 'normal',
1001n/a non in-place operations, if the in-place methods are not in place.
1002n/a
1003n/a - If the left hand object has the appropriate struct members, and
1004n/a they are filled, call the appropriate function and return the
1005n/a result. No coercion is done on the arguments; the left-hand object
1006n/a is the one the operation is performed on, and it's up to the
1007n/a function to deal with the right-hand object.
1008n/a
1009n/a - Otherwise, in-place modification is not supported. Handle it exactly as
1010n/a a non in-place operation of the same kind.
1011n/a
1012n/a */
1013n/a
1014n/astatic PyObject *
1015n/abinary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)
1016n/a{
1017n/a PyNumberMethods *mv = v->ob_type->tp_as_number;
1018n/a if (mv != NULL) {
1019n/a binaryfunc slot = NB_BINOP(mv, iop_slot);
1020n/a if (slot) {
1021n/a PyObject *x = (slot)(v, w);
1022n/a if (x != Py_NotImplemented) {
1023n/a return x;
1024n/a }
1025n/a Py_DECREF(x);
1026n/a }
1027n/a }
1028n/a return binary_op1(v, w, op_slot);
1029n/a}
1030n/a
1031n/astatic PyObject *
1032n/abinary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
1033n/a const char *op_name)
1034n/a{
1035n/a PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
1036n/a if (result == Py_NotImplemented) {
1037n/a Py_DECREF(result);
1038n/a return binop_type_error(v, w, op_name);
1039n/a }
1040n/a return result;
1041n/a}
1042n/a
1043n/a#define INPLACE_BINOP(func, iop, op, op_name) \
1044n/a PyObject * \
1045n/a func(PyObject *v, PyObject *w) { \
1046n/a return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1047n/a }
1048n/a
1049n/aINPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1050n/aINPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1051n/aINPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1052n/aINPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1053n/aINPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1054n/aINPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
1055n/aINPLACE_BINOP(PyNumber_InMatrixMultiply, nb_inplace_matrix_multiply, nb_matrix_multiply, "@=")
1056n/a
1057n/aPyObject *
1058n/aPyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
1059n/a{
1060n/a return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
1061n/a NB_SLOT(nb_floor_divide), "//=");
1062n/a}
1063n/a
1064n/aPyObject *
1065n/aPyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
1066n/a{
1067n/a return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
1068n/a NB_SLOT(nb_true_divide), "/=");
1069n/a}
1070n/a
1071n/aPyObject *
1072n/aPyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1073n/a{
1074n/a PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
1075n/a NB_SLOT(nb_add));
1076n/a if (result == Py_NotImplemented) {
1077n/a PySequenceMethods *m = v->ob_type->tp_as_sequence;
1078n/a Py_DECREF(result);
1079n/a if (m != NULL) {
1080n/a binaryfunc f = NULL;
1081n/a f = m->sq_inplace_concat;
1082n/a if (f == NULL)
1083n/a f = m->sq_concat;
1084n/a if (f != NULL)
1085n/a return (*f)(v, w);
1086n/a }
1087n/a result = binop_type_error(v, w, "+=");
1088n/a }
1089n/a return result;
1090n/a}
1091n/a
1092n/aPyObject *
1093n/aPyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1094n/a{
1095n/a PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
1096n/a NB_SLOT(nb_multiply));
1097n/a if (result == Py_NotImplemented) {
1098n/a ssizeargfunc f = NULL;
1099n/a PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1100n/a PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1101n/a Py_DECREF(result);
1102n/a if (mv != NULL) {
1103n/a f = mv->sq_inplace_repeat;
1104n/a if (f == NULL)
1105n/a f = mv->sq_repeat;
1106n/a if (f != NULL)
1107n/a return sequence_repeat(f, v, w);
1108n/a }
1109n/a else if (mw != NULL) {
1110n/a /* Note that the right hand operand should not be
1111n/a * mutated in this case so sq_inplace_repeat is not
1112n/a * used. */
1113n/a if (mw->sq_repeat)
1114n/a return sequence_repeat(mw->sq_repeat, w, v);
1115n/a }
1116n/a result = binop_type_error(v, w, "*=");
1117n/a }
1118n/a return result;
1119n/a}
1120n/a
1121n/aPyObject *
1122n/aPyNumber_InPlaceMatrixMultiply(PyObject *v, PyObject *w)
1123n/a{
1124n/a return binary_iop(v, w, NB_SLOT(nb_inplace_matrix_multiply),
1125n/a NB_SLOT(nb_matrix_multiply), "@=");
1126n/a}
1127n/a
1128n/aPyObject *
1129n/aPyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
1130n/a{
1131n/a return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
1132n/a NB_SLOT(nb_remainder), "%=");
1133n/a}
1134n/a
1135n/aPyObject *
1136n/aPyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1137n/a{
1138n/a if (v->ob_type->tp_as_number &&
1139n/a v->ob_type->tp_as_number->nb_inplace_power != NULL) {
1140n/a return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
1141n/a }
1142n/a else {
1143n/a return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
1144n/a }
1145n/a}
1146n/a
1147n/a
1148n/a/* Unary operators and functions */
1149n/a
1150n/aPyObject *
1151n/aPyNumber_Negative(PyObject *o)
1152n/a{
1153n/a PyNumberMethods *m;
1154n/a
1155n/a if (o == NULL) {
1156n/a return null_error();
1157n/a }
1158n/a
1159n/a m = o->ob_type->tp_as_number;
1160n/a if (m && m->nb_negative)
1161n/a return (*m->nb_negative)(o);
1162n/a
1163n/a return type_error("bad operand type for unary -: '%.200s'", o);
1164n/a}
1165n/a
1166n/aPyObject *
1167n/aPyNumber_Positive(PyObject *o)
1168n/a{
1169n/a PyNumberMethods *m;
1170n/a
1171n/a if (o == NULL) {
1172n/a return null_error();
1173n/a }
1174n/a
1175n/a m = o->ob_type->tp_as_number;
1176n/a if (m && m->nb_positive)
1177n/a return (*m->nb_positive)(o);
1178n/a
1179n/a return type_error("bad operand type for unary +: '%.200s'", o);
1180n/a}
1181n/a
1182n/aPyObject *
1183n/aPyNumber_Invert(PyObject *o)
1184n/a{
1185n/a PyNumberMethods *m;
1186n/a
1187n/a if (o == NULL) {
1188n/a return null_error();
1189n/a }
1190n/a
1191n/a m = o->ob_type->tp_as_number;
1192n/a if (m && m->nb_invert)
1193n/a return (*m->nb_invert)(o);
1194n/a
1195n/a return type_error("bad operand type for unary ~: '%.200s'", o);
1196n/a}
1197n/a
1198n/aPyObject *
1199n/aPyNumber_Absolute(PyObject *o)
1200n/a{
1201n/a PyNumberMethods *m;
1202n/a
1203n/a if (o == NULL) {
1204n/a return null_error();
1205n/a }
1206n/a
1207n/a m = o->ob_type->tp_as_number;
1208n/a if (m && m->nb_absolute)
1209n/a return m->nb_absolute(o);
1210n/a
1211n/a return type_error("bad operand type for abs(): '%.200s'", o);
1212n/a}
1213n/a
1214n/a/* Return a Python int from the object item.
1215n/a Raise TypeError if the result is not an int
1216n/a or if the object cannot be interpreted as an index.
1217n/a*/
1218n/aPyObject *
1219n/aPyNumber_Index(PyObject *item)
1220n/a{
1221n/a PyObject *result = NULL;
1222n/a if (item == NULL) {
1223n/a return null_error();
1224n/a }
1225n/a
1226n/a if (PyLong_Check(item)) {
1227n/a Py_INCREF(item);
1228n/a return item;
1229n/a }
1230n/a if (!PyIndex_Check(item)) {
1231n/a PyErr_Format(PyExc_TypeError,
1232n/a "'%.200s' object cannot be interpreted "
1233n/a "as an integer", item->ob_type->tp_name);
1234n/a return NULL;
1235n/a }
1236n/a result = item->ob_type->tp_as_number->nb_index(item);
1237n/a if (!result || PyLong_CheckExact(result))
1238n/a return result;
1239n/a if (!PyLong_Check(result)) {
1240n/a PyErr_Format(PyExc_TypeError,
1241n/a "__index__ returned non-int (type %.200s)",
1242n/a result->ob_type->tp_name);
1243n/a Py_DECREF(result);
1244n/a return NULL;
1245n/a }
1246n/a /* Issue #17576: warn if 'result' not of exact type int. */
1247n/a if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1248n/a "__index__ returned non-int (type %.200s). "
1249n/a "The ability to return an instance of a strict subclass of int "
1250n/a "is deprecated, and may be removed in a future version of Python.",
1251n/a result->ob_type->tp_name)) {
1252n/a Py_DECREF(result);
1253n/a return NULL;
1254n/a }
1255n/a return result;
1256n/a}
1257n/a
1258n/a/* Return an error on Overflow only if err is not NULL*/
1259n/a
1260n/aPy_ssize_t
1261n/aPyNumber_AsSsize_t(PyObject *item, PyObject *err)
1262n/a{
1263n/a Py_ssize_t result;
1264n/a PyObject *runerr;
1265n/a PyObject *value = PyNumber_Index(item);
1266n/a if (value == NULL)
1267n/a return -1;
1268n/a
1269n/a /* We're done if PyLong_AsSsize_t() returns without error. */
1270n/a result = PyLong_AsSsize_t(value);
1271n/a if (result != -1 || !(runerr = PyErr_Occurred()))
1272n/a goto finish;
1273n/a
1274n/a /* Error handling code -- only manage OverflowError differently */
1275n/a if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
1276n/a goto finish;
1277n/a
1278n/a PyErr_Clear();
1279n/a /* If no error-handling desired then the default clipping
1280n/a is sufficient.
1281n/a */
1282n/a if (!err) {
1283n/a assert(PyLong_Check(value));
1284n/a /* Whether or not it is less than or equal to
1285n/a zero is determined by the sign of ob_size
1286n/a */
1287n/a if (_PyLong_Sign(value) < 0)
1288n/a result = PY_SSIZE_T_MIN;
1289n/a else
1290n/a result = PY_SSIZE_T_MAX;
1291n/a }
1292n/a else {
1293n/a /* Otherwise replace the error with caller's error object. */
1294n/a PyErr_Format(err,
1295n/a "cannot fit '%.200s' into an index-sized integer",
1296n/a item->ob_type->tp_name);
1297n/a }
1298n/a
1299n/a finish:
1300n/a Py_DECREF(value);
1301n/a return result;
1302n/a}
1303n/a
1304n/a
1305n/aPyObject *
1306n/aPyNumber_Long(PyObject *o)
1307n/a{
1308n/a PyObject *result;
1309n/a PyNumberMethods *m;
1310n/a PyObject *trunc_func;
1311n/a Py_buffer view;
1312n/a _Py_IDENTIFIER(__trunc__);
1313n/a
1314n/a if (o == NULL) {
1315n/a return null_error();
1316n/a }
1317n/a
1318n/a if (PyLong_CheckExact(o)) {
1319n/a Py_INCREF(o);
1320n/a return o;
1321n/a }
1322n/a m = o->ob_type->tp_as_number;
1323n/a if (m && m->nb_int) { /* This should include subclasses of int */
1324n/a result = (PyObject *)_PyLong_FromNbInt(o);
1325n/a if (result != NULL && !PyLong_CheckExact(result)) {
1326n/a Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1327n/a }
1328n/a return result;
1329n/a }
1330n/a trunc_func = _PyObject_LookupSpecial(o, &PyId___trunc__);
1331n/a if (trunc_func) {
1332n/a result = PyEval_CallObject(trunc_func, NULL);
1333n/a Py_DECREF(trunc_func);
1334n/a if (result == NULL || PyLong_CheckExact(result)) {
1335n/a return result;
1336n/a }
1337n/a if (PyLong_Check(result)) {
1338n/a Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1339n/a return result;
1340n/a }
1341n/a /* __trunc__ is specified to return an Integral type,
1342n/a but int() needs to return an int. */
1343n/a m = result->ob_type->tp_as_number;
1344n/a if (m == NULL || m->nb_int == NULL) {
1345n/a PyErr_Format(
1346n/a PyExc_TypeError,
1347n/a "__trunc__ returned non-Integral (type %.200s)",
1348n/a result->ob_type->tp_name);
1349n/a Py_DECREF(result);
1350n/a return NULL;
1351n/a }
1352n/a Py_SETREF(result, (PyObject *)_PyLong_FromNbInt(result));
1353n/a if (result != NULL && !PyLong_CheckExact(result)) {
1354n/a Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1355n/a }
1356n/a return result;
1357n/a }
1358n/a if (PyErr_Occurred())
1359n/a return NULL;
1360n/a
1361n/a if (PyUnicode_Check(o))
1362n/a /* The below check is done in PyLong_FromUnicode(). */
1363n/a return PyLong_FromUnicodeObject(o, 10);
1364n/a
1365n/a if (PyBytes_Check(o))
1366n/a /* need to do extra error checking that PyLong_FromString()
1367n/a * doesn't do. In particular int('9\x005') must raise an
1368n/a * exception, not truncate at the null.
1369n/a */
1370n/a return _PyLong_FromBytes(PyBytes_AS_STRING(o),
1371n/a PyBytes_GET_SIZE(o), 10);
1372n/a
1373n/a if (PyByteArray_Check(o))
1374n/a return _PyLong_FromBytes(PyByteArray_AS_STRING(o),
1375n/a PyByteArray_GET_SIZE(o), 10);
1376n/a
1377n/a if (PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) == 0) {
1378n/a PyObject *bytes;
1379n/a
1380n/a /* Copy to NUL-terminated buffer. */
1381n/a bytes = PyBytes_FromStringAndSize((const char *)view.buf, view.len);
1382n/a if (bytes == NULL) {
1383n/a PyBuffer_Release(&view);
1384n/a return NULL;
1385n/a }
1386n/a result = _PyLong_FromBytes(PyBytes_AS_STRING(bytes),
1387n/a PyBytes_GET_SIZE(bytes), 10);
1388n/a Py_DECREF(bytes);
1389n/a PyBuffer_Release(&view);
1390n/a return result;
1391n/a }
1392n/a
1393n/a return type_error("int() argument must be a string, a bytes-like object "
1394n/a "or a number, not '%.200s'", o);
1395n/a}
1396n/a
1397n/aPyObject *
1398n/aPyNumber_Float(PyObject *o)
1399n/a{
1400n/a PyNumberMethods *m;
1401n/a
1402n/a if (o == NULL) {
1403n/a return null_error();
1404n/a }
1405n/a
1406n/a if (PyFloat_CheckExact(o)) {
1407n/a Py_INCREF(o);
1408n/a return o;
1409n/a }
1410n/a m = o->ob_type->tp_as_number;
1411n/a if (m && m->nb_float) { /* This should include subclasses of float */
1412n/a PyObject *res = m->nb_float(o);
1413n/a double val;
1414n/a if (!res || PyFloat_CheckExact(res)) {
1415n/a return res;
1416n/a }
1417n/a if (!PyFloat_Check(res)) {
1418n/a PyErr_Format(PyExc_TypeError,
1419n/a "%.50s.__float__ returned non-float (type %.50s)",
1420n/a o->ob_type->tp_name, res->ob_type->tp_name);
1421n/a Py_DECREF(res);
1422n/a return NULL;
1423n/a }
1424n/a /* Issue #26983: warn if 'res' not of exact type float. */
1425n/a if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1426n/a "%.50s.__float__ returned non-float (type %.50s). "
1427n/a "The ability to return an instance of a strict subclass of float "
1428n/a "is deprecated, and may be removed in a future version of Python.",
1429n/a o->ob_type->tp_name, res->ob_type->tp_name)) {
1430n/a Py_DECREF(res);
1431n/a return NULL;
1432n/a }
1433n/a val = PyFloat_AS_DOUBLE(res);
1434n/a Py_DECREF(res);
1435n/a return PyFloat_FromDouble(val);
1436n/a }
1437n/a if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
1438n/a return PyFloat_FromDouble(PyFloat_AS_DOUBLE(o));
1439n/a }
1440n/a return PyFloat_FromString(o);
1441n/a}
1442n/a
1443n/a
1444n/aPyObject *
1445n/aPyNumber_ToBase(PyObject *n, int base)
1446n/a{
1447n/a PyObject *res = NULL;
1448n/a PyObject *index = PyNumber_Index(n);
1449n/a
1450n/a if (!index)
1451n/a return NULL;
1452n/a if (PyLong_Check(index))
1453n/a res = _PyLong_Format(index, base);
1454n/a else
1455n/a /* It should not be possible to get here, as
1456n/a PyNumber_Index already has a check for the same
1457n/a condition */
1458n/a PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not int");
1459n/a Py_DECREF(index);
1460n/a return res;
1461n/a}
1462n/a
1463n/a
1464n/a/* Operations on sequences */
1465n/a
1466n/aint
1467n/aPySequence_Check(PyObject *s)
1468n/a{
1469n/a if (PyDict_Check(s))
1470n/a return 0;
1471n/a return s != NULL && s->ob_type->tp_as_sequence &&
1472n/a s->ob_type->tp_as_sequence->sq_item != NULL;
1473n/a}
1474n/a
1475n/aPy_ssize_t
1476n/aPySequence_Size(PyObject *s)
1477n/a{
1478n/a PySequenceMethods *m;
1479n/a
1480n/a if (s == NULL) {
1481n/a null_error();
1482n/a return -1;
1483n/a }
1484n/a
1485n/a m = s->ob_type->tp_as_sequence;
1486n/a if (m && m->sq_length)
1487n/a return m->sq_length(s);
1488n/a
1489n/a type_error("object of type '%.200s' has no len()", s);
1490n/a return -1;
1491n/a}
1492n/a
1493n/a#undef PySequence_Length
1494n/aPy_ssize_t
1495n/aPySequence_Length(PyObject *s)
1496n/a{
1497n/a return PySequence_Size(s);
1498n/a}
1499n/a#define PySequence_Length PySequence_Size
1500n/a
1501n/aPyObject *
1502n/aPySequence_Concat(PyObject *s, PyObject *o)
1503n/a{
1504n/a PySequenceMethods *m;
1505n/a
1506n/a if (s == NULL || o == NULL) {
1507n/a return null_error();
1508n/a }
1509n/a
1510n/a m = s->ob_type->tp_as_sequence;
1511n/a if (m && m->sq_concat)
1512n/a return m->sq_concat(s, o);
1513n/a
1514n/a /* Instances of user classes defining an __add__() method only
1515n/a have an nb_add slot, not an sq_concat slot. So we fall back
1516n/a to nb_add if both arguments appear to be sequences. */
1517n/a if (PySequence_Check(s) && PySequence_Check(o)) {
1518n/a PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
1519n/a if (result != Py_NotImplemented)
1520n/a return result;
1521n/a Py_DECREF(result);
1522n/a }
1523n/a return type_error("'%.200s' object can't be concatenated", s);
1524n/a}
1525n/a
1526n/aPyObject *
1527n/aPySequence_Repeat(PyObject *o, Py_ssize_t count)
1528n/a{
1529n/a PySequenceMethods *m;
1530n/a
1531n/a if (o == NULL) {
1532n/a return null_error();
1533n/a }
1534n/a
1535n/a m = o->ob_type->tp_as_sequence;
1536n/a if (m && m->sq_repeat)
1537n/a return m->sq_repeat(o, count);
1538n/a
1539n/a /* Instances of user classes defining a __mul__() method only
1540n/a have an nb_multiply slot, not an sq_repeat slot. so we fall back
1541n/a to nb_multiply if o appears to be a sequence. */
1542n/a if (PySequence_Check(o)) {
1543n/a PyObject *n, *result;
1544n/a n = PyLong_FromSsize_t(count);
1545n/a if (n == NULL)
1546n/a return NULL;
1547n/a result = binary_op1(o, n, NB_SLOT(nb_multiply));
1548n/a Py_DECREF(n);
1549n/a if (result != Py_NotImplemented)
1550n/a return result;
1551n/a Py_DECREF(result);
1552n/a }
1553n/a return type_error("'%.200s' object can't be repeated", o);
1554n/a}
1555n/a
1556n/aPyObject *
1557n/aPySequence_InPlaceConcat(PyObject *s, PyObject *o)
1558n/a{
1559n/a PySequenceMethods *m;
1560n/a
1561n/a if (s == NULL || o == NULL) {
1562n/a return null_error();
1563n/a }
1564n/a
1565n/a m = s->ob_type->tp_as_sequence;
1566n/a if (m && m->sq_inplace_concat)
1567n/a return m->sq_inplace_concat(s, o);
1568n/a if (m && m->sq_concat)
1569n/a return m->sq_concat(s, o);
1570n/a
1571n/a if (PySequence_Check(s) && PySequence_Check(o)) {
1572n/a PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
1573n/a NB_SLOT(nb_add));
1574n/a if (result != Py_NotImplemented)
1575n/a return result;
1576n/a Py_DECREF(result);
1577n/a }
1578n/a return type_error("'%.200s' object can't be concatenated", s);
1579n/a}
1580n/a
1581n/aPyObject *
1582n/aPySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
1583n/a{
1584n/a PySequenceMethods *m;
1585n/a
1586n/a if (o == NULL) {
1587n/a return null_error();
1588n/a }
1589n/a
1590n/a m = o->ob_type->tp_as_sequence;
1591n/a if (m && m->sq_inplace_repeat)
1592n/a return m->sq_inplace_repeat(o, count);
1593n/a if (m && m->sq_repeat)
1594n/a return m->sq_repeat(o, count);
1595n/a
1596n/a if (PySequence_Check(o)) {
1597n/a PyObject *n, *result;
1598n/a n = PyLong_FromSsize_t(count);
1599n/a if (n == NULL)
1600n/a return NULL;
1601n/a result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
1602n/a NB_SLOT(nb_multiply));
1603n/a Py_DECREF(n);
1604n/a if (result != Py_NotImplemented)
1605n/a return result;
1606n/a Py_DECREF(result);
1607n/a }
1608n/a return type_error("'%.200s' object can't be repeated", o);
1609n/a}
1610n/a
1611n/aPyObject *
1612n/aPySequence_GetItem(PyObject *s, Py_ssize_t i)
1613n/a{
1614n/a PySequenceMethods *m;
1615n/a
1616n/a if (s == NULL) {
1617n/a return null_error();
1618n/a }
1619n/a
1620n/a m = s->ob_type->tp_as_sequence;
1621n/a if (m && m->sq_item) {
1622n/a if (i < 0) {
1623n/a if (m->sq_length) {
1624n/a Py_ssize_t l = (*m->sq_length)(s);
1625n/a if (l < 0) {
1626n/a assert(PyErr_Occurred());
1627n/a return NULL;
1628n/a }
1629n/a i += l;
1630n/a }
1631n/a }
1632n/a return m->sq_item(s, i);
1633n/a }
1634n/a
1635n/a return type_error("'%.200s' object does not support indexing", s);
1636n/a}
1637n/a
1638n/aPyObject *
1639n/aPySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
1640n/a{
1641n/a PyMappingMethods *mp;
1642n/a
1643n/a if (!s) {
1644n/a return null_error();
1645n/a }
1646n/a
1647n/a mp = s->ob_type->tp_as_mapping;
1648n/a if (mp && mp->mp_subscript) {
1649n/a PyObject *res;
1650n/a PyObject *slice = _PySlice_FromIndices(i1, i2);
1651n/a if (!slice)
1652n/a return NULL;
1653n/a res = mp->mp_subscript(s, slice);
1654n/a Py_DECREF(slice);
1655n/a return res;
1656n/a }
1657n/a
1658n/a return type_error("'%.200s' object is unsliceable", s);
1659n/a}
1660n/a
1661n/aint
1662n/aPySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
1663n/a{
1664n/a PySequenceMethods *m;
1665n/a
1666n/a if (s == NULL) {
1667n/a null_error();
1668n/a return -1;
1669n/a }
1670n/a
1671n/a m = s->ob_type->tp_as_sequence;
1672n/a if (m && m->sq_ass_item) {
1673n/a if (i < 0) {
1674n/a if (m->sq_length) {
1675n/a Py_ssize_t l = (*m->sq_length)(s);
1676n/a if (l < 0)
1677n/a return -1;
1678n/a i += l;
1679n/a }
1680n/a }
1681n/a return m->sq_ass_item(s, i, o);
1682n/a }
1683n/a
1684n/a type_error("'%.200s' object does not support item assignment", s);
1685n/a return -1;
1686n/a}
1687n/a
1688n/aint
1689n/aPySequence_DelItem(PyObject *s, Py_ssize_t i)
1690n/a{
1691n/a PySequenceMethods *m;
1692n/a
1693n/a if (s == NULL) {
1694n/a null_error();
1695n/a return -1;
1696n/a }
1697n/a
1698n/a m = s->ob_type->tp_as_sequence;
1699n/a if (m && m->sq_ass_item) {
1700n/a if (i < 0) {
1701n/a if (m->sq_length) {
1702n/a Py_ssize_t l = (*m->sq_length)(s);
1703n/a if (l < 0)
1704n/a return -1;
1705n/a i += l;
1706n/a }
1707n/a }
1708n/a return m->sq_ass_item(s, i, (PyObject *)NULL);
1709n/a }
1710n/a
1711n/a type_error("'%.200s' object doesn't support item deletion", s);
1712n/a return -1;
1713n/a}
1714n/a
1715n/aint
1716n/aPySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
1717n/a{
1718n/a PyMappingMethods *mp;
1719n/a
1720n/a if (s == NULL) {
1721n/a null_error();
1722n/a return -1;
1723n/a }
1724n/a
1725n/a mp = s->ob_type->tp_as_mapping;
1726n/a if (mp && mp->mp_ass_subscript) {
1727n/a int res;
1728n/a PyObject *slice = _PySlice_FromIndices(i1, i2);
1729n/a if (!slice)
1730n/a return -1;
1731n/a res = mp->mp_ass_subscript(s, slice, o);
1732n/a Py_DECREF(slice);
1733n/a return res;
1734n/a }
1735n/a
1736n/a type_error("'%.200s' object doesn't support slice assignment", s);
1737n/a return -1;
1738n/a}
1739n/a
1740n/aint
1741n/aPySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
1742n/a{
1743n/a PyMappingMethods *mp;
1744n/a
1745n/a if (s == NULL) {
1746n/a null_error();
1747n/a return -1;
1748n/a }
1749n/a
1750n/a mp = s->ob_type->tp_as_mapping;
1751n/a if (mp && mp->mp_ass_subscript) {
1752n/a int res;
1753n/a PyObject *slice = _PySlice_FromIndices(i1, i2);
1754n/a if (!slice)
1755n/a return -1;
1756n/a res = mp->mp_ass_subscript(s, slice, NULL);
1757n/a Py_DECREF(slice);
1758n/a return res;
1759n/a }
1760n/a type_error("'%.200s' object doesn't support slice deletion", s);
1761n/a return -1;
1762n/a}
1763n/a
1764n/aPyObject *
1765n/aPySequence_Tuple(PyObject *v)
1766n/a{
1767n/a PyObject *it; /* iter(v) */
1768n/a Py_ssize_t n; /* guess for result tuple size */
1769n/a PyObject *result = NULL;
1770n/a Py_ssize_t j;
1771n/a
1772n/a if (v == NULL) {
1773n/a return null_error();
1774n/a }
1775n/a
1776n/a /* Special-case the common tuple and list cases, for efficiency. */
1777n/a if (PyTuple_CheckExact(v)) {
1778n/a /* Note that we can't know whether it's safe to return
1779n/a a tuple *subclass* instance as-is, hence the restriction
1780n/a to exact tuples here. In contrast, lists always make
1781n/a a copy, so there's no need for exactness below. */
1782n/a Py_INCREF(v);
1783n/a return v;
1784n/a }
1785n/a if (PyList_CheckExact(v))
1786n/a return PyList_AsTuple(v);
1787n/a
1788n/a /* Get iterator. */
1789n/a it = PyObject_GetIter(v);
1790n/a if (it == NULL)
1791n/a return NULL;
1792n/a
1793n/a /* Guess result size and allocate space. */
1794n/a n = PyObject_LengthHint(v, 10);
1795n/a if (n == -1)
1796n/a goto Fail;
1797n/a result = PyTuple_New(n);
1798n/a if (result == NULL)
1799n/a goto Fail;
1800n/a
1801n/a /* Fill the tuple. */
1802n/a for (j = 0; ; ++j) {
1803n/a PyObject *item = PyIter_Next(it);
1804n/a if (item == NULL) {
1805n/a if (PyErr_Occurred())
1806n/a goto Fail;
1807n/a break;
1808n/a }
1809n/a if (j >= n) {
1810n/a size_t newn = (size_t)n;
1811n/a /* The over-allocation strategy can grow a bit faster
1812n/a than for lists because unlike lists the
1813n/a over-allocation isn't permanent -- we reclaim
1814n/a the excess before the end of this routine.
1815n/a So, grow by ten and then add 25%.
1816n/a */
1817n/a newn += 10u;
1818n/a newn += newn >> 2;
1819n/a if (newn > PY_SSIZE_T_MAX) {
1820n/a /* Check for overflow */
1821n/a PyErr_NoMemory();
1822n/a Py_DECREF(item);
1823n/a goto Fail;
1824n/a }
1825n/a n = (Py_ssize_t)newn;
1826n/a if (_PyTuple_Resize(&result, n) != 0) {
1827n/a Py_DECREF(item);
1828n/a goto Fail;
1829n/a }
1830n/a }
1831n/a PyTuple_SET_ITEM(result, j, item);
1832n/a }
1833n/a
1834n/a /* Cut tuple back if guess was too large. */
1835n/a if (j < n &&
1836n/a _PyTuple_Resize(&result, j) != 0)
1837n/a goto Fail;
1838n/a
1839n/a Py_DECREF(it);
1840n/a return result;
1841n/a
1842n/aFail:
1843n/a Py_XDECREF(result);
1844n/a Py_DECREF(it);
1845n/a return NULL;
1846n/a}
1847n/a
1848n/aPyObject *
1849n/aPySequence_List(PyObject *v)
1850n/a{
1851n/a PyObject *result; /* result list */
1852n/a PyObject *rv; /* return value from PyList_Extend */
1853n/a
1854n/a if (v == NULL) {
1855n/a return null_error();
1856n/a }
1857n/a
1858n/a result = PyList_New(0);
1859n/a if (result == NULL)
1860n/a return NULL;
1861n/a
1862n/a rv = _PyList_Extend((PyListObject *)result, v);
1863n/a if (rv == NULL) {
1864n/a Py_DECREF(result);
1865n/a return NULL;
1866n/a }
1867n/a Py_DECREF(rv);
1868n/a return result;
1869n/a}
1870n/a
1871n/aPyObject *
1872n/aPySequence_Fast(PyObject *v, const char *m)
1873n/a{
1874n/a PyObject *it;
1875n/a
1876n/a if (v == NULL) {
1877n/a return null_error();
1878n/a }
1879n/a
1880n/a if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
1881n/a Py_INCREF(v);
1882n/a return v;
1883n/a }
1884n/a
1885n/a it = PyObject_GetIter(v);
1886n/a if (it == NULL) {
1887n/a if (PyErr_ExceptionMatches(PyExc_TypeError))
1888n/a PyErr_SetString(PyExc_TypeError, m);
1889n/a return NULL;
1890n/a }
1891n/a
1892n/a v = PySequence_List(it);
1893n/a Py_DECREF(it);
1894n/a
1895n/a return v;
1896n/a}
1897n/a
1898n/a/* Iterate over seq. Result depends on the operation:
1899n/a PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
1900n/a PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
1901n/a set ValueError and return -1 if none found; also return -1 on error.
1902n/a Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
1903n/a*/
1904n/aPy_ssize_t
1905n/a_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
1906n/a{
1907n/a Py_ssize_t n;
1908n/a int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
1909n/a PyObject *it; /* iter(seq) */
1910n/a
1911n/a if (seq == NULL || obj == NULL) {
1912n/a null_error();
1913n/a return -1;
1914n/a }
1915n/a
1916n/a it = PyObject_GetIter(seq);
1917n/a if (it == NULL) {
1918n/a type_error("argument of type '%.200s' is not iterable", seq);
1919n/a return -1;
1920n/a }
1921n/a
1922n/a n = wrapped = 0;
1923n/a for (;;) {
1924n/a int cmp;
1925n/a PyObject *item = PyIter_Next(it);
1926n/a if (item == NULL) {
1927n/a if (PyErr_Occurred())
1928n/a goto Fail;
1929n/a break;
1930n/a }
1931n/a
1932n/a cmp = PyObject_RichCompareBool(obj, item, Py_EQ);
1933n/a Py_DECREF(item);
1934n/a if (cmp < 0)
1935n/a goto Fail;
1936n/a if (cmp > 0) {
1937n/a switch (operation) {
1938n/a case PY_ITERSEARCH_COUNT:
1939n/a if (n == PY_SSIZE_T_MAX) {
1940n/a PyErr_SetString(PyExc_OverflowError,
1941n/a "count exceeds C integer size");
1942n/a goto Fail;
1943n/a }
1944n/a ++n;
1945n/a break;
1946n/a
1947n/a case PY_ITERSEARCH_INDEX:
1948n/a if (wrapped) {
1949n/a PyErr_SetString(PyExc_OverflowError,
1950n/a "index exceeds C integer size");
1951n/a goto Fail;
1952n/a }
1953n/a goto Done;
1954n/a
1955n/a case PY_ITERSEARCH_CONTAINS:
1956n/a n = 1;
1957n/a goto Done;
1958n/a
1959n/a default:
1960n/a assert(!"unknown operation");
1961n/a }
1962n/a }
1963n/a
1964n/a if (operation == PY_ITERSEARCH_INDEX) {
1965n/a if (n == PY_SSIZE_T_MAX)
1966n/a wrapped = 1;
1967n/a ++n;
1968n/a }
1969n/a }
1970n/a
1971n/a if (operation != PY_ITERSEARCH_INDEX)
1972n/a goto Done;
1973n/a
1974n/a PyErr_SetString(PyExc_ValueError,
1975n/a "sequence.index(x): x not in sequence");
1976n/a /* fall into failure code */
1977n/aFail:
1978n/a n = -1;
1979n/a /* fall through */
1980n/aDone:
1981n/a Py_DECREF(it);
1982n/a return n;
1983n/a
1984n/a}
1985n/a
1986n/a/* Return # of times o appears in s. */
1987n/aPy_ssize_t
1988n/aPySequence_Count(PyObject *s, PyObject *o)
1989n/a{
1990n/a return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
1991n/a}
1992n/a
1993n/a/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
1994n/a * Use sq_contains if possible, else defer to _PySequence_IterSearch().
1995n/a */
1996n/aint
1997n/aPySequence_Contains(PyObject *seq, PyObject *ob)
1998n/a{
1999n/a Py_ssize_t result;
2000n/a PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
2001n/a if (sqm != NULL && sqm->sq_contains != NULL)
2002n/a return (*sqm->sq_contains)(seq, ob);
2003n/a result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
2004n/a return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
2005n/a}
2006n/a
2007n/a/* Backwards compatibility */
2008n/a#undef PySequence_In
2009n/aint
2010n/aPySequence_In(PyObject *w, PyObject *v)
2011n/a{
2012n/a return PySequence_Contains(w, v);
2013n/a}
2014n/a
2015n/aPy_ssize_t
2016n/aPySequence_Index(PyObject *s, PyObject *o)
2017n/a{
2018n/a return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
2019n/a}
2020n/a
2021n/a/* Operations on mappings */
2022n/a
2023n/aint
2024n/aPyMapping_Check(PyObject *o)
2025n/a{
2026n/a return o && o->ob_type->tp_as_mapping &&
2027n/a o->ob_type->tp_as_mapping->mp_subscript;
2028n/a}
2029n/a
2030n/aPy_ssize_t
2031n/aPyMapping_Size(PyObject *o)
2032n/a{
2033n/a PyMappingMethods *m;
2034n/a
2035n/a if (o == NULL) {
2036n/a null_error();
2037n/a return -1;
2038n/a }
2039n/a
2040n/a m = o->ob_type->tp_as_mapping;
2041n/a if (m && m->mp_length)
2042n/a return m->mp_length(o);
2043n/a
2044n/a type_error("object of type '%.200s' has no len()", o);
2045n/a return -1;
2046n/a}
2047n/a
2048n/a#undef PyMapping_Length
2049n/aPy_ssize_t
2050n/aPyMapping_Length(PyObject *o)
2051n/a{
2052n/a return PyMapping_Size(o);
2053n/a}
2054n/a#define PyMapping_Length PyMapping_Size
2055n/a
2056n/aPyObject *
2057n/aPyMapping_GetItemString(PyObject *o, const char *key)
2058n/a{
2059n/a PyObject *okey, *r;
2060n/a
2061n/a if (key == NULL) {
2062n/a return null_error();
2063n/a }
2064n/a
2065n/a okey = PyUnicode_FromString(key);
2066n/a if (okey == NULL)
2067n/a return NULL;
2068n/a r = PyObject_GetItem(o, okey);
2069n/a Py_DECREF(okey);
2070n/a return r;
2071n/a}
2072n/a
2073n/aint
2074n/aPyMapping_SetItemString(PyObject *o, const char *key, PyObject *value)
2075n/a{
2076n/a PyObject *okey;
2077n/a int r;
2078n/a
2079n/a if (key == NULL) {
2080n/a null_error();
2081n/a return -1;
2082n/a }
2083n/a
2084n/a okey = PyUnicode_FromString(key);
2085n/a if (okey == NULL)
2086n/a return -1;
2087n/a r = PyObject_SetItem(o, okey, value);
2088n/a Py_DECREF(okey);
2089n/a return r;
2090n/a}
2091n/a
2092n/aint
2093n/aPyMapping_HasKeyString(PyObject *o, const char *key)
2094n/a{
2095n/a PyObject *v;
2096n/a
2097n/a v = PyMapping_GetItemString(o, key);
2098n/a if (v) {
2099n/a Py_DECREF(v);
2100n/a return 1;
2101n/a }
2102n/a PyErr_Clear();
2103n/a return 0;
2104n/a}
2105n/a
2106n/aint
2107n/aPyMapping_HasKey(PyObject *o, PyObject *key)
2108n/a{
2109n/a PyObject *v;
2110n/a
2111n/a v = PyObject_GetItem(o, key);
2112n/a if (v) {
2113n/a Py_DECREF(v);
2114n/a return 1;
2115n/a }
2116n/a PyErr_Clear();
2117n/a return 0;
2118n/a}
2119n/a
2120n/aPyObject *
2121n/aPyMapping_Keys(PyObject *o)
2122n/a{
2123n/a PyObject *keys;
2124n/a PyObject *fast;
2125n/a _Py_IDENTIFIER(keys);
2126n/a
2127n/a if (PyDict_CheckExact(o))
2128n/a return PyDict_Keys(o);
2129n/a keys = _PyObject_CallMethodId(o, &PyId_keys, NULL);
2130n/a if (keys == NULL)
2131n/a return NULL;
2132n/a fast = PySequence_Fast(keys, "o.keys() are not iterable");
2133n/a Py_DECREF(keys);
2134n/a return fast;
2135n/a}
2136n/a
2137n/aPyObject *
2138n/aPyMapping_Items(PyObject *o)
2139n/a{
2140n/a PyObject *items;
2141n/a PyObject *fast;
2142n/a _Py_IDENTIFIER(items);
2143n/a
2144n/a if (PyDict_CheckExact(o))
2145n/a return PyDict_Items(o);
2146n/a items = _PyObject_CallMethodId(o, &PyId_items, NULL);
2147n/a if (items == NULL)
2148n/a return NULL;
2149n/a fast = PySequence_Fast(items, "o.items() are not iterable");
2150n/a Py_DECREF(items);
2151n/a return fast;
2152n/a}
2153n/a
2154n/aPyObject *
2155n/aPyMapping_Values(PyObject *o)
2156n/a{
2157n/a PyObject *values;
2158n/a PyObject *fast;
2159n/a _Py_IDENTIFIER(values);
2160n/a
2161n/a if (PyDict_CheckExact(o))
2162n/a return PyDict_Values(o);
2163n/a values = _PyObject_CallMethodId(o, &PyId_values, NULL);
2164n/a if (values == NULL)
2165n/a return NULL;
2166n/a fast = PySequence_Fast(values, "o.values() are not iterable");
2167n/a Py_DECREF(values);
2168n/a return fast;
2169n/a}
2170n/a
2171n/a/* Operations on callable objects */
2172n/a
2173n/a/* XXX PyCallable_Check() is in object.c */
2174n/a
2175n/aPyObject *
2176n/aPyObject_CallObject(PyObject *callable, PyObject *args)
2177n/a{
2178n/a return PyEval_CallObjectWithKeywords(callable, args, NULL);
2179n/a}
2180n/a
2181n/aPyObject*
2182n/a_Py_CheckFunctionResult(PyObject *callable, PyObject *result, const char *where)
2183n/a{
2184n/a int err_occurred = (PyErr_Occurred() != NULL);
2185n/a
2186n/a assert((callable != NULL) ^ (where != NULL));
2187n/a
2188n/a if (result == NULL) {
2189n/a if (!err_occurred) {
2190n/a if (callable)
2191n/a PyErr_Format(PyExc_SystemError,
2192n/a "%R returned NULL without setting an error",
2193n/a callable);
2194n/a else
2195n/a PyErr_Format(PyExc_SystemError,
2196n/a "%s returned NULL without setting an error",
2197n/a where);
2198n/a#ifdef Py_DEBUG
2199n/a /* Ensure that the bug is caught in debug mode */
2200n/a Py_FatalError("a function returned NULL without setting an error");
2201n/a#endif
2202n/a return NULL;
2203n/a }
2204n/a }
2205n/a else {
2206n/a if (err_occurred) {
2207n/a Py_DECREF(result);
2208n/a
2209n/a if (callable) {
2210n/a _PyErr_FormatFromCause(PyExc_SystemError,
2211n/a "%R returned a result with an error set",
2212n/a callable);
2213n/a }
2214n/a else {
2215n/a _PyErr_FormatFromCause(PyExc_SystemError,
2216n/a "%s returned a result with an error set",
2217n/a where);
2218n/a }
2219n/a#ifdef Py_DEBUG
2220n/a /* Ensure that the bug is caught in debug mode */
2221n/a Py_FatalError("a function returned a result with an error set");
2222n/a#endif
2223n/a return NULL;
2224n/a }
2225n/a }
2226n/a return result;
2227n/a}
2228n/a
2229n/aPyObject *
2230n/aPyObject_Call(PyObject *callable, PyObject *args, PyObject *kwargs)
2231n/a{
2232n/a ternaryfunc call;
2233n/a PyObject *result;
2234n/a
2235n/a /* PyObject_Call() must not be called with an exception set,
2236n/a because it can clear it (directly or indirectly) and so the
2237n/a caller loses its exception */
2238n/a assert(!PyErr_Occurred());
2239n/a assert(PyTuple_Check(args));
2240n/a assert(kwargs == NULL || PyDict_Check(kwargs));
2241n/a
2242n/a if (PyFunction_Check(callable)) {
2243n/a return _PyFunction_FastCallDict(callable,
2244n/a &PyTuple_GET_ITEM(args, 0),
2245n/a PyTuple_GET_SIZE(args),
2246n/a kwargs);
2247n/a }
2248n/a else if (PyCFunction_Check(callable)) {
2249n/a return PyCFunction_Call(callable, args, kwargs);
2250n/a }
2251n/a else {
2252n/a call = callable->ob_type->tp_call;
2253n/a if (call == NULL) {
2254n/a PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
2255n/a callable->ob_type->tp_name);
2256n/a return NULL;
2257n/a }
2258n/a
2259n/a if (Py_EnterRecursiveCall(" while calling a Python object"))
2260n/a return NULL;
2261n/a
2262n/a result = (*call)(callable, args, kwargs);
2263n/a
2264n/a Py_LeaveRecursiveCall();
2265n/a
2266n/a return _Py_CheckFunctionResult(callable, result, NULL);
2267n/a }
2268n/a}
2269n/a
2270n/a/* Issue #29234: Inlining _PyStack_AsTuple() into callers increases their
2271n/a stack consumption, Disable inlining to optimize the stack consumption. */
2272n/aPyObject* _Py_NO_INLINE
2273n/a_PyStack_AsTuple(PyObject **stack, Py_ssize_t nargs)
2274n/a{
2275n/a PyObject *args;
2276n/a Py_ssize_t i;
2277n/a
2278n/a args = PyTuple_New(nargs);
2279n/a if (args == NULL) {
2280n/a return NULL;
2281n/a }
2282n/a
2283n/a for (i=0; i < nargs; i++) {
2284n/a PyObject *item = stack[i];
2285n/a Py_INCREF(item);
2286n/a PyTuple_SET_ITEM(args, i, item);
2287n/a }
2288n/a return args;
2289n/a}
2290n/a
2291n/aPyObject*
2292n/a_PyStack_AsTupleSlice(PyObject **stack, Py_ssize_t nargs,
2293n/a Py_ssize_t start, Py_ssize_t end)
2294n/a{
2295n/a PyObject *args;
2296n/a Py_ssize_t i;
2297n/a
2298n/a assert(0 <= start);
2299n/a assert(end <= nargs);
2300n/a assert(start <= end);
2301n/a
2302n/a args = PyTuple_New(end - start);
2303n/a if (args == NULL) {
2304n/a return NULL;
2305n/a }
2306n/a
2307n/a for (i=start; i < end; i++) {
2308n/a PyObject *item = stack[i];
2309n/a Py_INCREF(item);
2310n/a PyTuple_SET_ITEM(args, i - start, item);
2311n/a }
2312n/a return args;
2313n/a}
2314n/a
2315n/aPyObject *
2316n/a_PyObject_FastCallDict(PyObject *callable, PyObject **args, Py_ssize_t nargs,
2317n/a PyObject *kwargs)
2318n/a{
2319n/a /* _PyObject_FastCallDict() must not be called with an exception set,
2320n/a because it can clear it (directly or indirectly) and so the
2321n/a caller loses its exception */
2322n/a assert(!PyErr_Occurred());
2323n/a
2324n/a assert(callable != NULL);
2325n/a assert(nargs >= 0);
2326n/a assert(nargs == 0 || args != NULL);
2327n/a assert(kwargs == NULL || PyDict_Check(kwargs));
2328n/a
2329n/a if (PyFunction_Check(callable)) {
2330n/a return _PyFunction_FastCallDict(callable, args, nargs, kwargs);
2331n/a }
2332n/a else if (PyCFunction_Check(callable)) {
2333n/a return _PyCFunction_FastCallDict(callable, args, nargs, kwargs);
2334n/a }
2335n/a else {
2336n/a PyObject *argstuple, *result;
2337n/a ternaryfunc call;
2338n/a
2339n/a /* Slow-path: build a temporary tuple */
2340n/a call = callable->ob_type->tp_call;
2341n/a if (call == NULL) {
2342n/a PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
2343n/a callable->ob_type->tp_name);
2344n/a return NULL;
2345n/a }
2346n/a
2347n/a argstuple = _PyStack_AsTuple(args, nargs);
2348n/a if (argstuple == NULL) {
2349n/a return NULL;
2350n/a }
2351n/a
2352n/a if (Py_EnterRecursiveCall(" while calling a Python object")) {
2353n/a Py_DECREF(argstuple);
2354n/a return NULL;
2355n/a }
2356n/a
2357n/a result = (*call)(callable, argstuple, kwargs);
2358n/a
2359n/a Py_LeaveRecursiveCall();
2360n/a Py_DECREF(argstuple);
2361n/a
2362n/a result = _Py_CheckFunctionResult(callable, result, NULL);
2363n/a return result;
2364n/a }
2365n/a}
2366n/a
2367n/a/* Positional arguments are obj followed by args:
2368n/a call callable(obj, *args, **kwargs) */
2369n/aPyObject *
2370n/a_PyObject_FastCall_Prepend(PyObject *callable,
2371n/a PyObject *obj, PyObject **args, Py_ssize_t nargs)
2372n/a{
2373n/a PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
2374n/a PyObject **args2;
2375n/a PyObject *result;
2376n/a
2377n/a nargs++;
2378n/a if (nargs <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
2379n/a args2 = small_stack;
2380n/a }
2381n/a else {
2382n/a args2 = PyMem_Malloc(nargs * sizeof(PyObject *));
2383n/a if (args2 == NULL) {
2384n/a PyErr_NoMemory();
2385n/a return NULL;
2386n/a }
2387n/a }
2388n/a
2389n/a /* use borrowed references */
2390n/a args2[0] = obj;
2391n/a memcpy(&args2[1],
2392n/a args,
2393n/a (nargs - 1)* sizeof(PyObject *));
2394n/a
2395n/a result = _PyObject_FastCall(callable, args2, nargs);
2396n/a if (args2 != small_stack) {
2397n/a PyMem_Free(args2);
2398n/a }
2399n/a return result;
2400n/a}
2401n/a
2402n/a
2403n/a/* Call callable(obj, *args, **kwargs). */
2404n/aPyObject *
2405n/a_PyObject_Call_Prepend(PyObject *callable,
2406n/a PyObject *obj, PyObject *args, PyObject *kwargs)
2407n/a{
2408n/a PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
2409n/a PyObject **stack;
2410n/a Py_ssize_t argcount;
2411n/a PyObject *result;
2412n/a
2413n/a assert(PyTuple_Check(args));
2414n/a
2415n/a argcount = PyTuple_GET_SIZE(args);
2416n/a if (argcount + 1 <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
2417n/a stack = small_stack;
2418n/a }
2419n/a else {
2420n/a stack = PyMem_Malloc((argcount + 1) * sizeof(PyObject *));
2421n/a if (stack == NULL) {
2422n/a PyErr_NoMemory();
2423n/a return NULL;
2424n/a }
2425n/a }
2426n/a
2427n/a /* use borrowed references */
2428n/a stack[0] = obj;
2429n/a memcpy(&stack[1],
2430n/a &PyTuple_GET_ITEM(args, 0),
2431n/a argcount * sizeof(PyObject *));
2432n/a
2433n/a result = _PyObject_FastCallDict(callable,
2434n/a stack, argcount + 1,
2435n/a kwargs);
2436n/a if (stack != small_stack) {
2437n/a PyMem_Free(stack);
2438n/a }
2439n/a return result;
2440n/a}
2441n/a
2442n/aPyObject *
2443n/a_PyStack_AsDict(PyObject **values, PyObject *kwnames)
2444n/a{
2445n/a Py_ssize_t nkwargs;
2446n/a PyObject *kwdict;
2447n/a Py_ssize_t i;
2448n/a
2449n/a assert(kwnames != NULL);
2450n/a nkwargs = PyTuple_GET_SIZE(kwnames);
2451n/a kwdict = _PyDict_NewPresized(nkwargs);
2452n/a if (kwdict == NULL) {
2453n/a return NULL;
2454n/a }
2455n/a
2456n/a for (i = 0; i < nkwargs; i++) {
2457n/a PyObject *key = PyTuple_GET_ITEM(kwnames, i);
2458n/a PyObject *value = *values++;
2459n/a /* If key already exists, replace it with the new value */
2460n/a if (PyDict_SetItem(kwdict, key, value)) {
2461n/a Py_DECREF(kwdict);
2462n/a return NULL;
2463n/a }
2464n/a }
2465n/a return kwdict;
2466n/a}
2467n/a
2468n/aint
2469n/a_PyStack_UnpackDict(PyObject **args, Py_ssize_t nargs, PyObject *kwargs,
2470n/a PyObject ***p_stack, PyObject **p_kwnames)
2471n/a{
2472n/a PyObject **stack, **kwstack;
2473n/a Py_ssize_t nkwargs;
2474n/a Py_ssize_t pos, i;
2475n/a PyObject *key, *value;
2476n/a PyObject *kwnames;
2477n/a
2478n/a assert(nargs >= 0);
2479n/a assert(kwargs == NULL || PyDict_CheckExact(kwargs));
2480n/a
2481n/a if (kwargs == NULL || (nkwargs = PyDict_GET_SIZE(kwargs)) == 0) {
2482n/a *p_stack = args;
2483n/a *p_kwnames = NULL;
2484n/a return 0;
2485n/a }
2486n/a
2487n/a if ((size_t)nargs > PY_SSIZE_T_MAX / sizeof(stack[0]) - (size_t)nkwargs) {
2488n/a PyErr_NoMemory();
2489n/a return -1;
2490n/a }
2491n/a
2492n/a stack = PyMem_Malloc((nargs + nkwargs) * sizeof(stack[0]));
2493n/a if (stack == NULL) {
2494n/a PyErr_NoMemory();
2495n/a return -1;
2496n/a }
2497n/a
2498n/a kwnames = PyTuple_New(nkwargs);
2499n/a if (kwnames == NULL) {
2500n/a PyMem_Free(stack);
2501n/a return -1;
2502n/a }
2503n/a
2504n/a /* Copy position arguments (borrowed references) */
2505n/a memcpy(stack, args, nargs * sizeof(stack[0]));
2506n/a
2507n/a kwstack = stack + nargs;
2508n/a pos = i = 0;
2509n/a /* This loop doesn't support lookup function mutating the dictionary
2510n/a to change its size. It's a deliberate choice for speed, this function is
2511n/a called in the performance critical hot code. */
2512n/a while (PyDict_Next(kwargs, &pos, &key, &value)) {
2513n/a Py_INCREF(key);
2514n/a PyTuple_SET_ITEM(kwnames, i, key);
2515n/a /* The stack contains borrowed references */
2516n/a kwstack[i] = value;
2517n/a i++;
2518n/a }
2519n/a
2520n/a *p_stack = stack;
2521n/a *p_kwnames = kwnames;
2522n/a return 0;
2523n/a}
2524n/a
2525n/aPyObject *
2526n/a_PyObject_FastCallKeywords(PyObject *callable, PyObject **stack, Py_ssize_t nargs,
2527n/a PyObject *kwnames)
2528n/a{
2529n/a /* _PyObject_FastCallKeywords() must not be called with an exception set,
2530n/a because it can clear it (directly or indirectly) and so the
2531n/a caller loses its exception */
2532n/a assert(!PyErr_Occurred());
2533n/a
2534n/a assert(nargs >= 0);
2535n/a assert(kwnames == NULL || PyTuple_CheckExact(kwnames));
2536n/a
2537n/a /* kwnames must only contains str strings, no subclass, and all keys must
2538n/a be unique: these checks are implemented in Python/ceval.c and
2539n/a _PyArg_ParseStackAndKeywords(). */
2540n/a
2541n/a if (PyFunction_Check(callable)) {
2542n/a return _PyFunction_FastCallKeywords(callable, stack, nargs, kwnames);
2543n/a }
2544n/a if (PyCFunction_Check(callable)) {
2545n/a return _PyCFunction_FastCallKeywords(callable, stack, nargs, kwnames);
2546n/a }
2547n/a else {
2548n/a /* Slow-path: build a temporary tuple for positional arguments and a
2549n/a temporary dictionary for keyword arguments (if any) */
2550n/a
2551n/a ternaryfunc call;
2552n/a PyObject *argstuple;
2553n/a PyObject *kwdict, *result;
2554n/a Py_ssize_t nkwargs;
2555n/a
2556n/a nkwargs = (kwnames == NULL) ? 0 : PyTuple_GET_SIZE(kwnames);
2557n/a assert((nargs == 0 && nkwargs == 0) || stack != NULL);
2558n/a
2559n/a call = callable->ob_type->tp_call;
2560n/a if (call == NULL) {
2561n/a PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
2562n/a callable->ob_type->tp_name);
2563n/a return NULL;
2564n/a }
2565n/a
2566n/a argstuple = _PyStack_AsTuple(stack, nargs);
2567n/a if (argstuple == NULL) {
2568n/a return NULL;
2569n/a }
2570n/a
2571n/a if (nkwargs > 0) {
2572n/a kwdict = _PyStack_AsDict(stack + nargs, kwnames);
2573n/a if (kwdict == NULL) {
2574n/a Py_DECREF(argstuple);
2575n/a return NULL;
2576n/a }
2577n/a }
2578n/a else {
2579n/a kwdict = NULL;
2580n/a }
2581n/a
2582n/a if (Py_EnterRecursiveCall(" while calling a Python object")) {
2583n/a Py_DECREF(argstuple);
2584n/a Py_XDECREF(kwdict);
2585n/a return NULL;
2586n/a }
2587n/a
2588n/a result = (*call)(callable, argstuple, kwdict);
2589n/a
2590n/a Py_LeaveRecursiveCall();
2591n/a
2592n/a Py_DECREF(argstuple);
2593n/a Py_XDECREF(kwdict);
2594n/a
2595n/a result = _Py_CheckFunctionResult(callable, result, NULL);
2596n/a return result;
2597n/a }
2598n/a}
2599n/a
2600n/astatic PyObject *
2601n/a_PyObject_CallFunctionVa(PyObject *callable, const char *format,
2602n/a va_list va, int is_size_t)
2603n/a{
2604n/a PyObject* small_stack[_PY_FASTCALL_SMALL_STACK];
2605n/a const Py_ssize_t small_stack_len = Py_ARRAY_LENGTH(small_stack);
2606n/a PyObject **stack;
2607n/a Py_ssize_t nargs, i;
2608n/a PyObject *result;
2609n/a
2610n/a if (callable == NULL) {
2611n/a return null_error();
2612n/a }
2613n/a
2614n/a if (!format || !*format) {
2615n/a return _PyObject_CallNoArg(callable);
2616n/a }
2617n/a
2618n/a if (is_size_t) {
2619n/a stack = _Py_VaBuildStack_SizeT(small_stack, small_stack_len,
2620n/a format, va, &nargs);
2621n/a }
2622n/a else {
2623n/a stack = _Py_VaBuildStack(small_stack, small_stack_len,
2624n/a format, va, &nargs);
2625n/a }
2626n/a if (stack == NULL) {
2627n/a return NULL;
2628n/a }
2629n/a
2630n/a if (nargs == 1 && PyTuple_Check(stack[0])) {
2631n/a /* Special cases for backward compatibility:
2632n/a - PyObject_CallFunction(func, "O", tuple) calls func(*tuple)
2633n/a - PyObject_CallFunction(func, "(OOO)", arg1, arg2, arg3) calls
2634n/a func(*(arg1, arg2, arg3)): func(arg1, arg2, arg3) */
2635n/a PyObject *args = stack[0];
2636n/a result = _PyObject_FastCall(callable,
2637n/a &PyTuple_GET_ITEM(args, 0),
2638n/a PyTuple_GET_SIZE(args));
2639n/a }
2640n/a else {
2641n/a result = _PyObject_FastCall(callable, stack, nargs);
2642n/a }
2643n/a
2644n/a for (i = 0; i < nargs; ++i) {
2645n/a Py_DECREF(stack[i]);
2646n/a }
2647n/a if (stack != small_stack) {
2648n/a PyMem_Free(stack);
2649n/a }
2650n/a return result;
2651n/a}
2652n/a
2653n/aPyObject *
2654n/aPyObject_CallFunction(PyObject *callable, const char *format, ...)
2655n/a{
2656n/a va_list va;
2657n/a PyObject *result;
2658n/a
2659n/a va_start(va, format);
2660n/a result = _PyObject_CallFunctionVa(callable, format, va, 0);
2661n/a va_end(va);
2662n/a
2663n/a return result;
2664n/a}
2665n/a
2666n/aPyObject *
2667n/a_PyObject_CallFunction_SizeT(PyObject *callable, const char *format, ...)
2668n/a{
2669n/a va_list va;
2670n/a PyObject *result;
2671n/a
2672n/a va_start(va, format);
2673n/a result = _PyObject_CallFunctionVa(callable, format, va, 1);
2674n/a va_end(va);
2675n/a
2676n/a return result;
2677n/a}
2678n/a
2679n/astatic PyObject*
2680n/acallmethod(PyObject* callable, const char *format, va_list va, int is_size_t)
2681n/a{
2682n/a assert(callable != NULL);
2683n/a
2684n/a if (!PyCallable_Check(callable)) {
2685n/a type_error("attribute of type '%.200s' is not callable", callable);
2686n/a return NULL;
2687n/a }
2688n/a
2689n/a return _PyObject_CallFunctionVa(callable, format, va, is_size_t);
2690n/a}
2691n/a
2692n/aPyObject *
2693n/aPyObject_CallMethod(PyObject *obj, const char *name, const char *format, ...)
2694n/a{
2695n/a va_list va;
2696n/a PyObject *callable, *retval;
2697n/a
2698n/a if (obj == NULL || name == NULL) {
2699n/a return null_error();
2700n/a }
2701n/a
2702n/a callable = PyObject_GetAttrString(obj, name);
2703n/a if (callable == NULL)
2704n/a return NULL;
2705n/a
2706n/a va_start(va, format);
2707n/a retval = callmethod(callable, format, va, 0);
2708n/a va_end(va);
2709n/a
2710n/a Py_DECREF(callable);
2711n/a return retval;
2712n/a}
2713n/a
2714n/aPyObject *
2715n/a_PyObject_CallMethodId(PyObject *obj, _Py_Identifier *name,
2716n/a const char *format, ...)
2717n/a{
2718n/a va_list va;
2719n/a PyObject *callable, *retval;
2720n/a
2721n/a if (obj == NULL || name == NULL) {
2722n/a return null_error();
2723n/a }
2724n/a
2725n/a callable = _PyObject_GetAttrId(obj, name);
2726n/a if (callable == NULL)
2727n/a return NULL;
2728n/a
2729n/a va_start(va, format);
2730n/a retval = callmethod(callable, format, va, 0);
2731n/a va_end(va);
2732n/a
2733n/a Py_DECREF(callable);
2734n/a return retval;
2735n/a}
2736n/a
2737n/aPyObject *
2738n/a_PyObject_CallMethod_SizeT(PyObject *obj, const char *name,
2739n/a const char *format, ...)
2740n/a{
2741n/a va_list va;
2742n/a PyObject *callable, *retval;
2743n/a
2744n/a if (obj == NULL || name == NULL) {
2745n/a return null_error();
2746n/a }
2747n/a
2748n/a callable = PyObject_GetAttrString(obj, name);
2749n/a if (callable == NULL)
2750n/a return NULL;
2751n/a
2752n/a va_start(va, format);
2753n/a retval = callmethod(callable, format, va, 1);
2754n/a va_end(va);
2755n/a
2756n/a Py_DECREF(callable);
2757n/a return retval;
2758n/a}
2759n/a
2760n/aPyObject *
2761n/a_PyObject_CallMethodId_SizeT(PyObject *obj, _Py_Identifier *name,
2762n/a const char *format, ...)
2763n/a{
2764n/a va_list va;
2765n/a PyObject *callable, *retval;
2766n/a
2767n/a if (obj == NULL || name == NULL) {
2768n/a return null_error();
2769n/a }
2770n/a
2771n/a callable = _PyObject_GetAttrId(obj, name);
2772n/a if (callable == NULL) {
2773n/a return NULL;
2774n/a }
2775n/a
2776n/a va_start(va, format);
2777n/a retval = callmethod(callable, format, va, 1);
2778n/a va_end(va);
2779n/a
2780n/a Py_DECREF(callable);
2781n/a return retval;
2782n/a}
2783n/a
2784n/astatic PyObject *
2785n/aobject_vacall(PyObject *callable, va_list vargs)
2786n/a{
2787n/a PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
2788n/a PyObject **stack;
2789n/a Py_ssize_t nargs;
2790n/a PyObject *result;
2791n/a Py_ssize_t i;
2792n/a va_list countva;
2793n/a
2794n/a if (callable == NULL) {
2795n/a return null_error();
2796n/a }
2797n/a
2798n/a /* Count the number of arguments */
2799n/a va_copy(countva, vargs);
2800n/a nargs = 0;
2801n/a while (1) {
2802n/a PyObject *arg = va_arg(countva, PyObject *);
2803n/a if (arg == NULL) {
2804n/a break;
2805n/a }
2806n/a nargs++;
2807n/a }
2808n/a va_end(countva);
2809n/a
2810n/a /* Copy arguments */
2811n/a if (nargs <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
2812n/a stack = small_stack;
2813n/a }
2814n/a else {
2815n/a stack = PyMem_Malloc(nargs * sizeof(stack[0]));
2816n/a if (stack == NULL) {
2817n/a PyErr_NoMemory();
2818n/a return NULL;
2819n/a }
2820n/a }
2821n/a
2822n/a for (i = 0; i < nargs; ++i) {
2823n/a stack[i] = va_arg(vargs, PyObject *);
2824n/a }
2825n/a
2826n/a /* Call the function */
2827n/a result = _PyObject_FastCall(callable, stack, nargs);
2828n/a
2829n/a if (stack != small_stack) {
2830n/a PyMem_Free(stack);
2831n/a }
2832n/a return result;
2833n/a}
2834n/a
2835n/aPyObject *
2836n/aPyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...)
2837n/a{
2838n/a va_list vargs;
2839n/a PyObject *result;
2840n/a
2841n/a if (callable == NULL || name == NULL) {
2842n/a return null_error();
2843n/a }
2844n/a
2845n/a callable = PyObject_GetAttr(callable, name);
2846n/a if (callable == NULL) {
2847n/a return NULL;
2848n/a }
2849n/a
2850n/a va_start(vargs, name);
2851n/a result = object_vacall(callable, vargs);
2852n/a va_end(vargs);
2853n/a
2854n/a Py_DECREF(callable);
2855n/a return result;
2856n/a}
2857n/a
2858n/aPyObject *
2859n/a_PyObject_CallMethodIdObjArgs(PyObject *obj,
2860n/a struct _Py_Identifier *name, ...)
2861n/a{
2862n/a va_list vargs;
2863n/a PyObject *callable, *result;
2864n/a
2865n/a if (obj == NULL || name == NULL) {
2866n/a return null_error();
2867n/a }
2868n/a
2869n/a callable = _PyObject_GetAttrId(obj, name);
2870n/a if (callable == NULL) {
2871n/a return NULL;
2872n/a }
2873n/a
2874n/a va_start(vargs, name);
2875n/a result = object_vacall(callable, vargs);
2876n/a va_end(vargs);
2877n/a
2878n/a Py_DECREF(callable);
2879n/a return result;
2880n/a}
2881n/a
2882n/aPyObject *
2883n/aPyObject_CallFunctionObjArgs(PyObject *callable, ...)
2884n/a{
2885n/a va_list vargs;
2886n/a PyObject *result;
2887n/a
2888n/a va_start(vargs, callable);
2889n/a result = object_vacall(callable, vargs);
2890n/a va_end(vargs);
2891n/a
2892n/a return result;
2893n/a}
2894n/a
2895n/a
2896n/a/* isinstance(), issubclass() */
2897n/a
2898n/a/* abstract_get_bases() has logically 4 return states:
2899n/a *
2900n/a * 1. getattr(cls, '__bases__') could raise an AttributeError
2901n/a * 2. getattr(cls, '__bases__') could raise some other exception
2902n/a * 3. getattr(cls, '__bases__') could return a tuple
2903n/a * 4. getattr(cls, '__bases__') could return something other than a tuple
2904n/a *
2905n/a * Only state #3 is a non-error state and only it returns a non-NULL object
2906n/a * (it returns the retrieved tuple).
2907n/a *
2908n/a * Any raised AttributeErrors are masked by clearing the exception and
2909n/a * returning NULL. If an object other than a tuple comes out of __bases__,
2910n/a * then again, the return value is NULL. So yes, these two situations
2911n/a * produce exactly the same results: NULL is returned and no error is set.
2912n/a *
2913n/a * If some exception other than AttributeError is raised, then NULL is also
2914n/a * returned, but the exception is not cleared. That's because we want the
2915n/a * exception to be propagated along.
2916n/a *
2917n/a * Callers are expected to test for PyErr_Occurred() when the return value
2918n/a * is NULL to decide whether a valid exception should be propagated or not.
2919n/a * When there's no exception to propagate, it's customary for the caller to
2920n/a * set a TypeError.
2921n/a */
2922n/astatic PyObject *
2923n/aabstract_get_bases(PyObject *cls)
2924n/a{
2925n/a _Py_IDENTIFIER(__bases__);
2926n/a PyObject *bases;
2927n/a
2928n/a Py_ALLOW_RECURSION
2929n/a bases = _PyObject_GetAttrId(cls, &PyId___bases__);
2930n/a Py_END_ALLOW_RECURSION
2931n/a if (bases == NULL) {
2932n/a if (PyErr_ExceptionMatches(PyExc_AttributeError))
2933n/a PyErr_Clear();
2934n/a return NULL;
2935n/a }
2936n/a if (!PyTuple_Check(bases)) {
2937n/a Py_DECREF(bases);
2938n/a return NULL;
2939n/a }
2940n/a return bases;
2941n/a}
2942n/a
2943n/a
2944n/astatic int
2945n/aabstract_issubclass(PyObject *derived, PyObject *cls)
2946n/a{
2947n/a PyObject *bases = NULL;
2948n/a Py_ssize_t i, n;
2949n/a int r = 0;
2950n/a
2951n/a while (1) {
2952n/a if (derived == cls)
2953n/a return 1;
2954n/a bases = abstract_get_bases(derived);
2955n/a if (bases == NULL) {
2956n/a if (PyErr_Occurred())
2957n/a return -1;
2958n/a return 0;
2959n/a }
2960n/a n = PyTuple_GET_SIZE(bases);
2961n/a if (n == 0) {
2962n/a Py_DECREF(bases);
2963n/a return 0;
2964n/a }
2965n/a /* Avoid recursivity in the single inheritance case */
2966n/a if (n == 1) {
2967n/a derived = PyTuple_GET_ITEM(bases, 0);
2968n/a Py_DECREF(bases);
2969n/a continue;
2970n/a }
2971n/a for (i = 0; i < n; i++) {
2972n/a r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2973n/a if (r != 0)
2974n/a break;
2975n/a }
2976n/a Py_DECREF(bases);
2977n/a return r;
2978n/a }
2979n/a}
2980n/a
2981n/astatic int
2982n/acheck_class(PyObject *cls, const char *error)
2983n/a{
2984n/a PyObject *bases = abstract_get_bases(cls);
2985n/a if (bases == NULL) {
2986n/a /* Do not mask errors. */
2987n/a if (!PyErr_Occurred())
2988n/a PyErr_SetString(PyExc_TypeError, error);
2989n/a return 0;
2990n/a }
2991n/a Py_DECREF(bases);
2992n/a return -1;
2993n/a}
2994n/a
2995n/astatic int
2996n/arecursive_isinstance(PyObject *inst, PyObject *cls)
2997n/a{
2998n/a PyObject *icls;
2999n/a int retval = 0;
3000n/a _Py_IDENTIFIER(__class__);
3001n/a
3002n/a if (PyType_Check(cls)) {
3003n/a retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
3004n/a if (retval == 0) {
3005n/a PyObject *c = _PyObject_GetAttrId(inst, &PyId___class__);
3006n/a if (c == NULL) {
3007n/a if (PyErr_ExceptionMatches(PyExc_AttributeError))
3008n/a PyErr_Clear();
3009n/a else
3010n/a retval = -1;
3011n/a }
3012n/a else {
3013n/a if (c != (PyObject *)(inst->ob_type) &&
3014n/a PyType_Check(c))
3015n/a retval = PyType_IsSubtype(
3016n/a (PyTypeObject *)c,
3017n/a (PyTypeObject *)cls);
3018n/a Py_DECREF(c);
3019n/a }
3020n/a }
3021n/a }
3022n/a else {
3023n/a if (!check_class(cls,
3024n/a "isinstance() arg 2 must be a type or tuple of types"))
3025n/a return -1;
3026n/a icls = _PyObject_GetAttrId(inst, &PyId___class__);
3027n/a if (icls == NULL) {
3028n/a if (PyErr_ExceptionMatches(PyExc_AttributeError))
3029n/a PyErr_Clear();
3030n/a else
3031n/a retval = -1;
3032n/a }
3033n/a else {
3034n/a retval = abstract_issubclass(icls, cls);
3035n/a Py_DECREF(icls);
3036n/a }
3037n/a }
3038n/a
3039n/a return retval;
3040n/a}
3041n/a
3042n/aint
3043n/aPyObject_IsInstance(PyObject *inst, PyObject *cls)
3044n/a{
3045n/a _Py_IDENTIFIER(__instancecheck__);
3046n/a PyObject *checker;
3047n/a
3048n/a /* Quick test for an exact match */
3049n/a if (Py_TYPE(inst) == (PyTypeObject *)cls)
3050n/a return 1;
3051n/a
3052n/a /* We know what type's __instancecheck__ does. */
3053n/a if (PyType_CheckExact(cls)) {
3054n/a return recursive_isinstance(inst, cls);
3055n/a }
3056n/a
3057n/a if (PyTuple_Check(cls)) {
3058n/a Py_ssize_t i;
3059n/a Py_ssize_t n;
3060n/a int r = 0;
3061n/a
3062n/a if (Py_EnterRecursiveCall(" in __instancecheck__"))
3063n/a return -1;
3064n/a n = PyTuple_GET_SIZE(cls);
3065n/a for (i = 0; i < n; ++i) {
3066n/a PyObject *item = PyTuple_GET_ITEM(cls, i);
3067n/a r = PyObject_IsInstance(inst, item);
3068n/a if (r != 0)
3069n/a /* either found it, or got an error */
3070n/a break;
3071n/a }
3072n/a Py_LeaveRecursiveCall();
3073n/a return r;
3074n/a }
3075n/a
3076n/a checker = _PyObject_LookupSpecial(cls, &PyId___instancecheck__);
3077n/a if (checker != NULL) {
3078n/a PyObject *res;
3079n/a int ok = -1;
3080n/a if (Py_EnterRecursiveCall(" in __instancecheck__")) {
3081n/a Py_DECREF(checker);
3082n/a return ok;
3083n/a }
3084n/a res = PyObject_CallFunctionObjArgs(checker, inst, NULL);
3085n/a Py_LeaveRecursiveCall();
3086n/a Py_DECREF(checker);
3087n/a if (res != NULL) {
3088n/a ok = PyObject_IsTrue(res);
3089n/a Py_DECREF(res);
3090n/a }
3091n/a return ok;
3092n/a }
3093n/a else if (PyErr_Occurred())
3094n/a return -1;
3095n/a /* Probably never reached anymore. */
3096n/a return recursive_isinstance(inst, cls);
3097n/a}
3098n/a
3099n/astatic int
3100n/arecursive_issubclass(PyObject *derived, PyObject *cls)
3101n/a{
3102n/a if (PyType_Check(cls) && PyType_Check(derived)) {
3103n/a /* Fast path (non-recursive) */
3104n/a return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls);
3105n/a }
3106n/a if (!check_class(derived,
3107n/a "issubclass() arg 1 must be a class"))
3108n/a return -1;
3109n/a if (!check_class(cls,
3110n/a "issubclass() arg 2 must be a class"
3111n/a " or tuple of classes"))
3112n/a return -1;
3113n/a
3114n/a return abstract_issubclass(derived, cls);
3115n/a}
3116n/a
3117n/aint
3118n/aPyObject_IsSubclass(PyObject *derived, PyObject *cls)
3119n/a{
3120n/a _Py_IDENTIFIER(__subclasscheck__);
3121n/a PyObject *checker;
3122n/a
3123n/a /* We know what type's __subclasscheck__ does. */
3124n/a if (PyType_CheckExact(cls)) {
3125n/a /* Quick test for an exact match */
3126n/a if (derived == cls)
3127n/a return 1;
3128n/a return recursive_issubclass(derived, cls);
3129n/a }
3130n/a
3131n/a if (PyTuple_Check(cls)) {
3132n/a Py_ssize_t i;
3133n/a Py_ssize_t n;
3134n/a int r = 0;
3135n/a
3136n/a if (Py_EnterRecursiveCall(" in __subclasscheck__"))
3137n/a return -1;
3138n/a n = PyTuple_GET_SIZE(cls);
3139n/a for (i = 0; i < n; ++i) {
3140n/a PyObject *item = PyTuple_GET_ITEM(cls, i);
3141n/a r = PyObject_IsSubclass(derived, item);
3142n/a if (r != 0)
3143n/a /* either found it, or got an error */
3144n/a break;
3145n/a }
3146n/a Py_LeaveRecursiveCall();
3147n/a return r;
3148n/a }
3149n/a
3150n/a checker = _PyObject_LookupSpecial(cls, &PyId___subclasscheck__);
3151n/a if (checker != NULL) {
3152n/a PyObject *res;
3153n/a int ok = -1;
3154n/a if (Py_EnterRecursiveCall(" in __subclasscheck__")) {
3155n/a Py_DECREF(checker);
3156n/a return ok;
3157n/a }
3158n/a res = PyObject_CallFunctionObjArgs(checker, derived, NULL);
3159n/a Py_LeaveRecursiveCall();
3160n/a Py_DECREF(checker);
3161n/a if (res != NULL) {
3162n/a ok = PyObject_IsTrue(res);
3163n/a Py_DECREF(res);
3164n/a }
3165n/a return ok;
3166n/a }
3167n/a else if (PyErr_Occurred())
3168n/a return -1;
3169n/a /* Probably never reached anymore. */
3170n/a return recursive_issubclass(derived, cls);
3171n/a}
3172n/a
3173n/aint
3174n/a_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
3175n/a{
3176n/a return recursive_isinstance(inst, cls);
3177n/a}
3178n/a
3179n/aint
3180n/a_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
3181n/a{
3182n/a return recursive_issubclass(derived, cls);
3183n/a}
3184n/a
3185n/a
3186n/aPyObject *
3187n/aPyObject_GetIter(PyObject *o)
3188n/a{
3189n/a PyTypeObject *t = o->ob_type;
3190n/a getiterfunc f;
3191n/a
3192n/a f = t->tp_iter;
3193n/a if (f == NULL) {
3194n/a if (PySequence_Check(o))
3195n/a return PySeqIter_New(o);
3196n/a return type_error("'%.200s' object is not iterable", o);
3197n/a }
3198n/a else {
3199n/a PyObject *res = (*f)(o);
3200n/a if (res != NULL && !PyIter_Check(res)) {
3201n/a PyErr_Format(PyExc_TypeError,
3202n/a "iter() returned non-iterator "
3203n/a "of type '%.100s'",
3204n/a res->ob_type->tp_name);
3205n/a Py_DECREF(res);
3206n/a res = NULL;
3207n/a }
3208n/a return res;
3209n/a }
3210n/a}
3211n/a
3212n/a/* Return next item.
3213n/a * If an error occurs, return NULL. PyErr_Occurred() will be true.
3214n/a * If the iteration terminates normally, return NULL and clear the
3215n/a * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
3216n/a * will be false.
3217n/a * Else return the next object. PyErr_Occurred() will be false.
3218n/a */
3219n/aPyObject *
3220n/aPyIter_Next(PyObject *iter)
3221n/a{
3222n/a PyObject *result;
3223n/a result = (*iter->ob_type->tp_iternext)(iter);
3224n/a if (result == NULL &&
3225n/a PyErr_Occurred() &&
3226n/a PyErr_ExceptionMatches(PyExc_StopIteration))
3227n/a PyErr_Clear();
3228n/a return result;
3229n/a}
3230n/a
3231n/a
3232n/a/*
3233n/a * Flatten a sequence of bytes() objects into a C array of
3234n/a * NULL terminated string pointers with a NULL char* terminating the array.
3235n/a * (ie: an argv or env list)
3236n/a *
3237n/a * Memory allocated for the returned list is allocated using PyMem_Malloc()
3238n/a * and MUST be freed by _Py_FreeCharPArray().
3239n/a */
3240n/achar *const *
3241n/a_PySequence_BytesToCharpArray(PyObject* self)
3242n/a{
3243n/a char **array;
3244n/a Py_ssize_t i, argc;
3245n/a PyObject *item = NULL;
3246n/a Py_ssize_t size;
3247n/a
3248n/a argc = PySequence_Size(self);
3249n/a if (argc == -1)
3250n/a return NULL;
3251n/a
3252n/a assert(argc >= 0);
3253n/a
3254n/a if ((size_t)argc > (PY_SSIZE_T_MAX-sizeof(char *)) / sizeof(char *)) {
3255n/a PyErr_NoMemory();
3256n/a return NULL;
3257n/a }
3258n/a
3259n/a array = PyMem_Malloc((argc + 1) * sizeof(char *));
3260n/a if (array == NULL) {
3261n/a PyErr_NoMemory();
3262n/a return NULL;
3263n/a }
3264n/a for (i = 0; i < argc; ++i) {
3265n/a char *data;
3266n/a item = PySequence_GetItem(self, i);
3267n/a if (item == NULL) {
3268n/a /* NULL terminate before freeing. */
3269n/a array[i] = NULL;
3270n/a goto fail;
3271n/a }
3272n/a data = PyBytes_AsString(item);
3273n/a if (data == NULL) {
3274n/a /* NULL terminate before freeing. */
3275n/a array[i] = NULL;
3276n/a goto fail;
3277n/a }
3278n/a size = PyBytes_GET_SIZE(item) + 1;
3279n/a array[i] = PyMem_Malloc(size);
3280n/a if (!array[i]) {
3281n/a PyErr_NoMemory();
3282n/a goto fail;
3283n/a }
3284n/a memcpy(array[i], data, size);
3285n/a Py_DECREF(item);
3286n/a }
3287n/a array[argc] = NULL;
3288n/a
3289n/a return array;
3290n/a
3291n/afail:
3292n/a Py_XDECREF(item);
3293n/a _Py_FreeCharPArray(array);
3294n/a return NULL;
3295n/a}
3296n/a
3297n/a
3298n/a/* Free's a NULL terminated char** array of C strings. */
3299n/avoid
3300n/a_Py_FreeCharPArray(char *const array[])
3301n/a{
3302n/a Py_ssize_t i;
3303n/a for (i = 0; array[i] != NULL; ++i) {
3304n/a PyMem_Free(array[i]);
3305n/a }
3306n/a PyMem_Free((void*)array);
3307n/a}