LCOV - code coverage report
Current view: top level - Objects - abstract.c (source / functions) Hit Total Coverage
Test: CPython lcov report Lines: 531 1582 33.6 %
Date: 2017-04-19 Functions: 65 126 51.6 %

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

Generated by: LCOV version 1.10