Ignore:
Timestamp:
Mar 19, 2014, 11:11:30 AM (11 years ago)
Author:
dmik
Message:

python: Update vendor to 2.7.6.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • python/vendor/current/Objects/abstract.c

    r2 r388  
    77
    88#define NEW_STYLE_NUMBER(o) PyType_HasFeature((o)->ob_type, \
    9                                 Py_TPFLAGS_CHECKTYPES)
     9                Py_TPFLAGS_CHECKTYPES)
    1010
    1111
     
    1515type_error(const char *msg, PyObject *obj)
    1616{
    17         PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name);
    18         return NULL;
     17    PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name);
     18    return NULL;
    1919}
    2020
     
    2222null_error(void)
    2323{
    24         if (!PyErr_Occurred())
    25                 PyErr_SetString(PyExc_SystemError,
    26                                 "null argument to internal routine");
    27         return NULL;
     24    if (!PyErr_Occurred())
     25        PyErr_SetString(PyExc_SystemError,
     26                        "null argument to internal routine");
     27    return NULL;
    2828}
    2929
     
    3333PyObject_Cmp(PyObject *o1, PyObject *o2, int *result)
    3434{
    35         int r;
    36 
    37         if (o1 == NULL || o2 == NULL) {
    38                 null_error();
    39                 return -1;
    40         }
    41         r = PyObject_Compare(o1, o2);
    42         if (PyErr_Occurred())
    43                 return -1;
    44         *result = r;
    45         return 0;
     35    int r;
     36
     37    if (o1 == NULL || o2 == NULL) {
     38        null_error();
     39        return -1;
     40    }
     41    r = PyObject_Compare(o1, o2);
     42    if (PyErr_Occurred())
     43        return -1;
     44    *result = r;
     45    return 0;
    4646}
    4747
     
    4949PyObject_Type(PyObject *o)
    5050{
    51         PyObject *v;
    52 
    53         if (o == NULL)
    54                 return null_error();
    55         v = (PyObject *)o->ob_type;
    56         Py_INCREF(v);
    57         return v;
     51    PyObject *v;
     52
     53    if (o == NULL)
     54        return null_error();
     55    v = (PyObject *)o->ob_type;
     56    Py_INCREF(v);
     57    return v;
    5858}
    5959
     
    6161PyObject_Size(PyObject *o)
    6262{
    63         PySequenceMethods *m;
    64 
    65         if (o == NULL) {
    66                 null_error();
    67                 return -1;
    68         }
    69 
    70         m = o->ob_type->tp_as_sequence;
    71         if (m && m->sq_length)
    72                 return m->sq_length(o);
    73 
    74         return PyMapping_Size(o);
     63    PySequenceMethods *m;
     64
     65    if (o == NULL) {
     66        null_error();
     67        return -1;
     68    }
     69
     70    m = o->ob_type->tp_as_sequence;
     71    if (m && m->sq_length)
     72        return m->sq_length(o);
     73
     74    return PyMapping_Size(o);
    7575}
    7676
     
    7979PyObject_Length(PyObject *o)
    8080{
    81         return PyObject_Size(o);
     81    return PyObject_Size(o);
    8282}
    8383#define PyObject_Length PyObject_Size
     
    9393_PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
    9494{
    95         static PyObject *hintstrobj = NULL;
    96         PyObject *ro;
    97         Py_ssize_t rv;
    98 
    99         /* try o.__len__() */
    100         rv = PyObject_Size(o);
    101         if (rv >= 0)
    102                 return rv;
    103         if (PyErr_Occurred()) {
    104                 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
    105                         !PyErr_ExceptionMatches(PyExc_AttributeError))
    106                                 return -1;
    107                 PyErr_Clear();
    108         }
    109 
    110         /* cache a hashed version of the attribute string */
    111         if (hintstrobj == NULL) {
    112                 hintstrobj = PyString_InternFromString("__length_hint__");
    113                 if (hintstrobj == NULL)
    114                         return -1;
    115         }
    116 
    117         /* try o.__length_hint__() */
    118         ro = PyObject_CallMethodObjArgs(o, hintstrobj, NULL);
    119         if (ro == NULL) {
    120                 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
    121                         !PyErr_ExceptionMatches(PyExc_AttributeError))
    122                                 return -1;
    123                 PyErr_Clear();
    124                 return defaultvalue;
    125         }
    126         rv = PyLong_Check(ro) ? PyLong_AsSsize_t(ro) : defaultvalue;
    127         Py_DECREF(ro);
    128         return rv;
     95    static PyObject *hintstrobj = NULL;
     96    PyObject *ro, *hintmeth;
     97    Py_ssize_t rv;
     98
     99    /* try o.__len__() */
     100    rv = PyObject_Size(o);
     101    if (rv >= 0)
     102        return rv;
     103    if (PyErr_Occurred()) {
     104        if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
     105            !PyErr_ExceptionMatches(PyExc_AttributeError))
     106                return -1;
     107        PyErr_Clear();
     108    }
     109
     110    if (PyInstance_Check(o))
     111        return defaultvalue;
     112    /* try o.__length_hint__() */
     113    hintmeth = _PyObject_LookupSpecial(o, "__length_hint__", &hintstrobj);
     114    if (hintmeth == NULL) {
     115        if (PyErr_Occurred())
     116            return -1;
     117        else
     118            return defaultvalue;
     119    }
     120    ro = PyObject_CallFunctionObjArgs(hintmeth, NULL);
     121    Py_DECREF(hintmeth);
     122    if (ro == NULL) {
     123        if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
     124            !PyErr_ExceptionMatches(PyExc_AttributeError))
     125            return -1;
     126        PyErr_Clear();
     127        return defaultvalue;
     128    }
     129    rv = PyNumber_Check(ro) ? PyInt_AsSsize_t(ro) : defaultvalue;
     130    Py_DECREF(ro);
     131    return rv;
    129132}
    130133
     
    132135PyObject_GetItem(PyObject *o, PyObject *key)
    133136{
    134         PyMappingMethods *m;
    135 
    136         if (o == NULL || key == NULL)
    137                 return null_error();
    138 
    139         m = o->ob_type->tp_as_mapping;
    140         if (m && m->mp_subscript)
    141                 return m->mp_subscript(o, key);
    142 
    143         if (o->ob_type->tp_as_sequence) {
    144                 if (PyIndex_Check(key)) {
    145                         Py_ssize_t key_value;
    146                         key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
    147                         if (key_value == -1 && PyErr_Occurred())
    148                                 return NULL;
    149                         return PySequence_GetItem(o, key_value);
    150                 }
    151                 else if (o->ob_type->tp_as_sequence->sq_item)
    152                         return type_error("sequence index must "
    153                                           "be integer, not '%.200s'", key);
    154         }
    155 
    156         return type_error("'%.200s' object is unsubscriptable", o);
     137    PyMappingMethods *m;
     138
     139    if (o == NULL || key == NULL)
     140        return null_error();
     141
     142    m = o->ob_type->tp_as_mapping;
     143    if (m && m->mp_subscript)
     144        return m->mp_subscript(o, key);
     145
     146    if (o->ob_type->tp_as_sequence) {
     147        if (PyIndex_Check(key)) {
     148            Py_ssize_t key_value;
     149            key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
     150            if (key_value == -1 && PyErr_Occurred())
     151                return NULL;
     152            return PySequence_GetItem(o, key_value);
     153        }
     154        else if (o->ob_type->tp_as_sequence->sq_item)
     155            return type_error("sequence index must "
     156                              "be integer, not '%.200s'", key);
     157    }
     158
     159    return type_error("'%.200s' object has no attribute '__getitem__'", o);
    157160}
    158161
     
    160163PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
    161164{
    162         PyMappingMethods *m;
    163 
    164         if (o == NULL || key == NULL || value == NULL) {
    165                 null_error();
    166                 return -1;
    167         }
    168         m = o->ob_type->tp_as_mapping;
    169         if (m && m->mp_ass_subscript)
    170                 return m->mp_ass_subscript(o, key, value);
    171 
    172         if (o->ob_type->tp_as_sequence) {
    173                 if (PyIndex_Check(key)) {
    174                         Py_ssize_t key_value;
    175                         key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
    176                         if (key_value == -1 && PyErr_Occurred())
    177                                 return -1;
    178                         return PySequence_SetItem(o, key_value, value);
    179                 }
    180                 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
    181                         type_error("sequence index must be "
    182                                    "integer, not '%.200s'", key);
    183                         return -1;
    184                 }
    185         }
    186 
    187         type_error("'%.200s' object does not support item assignment", o);
    188         return -1;
     165    PyMappingMethods *m;
     166
     167    if (o == NULL || key == NULL || value == NULL) {
     168        null_error();
     169        return -1;
     170    }
     171    m = o->ob_type->tp_as_mapping;
     172    if (m && m->mp_ass_subscript)
     173        return m->mp_ass_subscript(o, key, value);
     174
     175    if (o->ob_type->tp_as_sequence) {
     176        if (PyIndex_Check(key)) {
     177            Py_ssize_t key_value;
     178            key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
     179            if (key_value == -1 && PyErr_Occurred())
     180                return -1;
     181            return PySequence_SetItem(o, key_value, value);
     182        }
     183        else if (o->ob_type->tp_as_sequence->sq_ass_item) {
     184            type_error("sequence index must be "
     185                       "integer, not '%.200s'", key);
     186            return -1;
     187        }
     188    }
     189
     190    type_error("'%.200s' object does not support item assignment", o);
     191    return -1;
    189192}
    190193
     
    192195PyObject_DelItem(PyObject *o, PyObject *key)
    193196{
    194         PyMappingMethods *m;
    195 
    196         if (o == NULL || key == NULL) {
    197                 null_error();
    198                 return -1;
    199         }
    200         m = o->ob_type->tp_as_mapping;
    201         if (m && m->mp_ass_subscript)
    202                 return m->mp_ass_subscript(o, key, (PyObject*)NULL);
    203 
    204         if (o->ob_type->tp_as_sequence) {
    205                 if (PyIndex_Check(key)) {
    206                         Py_ssize_t key_value;
    207                         key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
    208                         if (key_value == -1 && PyErr_Occurred())
    209                                 return -1;
    210                         return PySequence_DelItem(o, key_value);
    211                 }
    212                 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
    213                         type_error("sequence index must be "
    214                                    "integer, not '%.200s'", key);
    215                         return -1;
    216                 }
    217         }
    218 
    219         type_error("'%.200s' object does not support item deletion", o);
    220         return -1;
     197    PyMappingMethods *m;
     198
     199    if (o == NULL || key == NULL) {
     200        null_error();
     201        return -1;
     202    }
     203    m = o->ob_type->tp_as_mapping;
     204    if (m && m->mp_ass_subscript)
     205        return m->mp_ass_subscript(o, key, (PyObject*)NULL);
     206
     207    if (o->ob_type->tp_as_sequence) {
     208        if (PyIndex_Check(key)) {
     209            Py_ssize_t key_value;
     210            key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
     211            if (key_value == -1 && PyErr_Occurred())
     212                return -1;
     213            return PySequence_DelItem(o, key_value);
     214        }
     215        else if (o->ob_type->tp_as_sequence->sq_ass_item) {
     216            type_error("sequence index must be "
     217                       "integer, not '%.200s'", key);
     218            return -1;
     219        }
     220    }
     221
     222    type_error("'%.200s' object does not support item deletion", o);
     223    return -1;
    221224}
    222225
     
    224227PyObject_DelItemString(PyObject *o, char *key)
    225228{
    226         PyObject *okey;
    227         int ret;
    228 
    229         if (o == NULL || key == NULL) {
    230                 null_error();
    231                 return -1;
    232         }
    233         okey = PyString_FromString(key);
    234         if (okey == NULL)
    235                 return -1;
    236         ret = PyObject_DelItem(o, okey);
    237         Py_DECREF(okey);
    238         return ret;
     229    PyObject *okey;
     230    int ret;
     231
     232    if (o == NULL || key == NULL) {
     233        null_error();
     234        return -1;
     235    }
     236    okey = PyString_FromString(key);
     237    if (okey == NULL)
     238        return -1;
     239    ret = PyObject_DelItem(o, okey);
     240    Py_DECREF(okey);
     241    return ret;
    239242}
    240243
    241244int
    242245PyObject_AsCharBuffer(PyObject *obj,
    243                           const char **buffer,
    244                           Py_ssize_t *buffer_len)
    245 {
    246         PyBufferProcs *pb;
    247         char *pp;
    248         Py_ssize_t len;
    249 
    250         if (obj == NULL || buffer == NULL || buffer_len == NULL) {
    251                 null_error();
    252                 return -1;
    253         }
    254         pb = obj->ob_type->tp_as_buffer;
    255         if (pb == NULL ||
    256              pb->bf_getcharbuffer == NULL ||
    257              pb->bf_getsegcount == NULL) {
    258                 PyErr_SetString(PyExc_TypeError,
    259                                 "expected a character buffer object");
    260                 return -1;
    261         }
    262         if ((*pb->bf_getsegcount)(obj,NULL) != 1) {
    263                 PyErr_SetString(PyExc_TypeError,
    264                                 "expected a single-segment buffer object");
    265                 return -1;
    266         }
    267         len = (*pb->bf_getcharbuffer)(obj, 0, &pp);
    268         if (len < 0)
    269                 return -1;
    270         *buffer = pp;
    271         *buffer_len = len;
    272         return 0;
     246                          const char **buffer,
     247                          Py_ssize_t *buffer_len)
     248{
     249    PyBufferProcs *pb;
     250    char *pp;
     251    Py_ssize_t len;
     252
     253    if (obj == NULL || buffer == NULL || buffer_len == NULL) {
     254        null_error();
     255        return -1;
     256    }
     257    pb = obj->ob_type->tp_as_buffer;
     258    if (pb == NULL ||
     259         pb->bf_getcharbuffer == NULL ||
     260         pb->bf_getsegcount == NULL) {
     261        PyErr_SetString(PyExc_TypeError,
     262                        "expected a character buffer object");
     263        return -1;
     264    }
     265    if ((*pb->bf_getsegcount)(obj,NULL) != 1) {
     266        PyErr_SetString(PyExc_TypeError,
     267                        "expected a single-segment buffer object");
     268        return -1;
     269    }
     270    len = (*pb->bf_getcharbuffer)(obj, 0, &pp);
     271    if (len < 0)
     272        return -1;
     273    *buffer = pp;
     274    *buffer_len = len;
     275    return 0;
    273276}
    274277
     
    276279PyObject_CheckReadBuffer(PyObject *obj)
    277280{
    278         PyBufferProcs *pb = obj->ob_type->tp_as_buffer;
    279 
    280         if (pb == NULL ||
    281             pb->bf_getreadbuffer == NULL ||
    282             pb->bf_getsegcount == NULL ||
    283             (*pb->bf_getsegcount)(obj, NULL) != 1)
    284                 return 0;
    285         return 1;
     281    PyBufferProcs *pb = obj->ob_type->tp_as_buffer;
     282
     283    if (pb == NULL ||
     284        pb->bf_getreadbuffer == NULL ||
     285        pb->bf_getsegcount == NULL ||
     286        (*pb->bf_getsegcount)(obj, NULL) != 1)
     287        return 0;
     288    return 1;
    286289}
    287290
    288291int PyObject_AsReadBuffer(PyObject *obj,
    289                           const void **buffer,
    290                           Py_ssize_t *buffer_len)
    291 {
    292         PyBufferProcs *pb;
    293         void *pp;
    294         Py_ssize_t len;
    295 
    296         if (obj == NULL || buffer == NULL || buffer_len == NULL) {
    297                 null_error();
    298                 return -1;
    299         }
    300         pb = obj->ob_type->tp_as_buffer;
    301         if (pb == NULL ||
    302              pb->bf_getreadbuffer == NULL ||
    303              pb->bf_getsegcount == NULL) {
    304                 PyErr_SetString(PyExc_TypeError,
    305                                 "expected a readable buffer object");
    306                 return -1;
    307         }
    308         if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
    309                 PyErr_SetString(PyExc_TypeError,
    310                                 "expected a single-segment buffer object");
    311                 return -1;
    312         }
    313         len = (*pb->bf_getreadbuffer)(obj, 0, &pp);
    314         if (len < 0)
    315                 return -1;
    316         *buffer = pp;
    317         *buffer_len = len;
    318         return 0;
     292                          const void **buffer,
     293                          Py_ssize_t *buffer_len)
     294{
     295    PyBufferProcs *pb;
     296    void *pp;
     297    Py_ssize_t len;
     298
     299    if (obj == NULL || buffer == NULL || buffer_len == NULL) {
     300        null_error();
     301        return -1;
     302    }
     303    pb = obj->ob_type->tp_as_buffer;
     304    if (pb == NULL ||
     305         pb->bf_getreadbuffer == NULL ||
     306         pb->bf_getsegcount == NULL) {
     307        PyErr_SetString(PyExc_TypeError,
     308                        "expected a readable buffer object");
     309        return -1;
     310    }
     311    if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
     312        PyErr_SetString(PyExc_TypeError,
     313                        "expected a single-segment buffer object");
     314        return -1;
     315    }
     316    len = (*pb->bf_getreadbuffer)(obj, 0, &pp);
     317    if (len < 0)
     318        return -1;
     319    *buffer = pp;
     320    *buffer_len = len;
     321    return 0;
    319322}
    320323
    321324int PyObject_AsWriteBuffer(PyObject *obj,
    322                            void **buffer,
    323                            Py_ssize_t *buffer_len)
    324 {
    325         PyBufferProcs *pb;
    326         void*pp;
    327         Py_ssize_t len;
    328 
    329         if (obj == NULL || buffer == NULL || buffer_len == NULL) {
    330                 null_error();
    331                 return -1;
    332         }
    333         pb = obj->ob_type->tp_as_buffer;
    334         if (pb == NULL ||
    335              pb->bf_getwritebuffer == NULL ||
    336              pb->bf_getsegcount == NULL) {
    337                 PyErr_SetString(PyExc_TypeError,
    338                                 "expected a writeable buffer object");
    339                 return -1;
    340         }
    341         if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
    342                 PyErr_SetString(PyExc_TypeError,
    343                                 "expected a single-segment buffer object");
    344                 return -1;
    345         }
    346         len = (*pb->bf_getwritebuffer)(obj,0,&pp);
    347         if (len < 0)
    348                 return -1;
    349         *buffer = pp;
    350         *buffer_len = len;
    351         return 0;
     325                           void **buffer,
     326                           Py_ssize_t *buffer_len)
     327{
     328    PyBufferProcs *pb;
     329    void*pp;
     330    Py_ssize_t len;
     331
     332    if (obj == NULL || buffer == NULL || buffer_len == NULL) {
     333        null_error();
     334        return -1;
     335    }
     336    pb = obj->ob_type->tp_as_buffer;
     337    if (pb == NULL ||
     338         pb->bf_getwritebuffer == NULL ||
     339         pb->bf_getsegcount == NULL) {
     340        PyErr_SetString(PyExc_TypeError,
     341                        "expected a writeable buffer object");
     342        return -1;
     343    }
     344    if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
     345        PyErr_SetString(PyExc_TypeError,
     346                        "expected a single-segment buffer object");
     347        return -1;
     348    }
     349    len = (*pb->bf_getwritebuffer)(obj,0,&pp);
     350    if (len < 0)
     351        return -1;
     352    *buffer = pp;
     353    *buffer_len = len;
     354    return 0;
    352355}
    353356
     
    357360PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
    358361{
    359         if (!PyObject_CheckBuffer(obj)) {
    360                 PyErr_Format(PyExc_TypeError,
    361                              "'%100s' does not have the buffer interface",
    362                              Py_TYPE(obj)->tp_name);
    363                 return -1;
    364         }
    365         return (*(obj->ob_type->tp_as_buffer->bf_getbuffer))(obj, view, flags);
     362    if (!PyObject_CheckBuffer(obj)) {
     363        PyErr_Format(PyExc_TypeError,
     364                     "'%100s' does not have the buffer interface",
     365                     Py_TYPE(obj)->tp_name);
     366        return -1;
     367    }
     368    return (*(obj->ob_type->tp_as_buffer->bf_getbuffer))(obj, view, flags);
    366369}
    367370
     
    369372_IsFortranContiguous(Py_buffer *view)
    370373{
    371         Py_ssize_t sd, dim;
    372         int i;
    373 
    374         if (view->ndim == 0) return 1;
    375         if (view->strides == NULL) return (view->ndim == 1);
    376 
    377         sd = view->itemsize;
    378         if (view->ndim == 1) return (view->shape[0] == 1 ||
    379                                    sd == view->strides[0]);
    380         for (i=0; i<view->ndim; i++) {
    381                 dim = view->shape[i];
    382                 if (dim == 0) return 1;
    383                 if (view->strides[i] != sd) return 0;
    384                 sd *= dim;
    385         }
    386         return 1;
     374    Py_ssize_t sd, dim;
     375    int i;
     376
     377    if (view->ndim == 0) return 1;
     378    if (view->strides == NULL) return (view->ndim == 1);
     379
     380    sd = view->itemsize;
     381    if (view->ndim == 1) return (view->shape[0] == 1 ||
     382                               sd == view->strides[0]);
     383    for (i=0; i<view->ndim; i++) {
     384        dim = view->shape[i];
     385        if (dim == 0) return 1;
     386        if (view->strides[i] != sd) return 0;
     387        sd *= dim;
     388    }
     389    return 1;
    387390}
    388391
     
    390393_IsCContiguous(Py_buffer *view)
    391394{
    392         Py_ssize_t sd, dim;
    393         int i;
    394 
    395         if (view->ndim == 0) return 1;
    396         if (view->strides == NULL) return 1;
    397 
    398         sd = view->itemsize;
    399         if (view->ndim == 1) return (view->shape[0] == 1 ||
    400                                    sd == view->strides[0]);
    401         for (i=view->ndim-1; i>=0; i--) {
    402                 dim = view->shape[i];
    403                 if (dim == 0) return 1;
    404                 if (view->strides[i] != sd) return 0;
    405                 sd *= dim;
    406         }
    407         return 1;
     395    Py_ssize_t sd, dim;
     396    int i;
     397
     398    if (view->ndim == 0) return 1;
     399    if (view->strides == NULL) return 1;
     400
     401    sd = view->itemsize;
     402    if (view->ndim == 1) return (view->shape[0] == 1 ||
     403                               sd == view->strides[0]);
     404    for (i=view->ndim-1; i>=0; i--) {
     405        dim = view->shape[i];
     406        if (dim == 0) return 1;
     407        if (view->strides[i] != sd) return 0;
     408        sd *= dim;
     409    }
     410    return 1;
    408411}
    409412
     
    412415{
    413416
    414         if (view->suboffsets != NULL) return 0;
    415 
    416         if (fort == 'C')
    417                 return _IsCContiguous(view);
    418         else if (fort == 'F')
    419                 return _IsFortranContiguous(view);
    420         else if (fort == 'A')
    421                 return (_IsCContiguous(view) || _IsFortranContiguous(view));
    422         return 0;
     417    if (view->suboffsets != NULL) return 0;
     418
     419    if (fort == 'C')
     420        return _IsCContiguous(view);
     421    else if (fort == 'F')
     422        return _IsFortranContiguous(view);
     423    else if (fort == 'A')
     424        return (_IsCContiguous(view) || _IsFortranContiguous(view));
     425    return 0;
    423426}
    424427
     
    427430PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)
    428431{
    429         char* pointer;
    430         int i;
    431         pointer = (char *)view->buf;
    432         for (i = 0; i < view->ndim; i++) {
    433                 pointer += view->strides[i]*indices[i];
    434                 if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
    435                         pointer = *((char**)pointer) + view->suboffsets[i];
    436                 }
    437         }
    438         return (void*)pointer;
    439 }
    440 
    441 
    442 static void
    443 _add_one_to_index_F(int nd, Py_ssize_t *index, Py_ssize_t *shape)
    444 {
    445         int k;
    446 
    447         for (k=0; k<nd; k++) {
    448                 if (index[k] < shape[k]-1) {
    449                         index[k]++;
    450                         break;
    451                 }
    452                 else {
    453                         index[k] = 0;
    454                 }
    455         }
    456 }
    457 
    458 static void
    459 _add_one_to_index_C(int nd, Py_ssize_t *index, Py_ssize_t *shape)
    460 {
    461         int k;
    462 
    463         for (k=nd-1; k>=0; k--) {
    464                 if (index[k] < shape[k]-1) {
    465                         index[k]++;
    466                         break;
    467                 }
    468                 else {
    469                         index[k] = 0;
    470                 }
    471         }
     432    char* pointer;
     433    int i;
     434    pointer = (char *)view->buf;
     435    for (i = 0; i < view->ndim; i++) {
     436        pointer += view->strides[i]*indices[i];
     437        if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
     438            pointer = *((char**)pointer) + view->suboffsets[i];
     439        }
     440    }
     441    return (void*)pointer;
     442}
     443
     444
     445void
     446_Py_add_one_to_index_F(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
     447{
     448    int k;
     449
     450    for (k=0; k<nd; k++) {
     451        if (index[k] < shape[k]-1) {
     452            index[k]++;
     453            break;
     454        }
     455        else {
     456            index[k] = 0;
     457        }
     458    }
     459}
     460
     461void
     462_Py_add_one_to_index_C(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
     463{
     464    int k;
     465
     466    for (k=nd-1; k>=0; k--) {
     467        if (index[k] < shape[k]-1) {
     468            index[k]++;
     469            break;
     470        }
     471        else {
     472            index[k] = 0;
     473        }
     474    }
    472475}
    473476
     
    480483PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort)
    481484{
    482         int k;
    483         void (*addone)(int, Py_ssize_t *, Py_ssize_t *);
    484         Py_ssize_t *indices, elements;
    485         char *dest, *ptr;
    486 
    487         if (len > view->len) {
    488                 len = view->len;
    489         }
    490 
    491         if (PyBuffer_IsContiguous(view, fort)) {
    492                 /* simplest copy is all that is needed */
    493                 memcpy(buf, view->buf, len);
    494                 return 0;
    495         }
    496 
    497         /* Otherwise a more elaborate scheme is needed */
    498 
    499         /* XXX(nnorwitz): need to check for overflow! */
    500         indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
    501         if (indices == NULL) {
    502                 PyErr_NoMemory();
    503                 return -1;
    504         }
    505         for (k=0; k<view->ndim;k++) {
    506                 indices[k] = 0;
    507         }
    508 
    509         if (fort == 'F') {
    510                 addone = _add_one_to_index_F;
    511         }
    512         else {
    513                 addone = _add_one_to_index_C;
    514         }
    515         dest = buf;
    516         /* XXX : This is not going to be the fastest code in the world
    517                 several optimizations are possible.
    518         */
    519         elements = len / view->itemsize;
    520         while (elements--) {
    521                 addone(view->ndim, indices, view->shape);
    522                 ptr = PyBuffer_GetPointer(view, indices);
    523                 memcpy(dest, ptr, view->itemsize);
    524                 dest += view->itemsize;
    525         }
    526         PyMem_Free(indices);
    527         return 0;
     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    if (len > view->len) {
     491        len = view->len;
     492    }
     493
     494    if (PyBuffer_IsContiguous(view, fort)) {
     495        /* simplest copy is all that is needed */
     496        memcpy(buf, view->buf, len);
     497        return 0;
     498    }
     499
     500    /* Otherwise a more elaborate scheme is needed */
     501
     502    /* XXX(nnorwitz): need to check for overflow! */
     503    indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
     504    if (indices == NULL) {
     505        PyErr_NoMemory();
     506        return -1;
     507    }
     508    for (k=0; k<view->ndim;k++) {
     509        indices[k] = 0;
     510    }
     511
     512    if (fort == 'F') {
     513        addone = _Py_add_one_to_index_F;
     514    }
     515    else {
     516        addone = _Py_add_one_to_index_C;
     517    }
     518    dest = buf;
     519    /* XXX : This is not going to be the fastest code in the world
     520            several optimizations are possible.
     521    */
     522    elements = len / view->itemsize;
     523    while (elements--) {
     524        addone(view->ndim, indices, view->shape);
     525        ptr = PyBuffer_GetPointer(view, indices);
     526        memcpy(dest, ptr, view->itemsize);
     527        dest += view->itemsize;
     528    }
     529    PyMem_Free(indices);
     530    return 0;
    528531}
    529532
     
    531534PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
    532535{
    533         int k;
    534         void (*addone)(int, Py_ssize_t *, Py_ssize_t *);
    535         Py_ssize_t *indices, elements;
    536         char *src, *ptr;
    537 
    538         if (len > view->len) {
    539                 len = view->len;
    540         }
    541 
    542         if (PyBuffer_IsContiguous(view, fort)) {
    543                 /* simplest copy is all that is needed */
    544                 memcpy(view->buf, buf, len);
    545                 return 0;
    546         }
    547 
    548         /* Otherwise a more elaborate scheme is needed */
    549 
    550         /* XXX(nnorwitz): need to check for overflow! */
    551         indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
    552         if (indices == NULL) {
    553                 PyErr_NoMemory();
    554                 return -1;
    555         }
    556         for (k=0; k<view->ndim;k++) {
    557                 indices[k] = 0;
    558         }
    559 
    560         if (fort == 'F') {
    561                 addone = _add_one_to_index_F;
    562         }
    563         else {
    564                 addone = _add_one_to_index_C;
    565         }
    566         src = buf;
    567         /* XXX : This is not going to be the fastest code in the world
    568                 several optimizations are possible.
    569         */
    570         elements = len / view->itemsize;
    571         while (elements--) {
    572                 addone(view->ndim, indices, view->shape);
    573                 ptr = PyBuffer_GetPointer(view, indices);
    574                 memcpy(ptr, src, view->itemsize);
    575                 src += view->itemsize;
    576         }
    577 
    578         PyMem_Free(indices);
    579         return 0;
     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    if (len > view->len) {
     542        len = view->len;
     543    }
     544
     545    if (PyBuffer_IsContiguous(view, fort)) {
     546        /* simplest copy is all that is needed */
     547        memcpy(view->buf, buf, len);
     548        return 0;
     549    }
     550
     551    /* Otherwise a more elaborate scheme is needed */
     552
     553    /* XXX(nnorwitz): need to check for overflow! */
     554    indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
     555    if (indices == NULL) {
     556        PyErr_NoMemory();
     557        return -1;
     558    }
     559    for (k=0; k<view->ndim;k++) {
     560        indices[k] = 0;
     561    }
     562
     563    if (fort == 'F') {
     564        addone = _Py_add_one_to_index_F;
     565    }
     566    else {
     567        addone = _Py_add_one_to_index_C;
     568    }
     569    src = buf;
     570    /* XXX : This is not going to be the fastest code in the world
     571            several optimizations are possible.
     572    */
     573    elements = len / view->itemsize;
     574    while (elements--) {
     575        addone(view->ndim, indices, view->shape);
     576        ptr = PyBuffer_GetPointer(view, indices);
     577        memcpy(ptr, src, view->itemsize);
     578        src += view->itemsize;
     579    }
     580
     581    PyMem_Free(indices);
     582    return 0;
    580583}
    581584
    582585int PyObject_CopyData(PyObject *dest, PyObject *src)
    583586{
    584         Py_buffer view_dest, view_src;
    585         int k;
    586         Py_ssize_t *indices, elements;
    587         char *dptr, *sptr;
    588 
    589         if (!PyObject_CheckBuffer(dest) ||
    590             !PyObject_CheckBuffer(src)) {
    591                 PyErr_SetString(PyExc_TypeError,
    592                                 "both destination and source must have the "\
    593                                 "buffer interface");
    594                 return -1;
    595         }
    596 
    597         if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
    598         if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
    599                 PyBuffer_Release(&view_dest);
    600                 return -1;
    601         }
    602 
    603         if (view_dest.len < view_src.len) {
    604                 PyErr_SetString(PyExc_BufferError,
    605                                 "destination is too small to receive data from source");
    606                 PyBuffer_Release(&view_dest);
    607                 PyBuffer_Release(&view_src);
    608                 return -1;
    609         }
    610 
    611         if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
    612              PyBuffer_IsContiguous(&view_src, 'C')) ||
    613             (PyBuffer_IsContiguous(&view_dest, 'F') &&
    614              PyBuffer_IsContiguous(&view_src, 'F'))) {
    615                 /* simplest copy is all that is needed */
    616                 memcpy(view_dest.buf, view_src.buf, view_src.len);
    617                 PyBuffer_Release(&view_dest);
    618                 PyBuffer_Release(&view_src);
    619                 return 0;
    620         }
    621 
    622         /* Otherwise a more elaborate copy scheme is needed */
    623 
    624         /* XXX(nnorwitz): need to check for overflow! */
    625         indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
    626         if (indices == NULL) {
    627                 PyErr_NoMemory();
    628                 PyBuffer_Release(&view_dest);
    629                 PyBuffer_Release(&view_src);
    630                 return -1;
    631         }
    632         for (k=0; k<view_src.ndim;k++) {
    633                 indices[k] = 0;
    634         }
    635         elements = 1;
    636         for (k=0; k<view_src.ndim; k++) {
    637                 /* XXX(nnorwitz): can this overflow? */
    638                 elements *= view_src.shape[k];
    639         }
    640         while (elements--) {
    641                 _add_one_to_index_C(view_src.ndim, indices, view_src.shape);
    642                 dptr = PyBuffer_GetPointer(&view_dest, indices);
    643                 sptr = PyBuffer_GetPointer(&view_src, indices);
    644                 memcpy(dptr, sptr, view_src.itemsize);
    645         }
    646         PyMem_Free(indices);
    647         PyBuffer_Release(&view_dest);
    648         PyBuffer_Release(&view_src);
    649         return 0;
     587    Py_buffer view_dest, view_src;
     588    int k;
     589    Py_ssize_t *indices, elements;
     590    char *dptr, *sptr;
     591
     592    if (!PyObject_CheckBuffer(dest) ||
     593        !PyObject_CheckBuffer(src)) {
     594        PyErr_SetString(PyExc_TypeError,
     595                        "both destination and source must have the "\
     596                        "buffer interface");
     597        return -1;
     598    }
     599
     600    if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
     601    if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
     602        PyBuffer_Release(&view_dest);
     603        return -1;
     604    }
     605
     606    if (view_dest.len < view_src.len) {
     607        PyErr_SetString(PyExc_BufferError,
     608                        "destination is too small to receive data from source");
     609        PyBuffer_Release(&view_dest);
     610        PyBuffer_Release(&view_src);
     611        return -1;
     612    }
     613
     614    if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
     615         PyBuffer_IsContiguous(&view_src, 'C')) ||
     616        (PyBuffer_IsContiguous(&view_dest, 'F') &&
     617         PyBuffer_IsContiguous(&view_src, 'F'))) {
     618        /* simplest copy is all that is needed */
     619        memcpy(view_dest.buf, view_src.buf, view_src.len);
     620        PyBuffer_Release(&view_dest);
     621        PyBuffer_Release(&view_src);
     622        return 0;
     623    }
     624
     625    /* Otherwise a more elaborate copy scheme is needed */
     626
     627    /* XXX(nnorwitz): need to check for overflow! */
     628    indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
     629    if (indices == NULL) {
     630        PyErr_NoMemory();
     631        PyBuffer_Release(&view_dest);
     632        PyBuffer_Release(&view_src);
     633        return -1;
     634    }
     635    for (k=0; k<view_src.ndim;k++) {
     636        indices[k] = 0;
     637    }
     638    elements = 1;
     639    for (k=0; k<view_src.ndim; k++) {
     640        /* XXX(nnorwitz): can this overflow? */
     641        elements *= view_src.shape[k];
     642    }
     643    while (elements--) {
     644        _Py_add_one_to_index_C(view_src.ndim, indices, view_src.shape);
     645        dptr = PyBuffer_GetPointer(&view_dest, indices);
     646        sptr = PyBuffer_GetPointer(&view_src, indices);
     647        memcpy(dptr, sptr, view_src.itemsize);
     648    }
     649    PyMem_Free(indices);
     650    PyBuffer_Release(&view_dest);
     651    PyBuffer_Release(&view_src);
     652    return 0;
    650653}
    651654
    652655void
    653656PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
    654                                Py_ssize_t *strides, int itemsize,
    655                                char fort)
    656 {
    657         int k;
    658         Py_ssize_t sd;
    659 
    660         sd = itemsize;
    661         if (fort == 'F') {
    662                 for (k=0; k<nd; k++) {
    663                         strides[k] = sd;
    664                         sd *= shape[k];
    665                 }
    666         }
    667         else {
    668                 for (k=nd-1; k>=0; k--) {
    669                         strides[k] = sd;
    670                         sd *= shape[k];
    671                 }
    672         }
    673         return;
     657                               Py_ssize_t *strides, int itemsize,
     658                               char fort)
     659{
     660    int k;
     661    Py_ssize_t sd;
     662
     663    sd = itemsize;
     664    if (fort == 'F') {
     665        for (k=0; k<nd; k++) {
     666            strides[k] = sd;
     667            sd *= shape[k];
     668        }
     669    }
     670    else {
     671        for (k=nd-1; k>=0; k--) {
     672            strides[k] = sd;
     673            sd *= shape[k];
     674        }
     675    }
     676    return;
    674677}
    675678
    676679int
    677680PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
    678               int readonly, int flags)
    679 {
    680         if (view == NULL) return 0;
    681         if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
    682             (readonly == 1)) {
    683                 PyErr_SetString(PyExc_BufferError,
    684                                 "Object is not writable.");
    685                 return -1;
    686         }
    687 
    688         view->obj = obj;
    689         if (obj)
    690                 Py_INCREF(obj);
    691         view->buf = buf;
    692         view->len = len;
    693         view->readonly = readonly;
    694         view->itemsize = 1;
    695         view->format = NULL;
    696         if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
    697                 view->format = "B";
    698         view->ndim = 1;
    699         view->shape = NULL;
    700         if ((flags & PyBUF_ND) == PyBUF_ND)
    701                 view->shape = &(view->len);
    702         view->strides = NULL;
    703         if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
    704                 view->strides = &(view->itemsize);
    705         view->suboffsets = NULL;
    706         view->internal = NULL;
    707         return 0;
     681              int readonly, int flags)
     682{
     683    if (view == NULL) return 0;
     684    if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
     685        (readonly == 1)) {
     686        PyErr_SetString(PyExc_BufferError,
     687                        "Object is not writable.");
     688        return -1;
     689    }
     690
     691    view->obj = obj;
     692    if (obj)
     693        Py_INCREF(obj);
     694    view->buf = buf;
     695    view->len = len;
     696    view->readonly = readonly;
     697    view->itemsize = 1;
     698    view->format = NULL;
     699    if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
     700        view->format = "B";
     701    view->ndim = 1;
     702    view->shape = NULL;
     703    if ((flags & PyBUF_ND) == PyBUF_ND)
     704        view->shape = &(view->len);
     705    view->strides = NULL;
     706    if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
     707        view->strides = &(view->itemsize);
     708    view->suboffsets = NULL;
     709    view->internal = NULL;
     710    return 0;
    708711}
    709712
     
    711714PyBuffer_Release(Py_buffer *view)
    712715{
    713         PyObject *obj = view->obj;
    714         if (obj && Py_TYPE(obj)->tp_as_buffer && Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer)
    715                 Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer(obj, view);
    716         Py_XDECREF(obj);
    717         view->obj = NULL;
     716    PyObject *obj = view->obj;
     717    if (obj && Py_TYPE(obj)->tp_as_buffer && Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer)
     718        Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer(obj, view);
     719    Py_XDECREF(obj);
     720    view->obj = NULL;
    718721}
    719722
     
    721724PyObject_Format(PyObject* obj, PyObject *format_spec)
    722725{
    723         static PyObject * str__format__ = NULL;
    724         PyObject *empty = NULL;
    725         PyObject *result = NULL;
    726         int spec_is_unicode;
    727         int result_is_unicode;
    728 
    729         /* Initialize cached value */
    730         if (str__format__ == NULL) {
    731                 /* Initialize static variable needed by _PyType_Lookup */
    732                 str__format__ = PyString_InternFromString("__format__");
    733                 if (str__format__ == NULL)
    734                         goto done;
    735         }
    736 
    737         /* If no format_spec is provided, use an empty string */
    738         if (format_spec == NULL) {
    739                 empty = PyString_FromStringAndSize(NULL, 0);
    740                 format_spec = empty;
    741         }
    742 
    743         /* Check the format_spec type, and make sure it's str or unicode */
    744         if (PyUnicode_Check(format_spec))
    745                 spec_is_unicode = 1;
    746         else if (PyString_Check(format_spec))
    747                 spec_is_unicode = 0;
    748         else {
    749                 PyErr_Format(PyExc_TypeError,
    750                              "format expects arg 2 to be string "
    751                              "or unicode, not %.100s", Py_TYPE(format_spec)->tp_name);
    752                 goto done;
    753         }
    754 
    755         /* Make sure the type is initialized.  float gets initialized late */
    756         if (Py_TYPE(obj)->tp_dict == NULL)
    757                 if (PyType_Ready(Py_TYPE(obj)) < 0)
    758                         goto done;
    759 
    760         /* Check for a __format__ method and call it. */
    761         if (PyInstance_Check(obj)) {
    762                 /* We're an instance of a classic class */
    763                 PyObject *bound_method = PyObject_GetAttr(obj,
    764                                                           str__format__);
    765                 if (bound_method != NULL) {
    766                         result = PyObject_CallFunctionObjArgs(bound_method,
    767                                                               format_spec,
    768                                                               NULL);
    769                         Py_DECREF(bound_method);
    770                 } else {
    771                         PyObject *self_as_str;
    772                         PyObject *format_method;
    773 
    774                         PyErr_Clear();
    775                         /* Per the PEP, convert to str (or unicode,
    776                            depending on the type of the format
    777                            specifier).  For new-style classes, this
    778                            logic is done by object.__format__(). */
    779                         if (spec_is_unicode)
    780                                 self_as_str = PyObject_Unicode(obj);
    781                         else
    782                                 self_as_str = PyObject_Str(obj);
    783                         if (self_as_str == NULL)
    784                                 goto done;
    785 
    786                         /* Then call str.__format__ on that result */
    787                         format_method = PyObject_GetAttr(self_as_str,
    788                                                          str__format__);
    789                         if (format_method == NULL) {
    790                                 Py_DECREF(self_as_str);
    791                                 goto done;
    792                         }
    793                         result = PyObject_CallFunctionObjArgs(format_method,
    794                                                               format_spec,
    795                                                               NULL);
    796                         Py_DECREF(self_as_str);
    797                         Py_DECREF(format_method);
    798                         if (result == NULL)
    799                                 goto done;
     726    PyObject *empty = NULL;
     727    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    if (format_spec == NULL) {
     735        empty = PyString_FromStringAndSize(NULL, 0);
     736        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    if (PyUnicode_Check(format_spec))
     742        spec_is_unicode = 1;
     743    else if (PyString_Check(format_spec))
     744        spec_is_unicode = 0;
     745    else {
     746#else
     747    if (!PyString_Check(format_spec)) {
     748#endif
     749        PyErr_Format(PyExc_TypeError,
     750                     "format expects arg 2 to be string "
     751                     "or unicode, not %.100s", Py_TYPE(format_spec)->tp_name);
     752        goto done;
     753    }
     754
     755    /* Check for a __format__ method and call it. */
     756    if (PyInstance_Check(obj)) {
     757        /* We're an instance of a classic class */
     758        PyObject *bound_method = PyObject_GetAttrString(obj, "__format__");
     759        if (bound_method != NULL) {
     760            result = PyObject_CallFunctionObjArgs(bound_method,
     761                                                  format_spec,
     762                                                  NULL);
     763            Py_DECREF(bound_method);
     764        } else {
     765            PyObject *self_as_str = NULL;
     766            PyObject *format_method = NULL;
     767            Py_ssize_t format_len;
     768
     769            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            if (spec_is_unicode) {
     776                format_len = PyUnicode_GET_SIZE(format_spec);
     777                self_as_str = PyObject_Unicode(obj);
     778            } else
     779#endif
     780            {
     781                format_len = PyString_GET_SIZE(format_spec);
     782                self_as_str = PyObject_Str(obj);
     783            }
     784            if (self_as_str == NULL)
     785                goto done1;
     786
     787            if (format_len > 0) {
     788                /* See the almost identical code in
     789                   typeobject.c for new-style
     790                   classes. */
     791                if (PyErr_WarnEx(
     792                    PyExc_PendingDeprecationWarning,
     793                    "object.__format__ with a non-empty "
     794                    "format string is deprecated", 1)
     795                     < 0) {
     796                    goto done1;
    800797                }
    801         } else {
    802                 /* Not an instance of a classic class, use the code
    803                    from py3k */
    804 
    805                 /* Find the (unbound!) __format__ method (a borrowed
    806                    reference) */
    807                 PyObject *method = _PyType_Lookup(Py_TYPE(obj),
    808                                                   str__format__);
    809                 if (method == NULL) {
    810                         PyErr_Format(PyExc_TypeError,
    811                                      "Type %.100s doesn't define __format__",
    812                                      Py_TYPE(obj)->tp_name);
    813                         goto done;
    814                 }
    815                 /* And call it, binding it to the value */
    816                 result = PyObject_CallFunctionObjArgs(method, obj,
    817                                                       format_spec, NULL);
    818         }
    819 
    820         if (result == NULL)
    821                 goto done;
    822 
    823         /* Check the result type, and make sure it's str or unicode */
    824         if (PyUnicode_Check(result))
    825                 result_is_unicode = 1;
    826         else if (PyString_Check(result))
    827                 result_is_unicode = 0;
    828         else {
    829                 PyErr_Format(PyExc_TypeError,
    830                              "%.100s.__format__ must return string or "
    831                              "unicode, not %.100s", Py_TYPE(obj)->tp_name,
    832                              Py_TYPE(result)->tp_name);
    833                 Py_DECREF(result);
    834                 result = NULL;
    835                 goto done;
    836         }
    837 
    838         /* Convert to unicode, if needed.  Required if spec is unicode
    839            and result is str */
    840         if (spec_is_unicode && !result_is_unicode) {
    841                 PyObject *tmp = PyObject_Unicode(result);
    842                 /* This logic works whether or not tmp is NULL */
    843                 Py_DECREF(result);
    844                 result = tmp;
    845         }
     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            format_method = PyObject_GetAttrString(self_as_str, "__format__");
     809            if (format_method == NULL) {
     810                goto done1;
     811            }
     812            result = PyObject_CallFunctionObjArgs(format_method,
     813                                                  format_spec,
     814                                                  NULL);
     815done1:
     816            Py_XDECREF(self_as_str);
     817            Py_XDECREF(format_method);
     818            if (result == NULL)
     819                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        PyObject *method = _PyObject_LookupSpecial(obj, "__format__",
     829                                                   &format_cache);
     830        if (method == NULL) {
     831            if (!PyErr_Occurred())
     832                PyErr_Format(PyExc_TypeError,
     833                             "Type %.100s doesn't define __format__",
     834                             Py_TYPE(obj)->tp_name);
     835            goto done;
     836        }
     837        /* And call it. */
     838        result = PyObject_CallFunctionObjArgs(method, format_spec, NULL);
     839        Py_DECREF(method);
     840    }
     841
     842    if (result == NULL)
     843        goto done;
     844
     845    /* Check the result type, and make sure it's str or unicode */
     846#ifdef Py_USING_UNICODE
     847    if (PyUnicode_Check(result))
     848        result_is_unicode = 1;
     849    else if (PyString_Check(result))
     850        result_is_unicode = 0;
     851    else {
     852#else
     853    if (!PyString_Check(result)) {
     854#endif
     855        PyErr_Format(PyExc_TypeError,
     856                     "%.100s.__format__ must return string or "
     857                     "unicode, not %.100s", Py_TYPE(obj)->tp_name,
     858                     Py_TYPE(result)->tp_name);
     859        Py_DECREF(result);
     860        result = NULL;
     861        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    if (spec_is_unicode && !result_is_unicode) {
     868        PyObject *tmp = PyObject_Unicode(result);
     869        /* This logic works whether or not tmp is NULL */
     870        Py_DECREF(result);
     871        result = tmp;
     872    }
     873#endif
    846874
    847875done:
    848         Py_XDECREF(empty);
    849         return result;
     876    Py_XDECREF(empty);
     877    return result;
    850878}
    851879
     
    855883PyNumber_Check(PyObject *o)
    856884{
    857         return o && o->ob_type->tp_as_number &&
    858                (o->ob_type->tp_as_number->nb_int ||
    859                 o->ob_type->tp_as_number->nb_float);
     885    return o && o->ob_type->tp_as_number &&
     886           (o->ob_type->tp_as_number->nb_int ||
     887        o->ob_type->tp_as_number->nb_float);
    860888}
    861889
     
    866894#define NB_SLOT(x) offsetof(PyNumberMethods, x)
    867895#define NB_BINOP(nb_methods, slot) \
    868                 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
     896        (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
    869897#define NB_TERNOP(nb_methods, slot) \
    870                 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
     898        (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
    871899
    872900/*
    873901  Calling scheme used for binary operations:
    874902
    875   v     w       Action
     903  v     w       Action
    876904  -------------------------------------------------------------------
    877   new   new     w.op(v,w)[*], v.op(v,w), w.op(v,w)
    878   new   old     v.op(v,w), coerce(v,w), v.op(v,w)
    879   old   new     w.op(v,w), coerce(v,w), v.op(v,w)
    880   old   old     coerce(v,w), v.op(v,w)
     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)
    881909
    882910  [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
     
    895923binary_op1(PyObject *v, PyObject *w, const int op_slot)
    896924{
    897         PyObject *x;
    898         binaryfunc slotv = NULL;
    899         binaryfunc slotw = NULL;
    900 
    901         if (v->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(v))
    902                 slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot);
    903         if (w->ob_type != v->ob_type &&
    904             w->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(w)) {
    905                 slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot);
    906                 if (slotw == slotv)
    907                         slotw = NULL;
    908         }
    909         if (slotv) {
    910                 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
    911                         x = slotw(v, w);
    912                         if (x != Py_NotImplemented)
    913                                 return x;
    914                         Py_DECREF(x); /* can't do it */
    915                         slotw = NULL;
    916                 }
    917                 x = slotv(v, w);
    918                 if (x != Py_NotImplemented)
    919                         return x;
    920                 Py_DECREF(x); /* can't do it */
    921         }
    922         if (slotw) {
    923                 x = slotw(v, w);
    924                 if (x != Py_NotImplemented)
    925                         return x;
    926                 Py_DECREF(x); /* can't do it */
    927         }
    928         if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w)) {
    929                 int err = PyNumber_CoerceEx(&v, &w);
    930                 if (err < 0) {
    931                         return NULL;
    932                 }
    933                 if (err == 0) {
    934                         PyNumberMethods *mv = v->ob_type->tp_as_number;
    935                         if (mv) {
    936                                 binaryfunc slot;
    937                                 slot = NB_BINOP(mv, op_slot);
    938                                 if (slot) {
    939                                         x = slot(v, w);
    940                                         Py_DECREF(v);
    941                                         Py_DECREF(w);
    942                                         return x;
    943                                 }
    944                         }
    945                         /* CoerceEx incremented the reference counts */
    946                         Py_DECREF(v);
    947                         Py_DECREF(w);
    948                 }
    949         }
    950         Py_INCREF(Py_NotImplemented);
    951         return Py_NotImplemented;
     925    PyObject *x;
     926    binaryfunc slotv = NULL;
     927    binaryfunc slotw = NULL;
     928
     929    if (v->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(v))
     930        slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot);
     931    if (w->ob_type != v->ob_type &&
     932        w->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(w)) {
     933        slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot);
     934        if (slotw == slotv)
     935            slotw = NULL;
     936    }
     937    if (slotv) {
     938        if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
     939            x = slotw(v, w);
     940            if (x != Py_NotImplemented)
     941                return x;
     942            Py_DECREF(x); /* can't do it */
     943            slotw = NULL;
     944        }
     945        x = slotv(v, w);
     946        if (x != Py_NotImplemented)
     947            return x;
     948        Py_DECREF(x); /* can't do it */
     949    }
     950    if (slotw) {
     951        x = slotw(v, w);
     952        if (x != Py_NotImplemented)
     953            return x;
     954        Py_DECREF(x); /* can't do it */
     955    }
     956    if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w)) {
     957        int err = PyNumber_CoerceEx(&v, &w);
     958        if (err < 0) {
     959            return NULL;
     960        }
     961        if (err == 0) {
     962            PyNumberMethods *mv = v->ob_type->tp_as_number;
     963            if (mv) {
     964                binaryfunc slot;
     965                slot = NB_BINOP(mv, op_slot);
     966                if (slot) {
     967                    x = slot(v, w);
     968                    Py_DECREF(v);
     969                    Py_DECREF(w);
     970                    return x;
     971                }
     972            }
     973            /* CoerceEx incremented the reference counts */
     974            Py_DECREF(v);
     975            Py_DECREF(w);
     976        }
     977    }
     978    Py_INCREF(Py_NotImplemented);
     979    return Py_NotImplemented;
    952980}
    953981
     
    955983binop_type_error(PyObject *v, PyObject *w, const char *op_name)
    956984{
    957         PyErr_Format(PyExc_TypeError,
    958                      "unsupported operand type(s) for %.100s: "
    959                      "'%.100s' and '%.100s'",
    960                      op_name,
    961                      v->ob_type->tp_name,
    962                      w->ob_type->tp_name);
    963         return NULL;
     985    PyErr_Format(PyExc_TypeError,
     986                 "unsupported operand type(s) for %.100s: "
     987                 "'%.100s' and '%.100s'",
     988                 op_name,
     989                 v->ob_type->tp_name,
     990                 w->ob_type->tp_name);
     991    return NULL;
    964992}
    965993
     
    967995binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
    968996{
    969         PyObject *result = binary_op1(v, w, op_slot);
    970         if (result == Py_NotImplemented) {
    971                 Py_DECREF(result);
    972                 return binop_type_error(v, w, op_name);
    973         }
    974         return result;
     997    PyObject *result = binary_op1(v, w, op_slot);
     998    if (result == Py_NotImplemented) {
     999        Py_DECREF(result);
     1000        return binop_type_error(v, w, op_name);
     1001    }
     1002    return result;
    9751003}
    9761004
     
    9811009  *** In some cases, w.op is called before v.op; see binary_op1. ***
    9821010
    983   v     w       z       Action
     1011  v     w       z       Action
    9841012  -------------------------------------------------------------------
    985   new   new     new     v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
    986   new   old     new     v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
    987   old   new     new     w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
    988   old   old     new     z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
    989   new   new     old     v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
    990   new   old     old     v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
    991   old   new     old     w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
    992   old   old     old     coerce(v,w,z), v.op(v,w,z)
     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)
    9931021
    9941022  Legend:
     
    10061034static PyObject *
    10071035ternary_op(PyObject *v,
    1008            PyObject *w,
    1009            PyObject *z,
    1010            const int op_slot,
    1011            const char *op_name)
    1012 {
    1013         PyNumberMethods *mv, *mw, *mz;
    1014         PyObject *x = NULL;
    1015         ternaryfunc slotv = NULL;
    1016         ternaryfunc slotw = NULL;
    1017         ternaryfunc slotz = NULL;
    1018 
    1019         mv = v->ob_type->tp_as_number;
    1020         mw = w->ob_type->tp_as_number;
    1021         if (mv != NULL && NEW_STYLE_NUMBER(v))
    1022                 slotv = NB_TERNOP(mv, op_slot);
    1023         if (w->ob_type != v->ob_type &&
    1024             mw != NULL && NEW_STYLE_NUMBER(w)) {
    1025                 slotw = NB_TERNOP(mw, op_slot);
    1026                 if (slotw == slotv)
    1027                         slotw = NULL;
    1028         }
    1029         if (slotv) {
    1030                 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
    1031                         x = slotw(v, w, z);
    1032                         if (x != Py_NotImplemented)
    1033                                 return x;
    1034                         Py_DECREF(x); /* can't do it */
    1035                         slotw = NULL;
    1036                 }
    1037                 x = slotv(v, w, z);
    1038                 if (x != Py_NotImplemented)
    1039                         return x;
    1040                 Py_DECREF(x); /* can't do it */
    1041         }
    1042         if (slotw) {
    1043                 x = slotw(v, w, z);
    1044                 if (x != Py_NotImplemented)
    1045                         return x;
    1046                 Py_DECREF(x); /* can't do it */
    1047         }
    1048         mz = z->ob_type->tp_as_number;
    1049         if (mz != NULL && NEW_STYLE_NUMBER(z)) {
    1050                 slotz = NB_TERNOP(mz, op_slot);
    1051                 if (slotz == slotv || slotz == slotw)
    1052                         slotz = NULL;
    1053                 if (slotz) {
    1054                         x = slotz(v, w, z);
    1055                         if (x != Py_NotImplemented)
    1056                                 return x;
    1057                         Py_DECREF(x); /* can't do it */
    1058                 }
    1059         }
    1060 
    1061         if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w) ||
    1062                         (z != Py_None && !NEW_STYLE_NUMBER(z))) {
    1063                 /* we have an old style operand, coerce */
    1064                 PyObject *v1, *z1, *w2, *z2;
    1065                 int c;
    1066 
    1067                 c = PyNumber_Coerce(&v, &w);
    1068                 if (c != 0)
    1069                         goto error3;
    1070 
    1071                 /* Special case: if the third argument is None, it is
    1072                    treated as absent argument and not coerced. */
    1073                 if (z == Py_None) {
    1074                         if (v->ob_type->tp_as_number) {
    1075                                 slotz = NB_TERNOP(v->ob_type->tp_as_number,
    1076                                                   op_slot);
    1077                                 if (slotz)
    1078                                         x = slotz(v, w, z);
    1079                                 else
    1080                                         c = -1;
    1081                         }
    1082                         else
    1083                                 c = -1;
    1084                         goto error2;
    1085                 }
    1086                 v1 = v;
    1087                 z1 = z;
    1088                 c = PyNumber_Coerce(&v1, &z1);
    1089                 if (c != 0)
    1090                         goto error2;
    1091                 w2 = w;
    1092                 z2 = z1;
    1093                 c = PyNumber_Coerce(&w2, &z2);
    1094                 if (c != 0)
    1095                         goto error1;
    1096 
    1097                 if (v1->ob_type->tp_as_number != NULL) {
    1098                         slotv = NB_TERNOP(v1->ob_type->tp_as_number,
    1099                                           op_slot);
    1100                         if (slotv)
    1101                                 x = slotv(v1, w2, z2);
    1102                         else
    1103                                 c = -1;
    1104                 }
    1105                 else
    1106                         c = -1;
    1107 
    1108                 Py_DECREF(w2);
    1109                 Py_DECREF(z2);
    1110         error1:
    1111                 Py_DECREF(v1);
    1112                 Py_DECREF(z1);
    1113         error2:
    1114                 Py_DECREF(v);
    1115                 Py_DECREF(w);
    1116         error3:
    1117                 if (c >= 0)
    1118                         return x;
    1119         }
    1120 
    1121         if (z == Py_None)
    1122                 PyErr_Format(
    1123                         PyExc_TypeError,
    1124                         "unsupported operand type(s) for ** or pow(): "
    1125                         "'%.100s' and '%.100s'",
    1126                         v->ob_type->tp_name,
    1127                         w->ob_type->tp_name);
    1128         else
    1129                 PyErr_Format(
    1130                         PyExc_TypeError,
    1131                         "unsupported operand type(s) for pow(): "
    1132                         "'%.100s', '%.100s', '%.100s'",
    1133                         v->ob_type->tp_name,
    1134                         w->ob_type->tp_name,
    1135                         z->ob_type->tp_name);
    1136         return NULL;
     1036           PyObject *w,
     1037           PyObject *z,
     1038           const int op_slot,
     1039           const char *op_name)
     1040{
     1041    PyNumberMethods *mv, *mw, *mz;
     1042    PyObject *x = NULL;
     1043    ternaryfunc slotv = NULL;
     1044    ternaryfunc slotw = NULL;
     1045    ternaryfunc slotz = NULL;
     1046
     1047    mv = v->ob_type->tp_as_number;
     1048    mw = w->ob_type->tp_as_number;
     1049    if (mv != NULL && NEW_STYLE_NUMBER(v))
     1050        slotv = NB_TERNOP(mv, op_slot);
     1051    if (w->ob_type != v->ob_type &&
     1052        mw != NULL && NEW_STYLE_NUMBER(w)) {
     1053        slotw = NB_TERNOP(mw, op_slot);
     1054        if (slotw == slotv)
     1055            slotw = NULL;
     1056    }
     1057    if (slotv) {
     1058        if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
     1059            x = slotw(v, w, z);
     1060            if (x != Py_NotImplemented)
     1061                return x;
     1062            Py_DECREF(x); /* can't do it */
     1063            slotw = NULL;
     1064        }
     1065        x = slotv(v, w, z);
     1066        if (x != Py_NotImplemented)
     1067            return x;
     1068        Py_DECREF(x); /* can't do it */
     1069    }
     1070    if (slotw) {
     1071        x = slotw(v, w, z);
     1072        if (x != Py_NotImplemented)
     1073            return x;
     1074        Py_DECREF(x); /* can't do it */
     1075    }
     1076    mz = z->ob_type->tp_as_number;
     1077    if (mz != NULL && NEW_STYLE_NUMBER(z)) {
     1078        slotz = NB_TERNOP(mz, op_slot);
     1079        if (slotz == slotv || slotz == slotw)
     1080            slotz = NULL;
     1081        if (slotz) {
     1082            x = slotz(v, w, z);
     1083            if (x != Py_NotImplemented)
     1084                return x;
     1085            Py_DECREF(x); /* can't do it */
     1086        }
     1087    }
     1088
     1089    if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w) ||
     1090                    (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        c = PyNumber_Coerce(&v, &w);
     1096        if (c != 0)
     1097            goto error3;
     1098
     1099        /* Special case: if the third argument is None, it is
     1100           treated as absent argument and not coerced. */
     1101        if (z == Py_None) {
     1102            if (v->ob_type->tp_as_number) {
     1103                slotz = NB_TERNOP(v->ob_type->tp_as_number,
     1104                                  op_slot);
     1105                if (slotz)
     1106                    x = slotz(v, w, z);
     1107                else
     1108                    c = -1;
     1109            }
     1110            else
     1111                c = -1;
     1112            goto error2;
     1113        }
     1114        v1 = v;
     1115        z1 = z;
     1116        c = PyNumber_Coerce(&v1, &z1);
     1117        if (c != 0)
     1118            goto error2;
     1119        w2 = w;
     1120        z2 = z1;
     1121        c = PyNumber_Coerce(&w2, &z2);
     1122        if (c != 0)
     1123            goto error1;
     1124
     1125        if (v1->ob_type->tp_as_number != NULL) {
     1126            slotv = NB_TERNOP(v1->ob_type->tp_as_number,
     1127                              op_slot);
     1128            if (slotv)
     1129                x = slotv(v1, w2, z2);
     1130            else
     1131                c = -1;
     1132        }
     1133        else
     1134            c = -1;
     1135
     1136        Py_DECREF(w2);
     1137        Py_DECREF(z2);
     1138    error1:
     1139        Py_DECREF(v1);
     1140        Py_DECREF(z1);
     1141    error2:
     1142        Py_DECREF(v);
     1143        Py_DECREF(w);
     1144    error3:
     1145        if (c >= 0)
     1146            return x;
     1147    }
     1148
     1149    if (z == Py_None)
     1150        PyErr_Format(
     1151            PyExc_TypeError,
     1152            "unsupported operand type(s) for ** or pow(): "
     1153            "'%.100s' and '%.100s'",
     1154            v->ob_type->tp_name,
     1155            w->ob_type->tp_name);
     1156    else
     1157        PyErr_Format(
     1158            PyExc_TypeError,
     1159            "unsupported operand type(s) for pow(): "
     1160            "'%.100s', '%.100s', '%.100s'",
     1161            v->ob_type->tp_name,
     1162            w->ob_type->tp_name,
     1163            z->ob_type->tp_name);
     1164    return NULL;
    11371165}
    11381166
     
    11401168    PyObject * \
    11411169    func(PyObject *v, PyObject *w) { \
    1142             return binary_op(v, w, NB_SLOT(op), op_name); \
     1170        return binary_op(v, w, NB_SLOT(op), op_name); \
    11431171    }
    11441172
     
    11551183PyNumber_Add(PyObject *v, PyObject *w)
    11561184{
    1157         PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
    1158         if (result == Py_NotImplemented) {
    1159                 PySequenceMethods *m = v->ob_type->tp_as_sequence;
    1160                 Py_DECREF(result);
    1161                 if (m && m->sq_concat) {
    1162                         return (*m->sq_concat)(v, w);
    1163                 }
    1164                 result = binop_type_error(v, w, "+");
    1165         }
    1166         return result;
     1185    PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
     1186    if (result == Py_NotImplemented) {
     1187        PySequenceMethods *m = v->ob_type->tp_as_sequence;
     1188        Py_DECREF(result);
     1189        if (m && m->sq_concat) {
     1190            return (*m->sq_concat)(v, w);
     1191        }
     1192        result = binop_type_error(v, w, "+");
     1193    }
     1194    return result;
    11671195}
    11681196
     
    11701198sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
    11711199{
    1172         Py_ssize_t count;
    1173         if (PyIndex_Check(n)) {
    1174                 count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
    1175                 if (count == -1 && PyErr_Occurred())
    1176                         return NULL;
    1177         }
    1178         else {
    1179                 return type_error("can't multiply sequence by "
    1180                                   "non-int of type '%.200s'", n);
    1181         }
    1182         return (*repeatfunc)(seq, count);
     1200    Py_ssize_t count;
     1201    if (PyIndex_Check(n)) {
     1202        count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
     1203        if (count == -1 && PyErr_Occurred())
     1204            return NULL;
     1205    }
     1206    else {
     1207        return type_error("can't multiply sequence by "
     1208                          "non-int of type '%.200s'", n);
     1209    }
     1210    return (*repeatfunc)(seq, count);
    11831211}
    11841212
     
    11861214PyNumber_Multiply(PyObject *v, PyObject *w)
    11871215{
    1188         PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
    1189         if (result == Py_NotImplemented) {
    1190                 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
    1191                 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
    1192                 Py_DECREF(result);
    1193                 if  (mv && mv->sq_repeat) {
    1194                         return sequence_repeat(mv->sq_repeat, v, w);
    1195                 }
    1196                 else if (mw && mw->sq_repeat) {
    1197                         return sequence_repeat(mw->sq_repeat, w, v);
    1198                 }
    1199                 result = binop_type_error(v, w, "*");
    1200         }
    1201         return result;
     1216    PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
     1217    if (result == Py_NotImplemented) {
     1218        PySequenceMethods *mv = v->ob_type->tp_as_sequence;
     1219        PySequenceMethods *mw = w->ob_type->tp_as_sequence;
     1220        Py_DECREF(result);
     1221        if  (mv && mv->sq_repeat) {
     1222            return sequence_repeat(mv->sq_repeat, v, w);
     1223        }
     1224        else if (mw && mw->sq_repeat) {
     1225            return sequence_repeat(mw->sq_repeat, w, v);
     1226        }
     1227        result = binop_type_error(v, w, "*");
     1228    }
     1229    return result;
    12021230}
    12031231
     
    12051233PyNumber_FloorDivide(PyObject *v, PyObject *w)
    12061234{
    1207         /* XXX tp_flags test */
    1208         return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
     1235    /* XXX tp_flags test */
     1236    return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
    12091237}
    12101238
     
    12121240PyNumber_TrueDivide(PyObject *v, PyObject *w)
    12131241{
    1214         /* XXX tp_flags test */
    1215         return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
     1242    /* XXX tp_flags test */
     1243    return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
    12161244}
    12171245
     
    12191247PyNumber_Remainder(PyObject *v, PyObject *w)
    12201248{
    1221         return binary_op(v, w, NB_SLOT(nb_remainder), "%");
     1249    return binary_op(v, w, NB_SLOT(nb_remainder), "%");
    12221250}
    12231251
     
    12251253PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
    12261254{
    1227         return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
     1255    return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
    12281256}
    12291257
     
    12451273
    12461274#define HASINPLACE(t) \
    1247         PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
     1275    PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
    12481276
    12491277static PyObject *
    12501278binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)
    12511279{
    1252         PyNumberMethods *mv = v->ob_type->tp_as_number;
    1253         if (mv != NULL && HASINPLACE(v)) {
    1254                 binaryfunc slot = NB_BINOP(mv, iop_slot);
    1255                 if (slot) {
    1256                         PyObject *x = (slot)(v, w);
    1257                         if (x != Py_NotImplemented) {
    1258                                 return x;
    1259                         }
    1260                         Py_DECREF(x);
    1261                 }
    1262         }
    1263         return binary_op1(v, w, op_slot);
     1280    PyNumberMethods *mv = v->ob_type->tp_as_number;
     1281    if (mv != NULL && HASINPLACE(v)) {
     1282        binaryfunc slot = NB_BINOP(mv, iop_slot);
     1283        if (slot) {
     1284            PyObject *x = (slot)(v, w);
     1285            if (x != Py_NotImplemented) {
     1286                return x;
     1287            }
     1288            Py_DECREF(x);
     1289        }
     1290    }
     1291    return binary_op1(v, w, op_slot);
    12641292}
    12651293
    12661294static PyObject *
    12671295binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
    1268                 const char *op_name)
    1269 {
    1270         PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
    1271         if (result == Py_NotImplemented) {
    1272                 Py_DECREF(result);
    1273                 return binop_type_error(v, w, op_name);
    1274         }
    1275         return result;
     1296                const char *op_name)
     1297{
     1298    PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
     1299    if (result == Py_NotImplemented) {
     1300        Py_DECREF(result);
     1301        return binop_type_error(v, w, op_name);
     1302    }
     1303    return result;
    12761304}
    12771305
    12781306#define INPLACE_BINOP(func, iop, op, op_name) \
    1279         PyObject * \
    1280         func(PyObject *v, PyObject *w) { \
    1281                 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
    1282         }
     1307    PyObject * \
     1308    func(PyObject *v, PyObject *w) { \
     1309        return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
     1310    }
    12831311
    12841312INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
     
    12931321PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
    12941322{
    1295         /* XXX tp_flags test */
    1296         return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
    1297                           NB_SLOT(nb_floor_divide), "//=");
     1323    /* XXX tp_flags test */
     1324    return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
     1325                      NB_SLOT(nb_floor_divide), "//=");
    12981326}
    12991327
     
    13011329PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
    13021330{
    1303         /* XXX tp_flags test */
    1304         return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
    1305                           NB_SLOT(nb_true_divide), "/=");
     1331    /* XXX tp_flags test */
     1332    return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
     1333                      NB_SLOT(nb_true_divide), "/=");
    13061334}
    13071335
     
    13091337PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
    13101338{
    1311         PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
    1312                                        NB_SLOT(nb_add));
    1313         if (result == Py_NotImplemented) {
    1314                 PySequenceMethods *m = v->ob_type->tp_as_sequence;
    1315                 Py_DECREF(result);
    1316                 if (m != NULL) {
    1317                         binaryfunc f = NULL;
    1318                         if (HASINPLACE(v))
    1319                                 f = m->sq_inplace_concat;
    1320                         if (f == NULL)
    1321                                 f = m->sq_concat;
    1322                         if (f != NULL)
    1323                                 return (*f)(v, w);
    1324                 }
    1325                 result = binop_type_error(v, w, "+=");
    1326         }
    1327         return result;
     1339    PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
     1340                                   NB_SLOT(nb_add));
     1341    if (result == Py_NotImplemented) {
     1342        PySequenceMethods *m = v->ob_type->tp_as_sequence;
     1343        Py_DECREF(result);
     1344        if (m != NULL) {
     1345            binaryfunc f = NULL;
     1346            if (HASINPLACE(v))
     1347                f = m->sq_inplace_concat;
     1348            if (f == NULL)
     1349                f = m->sq_concat;
     1350            if (f != NULL)
     1351                return (*f)(v, w);
     1352        }
     1353        result = binop_type_error(v, w, "+=");
     1354    }
     1355    return result;
    13281356}
    13291357
     
    13311359PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
    13321360{
    1333         PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
    1334                                        NB_SLOT(nb_multiply));
    1335         if (result == Py_NotImplemented) {
    1336                 ssizeargfunc f = NULL;
    1337                 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
    1338                 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
    1339                 Py_DECREF(result);
    1340                 if (mv != NULL) {
    1341                         if (HASINPLACE(v))
    1342                                 f = mv->sq_inplace_repeat;
    1343                         if (f == NULL)
    1344                                 f = mv->sq_repeat;
    1345                         if (f != NULL)
    1346                                 return sequence_repeat(f, v, w);
    1347                 }
    1348                 else if (mw != NULL) {
    1349                         /* Note that the right hand operand should not be
    1350                         * mutated in this case so sq_inplace_repeat is not
    1351                         * used. */
    1352                         if (mw->sq_repeat)
    1353                                 return sequence_repeat(mw->sq_repeat, w, v);
    1354                 }
    1355                 result = binop_type_error(v, w, "*=");
    1356         }
    1357         return result;
     1361    PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
     1362                                   NB_SLOT(nb_multiply));
     1363    if (result == Py_NotImplemented) {
     1364        ssizeargfunc f = NULL;
     1365        PySequenceMethods *mv = v->ob_type->tp_as_sequence;
     1366        PySequenceMethods *mw = w->ob_type->tp_as_sequence;
     1367        Py_DECREF(result);
     1368        if (mv != NULL) {
     1369            if (HASINPLACE(v))
     1370                f = mv->sq_inplace_repeat;
     1371            if (f == NULL)
     1372                f = mv->sq_repeat;
     1373            if (f != NULL)
     1374                return sequence_repeat(f, v, w);
     1375        }
     1376        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            if (mw->sq_repeat)
     1381                return sequence_repeat(mw->sq_repeat, w, v);
     1382        }
     1383        result = binop_type_error(v, w, "*=");
     1384    }
     1385    return result;
    13581386}
    13591387
     
    13611389PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
    13621390{
    1363         return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
    1364                                 NB_SLOT(nb_remainder), "%=");
     1391    return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
     1392                            NB_SLOT(nb_remainder), "%=");
    13651393}
    13661394
     
    13681396PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
    13691397{
    1370         if (HASINPLACE(v) && v->ob_type->tp_as_number &&
    1371             v->ob_type->tp_as_number->nb_inplace_power != NULL) {
    1372                 return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
    1373         }
    1374         else {
    1375                 return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
    1376         }
     1398    if (HASINPLACE(v) && v->ob_type->tp_as_number &&
     1399        v->ob_type->tp_as_number->nb_inplace_power != NULL) {
     1400        return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
     1401    }
     1402    else {
     1403        return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
     1404    }
    13771405}
    13781406
     
    13831411PyNumber_Negative(PyObject *o)
    13841412{
    1385         PyNumberMethods *m;
    1386 
    1387         if (o == NULL)
    1388                 return null_error();
    1389         m = o->ob_type->tp_as_number;
    1390         if (m && m->nb_negative)
    1391                 return (*m->nb_negative)(o);
    1392 
    1393         return type_error("bad operand type for unary -: '%.200s'", o);
     1413    PyNumberMethods *m;
     1414
     1415    if (o == NULL)
     1416        return null_error();
     1417    m = o->ob_type->tp_as_number;
     1418    if (m && m->nb_negative)
     1419        return (*m->nb_negative)(o);
     1420
     1421    return type_error("bad operand type for unary -: '%.200s'", o);
    13941422}
    13951423
     
    13971425PyNumber_Positive(PyObject *o)
    13981426{
    1399         PyNumberMethods *m;
    1400 
    1401         if (o == NULL)
    1402                 return null_error();
    1403         m = o->ob_type->tp_as_number;
    1404         if (m && m->nb_positive)
    1405                 return (*m->nb_positive)(o);
    1406 
    1407         return type_error("bad operand type for unary +: '%.200s'", o);
     1427    PyNumberMethods *m;
     1428
     1429    if (o == NULL)
     1430        return null_error();
     1431    m = o->ob_type->tp_as_number;
     1432    if (m && m->nb_positive)
     1433        return (*m->nb_positive)(o);
     1434
     1435    return type_error("bad operand type for unary +: '%.200s'", o);
    14081436}
    14091437
     
    14111439PyNumber_Invert(PyObject *o)
    14121440{
    1413         PyNumberMethods *m;
    1414 
    1415         if (o == NULL)
    1416                 return null_error();
    1417         m = o->ob_type->tp_as_number;
    1418         if (m && m->nb_invert)
    1419                 return (*m->nb_invert)(o);
    1420 
    1421         return type_error("bad operand type for unary ~: '%.200s'", o);
     1441    PyNumberMethods *m;
     1442
     1443    if (o == NULL)
     1444        return null_error();
     1445    m = o->ob_type->tp_as_number;
     1446    if (m && m->nb_invert)
     1447        return (*m->nb_invert)(o);
     1448
     1449    return type_error("bad operand type for unary ~: '%.200s'", o);
    14221450}
    14231451
     
    14251453PyNumber_Absolute(PyObject *o)
    14261454{
    1427         PyNumberMethods *m;
    1428 
    1429         if (o == NULL)
    1430                 return null_error();
    1431         m = o->ob_type->tp_as_number;
    1432         if (m && m->nb_absolute)
    1433                 return m->nb_absolute(o);
    1434 
    1435         return type_error("bad operand type for abs(): '%.200s'", o);
     1455    PyNumberMethods *m;
     1456
     1457    if (o == NULL)
     1458        return null_error();
     1459    m = o->ob_type->tp_as_number;
     1460    if (m && m->nb_absolute)
     1461        return m->nb_absolute(o);
     1462
     1463    return type_error("bad operand type for abs(): '%.200s'", o);
    14361464}
    14371465
     
    14401468int_from_string(const char *s, Py_ssize_t len)
    14411469{
    1442         char *end;
    1443         PyObject *x;
    1444 
    1445         x = PyInt_FromString((char*)s, &end, 10);
    1446         if (x == NULL)
    1447                 return NULL;
    1448         if (end != s + len) {
    1449                 PyErr_SetString(PyExc_ValueError,
    1450                                 "null byte in argument for int()");
    1451                 Py_DECREF(x);
    1452                 return NULL;
    1453         }
    1454         return x;
    1455 }
    1456 
    1457 /* Return a Python Int or Long from the object item 
     1470    char *end;
     1471    PyObject *x;
     1472
     1473    x = PyInt_FromString((char*)s, &end, 10);
     1474    if (x == NULL)
     1475        return NULL;
     1476    if (end != s + len) {
     1477        PyErr_SetString(PyExc_ValueError,
     1478                        "null byte in argument for int()");
     1479        Py_DECREF(x);
     1480        return NULL;
     1481    }
     1482    return x;
     1483}
     1484
     1485/* Return a Python Int or Long from the object item
    14581486   Raise TypeError if the result is not an int-or-long
    1459    or if the object cannot be interpreted as an index. 
     1487   or if the object cannot be interpreted as an index.
    14601488*/
    14611489PyObject *
    14621490PyNumber_Index(PyObject *item)
    14631491{
    1464         PyObject *result = NULL;
    1465         if (item == NULL)
    1466                 return null_error();
    1467         if (PyInt_Check(item) || PyLong_Check(item)) {
    1468                 Py_INCREF(item);
    1469                 return item;
    1470         }
    1471         if (PyIndex_Check(item)) {
    1472                 result = item->ob_type->tp_as_number->nb_index(item);
    1473                 if (result &&
    1474                     !PyInt_Check(result) && !PyLong_Check(result)) {
    1475                         PyErr_Format(PyExc_TypeError,
    1476                                      "__index__ returned non-(int,long) " \
    1477                                      "(type %.200s)",
    1478                                      result->ob_type->tp_name);
    1479                         Py_DECREF(result);
    1480                         return NULL;
    1481                 }
    1482         }
    1483         else {
    1484                 PyErr_Format(PyExc_TypeError,
    1485                              "'%.200s' object cannot be interpreted "
    1486                              "as an index", item->ob_type->tp_name);
    1487         }
    1488         return result;
     1492    PyObject *result = NULL;
     1493    if (item == NULL)
     1494        return null_error();
     1495    if (PyInt_Check(item) || PyLong_Check(item)) {
     1496        Py_INCREF(item);
     1497        return item;
     1498    }
     1499    if (PyIndex_Check(item)) {
     1500        result = item->ob_type->tp_as_number->nb_index(item);
     1501        if (result &&
     1502            !PyInt_Check(result) && !PyLong_Check(result)) {
     1503            PyErr_Format(PyExc_TypeError,
     1504                         "__index__ returned non-(int,long) " \
     1505                         "(type %.200s)",
     1506                         result->ob_type->tp_name);
     1507            Py_DECREF(result);
     1508            return NULL;
     1509        }
     1510    }
     1511    else {
     1512        PyErr_Format(PyExc_TypeError,
     1513                     "'%.200s' object cannot be interpreted "
     1514                     "as an index", item->ob_type->tp_name);
     1515    }
     1516    return result;
    14891517}
    14901518
     
    14941522PyNumber_AsSsize_t(PyObject *item, PyObject *err)
    14951523{
    1496         Py_ssize_t result;
    1497         PyObject *runerr;
    1498         PyObject *value = PyNumber_Index(item);
    1499         if (value == NULL)
    1500                 return -1;
    1501 
    1502         /* We're done if PyInt_AsSsize_t() returns without error. */
    1503         result = PyInt_AsSsize_t(value);
    1504         if (result != -1 || !(runerr = PyErr_Occurred()))
    1505                 goto finish;
    1506 
    1507         /* Error handling code -- only manage OverflowError differently */
    1508         if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
    1509                 goto finish;
    1510 
    1511         PyErr_Clear();
    1512         /* If no error-handling desired then the default clipping
    1513            is sufficient.
    1514         */
    1515         if (!err) {
    1516                 assert(PyLong_Check(value));
    1517                 /* Whether or not it is less than or equal to
    1518                    zero is determined by the sign of ob_size
    1519                 */
    1520                 if (_PyLong_Sign(value) < 0)
    1521                         result = PY_SSIZE_T_MIN;
    1522                 else
    1523                         result = PY_SSIZE_T_MAX;
    1524         }
    1525         else {
    1526                 /* Otherwise replace the error with caller's error object. */
    1527                 PyErr_Format(err,
    1528                              "cannot fit '%.200s' into an index-sized integer",
    1529                              item->ob_type->tp_name);
    1530         }
    1531        
     1524    Py_ssize_t result;
     1525    PyObject *runerr;
     1526    PyObject *value = PyNumber_Index(item);
     1527    if (value == NULL)
     1528        return -1;
     1529
     1530    /* We're done if PyInt_AsSsize_t() returns without error. */
     1531    result = PyInt_AsSsize_t(value);
     1532    if (result != -1 || !(runerr = PyErr_Occurred()))
     1533        goto finish;
     1534
     1535    /* Error handling code -- only manage OverflowError differently */
     1536    if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
     1537        goto finish;
     1538
     1539    PyErr_Clear();
     1540    /* If no error-handling desired then the default clipping
     1541       is sufficient.
     1542    */
     1543    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        if (_PyLong_Sign(value) < 0)
     1549            result = PY_SSIZE_T_MIN;
     1550        else
     1551            result = PY_SSIZE_T_MAX;
     1552    }
     1553    else {
     1554        /* Otherwise replace the error with caller's error object. */
     1555        PyErr_Format(err,
     1556                     "cannot fit '%.200s' into an index-sized integer",
     1557                     item->ob_type->tp_name);
     1558    }
     1559
    15321560 finish:
    1533         Py_DECREF(value);
    1534         return result;
     1561    Py_DECREF(value);
     1562    return result;
    15351563}
    15361564
     
    15391567_PyNumber_ConvertIntegralToInt(PyObject *integral, const char* error_format)
    15401568{
    1541         const char *type_name;
    1542         static PyObject *int_name = NULL;
    1543         if (int_name == NULL) {
    1544                 int_name = PyString_InternFromString("__int__");
    1545                 if (int_name == NULL)
    1546                         return NULL;
    1547         }
    1548 
    1549         if (integral && (!PyInt_Check(integral) &&
    1550                         !PyLong_Check(integral))) {
    1551                 /* Don't go through tp_as_number->nb_int to avoid
    1552                    hitting the classic class fallback to __trunc__. */
    1553                 PyObject *int_func = PyObject_GetAttr(integral, int_name);
    1554                 if (int_func == NULL) {
    1555                         PyErr_Clear(); /* Raise a different error. */
    1556                         goto non_integral_error;
    1557                 }
    1558                 Py_DECREF(integral);
    1559                 integral = PyEval_CallObject(int_func, NULL);
    1560                 Py_DECREF(int_func);
    1561                 if (integral && (!PyInt_Check(integral) &&
    1562                                   !PyLong_Check(integral))) {
    1563                         goto non_integral_error;
    1564                 }
    1565         }
    1566         return integral;
     1569    const char *type_name;
     1570    static PyObject *int_name = NULL;
     1571    if (int_name == NULL) {
     1572        int_name = PyString_InternFromString("__int__");
     1573        if (int_name == NULL)
     1574            return NULL;
     1575    }
     1576
     1577    if (integral && (!PyInt_Check(integral) &&
     1578                    !PyLong_Check(integral))) {
     1579        /* Don't go through tp_as_number->nb_int to avoid
     1580           hitting the classic class fallback to __trunc__. */
     1581        PyObject *int_func = PyObject_GetAttr(integral, int_name);
     1582        if (int_func == NULL) {
     1583            PyErr_Clear(); /* Raise a different error. */
     1584            goto non_integral_error;
     1585        }
     1586        Py_DECREF(integral);
     1587        integral = PyEval_CallObject(int_func, NULL);
     1588        Py_DECREF(int_func);
     1589        if (integral && (!PyInt_Check(integral) &&
     1590                          !PyLong_Check(integral))) {
     1591            goto non_integral_error;
     1592        }
     1593    }
     1594    return integral;
    15671595
    15681596non_integral_error:
    1569         if (PyInstance_Check(integral)) {
    1570                 type_name = PyString_AS_STRING(((PyInstanceObject *)integral)
    1571                                                ->in_class->cl_name);
    1572         }
    1573         else {
    1574                 type_name = integral->ob_type->tp_name;
    1575         }
    1576         PyErr_Format(PyExc_TypeError, error_format, type_name);
    1577         Py_DECREF(integral);
    1578         return NULL;
     1597    if (PyInstance_Check(integral)) {
     1598        type_name = PyString_AS_STRING(((PyInstanceObject *)integral)
     1599                                       ->in_class->cl_name);
     1600    }
     1601    else {
     1602        type_name = integral->ob_type->tp_name;
     1603    }
     1604    PyErr_Format(PyExc_TypeError, error_format, type_name);
     1605    Py_DECREF(integral);
     1606    return NULL;
    15791607}
    15801608
     
    15831611PyNumber_Int(PyObject *o)
    15841612{
    1585         PyNumberMethods *m;
    1586         static PyObject *trunc_name = NULL;
    1587         PyObject *trunc_func;
    1588         const char *buffer;
    1589         Py_ssize_t buffer_len;
    1590 
    1591         if (trunc_name == NULL) {
    1592                 trunc_name = PyString_InternFromString("__trunc__");
    1593                 if (trunc_name == NULL)
    1594                         return NULL;
    1595         }
    1596 
    1597         if (o == NULL)
    1598                 return null_error();
    1599         if (PyInt_CheckExact(o)) {
    1600                 Py_INCREF(o);
    1601                 return o;
    1602         }
    1603         m = o->ob_type->tp_as_number;
    1604         if (m && m->nb_int) { /* This should include subclasses of int */
    1605                 /* Classic classes always take this branch. */
    1606                 PyObject *res = m->nb_int(o);
    1607                 if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
    1608                         PyErr_Format(PyExc_TypeError,
    1609                                      "__int__ returned non-int (type %.200s)",
    1610                                      res->ob_type->tp_name);
    1611                         Py_DECREF(res);
    1612                         return NULL;
    1613                 }
    1614                 return res;
    1615         }
    1616         if (PyInt_Check(o)) { /* A int subclass without nb_int */
    1617                 PyIntObject *io = (PyIntObject*)o;
    1618                 return PyInt_FromLong(io->ob_ival);
    1619         }
    1620         trunc_func = PyObject_GetAttr(o, trunc_name);
    1621         if (trunc_func) {
    1622                 PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
    1623                 Py_DECREF(trunc_func);
    1624                 /* __trunc__ is specified to return an Integral type, but
    1625                    int() needs to return an int. */
    1626                 return _PyNumber_ConvertIntegralToInt(
    1627                         truncated,
    1628                         "__trunc__ returned non-Integral (type %.200s)");
    1629         }
    1630         PyErr_Clear();  /* It's not an error if  o.__trunc__ doesn't exist. */
    1631 
    1632         if (PyString_Check(o))
    1633                 return int_from_string(PyString_AS_STRING(o),
    1634                                        PyString_GET_SIZE(o));
     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    if (trunc_name == NULL) {
     1620        trunc_name = PyString_InternFromString("__trunc__");
     1621        if (trunc_name == NULL)
     1622            return NULL;
     1623    }
     1624
     1625    if (o == NULL)
     1626        return null_error();
     1627    if (PyInt_CheckExact(o)) {
     1628        Py_INCREF(o);
     1629        return o;
     1630    }
     1631    m = o->ob_type->tp_as_number;
     1632    if (m && m->nb_int) { /* This should include subclasses of int */
     1633        /* Classic classes always take this branch. */
     1634        PyObject *res = m->nb_int(o);
     1635        if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
     1636            PyErr_Format(PyExc_TypeError,
     1637                         "__int__ returned non-int (type %.200s)",
     1638                         res->ob_type->tp_name);
     1639            Py_DECREF(res);
     1640            return NULL;
     1641        }
     1642        return res;
     1643    }
     1644    if (PyInt_Check(o)) { /* A int subclass without nb_int */
     1645        PyIntObject *io = (PyIntObject*)o;
     1646        return PyInt_FromLong(io->ob_ival);
     1647    }
     1648    trunc_func = PyObject_GetAttr(o, trunc_name);
     1649    if (trunc_func) {
     1650        PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
     1651        Py_DECREF(trunc_func);
     1652        /* __trunc__ is specified to return an Integral type, but
     1653           int() needs to return an int. */
     1654        return _PyNumber_ConvertIntegralToInt(
     1655            truncated,
     1656            "__trunc__ returned non-Integral (type %.200s)");
     1657    }
     1658    PyErr_Clear();  /* It's not an error if  o.__trunc__ doesn't exist. */
     1659
     1660    if (PyString_Check(o))
     1661        return int_from_string(PyString_AS_STRING(o),
     1662                               PyString_GET_SIZE(o));
    16351663#ifdef Py_USING_UNICODE
    1636         if (PyUnicode_Check(o))
    1637                 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o),
    1638                                         PyUnicode_GET_SIZE(o),
    1639                                         10);
     1664    if (PyUnicode_Check(o))
     1665        return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o),
     1666                                PyUnicode_GET_SIZE(o),
     1667                                10);
    16401668#endif
    1641         if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
    1642                 return int_from_string((char*)buffer, buffer_len);
    1643 
    1644         return type_error("int() argument must be a string or a "
    1645                           "number, not '%.200s'", o);
     1669    if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
     1670        return int_from_string((char*)buffer, buffer_len);
     1671
     1672    return type_error("int() argument must be a string or a "
     1673                      "number, not '%.200s'", o);
    16461674}
    16471675
     
    16501678long_from_string(const char *s, Py_ssize_t len)
    16511679{
    1652         char *end;
    1653         PyObject *x;
    1654 
    1655         x = PyLong_FromString((char*)s, &end, 10);
    1656         if (x == NULL)
    1657                 return NULL;
    1658         if (end != s + len) {
    1659                 PyErr_SetString(PyExc_ValueError,
    1660                                 "null byte in argument for long()");
    1661                 Py_DECREF(x);
    1662                 return NULL;
    1663         }
    1664         return x;
     1680    char *end;
     1681    PyObject *x;
     1682
     1683    x = PyLong_FromString((char*)s, &end, 10);
     1684    if (x == NULL)
     1685        return NULL;
     1686    if (end != s + len) {
     1687        PyErr_SetString(PyExc_ValueError,
     1688                        "null byte in argument for long()");
     1689        Py_DECREF(x);
     1690        return NULL;
     1691    }
     1692    return x;
    16651693}
    16661694
     
    16681696PyNumber_Long(PyObject *o)
    16691697{
    1670         PyNumberMethods *m;
    1671         static PyObject *trunc_name = NULL;
    1672         PyObject *trunc_func;
    1673         const char *buffer;
    1674         Py_ssize_t buffer_len;
    1675 
    1676         if (trunc_name == NULL) {
    1677                 trunc_name = PyString_InternFromString("__trunc__");
    1678                 if (trunc_name == NULL)
    1679                         return NULL;
    1680         }
    1681 
    1682         if (o == NULL)
    1683                 return null_error();
    1684         m = o->ob_type->tp_as_number;
    1685         if (m && m->nb_long) { /* This should include subclasses of long */
    1686                 /* Classic classes always take this branch. */
    1687                 PyObject *res = m->nb_long(o);
    1688                 if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
    1689                         PyErr_Format(PyExc_TypeError,
    1690                                      "__long__ returned non-long (type %.200s)",
    1691                                      res->ob_type->tp_name);
    1692                         Py_DECREF(res);
    1693                         return NULL;
    1694                 }
    1695                 return res;
    1696         }
    1697         if (PyLong_Check(o)) /* A long subclass without nb_long */
    1698                 return _PyLong_Copy((PyLongObject *)o);
    1699         trunc_func = PyObject_GetAttr(o, trunc_name);
    1700         if (trunc_func) {
    1701                 PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
    1702                 PyObject *int_instance;
    1703                 Py_DECREF(trunc_func);
    1704                 /* __trunc__ is specified to return an Integral type,
    1705                    but long() needs to return a long. */
    1706                 int_instance = _PyNumber_ConvertIntegralToInt(
    1707                         truncated,
    1708                         "__trunc__ returned non-Integral (type %.200s)");
    1709                 if (int_instance && PyInt_Check(int_instance)) {
    1710                         /* Make sure that long() returns a long instance. */
    1711                         long value = PyInt_AS_LONG(int_instance);
    1712                         Py_DECREF(int_instance);
    1713                         return PyLong_FromLong(value);
    1714                 }
    1715                 return int_instance;
    1716         }
    1717         PyErr_Clear();  /* It's not an error if  o.__trunc__ doesn't exist. */
    1718 
    1719         if (PyString_Check(o))
    1720                 /* need to do extra error checking that PyLong_FromString()
    1721                  * doesn't do.  In particular long('9.5') must raise an
    1722                  * exception, not truncate the float.
    1723                  */
    1724                 return long_from_string(PyString_AS_STRING(o),
    1725                                         PyString_GET_SIZE(o));
     1698    PyNumberMethods *m;
     1699    static PyObject *trunc_name = NULL;
     1700    PyObject *trunc_func;
     1701    const char *buffer;
     1702    Py_ssize_t buffer_len;
     1703
     1704    if (trunc_name == NULL) {
     1705        trunc_name = PyString_InternFromString("__trunc__");
     1706        if (trunc_name == NULL)
     1707            return NULL;
     1708    }
     1709
     1710    if (o == NULL)
     1711        return null_error();
     1712    m = o->ob_type->tp_as_number;
     1713    if (m && m->nb_long) { /* This should include subclasses of long */
     1714        /* Classic classes always take this branch. */
     1715        PyObject *res = m->nb_long(o);
     1716        if (res == NULL)
     1717            return NULL;
     1718        if (PyInt_Check(res)) {
     1719            long value = PyInt_AS_LONG(res);
     1720            Py_DECREF(res);
     1721            return PyLong_FromLong(value);
     1722        }
     1723        else if (!PyLong_Check(res)) {
     1724            PyErr_Format(PyExc_TypeError,
     1725                         "__long__ returned non-long (type %.200s)",
     1726                         res->ob_type->tp_name);
     1727            Py_DECREF(res);
     1728            return NULL;
     1729        }
     1730        return res;
     1731    }
     1732    if (PyLong_Check(o)) /* A long subclass without nb_long */
     1733        return _PyLong_Copy((PyLongObject *)o);
     1734    trunc_func = PyObject_GetAttr(o, trunc_name);
     1735    if (trunc_func) {
     1736        PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
     1737        PyObject *int_instance;
     1738        Py_DECREF(trunc_func);
     1739        /* __trunc__ is specified to return an Integral type,
     1740           but long() needs to return a long. */
     1741        int_instance = _PyNumber_ConvertIntegralToInt(
     1742            truncated,
     1743            "__trunc__ returned non-Integral (type %.200s)");
     1744        if (int_instance && PyInt_Check(int_instance)) {
     1745            /* Make sure that long() returns a long instance. */
     1746            long value = PyInt_AS_LONG(int_instance);
     1747            Py_DECREF(int_instance);
     1748            return PyLong_FromLong(value);
     1749        }
     1750        return int_instance;
     1751    }
     1752    PyErr_Clear();  /* It's not an error if  o.__trunc__ doesn't exist. */
     1753
     1754    if (PyString_Check(o))
     1755        /* need to do extra error checking that PyLong_FromString()
     1756         * doesn't do.  In particular long('9.5') must raise an
     1757         * exception, not truncate the float.
     1758         */
     1759        return long_from_string(PyString_AS_STRING(o),
     1760                                PyString_GET_SIZE(o));
    17261761#ifdef Py_USING_UNICODE
    1727         if (PyUnicode_Check(o))
    1728                 /* The above check is done in PyLong_FromUnicode(). */
    1729                 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o),
    1730                                           PyUnicode_GET_SIZE(o),
    1731                                           10);
     1762    if (PyUnicode_Check(o))
     1763        /* The above check is done in PyLong_FromUnicode(). */
     1764        return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o),
     1765                                  PyUnicode_GET_SIZE(o),
     1766                                  10);
    17321767#endif
    1733         if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
    1734                 return long_from_string(buffer, buffer_len);
    1735 
    1736         return type_error("long() argument must be a string or a "
    1737                           "number, not '%.200s'", o);
     1768    if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
     1769        return long_from_string(buffer, buffer_len);
     1770
     1771    return type_error("long() argument must be a string or a "
     1772                      "number, not '%.200s'", o);
    17381773}
    17391774
     
    17411776PyNumber_Float(PyObject *o)
    17421777{
    1743         PyNumberMethods *m;
    1744 
    1745         if (o == NULL)
    1746                 return null_error();
    1747         m = o->ob_type->tp_as_number;
    1748         if (m && m->nb_float) { /* This should include subclasses of float */
    1749                 PyObject *res = m->nb_float(o);
    1750                 if (res && !PyFloat_Check(res)) {
    1751                         PyErr_Format(PyExc_TypeError,
    1752                           "__float__ returned non-float (type %.200s)",
    1753                           res->ob_type->tp_name);
    1754                         Py_DECREF(res);
    1755                         return NULL;
    1756                 }
    1757                 return res;
    1758         }
    1759         if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
    1760                 PyFloatObject *po = (PyFloatObject *)o;
    1761                 return PyFloat_FromDouble(po->ob_fval);
    1762         }
    1763         return PyFloat_FromString(o, NULL);
     1778    PyNumberMethods *m;
     1779
     1780    if (o == NULL)
     1781        return null_error();
     1782    m = o->ob_type->tp_as_number;
     1783    if (m && m->nb_float) { /* This should include subclasses of float */
     1784        PyObject *res = m->nb_float(o);
     1785        if (res && !PyFloat_Check(res)) {
     1786            PyErr_Format(PyExc_TypeError,
     1787              "__float__ returned non-float (type %.200s)",
     1788              res->ob_type->tp_name);
     1789            Py_DECREF(res);
     1790            return NULL;
     1791        }
     1792        return res;
     1793    }
     1794    if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
     1795        PyFloatObject *po = (PyFloatObject *)o;
     1796        return PyFloat_FromDouble(po->ob_fval);
     1797    }
     1798    return PyFloat_FromString(o, NULL);
    17641799}
    17651800
     
    17671802PyNumber_ToBase(PyObject *n, int base)
    17681803{
    1769         PyObject *res = NULL;
    1770         PyObject *index = PyNumber_Index(n);
    1771 
    1772         if (!index)
    1773                 return NULL;
    1774         if (PyLong_Check(index))
    1775                 res = _PyLong_Format(index, base, 0, 1);
    1776         else if (PyInt_Check(index))
    1777                 res = _PyInt_Format((PyIntObject*)index, base, 1);
    1778         else
    1779                 /* It should not be possible to get here, as
    1780                    PyNumber_Index already has a check for the same
    1781                    condition */
    1782                 PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not "
    1783                                 "int or long");
    1784         Py_DECREF(index);
    1785         return res;
     1804    PyObject *res = NULL;
     1805    PyObject *index = PyNumber_Index(n);
     1806
     1807    if (!index)
     1808        return NULL;
     1809    if (PyLong_Check(index))
     1810        res = _PyLong_Format(index, base, 0, 1);
     1811    else if (PyInt_Check(index))
     1812        res = _PyInt_Format((PyIntObject*)index, base, 1);
     1813    else
     1814        /* It should not be possible to get here, as
     1815           PyNumber_Index already has a check for the same
     1816           condition */
     1817        PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not "
     1818                        "int or long");
     1819    Py_DECREF(index);
     1820    return res;
    17861821}
    17871822
     
    17921827PySequence_Check(PyObject *s)
    17931828{
    1794         if (s && PyInstance_Check(s))
    1795                 return PyObject_HasAttrString(s, "__getitem__");
    1796         if (PyObject_IsInstance(s, (PyObject *)&PyDict_Type))
    1797                 return 0;
    1798         return s != NULL && s->ob_type->tp_as_sequence &&
    1799                 s->ob_type->tp_as_sequence->sq_item != NULL;
     1829    if (s == NULL)
     1830        return 0;
     1831    if (PyInstance_Check(s))
     1832        return PyObject_HasAttrString(s, "__getitem__");
     1833    if (PyDict_Check(s))
     1834        return 0;
     1835    return  s->ob_type->tp_as_sequence &&
     1836        s->ob_type->tp_as_sequence->sq_item != NULL;
    18001837}
    18011838
     
    18031840PySequence_Size(PyObject *s)
    18041841{
    1805         PySequenceMethods *m;
    1806 
    1807         if (s == NULL) {
    1808                 null_error();
    1809                 return -1;
    1810         }
    1811 
    1812         m = s->ob_type->tp_as_sequence;
    1813         if (m && m->sq_length)
    1814                 return m->sq_length(s);
    1815 
    1816         type_error("object of type '%.200s' has no len()", s);
    1817         return -1;
     1842    PySequenceMethods *m;
     1843
     1844    if (s == NULL) {
     1845        null_error();
     1846        return -1;
     1847    }
     1848
     1849    m = s->ob_type->tp_as_sequence;
     1850    if (m && m->sq_length)
     1851        return m->sq_length(s);
     1852
     1853    type_error("object of type '%.200s' has no len()", s);
     1854    return -1;
    18181855}
    18191856
     
    18221859PySequence_Length(PyObject *s)
    18231860{
    1824         return PySequence_Size(s);
     1861    return PySequence_Size(s);
    18251862}
    18261863#define PySequence_Length PySequence_Size
     
    18291866PySequence_Concat(PyObject *s, PyObject *o)
    18301867{
    1831         PySequenceMethods *m;
    1832 
    1833         if (s == NULL || o == NULL)
    1834                 return null_error();
    1835 
    1836         m = s->ob_type->tp_as_sequence;
    1837         if (m && m->sq_concat)
    1838                 return m->sq_concat(s, o);
    1839 
    1840         /* Instances of user classes defining an __add__() method only
    1841            have an nb_add slot, not an sq_concat slot.  So we fall back
    1842            to nb_add if both arguments appear to be sequences. */
    1843         if (PySequence_Check(s) && PySequence_Check(o)) {
    1844                 PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
    1845                 if (result != Py_NotImplemented)
    1846                         return result;
    1847                 Py_DECREF(result);
    1848         }
    1849         return type_error("'%.200s' object can't be concatenated", s);
     1868    PySequenceMethods *m;
     1869
     1870    if (s == NULL || o == NULL)
     1871        return null_error();
     1872
     1873    m = s->ob_type->tp_as_sequence;
     1874    if (m && m->sq_concat)
     1875        return m->sq_concat(s, o);
     1876
     1877    /* Instances of user classes defining an __add__() method only
     1878       have an nb_add slot, not an sq_concat slot.  So we fall back
     1879       to nb_add if both arguments appear to be sequences. */
     1880    if (PySequence_Check(s) && PySequence_Check(o)) {
     1881        PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
     1882        if (result != Py_NotImplemented)
     1883            return result;
     1884        Py_DECREF(result);
     1885    }
     1886    return type_error("'%.200s' object can't be concatenated", s);
    18501887}
    18511888
     
    18531890PySequence_Repeat(PyObject *o, Py_ssize_t count)
    18541891{
    1855         PySequenceMethods *m;
    1856 
    1857         if (o == NULL)
    1858                 return null_error();
    1859 
    1860         m = o->ob_type->tp_as_sequence;
    1861         if (m && m->sq_repeat)
    1862                 return m->sq_repeat(o, count);
    1863 
    1864         /* Instances of user classes defining a __mul__() method only
    1865            have an nb_multiply slot, not an sq_repeat slot. so we fall back
    1866            to nb_multiply if o appears to be a sequence. */
    1867         if (PySequence_Check(o)) {
    1868                 PyObject *n, *result;
    1869                 n = PyInt_FromSsize_t(count);
    1870                 if (n == NULL)
    1871                         return NULL;
    1872                 result = binary_op1(o, n, NB_SLOT(nb_multiply));
    1873                 Py_DECREF(n);
    1874                 if (result != Py_NotImplemented)
    1875                         return result;
    1876                 Py_DECREF(result);
    1877         }
    1878         return type_error("'%.200s' object can't be repeated", o);
     1892    PySequenceMethods *m;
     1893
     1894    if (o == NULL)
     1895        return null_error();
     1896
     1897    m = o->ob_type->tp_as_sequence;
     1898    if (m && m->sq_repeat)
     1899        return m->sq_repeat(o, count);
     1900
     1901    /* Instances of user classes defining a __mul__() method only
     1902       have an nb_multiply slot, not an sq_repeat slot. so we fall back
     1903       to nb_multiply if o appears to be a sequence. */
     1904    if (PySequence_Check(o)) {
     1905        PyObject *n, *result;
     1906        n = PyInt_FromSsize_t(count);
     1907        if (n == NULL)
     1908            return NULL;
     1909        result = binary_op1(o, n, NB_SLOT(nb_multiply));
     1910        Py_DECREF(n);
     1911        if (result != Py_NotImplemented)
     1912            return result;
     1913        Py_DECREF(result);
     1914    }
     1915    return type_error("'%.200s' object can't be repeated", o);
    18791916}
    18801917
     
    18821919PySequence_InPlaceConcat(PyObject *s, PyObject *o)
    18831920{
    1884         PySequenceMethods *m;
    1885 
    1886         if (s == NULL || o == NULL)
    1887                 return null_error();
    1888 
    1889         m = s->ob_type->tp_as_sequence;
    1890         if (m && HASINPLACE(s) && m->sq_inplace_concat)
    1891                 return m->sq_inplace_concat(s, o);
    1892         if (m && m->sq_concat)
    1893                 return m->sq_concat(s, o);
    1894 
    1895         if (PySequence_Check(s) && PySequence_Check(o)) {
    1896                 PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
    1897                                                NB_SLOT(nb_add));
    1898                 if (result != Py_NotImplemented)
    1899                         return result;
    1900                 Py_DECREF(result);
    1901         }
    1902         return type_error("'%.200s' object can't be concatenated", s);
     1921    PySequenceMethods *m;
     1922
     1923    if (s == NULL || o == NULL)
     1924        return null_error();
     1925
     1926    m = s->ob_type->tp_as_sequence;
     1927    if (m && HASINPLACE(s) && m->sq_inplace_concat)
     1928        return m->sq_inplace_concat(s, o);
     1929    if (m && m->sq_concat)
     1930        return m->sq_concat(s, o);
     1931
     1932    if (PySequence_Check(s) && PySequence_Check(o)) {
     1933        PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
     1934                                       NB_SLOT(nb_add));
     1935        if (result != Py_NotImplemented)
     1936            return result;
     1937        Py_DECREF(result);
     1938    }
     1939    return type_error("'%.200s' object can't be concatenated", s);
    19031940}
    19041941
     
    19061943PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
    19071944{
    1908         PySequenceMethods *m;
    1909 
    1910         if (o == NULL)
    1911                 return null_error();
    1912 
    1913         m = o->ob_type->tp_as_sequence;
    1914         if (m && HASINPLACE(o) && m->sq_inplace_repeat)
    1915                 return m->sq_inplace_repeat(o, count);
    1916         if (m && m->sq_repeat)
    1917                 return m->sq_repeat(o, count);
    1918 
    1919         if (PySequence_Check(o)) {
    1920                 PyObject *n, *result;
    1921                 n = PyInt_FromSsize_t(count);
    1922                 if (n == NULL)
    1923                         return NULL;
    1924                 result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
    1925                                      NB_SLOT(nb_multiply));
    1926                 Py_DECREF(n);
    1927                 if (result != Py_NotImplemented)
    1928                         return result;
    1929                 Py_DECREF(result);
    1930         }
    1931         return type_error("'%.200s' object can't be repeated", o);
     1945    PySequenceMethods *m;
     1946
     1947    if (o == NULL)
     1948        return null_error();
     1949
     1950    m = o->ob_type->tp_as_sequence;
     1951    if (m && HASINPLACE(o) && m->sq_inplace_repeat)
     1952        return m->sq_inplace_repeat(o, count);
     1953    if (m && m->sq_repeat)
     1954        return m->sq_repeat(o, count);
     1955
     1956    if (PySequence_Check(o)) {
     1957        PyObject *n, *result;
     1958        n = PyInt_FromSsize_t(count);
     1959        if (n == NULL)
     1960            return NULL;
     1961        result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
     1962                             NB_SLOT(nb_multiply));
     1963        Py_DECREF(n);
     1964        if (result != Py_NotImplemented)
     1965            return result;
     1966        Py_DECREF(result);
     1967    }
     1968    return type_error("'%.200s' object can't be repeated", o);
    19321969}
    19331970
     
    19351972PySequence_GetItem(PyObject *s, Py_ssize_t i)
    19361973{
    1937         PySequenceMethods *m;
    1938 
    1939         if (s == NULL)
    1940                 return null_error();
    1941 
    1942         m = s->ob_type->tp_as_sequence;
    1943         if (m && m->sq_item) {
    1944                 if (i < 0) {
    1945                         if (m->sq_length) {
    1946                                 Py_ssize_t l = (*m->sq_length)(s);
    1947                                 if (l < 0)
    1948                                         return NULL;
    1949                                 i += l;
    1950                         }
    1951                 }
    1952                 return m->sq_item(s, i);
    1953         }
    1954 
    1955         return type_error("'%.200s' object does not support indexing", s);
     1974    PySequenceMethods *m;
     1975
     1976    if (s == NULL)
     1977        return null_error();
     1978
     1979    m = s->ob_type->tp_as_sequence;
     1980    if (m && m->sq_item) {
     1981        if (i < 0) {
     1982            if (m->sq_length) {
     1983                Py_ssize_t l = (*m->sq_length)(s);
     1984                if (l < 0)
     1985                    return NULL;
     1986                i += l;
     1987            }
     1988        }
     1989        return m->sq_item(s, i);
     1990    }
     1991
     1992    return type_error("'%.200s' object does not support indexing", s);
    19561993}
    19571994
     
    19591996PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
    19601997{
    1961         PySequenceMethods *m;
    1962         PyMappingMethods *mp;
    1963 
    1964         if (!s) return null_error();
    1965 
    1966         m = s->ob_type->tp_as_sequence;
    1967         if (m && m->sq_slice) {
    1968                 if (i1 < 0 || i2 < 0) {
    1969                         if (m->sq_length) {
    1970                                 Py_ssize_t l = (*m->sq_length)(s);
    1971                                 if (l < 0)
    1972                                         return NULL;
    1973                                 if (i1 < 0)
    1974                                         i1 += l;
    1975                                 if (i2 < 0)
    1976                                         i2 += l;
    1977                         }
    1978                 }
    1979                 return m->sq_slice(s, i1, i2);
    1980         } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_subscript) {
    1981                 PyObject *res;
    1982                 PyObject *slice = _PySlice_FromIndices(i1, i2);
    1983                 if (!slice)
    1984                         return NULL;
    1985                 res = mp->mp_subscript(s, slice);
    1986                 Py_DECREF(slice);
    1987                 return res;
    1988         }
    1989 
    1990         return type_error("'%.200s' object is unsliceable", s);
     1998    PySequenceMethods *m;
     1999    PyMappingMethods *mp;
     2000
     2001    if (!s) return null_error();
     2002
     2003    m = s->ob_type->tp_as_sequence;
     2004    if (m && m->sq_slice) {
     2005        if (i1 < 0 || i2 < 0) {
     2006            if (m->sq_length) {
     2007                Py_ssize_t l = (*m->sq_length)(s);
     2008                if (l < 0)
     2009                    return NULL;
     2010                if (i1 < 0)
     2011                    i1 += l;
     2012                if (i2 < 0)
     2013                    i2 += l;
     2014            }
     2015        }
     2016        return m->sq_slice(s, i1, i2);
     2017    } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_subscript) {
     2018        PyObject *res;
     2019        PyObject *slice = _PySlice_FromIndices(i1, i2);
     2020        if (!slice)
     2021            return NULL;
     2022        res = mp->mp_subscript(s, slice);
     2023        Py_DECREF(slice);
     2024        return res;
     2025    }
     2026
     2027    return type_error("'%.200s' object is unsliceable", s);
    19912028}
    19922029
     
    19942031PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
    19952032{
    1996         PySequenceMethods *m;
    1997 
    1998         if (s == NULL) {
    1999                 null_error();
    2000                 return -1;
    2001         }
    2002 
    2003         m = s->ob_type->tp_as_sequence;
    2004         if (m && m->sq_ass_item) {
    2005                 if (i < 0) {
    2006                         if (m->sq_length) {
    2007                                 Py_ssize_t l = (*m->sq_length)(s);
    2008                                 if (l < 0)
    2009                                         return -1;
    2010                                 i += l;
    2011                         }
    2012                 }
    2013                 return m->sq_ass_item(s, i, o);
    2014         }
    2015 
    2016         type_error("'%.200s' object does not support item assignment", s);
    2017         return -1;
     2033    PySequenceMethods *m;
     2034
     2035    if (s == NULL) {
     2036        null_error();
     2037        return -1;
     2038    }
     2039
     2040    m = s->ob_type->tp_as_sequence;
     2041    if (m && m->sq_ass_item) {
     2042        if (i < 0) {
     2043            if (m->sq_length) {
     2044                Py_ssize_t l = (*m->sq_length)(s);
     2045                if (l < 0)
     2046                    return -1;
     2047                i += l;
     2048            }
     2049        }
     2050        return m->sq_ass_item(s, i, o);
     2051    }
     2052
     2053    type_error("'%.200s' object does not support item assignment", s);
     2054    return -1;
    20182055}
    20192056
     
    20212058PySequence_DelItem(PyObject *s, Py_ssize_t i)
    20222059{
    2023         PySequenceMethods *m;
    2024 
    2025         if (s == NULL) {
    2026                 null_error();
    2027                 return -1;
    2028         }
    2029 
    2030         m = s->ob_type->tp_as_sequence;
    2031         if (m && m->sq_ass_item) {
    2032                 if (i < 0) {
    2033                         if (m->sq_length) {
    2034                                 Py_ssize_t l = (*m->sq_length)(s);
    2035                                 if (l < 0)
    2036                                         return -1;
    2037                                 i += l;
    2038                         }
    2039                 }
    2040                 return m->sq_ass_item(s, i, (PyObject *)NULL);
    2041         }
    2042 
    2043         type_error("'%.200s' object doesn't support item deletion", s);
    2044         return -1;
     2060    PySequenceMethods *m;
     2061
     2062    if (s == NULL) {
     2063        null_error();
     2064        return -1;
     2065    }
     2066
     2067    m = s->ob_type->tp_as_sequence;
     2068    if (m && m->sq_ass_item) {
     2069        if (i < 0) {
     2070            if (m->sq_length) {
     2071                Py_ssize_t l = (*m->sq_length)(s);
     2072                if (l < 0)
     2073                    return -1;
     2074                i += l;
     2075            }
     2076        }
     2077        return m->sq_ass_item(s, i, (PyObject *)NULL);
     2078    }
     2079
     2080    type_error("'%.200s' object doesn't support item deletion", s);
     2081    return -1;
    20452082}
    20462083
     
    20482085PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
    20492086{
    2050         PySequenceMethods *m;
    2051         PyMappingMethods *mp;
    2052 
    2053         if (s == NULL) {
    2054                 null_error();
    2055                 return -1;
    2056         }
    2057 
    2058         m = s->ob_type->tp_as_sequence;
    2059         if (m && m->sq_ass_slice) {
    2060                 if (i1 < 0 || i2 < 0) {
    2061                         if (m->sq_length) {
    2062                                 Py_ssize_t l = (*m->sq_length)(s);
    2063                                 if (l < 0)
    2064                                         return -1;
    2065                                 if (i1 < 0)
    2066                                         i1 += l;
    2067                                 if (i2 < 0)
    2068                                         i2 += l;
    2069                         }
    2070                 }
    2071                 return m->sq_ass_slice(s, i1, i2, o);
    2072         } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_ass_subscript) {
    2073                 int res;
    2074                 PyObject *slice = _PySlice_FromIndices(i1, i2);
    2075                 if (!slice)
    2076                         return -1;
    2077                 res = mp->mp_ass_subscript(s, slice, o);
    2078                 Py_DECREF(slice);
    2079                 return res;
    2080         }
    2081 
    2082         type_error("'%.200s' object doesn't support slice assignment", s);
    2083         return -1;
     2087    PySequenceMethods *m;
     2088    PyMappingMethods *mp;
     2089
     2090    if (s == NULL) {
     2091        null_error();
     2092        return -1;
     2093    }
     2094
     2095    m = s->ob_type->tp_as_sequence;
     2096    if (m && m->sq_ass_slice) {
     2097        if (i1 < 0 || i2 < 0) {
     2098            if (m->sq_length) {
     2099                Py_ssize_t l = (*m->sq_length)(s);
     2100                if (l < 0)
     2101                    return -1;
     2102                if (i1 < 0)
     2103                    i1 += l;
     2104                if (i2 < 0)
     2105                    i2 += l;
     2106            }
     2107        }
     2108        return m->sq_ass_slice(s, i1, i2, o);
     2109    } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_ass_subscript) {
     2110        int res;
     2111        PyObject *slice = _PySlice_FromIndices(i1, i2);
     2112        if (!slice)
     2113            return -1;
     2114        res = mp->mp_ass_subscript(s, slice, o);
     2115        Py_DECREF(slice);
     2116        return res;
     2117    }
     2118
     2119    type_error("'%.200s' object doesn't support slice assignment", s);
     2120    return -1;
    20842121}
    20852122
     
    20872124PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
    20882125{
    2089         PySequenceMethods *m;
    2090 
    2091         if (s == NULL) {
    2092                 null_error();
    2093                 return -1;
    2094         }
    2095 
    2096         m = s->ob_type->tp_as_sequence;
    2097         if (m && m->sq_ass_slice) {
    2098                 if (i1 < 0 || i2 < 0) {
    2099                         if (m->sq_length) {
    2100                                 Py_ssize_t l = (*m->sq_length)(s);
    2101                                 if (l < 0)
    2102                                         return -1;
    2103                                 if (i1 < 0)
    2104                                         i1 += l;
    2105                                 if (i2 < 0)
    2106                                         i2 += l;
    2107                         }
    2108                 }
    2109                 return m->sq_ass_slice(s, i1, i2, (PyObject *)NULL);
    2110         }
    2111         type_error("'%.200s' object doesn't support slice deletion", s);
    2112         return -1;
     2126    PySequenceMethods *m;
     2127
     2128    if (s == NULL) {
     2129        null_error();
     2130        return -1;
     2131    }
     2132
     2133    m = s->ob_type->tp_as_sequence;
     2134    if (m && m->sq_ass_slice) {
     2135        if (i1 < 0 || i2 < 0) {
     2136            if (m->sq_length) {
     2137                Py_ssize_t l = (*m->sq_length)(s);
     2138                if (l < 0)
     2139                    return -1;
     2140                if (i1 < 0)
     2141                    i1 += l;
     2142                if (i2 < 0)
     2143                    i2 += l;
     2144            }
     2145        }
     2146        return m->sq_ass_slice(s, i1, i2, (PyObject *)NULL);
     2147    }
     2148    type_error("'%.200s' object doesn't support slice deletion", s);
     2149    return -1;
    21132150}
    21142151
     
    21162153PySequence_Tuple(PyObject *v)
    21172154{
    2118         PyObject *it;  /* iter(v) */
    2119         Py_ssize_t n;         /* guess for result tuple size */
    2120         PyObject *result = NULL;
    2121         Py_ssize_t j;
    2122 
    2123         if (v == NULL)
    2124                 return null_error();
    2125 
    2126         /* Special-case the common tuple and list cases, for efficiency. */
    2127         if (PyTuple_CheckExact(v)) {
    2128                 /* Note that we can't know whether it's safe to return
    2129                    a tuple *subclass* instance as-is, hence the restriction
    2130                    to exact tuples here.  In contrast, lists always make
    2131                    a copy, so there's no need for exactness below. */
    2132                 Py_INCREF(v);
    2133                 return v;
    2134         }
    2135         if (PyList_Check(v))
    2136                 return PyList_AsTuple(v);
    2137 
    2138         /* Get iterator. */
    2139         it = PyObject_GetIter(v);
    2140         if (it == NULL)
    2141                 return NULL;
    2142 
    2143         /* Guess result size and allocate space. */
    2144         n = _PyObject_LengthHint(v, 10);
    2145         if (n == -1)
    2146                 goto Fail;
    2147         result = PyTuple_New(n);
    2148         if (result == NULL)
    2149                 goto Fail;
    2150 
    2151         /* Fill the tuple. */
    2152         for (j = 0; ; ++j) {
    2153                 PyObject *item = PyIter_Next(it);
    2154                 if (item == NULL) {
    2155                         if (PyErr_Occurred())
    2156                                 goto Fail;
    2157                         break;
    2158                 }
    2159                 if (j >= n) {
    2160                         Py_ssize_t oldn = n;
    2161                         /* The over-allocation strategy can grow a bit faster
    2162                            than for lists because unlike lists the
    2163                            over-allocation isn't permanent -- we reclaim
    2164                            the excess before the end of this routine.
    2165                            So, grow by ten and then add 25%.
    2166                         */
    2167                         n += 10;
    2168                         n += n >> 2;
    2169                         if (n < oldn) {
    2170                                 /* Check for overflow */
    2171                                 PyErr_NoMemory();
    2172                                 Py_DECREF(item);
    2173                                 goto Fail;
    2174                         }
    2175                         if (_PyTuple_Resize(&result, n) != 0) {
    2176                                 Py_DECREF(item);
    2177                                 goto Fail;
    2178                         }
    2179                 }
    2180                 PyTuple_SET_ITEM(result, j, item);
    2181         }
    2182 
    2183         /* Cut tuple back if guess was too large. */
    2184         if (j < n &&
    2185             _PyTuple_Resize(&result, j) != 0)
    2186                 goto Fail;
    2187 
    2188         Py_DECREF(it);
    2189         return result;
     2155    PyObject *it;  /* iter(v) */
     2156    Py_ssize_t n;         /* guess for result tuple size */
     2157    PyObject *result = NULL;
     2158    Py_ssize_t j;
     2159
     2160    if (v == NULL)
     2161        return null_error();
     2162
     2163    /* Special-case the common tuple and list cases, for efficiency. */
     2164    if (PyTuple_CheckExact(v)) {
     2165        /* Note that we can't know whether it's safe to return
     2166           a tuple *subclass* instance as-is, hence the restriction
     2167           to exact tuples here.  In contrast, lists always make
     2168           a copy, so there's no need for exactness below. */
     2169        Py_INCREF(v);
     2170        return v;
     2171    }
     2172    if (PyList_Check(v))
     2173        return PyList_AsTuple(v);
     2174
     2175    /* Get iterator. */
     2176    it = PyObject_GetIter(v);
     2177    if (it == NULL)
     2178        return NULL;
     2179
     2180    /* Guess result size and allocate space. */
     2181    n = _PyObject_LengthHint(v, 10);
     2182    if (n == -1)
     2183        goto Fail;
     2184    result = PyTuple_New(n);
     2185    if (result == NULL)
     2186        goto Fail;
     2187
     2188    /* Fill the tuple. */
     2189    for (j = 0; ; ++j) {
     2190        PyObject *item = PyIter_Next(it);
     2191        if (item == NULL) {
     2192            if (PyErr_Occurred())
     2193                goto Fail;
     2194            break;
     2195        }
     2196        if (j >= n) {
     2197            Py_ssize_t oldn = n;
     2198            /* The over-allocation strategy can grow a bit faster
     2199               than for lists because unlike lists the
     2200               over-allocation isn't permanent -- we reclaim
     2201               the excess before the end of this routine.
     2202               So, grow by ten and then add 25%.
     2203            */
     2204            n += 10;
     2205            n += n >> 2;
     2206            if (n < oldn) {
     2207                /* Check for overflow */
     2208                PyErr_NoMemory();
     2209                Py_DECREF(item);
     2210                goto Fail;
     2211            }
     2212            if (_PyTuple_Resize(&result, n) != 0) {
     2213                Py_DECREF(item);
     2214                goto Fail;
     2215            }
     2216        }
     2217        PyTuple_SET_ITEM(result, j, item);
     2218    }
     2219
     2220    /* Cut tuple back if guess was too large. */
     2221    if (j < n &&
     2222        _PyTuple_Resize(&result, j) != 0)
     2223        goto Fail;
     2224
     2225    Py_DECREF(it);
     2226    return result;
    21902227
    21912228Fail:
    2192         Py_XDECREF(result);
    2193         Py_DECREF(it);
    2194         return NULL;
     2229    Py_XDECREF(result);
     2230    Py_DECREF(it);
     2231    return NULL;
    21952232}
    21962233
     
    21982235PySequence_List(PyObject *v)
    21992236{
    2200         PyObject *result;  /* result list */
    2201         PyObject *rv;      /* return value from PyList_Extend */
    2202 
    2203         if (v == NULL)
    2204                 return null_error();
    2205 
    2206         result = PyList_New(0);
    2207         if (result == NULL)
    2208                 return NULL;
    2209 
    2210         rv = _PyList_Extend((PyListObject *)result, v);
    2211         if (rv == NULL) {
    2212                 Py_DECREF(result);
    2213                 return NULL;
    2214         }
    2215         Py_DECREF(rv);
    2216         return result;
     2237    PyObject *result;  /* result list */
     2238    PyObject *rv;      /* return value from PyList_Extend */
     2239
     2240    if (v == NULL)
     2241        return null_error();
     2242
     2243    result = PyList_New(0);
     2244    if (result == NULL)
     2245        return NULL;
     2246
     2247    rv = _PyList_Extend((PyListObject *)result, v);
     2248    if (rv == NULL) {
     2249        Py_DECREF(result);
     2250        return NULL;
     2251    }
     2252    Py_DECREF(rv);
     2253    return result;
    22172254}
    22182255
     
    22202257PySequence_Fast(PyObject *v, const char *m)
    22212258{
    2222         PyObject *it;
    2223 
    2224         if (v == NULL)
    2225                 return null_error();
    2226 
    2227         if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
    2228                 Py_INCREF(v);
    2229                 return v;
    2230         }
    2231 
    2232         it = PyObject_GetIter(v);
    2233         if (it == NULL) {
    2234                 if (PyErr_ExceptionMatches(PyExc_TypeError))
    2235                         PyErr_SetString(PyExc_TypeError, m);
    2236                 return NULL;
    2237         }
    2238 
    2239         v = PySequence_List(it);
    2240         Py_DECREF(it);
    2241 
    2242         return v;
     2259    PyObject *it;
     2260
     2261    if (v == NULL)
     2262        return null_error();
     2263
     2264    if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
     2265        Py_INCREF(v);
     2266        return v;
     2267    }
     2268
     2269    it = PyObject_GetIter(v);
     2270    if (it == NULL) {
     2271        if (PyErr_ExceptionMatches(PyExc_TypeError))
     2272            PyErr_SetString(PyExc_TypeError, m);
     2273        return NULL;
     2274    }
     2275
     2276    v = PySequence_List(it);
     2277    Py_DECREF(it);
     2278
     2279    return v;
    22432280}
    22442281
     
    22462283   PY_ITERSEARCH_COUNT:  -1 if error, else # of times obj appears in seq.
    22472284   PY_ITERSEARCH_INDEX:  0-based index of first occurrence of obj in seq;
    2248         set ValueError and return -1 if none found; also return -1 on error.
     2285    set ValueError and return -1 if none found; also return -1 on error.
    22492286   Py_ITERSEARCH_CONTAINS:  return 1 if obj in seq, else 0; -1 on error.
    22502287*/
     
    22522289_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
    22532290{
    2254         Py_ssize_t n;
    2255         int wrapped;  /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
    2256         PyObject *it;  /* iter(seq) */
    2257 
    2258         if (seq == NULL || obj == NULL) {
    2259                 null_error();
    2260                 return -1;
    2261         }
    2262 
    2263         it = PyObject_GetIter(seq);
    2264         if (it == NULL) {
    2265                 type_error("argument of type '%.200s' is not iterable", seq);
    2266                 return -1;
    2267         }
    2268 
    2269         n = wrapped = 0;
    2270         for (;;) {
    2271                 int cmp;
    2272                 PyObject *item = PyIter_Next(it);
    2273                 if (item == NULL) {
    2274                         if (PyErr_Occurred())
    2275                                 goto Fail;
    2276                         break;
    2277                 }
    2278 
    2279                 cmp = PyObject_RichCompareBool(obj, item, Py_EQ);
    2280                 Py_DECREF(item);
    2281                 if (cmp < 0)
    2282                         goto Fail;
    2283                 if (cmp > 0) {
    2284                         switch (operation) {
    2285                         case PY_ITERSEARCH_COUNT:
    2286                                 if (n == PY_SSIZE_T_MAX) {
    2287                                         PyErr_SetString(PyExc_OverflowError,
    2288                                                "count exceeds C integer size");
    2289                                         goto Fail;
    2290                                 }
    2291                                 ++n;
    2292                                 break;
    2293 
    2294                         case PY_ITERSEARCH_INDEX:
    2295                                 if (wrapped) {
    2296                                         PyErr_SetString(PyExc_OverflowError,
    2297                                                "index exceeds C integer size");
    2298                                         goto Fail;
    2299                                 }
    2300                                 goto Done;
    2301 
    2302                         case PY_ITERSEARCH_CONTAINS:
    2303                                 n = 1;
    2304                                 goto Done;
    2305 
    2306                         default:
    2307                                 assert(!"unknown operation");
    2308                         }
    2309                 }
    2310 
    2311                 if (operation == PY_ITERSEARCH_INDEX) {
    2312                         if (n == PY_SSIZE_T_MAX)
    2313                                 wrapped = 1;
    2314                         ++n;
    2315                 }
    2316         }
    2317 
    2318         if (operation != PY_ITERSEARCH_INDEX)
    2319                 goto Done;
    2320 
    2321         PyErr_SetString(PyExc_ValueError,
    2322                         "sequence.index(x): x not in sequence");
    2323         /* fall into failure code */
     2291    Py_ssize_t n;
     2292    int wrapped;  /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
     2293    PyObject *it;  /* iter(seq) */
     2294
     2295    if (seq == NULL || obj == NULL) {
     2296        null_error();
     2297        return -1;
     2298    }
     2299
     2300    it = PyObject_GetIter(seq);
     2301    if (it == NULL) {
     2302        type_error("argument of type '%.200s' is not iterable", seq);
     2303        return -1;
     2304    }
     2305
     2306    n = wrapped = 0;
     2307    for (;;) {
     2308        int cmp;
     2309        PyObject *item = PyIter_Next(it);
     2310        if (item == NULL) {
     2311            if (PyErr_Occurred())
     2312                goto Fail;
     2313            break;
     2314        }
     2315
     2316        cmp = PyObject_RichCompareBool(obj, item, Py_EQ);
     2317        Py_DECREF(item);
     2318        if (cmp < 0)
     2319            goto Fail;
     2320        if (cmp > 0) {
     2321            switch (operation) {
     2322            case PY_ITERSEARCH_COUNT:
     2323                if (n == PY_SSIZE_T_MAX) {
     2324                    PyErr_SetString(PyExc_OverflowError,
     2325                           "count exceeds C integer size");
     2326                    goto Fail;
     2327                }
     2328                ++n;
     2329                break;
     2330
     2331            case PY_ITERSEARCH_INDEX:
     2332                if (wrapped) {
     2333                    PyErr_SetString(PyExc_OverflowError,
     2334                           "index exceeds C integer size");
     2335                    goto Fail;
     2336                }
     2337                goto Done;
     2338
     2339            case PY_ITERSEARCH_CONTAINS:
     2340                n = 1;
     2341                goto Done;
     2342
     2343            default:
     2344                assert(!"unknown operation");
     2345            }
     2346        }
     2347
     2348        if (operation == PY_ITERSEARCH_INDEX) {
     2349            if (n == PY_SSIZE_T_MAX)
     2350                wrapped = 1;
     2351            ++n;
     2352        }
     2353    }
     2354
     2355    if (operation != PY_ITERSEARCH_INDEX)
     2356        goto Done;
     2357
     2358    PyErr_SetString(PyExc_ValueError,
     2359                    "sequence.index(x): x not in sequence");
     2360    /* fall into failure code */
    23242361Fail:
    2325         n = -1;
    2326         /* fall through */
     2362    n = -1;
     2363    /* fall through */
    23272364Done:
    2328         Py_DECREF(it);
    2329         return n;
     2365    Py_DECREF(it);
     2366    return n;
    23302367
    23312368}
     
    23352372PySequence_Count(PyObject *s, PyObject *o)
    23362373{
    2337         return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
     2374    return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
    23382375}
    23392376
     
    23442381PySequence_Contains(PyObject *seq, PyObject *ob)
    23452382{
    2346         Py_ssize_t result;
    2347         if (PyType_HasFeature(seq->ob_type, Py_TPFLAGS_HAVE_SEQUENCE_IN)) {
    2348                 PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
    2349                 if (sqm != NULL && sqm->sq_contains != NULL)
    2350                         return (*sqm->sq_contains)(seq, ob);
    2351         }
    2352         result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
    2353         return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
     2383    Py_ssize_t result;
     2384    if (PyType_HasFeature(seq->ob_type, Py_TPFLAGS_HAVE_SEQUENCE_IN)) {
     2385        PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
     2386        if (sqm != NULL && sqm->sq_contains != NULL)
     2387            return (*sqm->sq_contains)(seq, ob);
     2388    }
     2389    result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
     2390    return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
    23542391}
    23552392
     
    23592396PySequence_In(PyObject *w, PyObject *v)
    23602397{
    2361         return PySequence_Contains(w, v);
     2398    return PySequence_Contains(w, v);
    23622399}
    23632400
     
    23652402PySequence_Index(PyObject *s, PyObject *o)
    23662403{
    2367         return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
     2404    return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
    23682405}
    23692406
     
    23732410PyMapping_Check(PyObject *o)
    23742411{
    2375         if (o && PyInstance_Check(o))
    2376                 return PyObject_HasAttrString(o, "__getitem__");
    2377 
    2378         return  o && o->ob_type->tp_as_mapping &&
    2379                 o->ob_type->tp_as_mapping->mp_subscript &&
    2380                 !(o->ob_type->tp_as_sequence &&
    2381                   o->ob_type->tp_as_sequence->sq_slice);
     2412    if (o && PyInstance_Check(o))
     2413        return PyObject_HasAttrString(o, "__getitem__");
     2414
     2415    return  o && o->ob_type->tp_as_mapping &&
     2416        o->ob_type->tp_as_mapping->mp_subscript &&
     2417        !(o->ob_type->tp_as_sequence &&
     2418          o->ob_type->tp_as_sequence->sq_slice);
    23822419}
    23832420
     
    23852422PyMapping_Size(PyObject *o)
    23862423{
    2387         PyMappingMethods *m;
    2388 
    2389         if (o == NULL) {
    2390                 null_error();
    2391                 return -1;
    2392         }
    2393 
    2394         m = o->ob_type->tp_as_mapping;
    2395         if (m && m->mp_length)
    2396                 return m->mp_length(o);
    2397 
    2398         type_error("object of type '%.200s' has no len()", o);
    2399         return -1;
     2424    PyMappingMethods *m;
     2425
     2426    if (o == NULL) {
     2427        null_error();
     2428        return -1;
     2429    }
     2430
     2431    m = o->ob_type->tp_as_mapping;
     2432    if (m && m->mp_length)
     2433        return m->mp_length(o);
     2434
     2435    type_error("object of type '%.200s' has no len()", o);
     2436    return -1;
    24002437}
    24012438
     
    24042441PyMapping_Length(PyObject *o)
    24052442{
    2406         return PyMapping_Size(o);
     2443    return PyMapping_Size(o);
    24072444}
    24082445#define PyMapping_Length PyMapping_Size
     
    24112448PyMapping_GetItemString(PyObject *o, char *key)
    24122449{
    2413         PyObject *okey, *r;
    2414 
    2415         if (key == NULL)
    2416                 return null_error();
    2417 
    2418         okey = PyString_FromString(key);
    2419         if (okey == NULL)
    2420                 return NULL;
    2421         r = PyObject_GetItem(o, okey);
    2422         Py_DECREF(okey);
    2423         return r;
     2450    PyObject *okey, *r;
     2451
     2452    if (key == NULL)
     2453        return null_error();
     2454
     2455    okey = PyString_FromString(key);
     2456    if (okey == NULL)
     2457        return NULL;
     2458    r = PyObject_GetItem(o, okey);
     2459    Py_DECREF(okey);
     2460    return r;
    24242461}
    24252462
     
    24272464PyMapping_SetItemString(PyObject *o, char *key, PyObject *value)
    24282465{
    2429         PyObject *okey;
    2430         int r;
    2431 
    2432         if (key == NULL) {
    2433                 null_error();
    2434                 return -1;
    2435         }
    2436 
    2437         okey = PyString_FromString(key);
    2438         if (okey == NULL)
    2439                 return -1;
    2440         r = PyObject_SetItem(o, okey, value);
    2441         Py_DECREF(okey);
    2442         return r;
     2466    PyObject *okey;
     2467    int r;
     2468
     2469    if (key == NULL) {
     2470        null_error();
     2471        return -1;
     2472    }
     2473
     2474    okey = PyString_FromString(key);
     2475    if (okey == NULL)
     2476        return -1;
     2477    r = PyObject_SetItem(o, okey, value);
     2478    Py_DECREF(okey);
     2479    return r;
    24432480}
    24442481
     
    24462483PyMapping_HasKeyString(PyObject *o, char *key)
    24472484{
    2448         PyObject *v;
    2449 
    2450         v = PyMapping_GetItemString(o, key);
    2451         if (v) {
    2452                 Py_DECREF(v);
    2453                 return 1;
    2454         }
    2455         PyErr_Clear();
    2456         return 0;
     2485    PyObject *v;
     2486
     2487    v = PyMapping_GetItemString(o, key);
     2488    if (v) {
     2489        Py_DECREF(v);
     2490        return 1;
     2491    }
     2492    PyErr_Clear();
     2493    return 0;
    24572494}
    24582495
     
    24602497PyMapping_HasKey(PyObject *o, PyObject *key)
    24612498{
    2462         PyObject *v;
    2463 
    2464         v = PyObject_GetItem(o, key);
    2465         if (v) {
    2466                 Py_DECREF(v);
    2467                 return 1;
    2468         }
    2469         PyErr_Clear();
    2470         return 0;
     2499    PyObject *v;
     2500
     2501    v = PyObject_GetItem(o, key);
     2502    if (v) {
     2503        Py_DECREF(v);
     2504        return 1;
     2505    }
     2506    PyErr_Clear();
     2507    return 0;
    24712508}
    24722509
     
    24782515PyObject_CallObject(PyObject *o, PyObject *a)
    24792516{
    2480         return PyEval_CallObjectWithKeywords(o, a, NULL);
     2517    return PyEval_CallObjectWithKeywords(o, a, NULL);
    24812518}
    24822519
     
    24842521PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw)
    24852522{
    2486         ternaryfunc call;
    2487 
    2488         if ((call = func->ob_type->tp_call) != NULL) {
    2489                 PyObject *result;
    2490                 if (Py_EnterRecursiveCall(" while calling a Python object"))
    2491                     return NULL;
    2492                 result = (*call)(func, arg, kw);
    2493                 Py_LeaveRecursiveCall();
    2494                 if (result == NULL && !PyErr_Occurred())
    2495                         PyErr_SetString(
    2496                                 PyExc_SystemError,
    2497                                 "NULL result without error in PyObject_Call");
    2498                 return result;
    2499         }
    2500         PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
    2501                      func->ob_type->tp_name);
    2502         return NULL;
     2523    ternaryfunc call;
     2524
     2525    if ((call = func->ob_type->tp_call) != NULL) {
     2526        PyObject *result;
     2527        if (Py_EnterRecursiveCall(" while calling a Python object"))
     2528            return NULL;
     2529        result = (*call)(func, arg, kw);
     2530        Py_LeaveRecursiveCall();
     2531        if (result == NULL && !PyErr_Occurred())
     2532            PyErr_SetString(
     2533                PyExc_SystemError,
     2534                "NULL result without error in PyObject_Call");
     2535        return result;
     2536    }
     2537    PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
     2538                 func->ob_type->tp_name);
     2539    return NULL;
    25032540}
    25042541
     
    25062543call_function_tail(PyObject *callable, PyObject *args)
    25072544{
    2508         PyObject *retval;
    2509 
    2510         if (args == NULL)
    2511                 return NULL;
    2512 
    2513         if (!PyTuple_Check(args)) {
    2514                 PyObject *a;
    2515 
    2516                 a = PyTuple_New(1);
    2517                 if (a == NULL) {
    2518                         Py_DECREF(args);
    2519                         return NULL;
    2520                 }
    2521                 PyTuple_SET_ITEM(a, 0, args);
    2522                 args = a;
    2523         }
    2524         retval = PyObject_Call(callable, args, NULL);
    2525 
    2526         Py_DECREF(args);
    2527 
    2528         return retval;
     2545    PyObject *retval;
     2546
     2547    if (args == NULL)
     2548        return NULL;
     2549
     2550    if (!PyTuple_Check(args)) {
     2551        PyObject *a;
     2552
     2553        a = PyTuple_New(1);
     2554        if (a == NULL) {
     2555            Py_DECREF(args);
     2556            return NULL;
     2557        }
     2558        PyTuple_SET_ITEM(a, 0, args);
     2559        args = a;
     2560    }
     2561    retval = PyObject_Call(callable, args, NULL);
     2562
     2563    Py_DECREF(args);
     2564
     2565    return retval;
    25292566}
    25302567
     
    25322569PyObject_CallFunction(PyObject *callable, char *format, ...)
    25332570{
    2534         va_list va;
    2535         PyObject *args;
    2536 
    2537         if (callable == NULL)
    2538                 return null_error();
    2539 
    2540         if (format && *format) {
    2541                 va_start(va, format);
    2542                 args = Py_VaBuildValue(format, va);
    2543                 va_end(va);
    2544         }
    2545         else
    2546                 args = PyTuple_New(0);
    2547 
    2548         return call_function_tail(callable, args);
     2571    va_list va;
     2572    PyObject *args;
     2573
     2574    if (callable == NULL)
     2575        return null_error();
     2576
     2577    if (format && *format) {
     2578        va_start(va, format);
     2579        args = Py_VaBuildValue(format, va);
     2580        va_end(va);
     2581    }
     2582    else
     2583        args = PyTuple_New(0);
     2584
     2585    return call_function_tail(callable, args);
    25492586}
    25502587
     
    25522589_PyObject_CallFunction_SizeT(PyObject *callable, char *format, ...)
    25532590{
    2554         va_list va;
    2555         PyObject *args;
    2556 
    2557         if (callable == NULL)
    2558                 return null_error();
    2559 
    2560         if (format && *format) {
    2561                 va_start(va, format);
    2562                 args = _Py_VaBuildValue_SizeT(format, va);
    2563                 va_end(va);
    2564         }
    2565         else
    2566                 args = PyTuple_New(0);
    2567 
    2568         return call_function_tail(callable, args);
     2591    va_list va;
     2592    PyObject *args;
     2593
     2594    if (callable == NULL)
     2595        return null_error();
     2596
     2597    if (format && *format) {
     2598        va_start(va, format);
     2599        args = _Py_VaBuildValue_SizeT(format, va);
     2600        va_end(va);
     2601    }
     2602    else
     2603        args = PyTuple_New(0);
     2604
     2605    return call_function_tail(callable, args);
    25692606}
    25702607
     
    25722609PyObject_CallMethod(PyObject *o, char *name, char *format, ...)
    25732610{
    2574         va_list va;
    2575         PyObject *args;
    2576         PyObject *func = NULL;
    2577         PyObject *retval = NULL;
    2578 
    2579         if (o == NULL || name == NULL)
    2580                 return null_error();
    2581 
    2582         func = PyObject_GetAttrString(o, name);
    2583         if (func == NULL) {
    2584                 PyErr_SetString(PyExc_AttributeError, name);
    2585                 return 0;
    2586         }
    2587 
    2588         if (!PyCallable_Check(func)) {
    2589                 type_error("attribute of type '%.200s' is not callable", func);
    2590                 goto exit;
    2591         }
    2592 
    2593         if (format && *format) {
    2594                 va_start(va, format);
    2595                 args = Py_VaBuildValue(format, va);
    2596                 va_end(va);
    2597         }
    2598         else
    2599                 args = PyTuple_New(0);
    2600 
    2601         retval = call_function_tail(func, args);
     2611    va_list va;
     2612    PyObject *args;
     2613    PyObject *func = NULL;
     2614    PyObject *retval = NULL;
     2615
     2616    if (o == NULL || name == NULL)
     2617        return null_error();
     2618
     2619    func = PyObject_GetAttrString(o, name);
     2620    if (func == NULL) {
     2621        PyErr_SetString(PyExc_AttributeError, name);
     2622        return 0;
     2623    }
     2624
     2625    if (!PyCallable_Check(func)) {
     2626        type_error("attribute of type '%.200s' is not callable", func);
     2627        goto exit;
     2628    }
     2629
     2630    if (format && *format) {
     2631        va_start(va, format);
     2632        args = Py_VaBuildValue(format, va);
     2633        va_end(va);
     2634    }
     2635    else
     2636        args = PyTuple_New(0);
     2637
     2638    retval = call_function_tail(func, args);
    26022639
    26032640  exit:
    2604         /* args gets consumed in call_function_tail */
    2605         Py_XDECREF(func);
    2606 
    2607         return retval;
     2641    /* args gets consumed in call_function_tail */
     2642    Py_XDECREF(func);
     2643
     2644    return retval;
    26082645}
    26092646
     
    26112648_PyObject_CallMethod_SizeT(PyObject *o, char *name, char *format, ...)
    26122649{
    2613         va_list va;
    2614         PyObject *args;
    2615         PyObject *func = NULL;
    2616         PyObject *retval = NULL;
    2617 
    2618         if (o == NULL || name == NULL)
    2619                 return null_error();
    2620 
    2621         func = PyObject_GetAttrString(o, name);
    2622         if (func == NULL) {
    2623                 PyErr_SetString(PyExc_AttributeError, name);
    2624                 return 0;
    2625         }
    2626 
    2627         if (!PyCallable_Check(func)) {
    2628                 type_error("attribute of type '%.200s' is not callable", func);
    2629                 goto exit;
    2630         }
    2631 
    2632         if (format && *format) {
    2633                 va_start(va, format);
    2634                 args = _Py_VaBuildValue_SizeT(format, va);
    2635                 va_end(va);
    2636         }
    2637         else
    2638                 args = PyTuple_New(0);
    2639 
    2640         retval = call_function_tail(func, args);
     2650    va_list va;
     2651    PyObject *args;
     2652    PyObject *func = NULL;
     2653    PyObject *retval = NULL;
     2654
     2655    if (o == NULL || name == NULL)
     2656        return null_error();
     2657
     2658    func = PyObject_GetAttrString(o, name);
     2659    if (func == NULL) {
     2660        PyErr_SetString(PyExc_AttributeError, name);
     2661        return 0;
     2662    }
     2663
     2664    if (!PyCallable_Check(func)) {
     2665        type_error("attribute of type '%.200s' is not callable", func);
     2666        goto exit;
     2667    }
     2668
     2669    if (format && *format) {
     2670        va_start(va, format);
     2671        args = _Py_VaBuildValue_SizeT(format, va);
     2672        va_end(va);
     2673    }
     2674    else
     2675        args = PyTuple_New(0);
     2676
     2677    retval = call_function_tail(func, args);
    26412678
    26422679  exit:
    2643         /* args gets consumed in call_function_tail */
    2644         Py_XDECREF(func);
    2645 
    2646         return retval;
     2680    /* args gets consumed in call_function_tail */
     2681    Py_XDECREF(func);
     2682
     2683    return retval;
    26472684}
    26482685
     
    26512688objargs_mktuple(va_list va)
    26522689{
    2653         int i, n = 0;
    2654         va_list countva;
    2655         PyObject *result, *tmp;
     2690    int i, n = 0;
     2691    va_list countva;
     2692    PyObject *result, *tmp;
    26562693
    26572694#ifdef VA_LIST_IS_ARRAY
    2658         memcpy(countva, va, sizeof(va_list));
     2695    memcpy(countva, va, sizeof(va_list));
    26592696#else
    26602697#ifdef __va_copy
    2661         __va_copy(countva, va);
     2698    __va_copy(countva, va);
    26622699#else
    2663         countva = va;
     2700    countva = va;
    26642701#endif
    26652702#endif
    26662703
    2667         while (((PyObject *)va_arg(countva, PyObject *)) != NULL)
    2668                 ++n;
    2669         result = PyTuple_New(n);
    2670         if (result != NULL && n > 0) {
    2671                 for (i = 0; i < n; ++i) {
    2672                         tmp = (PyObject *)va_arg(va, PyObject *);
    2673                         PyTuple_SET_ITEM(result, i, tmp);
    2674                         Py_INCREF(tmp);
    2675                 }
    2676         }
    2677         return result;
     2704    while (((PyObject *)va_arg(countva, PyObject *)) != NULL)
     2705        ++n;
     2706    result = PyTuple_New(n);
     2707    if (result != NULL && n > 0) {
     2708        for (i = 0; i < n; ++i) {
     2709            tmp = (PyObject *)va_arg(va, PyObject *);
     2710            PyTuple_SET_ITEM(result, i, tmp);
     2711            Py_INCREF(tmp);
     2712        }
     2713    }
     2714    return result;
    26782715}
    26792716
     
    26812718PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...)
    26822719{
    2683         PyObject *args, *tmp;
    2684         va_list vargs;
    2685 
    2686         if (callable == NULL || name == NULL)
    2687                 return null_error();
    2688 
    2689         callable = PyObject_GetAttr(callable, name);
    2690         if (callable == NULL)
    2691                 return NULL;
    2692 
    2693         /* count the args */
    2694         va_start(vargs, name);
    2695         args = objargs_mktuple(vargs);
    2696         va_end(vargs);
    2697         if (args == NULL) {
    2698                 Py_DECREF(callable);
    2699                 return NULL;
    2700         }
    2701         tmp = PyObject_Call(callable, args, NULL);
    2702         Py_DECREF(args);
    2703         Py_DECREF(callable);
    2704 
    2705         return tmp;
     2720    PyObject *args, *tmp;
     2721    va_list vargs;
     2722
     2723    if (callable == NULL || name == NULL)
     2724        return null_error();
     2725
     2726    callable = PyObject_GetAttr(callable, name);
     2727    if (callable == NULL)
     2728        return NULL;
     2729
     2730    /* count the args */
     2731    va_start(vargs, name);
     2732    args = objargs_mktuple(vargs);
     2733    va_end(vargs);
     2734    if (args == NULL) {
     2735        Py_DECREF(callable);
     2736        return NULL;
     2737    }
     2738    tmp = PyObject_Call(callable, args, NULL);
     2739    Py_DECREF(args);
     2740    Py_DECREF(callable);
     2741
     2742    return tmp;
    27062743}
    27072744
     
    27092746PyObject_CallFunctionObjArgs(PyObject *callable, ...)
    27102747{
    2711         PyObject *args, *tmp;
    2712         va_list vargs;
    2713 
    2714         if (callable == NULL)
    2715                 return null_error();
    2716 
    2717         /* count the args */
    2718         va_start(vargs, callable);
    2719         args = objargs_mktuple(vargs);
    2720         va_end(vargs);
    2721         if (args == NULL)
    2722                 return NULL;
    2723         tmp = PyObject_Call(callable, args, NULL);
    2724         Py_DECREF(args);
    2725 
    2726         return tmp;
     2748    PyObject *args, *tmp;
     2749    va_list vargs;
     2750
     2751    if (callable == NULL)
     2752        return null_error();
     2753
     2754    /* count the args */
     2755    va_start(vargs, callable);
     2756    args = objargs_mktuple(vargs);
     2757    va_end(vargs);
     2758    if (args == NULL)
     2759        return NULL;
     2760    tmp = PyObject_Call(callable, args, NULL);
     2761    Py_DECREF(args);
     2762
     2763    return tmp;
    27272764}
    27282765
     
    27592796abstract_get_bases(PyObject *cls)
    27602797{
    2761         static PyObject *__bases__ = NULL;
    2762         PyObject *bases;
    2763 
    2764         if (__bases__ == NULL) {
    2765                 __bases__ = PyString_InternFromString("__bases__");
    2766                 if (__bases__ == NULL)
    2767                         return NULL;
    2768         }
    2769         bases = PyObject_GetAttr(cls, __bases__);
    2770         if (bases == NULL) {
    2771                 if (PyErr_ExceptionMatches(PyExc_AttributeError))
    2772                         PyErr_Clear();
    2773                 return NULL;
    2774         }
    2775         if (!PyTuple_Check(bases)) {
    2776                 Py_DECREF(bases);
    2777                 return NULL;
    2778         }
    2779         return bases;
     2798    static PyObject *__bases__ = NULL;
     2799    PyObject *bases;
     2800
     2801    if (__bases__ == NULL) {
     2802        __bases__ = PyString_InternFromString("__bases__");
     2803        if (__bases__ == NULL)
     2804            return NULL;
     2805    }
     2806    bases = PyObject_GetAttr(cls, __bases__);
     2807    if (bases == NULL) {
     2808        if (PyErr_ExceptionMatches(PyExc_AttributeError))
     2809            PyErr_Clear();
     2810        return NULL;
     2811    }
     2812    if (!PyTuple_Check(bases)) {
     2813        Py_DECREF(bases);
     2814        return NULL;
     2815    }
     2816    return bases;
    27802817}
    27812818
     
    27842821abstract_issubclass(PyObject *derived, PyObject *cls)
    27852822{
    2786         PyObject *bases = NULL;
    2787         Py_ssize_t i, n;
    2788         int r = 0;
    2789 
    2790         while (1) {
    2791                 if (derived == cls)
    2792                         return 1;
    2793                 bases = abstract_get_bases(derived);
    2794                 if (bases == NULL) {
    2795                         if (PyErr_Occurred())
    2796                                 return -1;
    2797                         return 0;
    2798                 }
    2799                 n = PyTuple_GET_SIZE(bases);
    2800                 if (n == 0) {
    2801                         Py_DECREF(bases);
    2802                         return 0;
    2803                 }
    2804                 /* Avoid recursivity in the single inheritance case */
    2805                 if (n == 1) {
    2806                         derived = PyTuple_GET_ITEM(bases, 0);
    2807                         Py_DECREF(bases);
    2808                         continue;
    2809                 }
    2810                 for (i = 0; i < n; i++) {
    2811                         r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
    2812                         if (r != 0)
    2813                                 break;
    2814                 }
    2815                 Py_DECREF(bases);
    2816                 return r;
    2817         }
     2823    PyObject *bases = NULL;
     2824    Py_ssize_t i, n;
     2825    int r = 0;
     2826
     2827    while (1) {
     2828        if (derived == cls)
     2829            return 1;
     2830        bases = abstract_get_bases(derived);
     2831        if (bases == NULL) {
     2832            if (PyErr_Occurred())
     2833                return -1;
     2834            return 0;
     2835        }
     2836        n = PyTuple_GET_SIZE(bases);
     2837        if (n == 0) {
     2838            Py_DECREF(bases);
     2839            return 0;
     2840        }
     2841        /* Avoid recursivity in the single inheritance case */
     2842        if (n == 1) {
     2843            derived = PyTuple_GET_ITEM(bases, 0);
     2844            Py_DECREF(bases);
     2845            continue;
     2846        }
     2847        for (i = 0; i < n; i++) {
     2848            r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
     2849            if (r != 0)
     2850                break;
     2851        }
     2852        Py_DECREF(bases);
     2853        return r;
     2854    }
    28182855}
    28192856
     
    28212858check_class(PyObject *cls, const char *error)
    28222859{
    2823         PyObject *bases = abstract_get_bases(cls);
    2824         if (bases == NULL) {
    2825                 /* Do not mask errors. */
    2826                 if (!PyErr_Occurred())
    2827                         PyErr_SetString(PyExc_TypeError, error);
    2828                 return 0;
    2829         }
    2830         Py_DECREF(bases);
    2831         return -1;
     2860    PyObject *bases = abstract_get_bases(cls);
     2861    if (bases == NULL) {
     2862        /* Do not mask errors. */
     2863        if (!PyErr_Occurred())
     2864            PyErr_SetString(PyExc_TypeError, error);
     2865        return 0;
     2866    }
     2867    Py_DECREF(bases);
     2868    return -1;
    28322869}
    28332870
     
    28352872recursive_isinstance(PyObject *inst, PyObject *cls)
    28362873{
    2837         PyObject *icls;
    2838         static PyObject *__class__ = NULL;
    2839         int retval = 0;
    2840 
    2841         if (__class__ == NULL) {
    2842                 __class__ = PyString_InternFromString("__class__");
    2843                 if (__class__ == NULL)
    2844                         return -1;
    2845         }
    2846 
    2847         if (PyClass_Check(cls) && PyInstance_Check(inst)) {
    2848                 PyObject *inclass =
    2849                         (PyObject*)((PyInstanceObject*)inst)->in_class;
    2850                 retval = PyClass_IsSubclass(inclass, cls);
    2851         }
    2852         else if (PyType_Check(cls)) {
    2853                 retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
    2854                 if (retval == 0) {
    2855                         PyObject *c = PyObject_GetAttr(inst, __class__);
    2856                         if (c == NULL) {
    2857                                 PyErr_Clear();
    2858                         }
    2859                         else {
    2860                                 if (c != (PyObject *)(inst->ob_type) &&
    2861                                     PyType_Check(c))
    2862                                         retval = PyType_IsSubtype(
    2863                                                 (PyTypeObject *)c,
    2864                                                 (PyTypeObject *)cls);
    2865                                 Py_DECREF(c);
    2866                         }
    2867                 }
    2868         }
    2869         else {
    2870                 if (!check_class(cls,
    2871                         "isinstance() arg 2 must be a class, type,"
    2872                         " or tuple of classes and types"))
    2873                         return -1;
    2874                 icls = PyObject_GetAttr(inst, __class__);
    2875                 if (icls == NULL) {
    2876                         PyErr_Clear();
    2877                         retval = 0;
    2878                 }
    2879                 else {
    2880                         retval = abstract_issubclass(icls, cls);
    2881                         Py_DECREF(icls);
    2882                 }
    2883         }
    2884 
    2885         return retval;
     2874    PyObject *icls;
     2875    static PyObject *__class__ = NULL;
     2876    int retval = 0;
     2877
     2878    if (__class__ == NULL) {
     2879        __class__ = PyString_InternFromString("__class__");
     2880        if (__class__ == NULL)
     2881            return -1;
     2882    }
     2883
     2884    if (PyClass_Check(cls) && PyInstance_Check(inst)) {
     2885        PyObject *inclass =
     2886            (PyObject*)((PyInstanceObject*)inst)->in_class;
     2887        retval = PyClass_IsSubclass(inclass, cls);
     2888    }
     2889    else if (PyType_Check(cls)) {
     2890        retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
     2891        if (retval == 0) {
     2892            PyObject *c = PyObject_GetAttr(inst, __class__);
     2893            if (c == NULL) {
     2894                PyErr_Clear();
     2895            }
     2896            else {
     2897                if (c != (PyObject *)(inst->ob_type) &&
     2898                    PyType_Check(c))
     2899                    retval = PyType_IsSubtype(
     2900                        (PyTypeObject *)c,
     2901                        (PyTypeObject *)cls);
     2902                Py_DECREF(c);
     2903            }
     2904        }
     2905    }
     2906    else {
     2907        if (!check_class(cls,
     2908            "isinstance() arg 2 must be a class, type,"
     2909            " or tuple of classes and types"))
     2910            return -1;
     2911        icls = PyObject_GetAttr(inst, __class__);
     2912        if (icls == NULL) {
     2913            PyErr_Clear();
     2914            retval = 0;
     2915        }
     2916        else {
     2917            retval = abstract_issubclass(icls, cls);
     2918            Py_DECREF(icls);
     2919        }
     2920    }
     2921
     2922    return retval;
    28862923}
    28872924
     
    28892926PyObject_IsInstance(PyObject *inst, PyObject *cls)
    28902927{
    2891         static PyObject *name = NULL;
    2892         PyObject *checker;
    2893 
    2894         /* Quick test for an exact match */
    2895         if (Py_TYPE(inst) == (PyTypeObject *)cls)
    2896                 return 1;
    2897 
    2898         if (PyTuple_Check(cls)) {
    2899                 Py_ssize_t i;
    2900                 Py_ssize_t n;
    2901                 int r = 0;
    2902 
    2903                 if (Py_EnterRecursiveCall(" in __instancecheck__"))
    2904                         return -1;
    2905                 n = PyTuple_GET_SIZE(cls);
    2906                 for (i = 0; i < n; ++i) {
    2907                         PyObject *item = PyTuple_GET_ITEM(cls, i);
    2908                         r = PyObject_IsInstance(inst, item);
    2909                         if (r != 0)
    2910                                 /* either found it, or got an error */
    2911                                 break;
    2912                 }
    2913                 Py_LeaveRecursiveCall();
    2914                 return r;
    2915         }
    2916         if (name == NULL) {
    2917                 name = PyString_InternFromString("__instancecheck__");
    2918                 if (name == NULL)
    2919                         return -1;
    2920         }
    2921         checker = PyObject_GetAttr(cls, name);
    2922         if (checker == NULL && PyErr_Occurred())
    2923                 PyErr_Clear();
    2924         if (checker != NULL) {
    2925                 PyObject *res;
    2926                 int ok = -1;
    2927                 if (Py_EnterRecursiveCall(" in __instancecheck__")) {
    2928                         Py_DECREF(checker);
    2929                         return ok;
    2930                 }
    2931                 res = PyObject_CallFunctionObjArgs(checker, inst, NULL);
    2932                 Py_LeaveRecursiveCall();
    2933                 Py_DECREF(checker);
    2934                 if (res != NULL) {
    2935                         ok = PyObject_IsTrue(res);
    2936                         Py_DECREF(res);
    2937                 }
    2938                 return ok;
    2939         }
    2940         return recursive_isinstance(inst, cls);
     2928    static PyObject *name = NULL;
     2929
     2930    /* Quick test for an exact match */
     2931    if (Py_TYPE(inst) == (PyTypeObject *)cls)
     2932        return 1;
     2933
     2934    if (PyTuple_Check(cls)) {
     2935        Py_ssize_t i;
     2936        Py_ssize_t n;
     2937        int r = 0;
     2938
     2939        if (Py_EnterRecursiveCall(" in __instancecheck__"))
     2940            return -1;
     2941        n = PyTuple_GET_SIZE(cls);
     2942        for (i = 0; i < n; ++i) {
     2943            PyObject *item = PyTuple_GET_ITEM(cls, i);
     2944            r = PyObject_IsInstance(inst, item);
     2945            if (r != 0)
     2946                /* either found it, or got an error */
     2947                break;
     2948        }
     2949        Py_LeaveRecursiveCall();
     2950        return r;
     2951    }
     2952
     2953    if (!(PyClass_Check(cls) || PyInstance_Check(cls))) {
     2954        PyObject *checker;
     2955        checker = _PyObject_LookupSpecial(cls, "__instancecheck__", &name);
     2956        if (checker != NULL) {
     2957            PyObject *res;
     2958            int ok = -1;
     2959            if (Py_EnterRecursiveCall(" in __instancecheck__")) {
     2960                Py_DECREF(checker);
     2961                return ok;
     2962            }
     2963            res = PyObject_CallFunctionObjArgs(checker, inst, NULL);
     2964            Py_LeaveRecursiveCall();
     2965            Py_DECREF(checker);
     2966            if (res != NULL) {
     2967                ok = PyObject_IsTrue(res);
     2968                Py_DECREF(res);
     2969            }
     2970            return ok;
     2971        }
     2972        else if (PyErr_Occurred())
     2973            return -1;
     2974    }
     2975    return recursive_isinstance(inst, cls);
    29412976}
    29422977
     
    29442979recursive_issubclass(PyObject *derived, PyObject *cls)
    29452980{
    2946         int retval;
    2947 
    2948         if (PyType_Check(cls) && PyType_Check(derived)) {
    2949                 /* Fast path (non-recursive) */
    2950                 return PyType_IsSubtype(
    2951                         (PyTypeObject *)derived, (PyTypeObject *)cls);
    2952         }
    2953         if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
    2954                 if (!check_class(derived,
    2955                                 "issubclass() arg 1 must be a class"))
    2956                         return -1;
    2957 
    2958                 if (!check_class(cls,
    2959                                 "issubclass() arg 2 must be a class"
    2960                                 " or tuple of classes"))
    2961                         return -1;
    2962                 retval = abstract_issubclass(derived, cls);
    2963         }
    2964         else {
    2965                 /* shortcut */
    2966                 if (!(retval = (derived == cls)))
    2967                         retval = PyClass_IsSubclass(derived, cls);
    2968         }
    2969 
    2970         return retval;
     2981    int retval;
     2982
     2983    if (PyType_Check(cls) && PyType_Check(derived)) {
     2984        /* Fast path (non-recursive) */
     2985        return PyType_IsSubtype(
     2986            (PyTypeObject *)derived, (PyTypeObject *)cls);
     2987    }
     2988    if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
     2989        if (!check_class(derived,
     2990                        "issubclass() arg 1 must be a class"))
     2991            return -1;
     2992
     2993        if (!check_class(cls,
     2994                        "issubclass() arg 2 must be a class"
     2995                        " or tuple of classes"))
     2996            return -1;
     2997        retval = abstract_issubclass(derived, cls);
     2998    }
     2999    else {
     3000        /* shortcut */
     3001        if (!(retval = (derived == cls)))
     3002            retval = PyClass_IsSubclass(derived, cls);
     3003    }
     3004
     3005    return retval;
    29713006}
    29723007
     
    29743009PyObject_IsSubclass(PyObject *derived, PyObject *cls)
    29753010{
    2976         static PyObject *name = NULL;
    2977         PyObject *t, *v, *tb;
    2978         PyObject *checker;
    2979        
    2980         if (PyTuple_Check(cls)) {
    2981                 Py_ssize_t i;
    2982                 Py_ssize_t n;
    2983                 int r = 0;
    2984  
    2985                 if (Py_EnterRecursiveCall(" in __subclasscheck__"))
    2986                         return -1;
    2987                 n = PyTuple_GET_SIZE(cls);
    2988                 for (i = 0; i < n; ++i) {
    2989                         PyObject *item = PyTuple_GET_ITEM(cls, i);
    2990                         r = PyObject_IsSubclass(derived, item);
    2991                         if (r != 0)
    2992                                 /* either found it, or got an error */
    2993                                 break;
    2994                 }
    2995                 Py_LeaveRecursiveCall();
    2996                 return r;
    2997         }
    2998         if (name == NULL) {
    2999                 name = PyString_InternFromString("__subclasscheck__");
    3000                 if (name == NULL)
    3001                         return -1;
    3002         }
    3003         PyErr_Fetch(&t, &v, &tb);
    3004         checker = PyObject_GetAttr(cls, name);
    3005         PyErr_Restore(t, v, tb);
    3006         if (checker != NULL) {
    3007                 PyObject *res;
    3008                 int ok = -1;
    3009                 if (Py_EnterRecursiveCall(" in __subclasscheck__")) {
    3010                         Py_DECREF(checker);
    3011                         return ok;
    3012                 }
    3013                 res = PyObject_CallFunctionObjArgs(checker, derived, NULL);
    3014                 Py_LeaveRecursiveCall();
    3015                 Py_DECREF(checker);
    3016                 if (res != NULL) {
    3017                         ok = PyObject_IsTrue(res);
    3018                         Py_DECREF(res);
    3019                 }
    3020                 return ok;
    3021         }
    3022         return recursive_issubclass(derived, cls);
     3011    static PyObject *name = NULL;
     3012
     3013    if (PyTuple_Check(cls)) {
     3014        Py_ssize_t i;
     3015        Py_ssize_t n;
     3016        int r = 0;
     3017
     3018        if (Py_EnterRecursiveCall(" in __subclasscheck__"))
     3019            return -1;
     3020        n = PyTuple_GET_SIZE(cls);
     3021        for (i = 0; i < n; ++i) {
     3022            PyObject *item = PyTuple_GET_ITEM(cls, i);
     3023            r = PyObject_IsSubclass(derived, item);
     3024            if (r != 0)
     3025                /* either found it, or got an error */
     3026                break;
     3027        }
     3028        Py_LeaveRecursiveCall();
     3029        return r;
     3030    }
     3031    if (!(PyClass_Check(cls) || PyInstance_Check(cls))) {
     3032        PyObject *checker;
     3033        checker = _PyObject_LookupSpecial(cls, "__subclasscheck__", &name);
     3034        if (checker != NULL) {
     3035            PyObject *res;
     3036            int ok = -1;
     3037            if (Py_EnterRecursiveCall(" in __subclasscheck__")) {
     3038                Py_DECREF(checker);
     3039                return ok;
     3040            }
     3041            res = PyObject_CallFunctionObjArgs(checker, derived, NULL);
     3042            Py_LeaveRecursiveCall();
     3043            Py_DECREF(checker);
     3044            if (res != NULL) {
     3045                ok = PyObject_IsTrue(res);
     3046                Py_DECREF(res);
     3047            }
     3048            return ok;
     3049        }
     3050        else if (PyErr_Occurred()) {
     3051            return -1;
     3052        }
     3053    }
     3054    return recursive_issubclass(derived, cls);
    30233055}
    30243056
     
    30263058_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
    30273059{
    3028         return recursive_isinstance(inst, cls);
     3060    return recursive_isinstance(inst, cls);
    30293061}
    30303062
     
    30323064_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
    30333065{
    3034         return recursive_issubclass(derived, cls);
     3066    return recursive_issubclass(derived, cls);
    30353067}
    30363068
     
    30393071PyObject_GetIter(PyObject *o)
    30403072{
    3041         PyTypeObject *t = o->ob_type;
    3042         getiterfunc f = NULL;
    3043         if (PyType_HasFeature(t, Py_TPFLAGS_HAVE_ITER))
    3044                 f = t->tp_iter;
    3045         if (f == NULL) {
    3046                 if (PySequence_Check(o))
    3047                         return PySeqIter_New(o);
    3048                 return type_error("'%.200s' object is not iterable", o);
    3049         }
    3050         else {
    3051                 PyObject *res = (*f)(o);
    3052                 if (res != NULL && !PyIter_Check(res)) {
    3053                         PyErr_Format(PyExc_TypeError,
    3054                                      "iter() returned non-iterator "
    3055                                      "of type '%.100s'",
    3056                                      res->ob_type->tp_name);
    3057                         Py_DECREF(res);
    3058                         res = NULL;
    3059                 }
    3060                 return res;
    3061         }
     3073    PyTypeObject *t = o->ob_type;
     3074    getiterfunc f = NULL;
     3075    if (PyType_HasFeature(t, Py_TPFLAGS_HAVE_ITER))
     3076        f = t->tp_iter;
     3077    if (f == NULL) {
     3078        if (PySequence_Check(o))
     3079            return PySeqIter_New(o);
     3080        return type_error("'%.200s' object is not iterable", o);
     3081    }
     3082    else {
     3083        PyObject *res = (*f)(o);
     3084        if (res != NULL && !PyIter_Check(res)) {
     3085            PyErr_Format(PyExc_TypeError,
     3086                         "iter() returned non-iterator "
     3087                         "of type '%.100s'",
     3088                         res->ob_type->tp_name);
     3089            Py_DECREF(res);
     3090            res = NULL;
     3091        }
     3092        return res;
     3093    }
    30623094}
    30633095
     
    30723104PyIter_Next(PyObject *iter)
    30733105{
    3074         PyObject *result;
    3075         assert(PyIter_Check(iter));
    3076         result = (*iter->ob_type->tp_iternext)(iter);
    3077         if (result == NULL &&
    3078             PyErr_Occurred() &&
    3079             PyErr_ExceptionMatches(PyExc_StopIteration))
    3080                 PyErr_Clear();
    3081         return result;
    3082 }
     3106    PyObject *result;
     3107    result = (*iter->ob_type->tp_iternext)(iter);
     3108    if (result == NULL &&
     3109        PyErr_Occurred() &&
     3110        PyErr_ExceptionMatches(PyExc_StopIteration))
     3111        PyErr_Clear();
     3112    return result;
     3113}
Note: See TracChangeset for help on using the changeset viewer.