LCOV - code coverage report
Current view: top level - Objects - classobject.c (source / functions) Hit Total Coverage
Test: CPython lcov report Lines: 470 1389 33.8 %
Date: 2017-04-19 Functions: 38 110 34.5 %

          Line data    Source code
       1             : 
       2             : /* Class object implementation */
       3             : 
       4             : #include "Python.h"
       5             : #include "structmember.h"
       6             : 
       7             : /* Free list for method objects to save malloc/free overhead
       8             :  * The im_self element is used to chain the elements.
       9             :  */
      10             : static PyMethodObject *free_list;
      11             : static int numfree = 0;
      12             : #ifndef PyMethod_MAXFREELIST
      13             : #define PyMethod_MAXFREELIST 256
      14             : #endif
      15             : 
      16             : #define TP_DESCR_GET(t) \
      17             :     (PyType_HasFeature(t, Py_TPFLAGS_HAVE_CLASS) ? (t)->tp_descr_get : NULL)
      18             : 
      19             : /* Forward */
      20             : static PyObject *class_lookup(PyClassObject *, PyObject *,
      21             :                               PyClassObject **);
      22             : static PyObject *instance_getattr1(PyInstanceObject *, PyObject *);
      23             : static PyObject *instance_getattr2(PyInstanceObject *, PyObject *);
      24             : 
      25             : static PyObject *getattrstr, *setattrstr, *delattrstr;
      26             : 
      27             : 
      28             : PyObject *
      29         264 : PyClass_New(PyObject *bases, PyObject *dict, PyObject *name)
      30             :      /* bases is NULL or tuple of classobjects! */
      31             : {
      32             :     PyClassObject *op, *dummy;
      33             :     static PyObject *docstr, *modstr, *namestr;
      34         264 :     if (docstr == NULL) {
      35           3 :         docstr= PyString_InternFromString("__doc__");
      36           3 :         if (docstr == NULL)
      37           0 :             return NULL;
      38             :     }
      39         264 :     if (modstr == NULL) {
      40           3 :         modstr= PyString_InternFromString("__module__");
      41           3 :         if (modstr == NULL)
      42           0 :             return NULL;
      43             :     }
      44         264 :     if (namestr == NULL) {
      45           3 :         namestr= PyString_InternFromString("__name__");
      46           3 :         if (namestr == NULL)
      47           0 :             return NULL;
      48             :     }
      49         264 :     if (name == NULL || !PyString_Check(name)) {
      50           0 :         PyErr_SetString(PyExc_TypeError,
      51             :                         "PyClass_New: name must be a string");
      52           0 :         return NULL;
      53             :     }
      54         264 :     if (dict == NULL || !PyDict_Check(dict)) {
      55           0 :         PyErr_SetString(PyExc_TypeError,
      56             :                         "PyClass_New: dict must be a dictionary");
      57           0 :         return NULL;
      58             :     }
      59         264 :     if (PyDict_GetItem(dict, docstr) == NULL) {
      60         123 :         if (PyDict_SetItem(dict, docstr, Py_None) < 0)
      61           0 :             return NULL;
      62             :     }
      63         264 :     if (PyDict_GetItem(dict, modstr) == NULL) {
      64           0 :         PyObject *globals = PyEval_GetGlobals();
      65           0 :         if (globals != NULL) {
      66           0 :             PyObject *modname = PyDict_GetItem(globals, namestr);
      67           0 :             if (modname != NULL) {
      68           0 :                 if (PyDict_SetItem(dict, modstr, modname) < 0)
      69           0 :                     return NULL;
      70             :             }
      71             :         }
      72             :     }
      73         264 :     if (bases == NULL) {
      74           0 :         bases = PyTuple_New(0);
      75           0 :         if (bases == NULL)
      76           0 :             return NULL;
      77             :     }
      78             :     else {
      79             :         Py_ssize_t i, n;
      80             :         PyObject *base;
      81         264 :         if (!PyTuple_Check(bases)) {
      82           0 :             PyErr_SetString(PyExc_TypeError,
      83             :                             "PyClass_New: bases must be a tuple");
      84           0 :             return NULL;
      85             :         }
      86         264 :         n = PyTuple_Size(bases);
      87         366 :         for (i = 0; i < n; i++) {
      88         102 :             base = PyTuple_GET_ITEM(bases, i);
      89         102 :             if (!PyClass_Check(base)) {
      90           0 :                 if (PyCallable_Check(
      91           0 :                     (PyObject *) base->ob_type))
      92           0 :                     return PyObject_CallFunctionObjArgs(
      93           0 :                         (PyObject *) base->ob_type,
      94             :                         name, bases, dict, NULL);
      95           0 :                 PyErr_SetString(PyExc_TypeError,
      96             :                     "PyClass_New: base must be a class");
      97           0 :                 return NULL;
      98             :             }
      99             :         }
     100         264 :         Py_INCREF(bases);
     101             :     }
     102             : 
     103         264 :     if (getattrstr == NULL) {
     104           3 :         getattrstr = PyString_InternFromString("__getattr__");
     105           3 :         if (getattrstr == NULL)
     106           0 :             goto alloc_error;
     107           3 :         setattrstr = PyString_InternFromString("__setattr__");
     108           3 :         if (setattrstr == NULL)
     109           0 :             goto alloc_error;
     110           3 :         delattrstr = PyString_InternFromString("__delattr__");
     111           3 :         if (delattrstr == NULL)
     112           0 :             goto alloc_error;
     113             :     }
     114             : 
     115         264 :     op = PyObject_GC_New(PyClassObject, &PyClass_Type);
     116         264 :     if (op == NULL) {
     117             : alloc_error:
     118           0 :         Py_DECREF(bases);
     119           0 :         return NULL;
     120             :     }
     121         264 :     op->cl_bases = bases;
     122         264 :     Py_INCREF(dict);
     123         264 :     op->cl_dict = dict;
     124         264 :     Py_XINCREF(name);
     125         264 :     op->cl_name = name;
     126         264 :     op->cl_weakreflist = NULL;
     127             : 
     128         264 :     op->cl_getattr = class_lookup(op, getattrstr, &dummy);
     129         264 :     op->cl_setattr = class_lookup(op, setattrstr, &dummy);
     130         264 :     op->cl_delattr = class_lookup(op, delattrstr, &dummy);
     131         264 :     Py_XINCREF(op->cl_getattr);
     132         264 :     Py_XINCREF(op->cl_setattr);
     133         264 :     Py_XINCREF(op->cl_delattr);
     134         264 :     _PyObject_GC_TRACK(op);
     135         264 :     return (PyObject *) op;
     136             : }
     137             : 
     138             : PyObject *
     139           0 : PyMethod_Function(PyObject *im)
     140             : {
     141           0 :     if (!PyMethod_Check(im)) {
     142           0 :         PyErr_BadInternalCall();
     143           0 :         return NULL;
     144             :     }
     145           0 :     return ((PyMethodObject *)im)->im_func;
     146             : }
     147             : 
     148             : PyObject *
     149           0 : PyMethod_Self(PyObject *im)
     150             : {
     151           0 :     if (!PyMethod_Check(im)) {
     152           0 :         PyErr_BadInternalCall();
     153           0 :         return NULL;
     154             :     }
     155           0 :     return ((PyMethodObject *)im)->im_self;
     156             : }
     157             : 
     158             : PyObject *
     159           0 : PyMethod_Class(PyObject *im)
     160             : {
     161           0 :     if (!PyMethod_Check(im)) {
     162           0 :         PyErr_BadInternalCall();
     163           0 :         return NULL;
     164             :     }
     165           0 :     return ((PyMethodObject *)im)->im_class;
     166             : }
     167             : 
     168             : PyDoc_STRVAR(class_doc,
     169             : "classobj(name, bases, dict)\n\
     170             : \n\
     171             : Create a class object.  The name must be a string; the second argument\n\
     172             : a tuple of classes, and the third a dictionary.");
     173             : 
     174             : static PyObject *
     175         264 : class_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
     176             : {
     177             :     PyObject *name, *bases, *dict;
     178             :     static char *kwlist[] = {"name", "bases", "dict", 0};
     179             : 
     180         264 :     if (!PyArg_ParseTupleAndKeywords(args, kwds, "SOO", kwlist,
     181             :                                      &name, &bases, &dict))
     182           0 :         return NULL;
     183         264 :     return PyClass_New(bases, dict, name);
     184             : }
     185             : 
     186             : /* Class methods */
     187             : 
     188             : static void
     189         231 : class_dealloc(PyClassObject *op)
     190             : {
     191         231 :     _PyObject_GC_UNTRACK(op);
     192         231 :     if (op->cl_weakreflist != NULL)
     193           3 :         PyObject_ClearWeakRefs((PyObject *) op);
     194         231 :     Py_DECREF(op->cl_bases);
     195         231 :     Py_DECREF(op->cl_dict);
     196         231 :     Py_XDECREF(op->cl_name);
     197         231 :     Py_XDECREF(op->cl_getattr);
     198         231 :     Py_XDECREF(op->cl_setattr);
     199         231 :     Py_XDECREF(op->cl_delattr);
     200         231 :     PyObject_GC_Del(op);
     201         231 : }
     202             : 
     203             : static PyObject *
     204       59178 : class_lookup(PyClassObject *cp, PyObject *name, PyClassObject **pclass)
     205             : {
     206             :     Py_ssize_t i, n;
     207       59178 :     PyObject *value = PyDict_GetItem(cp->cl_dict, name);
     208       59178 :     if (value != NULL) {
     209       48605 :         *pclass = cp;
     210       48605 :         return value;
     211             :     }
     212       10573 :     n = PyTuple_Size(cp->cl_bases);
     213       11707 :     for (i = 0; i < n; i++) {
     214             :         /* XXX What if one of the bases is not a class? */
     215        1378 :         PyObject *v = class_lookup(
     216             :             (PyClassObject *)
     217        1378 :             PyTuple_GetItem(cp->cl_bases, i), name, pclass);
     218        1378 :         if (v != NULL)
     219         244 :             return v;
     220             :     }
     221       10329 :     return NULL;
     222             : }
     223             : 
     224             : static PyObject *
     225        6108 : class_getattr(register PyClassObject *op, PyObject *name)
     226             : {
     227             :     register PyObject *v;
     228             :     register char *sname;
     229             :     PyClassObject *klass;
     230             :     descrgetfunc f;
     231             : 
     232        6108 :     if (!PyString_Check(name)) {
     233           0 :         PyErr_SetString(PyExc_TypeError, "attribute name must be a string");
     234           0 :         return NULL;
     235             :     }
     236             : 
     237        6108 :     sname = PyString_AsString(name);
     238        6108 :     if (sname[0] == '_' && sname[1] == '_') {
     239         174 :         if (strcmp(sname, "__dict__") == 0) {
     240           0 :             if (PyEval_GetRestricted()) {
     241           0 :                 PyErr_SetString(PyExc_RuntimeError,
     242             :                "class.__dict__ not accessible in restricted mode");
     243           0 :                 return NULL;
     244             :             }
     245           0 :             Py_INCREF(op->cl_dict);
     246           0 :             return op->cl_dict;
     247             :         }
     248         174 :         if (strcmp(sname, "__bases__") == 0) {
     249          12 :             Py_INCREF(op->cl_bases);
     250          12 :             return op->cl_bases;
     251             :         }
     252         162 :         if (strcmp(sname, "__name__") == 0) {
     253          36 :             if (op->cl_name == NULL)
     254           0 :                 v = Py_None;
     255             :             else
     256          36 :                 v = op->cl_name;
     257          36 :             Py_INCREF(v);
     258          36 :             return v;
     259             :         }
     260             :     }
     261        6060 :     v = class_lookup(op, name, &klass);
     262        6060 :     if (v == NULL) {
     263         111 :         PyErr_Format(PyExc_AttributeError,
     264             :                      "class %.50s has no attribute '%.400s'",
     265         111 :                      PyString_AS_STRING(op->cl_name), sname);
     266         111 :         return NULL;
     267             :     }
     268        5949 :     f = TP_DESCR_GET(v->ob_type);
     269        5949 :     if (f == NULL)
     270        5931 :         Py_INCREF(v);
     271             :     else
     272          18 :         v = f(v, (PyObject *)NULL, (PyObject *)op);
     273        5949 :     return v;
     274             : }
     275             : 
     276             : static void
     277           0 : set_slot(PyObject **slot, PyObject *v)
     278             : {
     279           0 :     PyObject *temp = *slot;
     280           0 :     Py_XINCREF(v);
     281           0 :     *slot = v;
     282           0 :     Py_XDECREF(temp);
     283           0 : }
     284             : 
     285             : static void
     286           0 : set_attr_slots(PyClassObject *c)
     287             : {
     288             :     PyClassObject *dummy;
     289             : 
     290           0 :     set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy));
     291           0 :     set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy));
     292           0 :     set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy));
     293           0 : }
     294             : 
     295             : static char *
     296           0 : set_dict(PyClassObject *c, PyObject *v)
     297             : {
     298           0 :     if (v == NULL || !PyDict_Check(v))
     299           0 :         return "__dict__ must be a dictionary object";
     300           0 :     set_slot(&c->cl_dict, v);
     301           0 :     set_attr_slots(c);
     302           0 :     return "";
     303             : }
     304             : 
     305             : static char *
     306           0 : set_bases(PyClassObject *c, PyObject *v)
     307             : {
     308             :     Py_ssize_t i, n;
     309             : 
     310           0 :     if (v == NULL || !PyTuple_Check(v))
     311           0 :         return "__bases__ must be a tuple object";
     312           0 :     n = PyTuple_Size(v);
     313           0 :     for (i = 0; i < n; i++) {
     314           0 :         PyObject *x = PyTuple_GET_ITEM(v, i);
     315           0 :         if (!PyClass_Check(x))
     316           0 :             return "__bases__ items must be classes";
     317           0 :         if (PyClass_IsSubclass(x, (PyObject *)c))
     318           0 :             return "a __bases__ item causes an inheritance cycle";
     319             :     }
     320           0 :     set_slot(&c->cl_bases, v);
     321           0 :     set_attr_slots(c);
     322           0 :     return "";
     323             : }
     324             : 
     325             : static char *
     326           0 : set_name(PyClassObject *c, PyObject *v)
     327             : {
     328           0 :     if (v == NULL || !PyString_Check(v))
     329           0 :         return "__name__ must be a string object";
     330           0 :     if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v))
     331           0 :         return "__name__ must not contain null bytes";
     332           0 :     set_slot(&c->cl_name, v);
     333           0 :     return "";
     334             : }
     335             : 
     336             : static int
     337           0 : class_setattr(PyClassObject *op, PyObject *name, PyObject *v)
     338             : {
     339             :     char *sname;
     340           0 :     if (PyEval_GetRestricted()) {
     341           0 :         PyErr_SetString(PyExc_RuntimeError,
     342             :                    "classes are read-only in restricted mode");
     343           0 :         return -1;
     344             :     }
     345           0 :     if (!PyString_Check(name)) {
     346           0 :         PyErr_SetString(PyExc_TypeError, "attribute name must be a string");
     347           0 :         return -1;
     348             :     }
     349           0 :     sname = PyString_AsString(name);
     350           0 :     if (sname[0] == '_' && sname[1] == '_') {
     351           0 :         Py_ssize_t n = PyString_Size(name);
     352           0 :         if (sname[n-1] == '_' && sname[n-2] == '_') {
     353           0 :             char *err = NULL;
     354           0 :             if (strcmp(sname, "__dict__") == 0)
     355           0 :                 err = set_dict(op, v);
     356           0 :             else if (strcmp(sname, "__bases__") == 0)
     357           0 :                 err = set_bases(op, v);
     358           0 :             else if (strcmp(sname, "__name__") == 0)
     359           0 :                 err = set_name(op, v);
     360           0 :             else if (strcmp(sname, "__getattr__") == 0)
     361           0 :                 set_slot(&op->cl_getattr, v);
     362           0 :             else if (strcmp(sname, "__setattr__") == 0)
     363           0 :                 set_slot(&op->cl_setattr, v);
     364           0 :             else if (strcmp(sname, "__delattr__") == 0)
     365           0 :                 set_slot(&op->cl_delattr, v);
     366             :             /* For the last three, we fall through to update the
     367             :                dictionary as well. */
     368           0 :             if (err != NULL) {
     369           0 :                 if (*err == '\0')
     370           0 :                     return 0;
     371           0 :                 PyErr_SetString(PyExc_TypeError, err);
     372           0 :                 return -1;
     373             :             }
     374             :         }
     375             :     }
     376           0 :     if (v == NULL) {
     377           0 :         int rv = PyDict_DelItem(op->cl_dict, name);
     378           0 :         if (rv < 0)
     379           0 :             PyErr_Format(PyExc_AttributeError,
     380             :                          "class %.50s has no attribute '%.400s'",
     381           0 :                          PyString_AS_STRING(op->cl_name), sname);
     382           0 :         return rv;
     383             :     }
     384             :     else
     385           0 :         return PyDict_SetItem(op->cl_dict, name, v);
     386             : }
     387             : 
     388             : static PyObject *
     389           0 : class_repr(PyClassObject *op)
     390             : {
     391           0 :     PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
     392             :     char *name;
     393           0 :     if (op->cl_name == NULL || !PyString_Check(op->cl_name))
     394           0 :         name = "?";
     395             :     else
     396           0 :         name = PyString_AsString(op->cl_name);
     397           0 :     if (mod == NULL || !PyString_Check(mod))
     398           0 :         return PyString_FromFormat("<class ?.%s at %p>", name, op);
     399             :     else
     400           0 :         return PyString_FromFormat("<class %s.%s at %p>",
     401             :                                    PyString_AsString(mod),
     402             :                                    name, op);
     403             : }
     404             : 
     405             : static PyObject *
     406           0 : class_str(PyClassObject *op)
     407             : {
     408           0 :     PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
     409           0 :     PyObject *name = op->cl_name;
     410             :     PyObject *res;
     411             :     Py_ssize_t m, n;
     412             : 
     413           0 :     if (name == NULL || !PyString_Check(name))
     414           0 :         return class_repr(op);
     415           0 :     if (mod == NULL || !PyString_Check(mod)) {
     416           0 :         Py_INCREF(name);
     417           0 :         return name;
     418             :     }
     419           0 :     m = PyString_GET_SIZE(mod);
     420           0 :     n = PyString_GET_SIZE(name);
     421           0 :     res = PyString_FromStringAndSize((char *)NULL, m+1+n);
     422           0 :     if (res != NULL) {
     423           0 :         char *s = PyString_AS_STRING(res);
     424           0 :         memcpy(s, PyString_AS_STRING(mod), m);
     425           0 :         s += m;
     426           0 :         *s++ = '.';
     427           0 :         memcpy(s, PyString_AS_STRING(name), n);
     428             :     }
     429           0 :     return res;
     430             : }
     431             : 
     432             : static int
     433        1488 : class_traverse(PyClassObject *o, visitproc visit, void *arg)
     434             : {
     435        1488 :     Py_VISIT(o->cl_bases);
     436        1488 :     Py_VISIT(o->cl_dict);
     437        1488 :     Py_VISIT(o->cl_name);
     438        1488 :     Py_VISIT(o->cl_getattr);
     439        1488 :     Py_VISIT(o->cl_setattr);
     440        1488 :     Py_VISIT(o->cl_delattr);
     441        1488 :     return 0;
     442             : }
     443             : 
     444             : PyTypeObject PyClass_Type = {
     445             :     PyObject_HEAD_INIT(&PyType_Type)
     446             :     0,
     447             :     "classobj",
     448             :     sizeof(PyClassObject),
     449             :     0,
     450             :     (destructor)class_dealloc,                  /* tp_dealloc */
     451             :     0,                                          /* tp_print */
     452             :     0,                                          /* tp_getattr */
     453             :     0,                                          /* tp_setattr */
     454             :     0,                                          /* tp_compare */
     455             :     (reprfunc)class_repr,                       /* tp_repr */
     456             :     0,                                          /* tp_as_number */
     457             :     0,                                          /* tp_as_sequence */
     458             :     0,                                          /* tp_as_mapping */
     459             :     0,                                          /* tp_hash */
     460             :     PyInstance_New,                             /* tp_call */
     461             :     (reprfunc)class_str,                        /* tp_str */
     462             :     (getattrofunc)class_getattr,                /* tp_getattro */
     463             :     (setattrofunc)class_setattr,                /* tp_setattro */
     464             :     0,                                          /* tp_as_buffer */
     465             :     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
     466             :     class_doc,                                  /* tp_doc */
     467             :     (traverseproc)class_traverse,               /* tp_traverse */
     468             :     0,                                          /* tp_clear */
     469             :     0,                                          /* tp_richcompare */
     470             :     offsetof(PyClassObject, cl_weakreflist), /* tp_weaklistoffset */
     471             :     0,                                          /* tp_iter */
     472             :     0,                                          /* tp_iternext */
     473             :     0,                                          /* tp_methods */
     474             :     0,                                          /* tp_members */
     475             :     0,                                          /* tp_getset */
     476             :     0,                                          /* tp_base */
     477             :     0,                                          /* tp_dict */
     478             :     0,                                          /* tp_descr_get */
     479             :     0,                                          /* tp_descr_set */
     480             :     0,                                          /* tp_dictoffset */
     481             :     0,                                          /* tp_init */
     482             :     0,                                          /* tp_alloc */
     483             :     class_new,                                  /* tp_new */
     484             : };
     485             : 
     486             : int
     487        4513 : PyClass_IsSubclass(PyObject *klass, PyObject *base)
     488             : {
     489             :     Py_ssize_t i, n;
     490             :     PyClassObject *cp;
     491        4513 :     if (klass == base)
     492        1222 :         return 1;
     493        3291 :     if (PyTuple_Check(base)) {
     494           0 :         n = PyTuple_GET_SIZE(base);
     495           0 :         for (i = 0; i < n; i++) {
     496           0 :             if (PyClass_IsSubclass(klass, PyTuple_GET_ITEM(base, i)))
     497           0 :                 return 1;
     498             :         }
     499           0 :         return 0;
     500             :     }
     501        3291 :     if (klass == NULL || !PyClass_Check(klass))
     502           0 :         return 0;
     503        3291 :     cp = (PyClassObject *)klass;
     504        3291 :     n = PyTuple_Size(cp->cl_bases);
     505        3741 :     for (i = 0; i < n; i++) {
     506         468 :         if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
     507          18 :             return 1;
     508             :     }
     509        3273 :     return 0;
     510             : }
     511             : 
     512             : 
     513             : /* Instance objects */
     514             : 
     515             : PyObject *
     516        5331 : PyInstance_NewRaw(PyObject *klass, PyObject *dict)
     517             : {
     518             :     PyInstanceObject *inst;
     519             : 
     520        5331 :     if (!PyClass_Check(klass)) {
     521           0 :         PyErr_BadInternalCall();
     522           0 :         return NULL;
     523             :     }
     524        5331 :     if (dict == NULL) {
     525        5331 :         dict = PyDict_New();
     526        5331 :         if (dict == NULL)
     527           0 :             return NULL;
     528             :     }
     529             :     else {
     530           0 :         if (!PyDict_Check(dict)) {
     531           0 :             PyErr_BadInternalCall();
     532           0 :             return NULL;
     533             :         }
     534           0 :         Py_INCREF(dict);
     535             :     }
     536        5331 :     inst = PyObject_GC_New(PyInstanceObject, &PyInstance_Type);
     537        5331 :     if (inst == NULL) {
     538           0 :         Py_DECREF(dict);
     539           0 :         return NULL;
     540             :     }
     541        5331 :     inst->in_weakreflist = NULL;
     542        5331 :     Py_INCREF(klass);
     543        5331 :     inst->in_class = (PyClassObject *)klass;
     544        5331 :     inst->in_dict = dict;
     545        5331 :     _PyObject_GC_TRACK(inst);
     546        5331 :     return (PyObject *)inst;
     547             : }
     548             : 
     549             : PyObject *
     550        5331 : PyInstance_New(PyObject *klass, PyObject *arg, PyObject *kw)
     551             : {
     552             :     register PyInstanceObject *inst;
     553             :     PyObject *init;
     554             :     static PyObject *initstr;
     555             : 
     556        5331 :     if (initstr == NULL) {
     557           3 :         initstr = PyString_InternFromString("__init__");
     558           3 :         if (initstr == NULL)
     559           0 :             return NULL;
     560             :     }
     561        5331 :     inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL);
     562        5331 :     if (inst == NULL)
     563           0 :         return NULL;
     564        5331 :     init = instance_getattr2(inst, initstr);
     565        5331 :     if (init == NULL) {
     566         258 :         if (PyErr_Occurred()) {
     567           0 :             Py_DECREF(inst);
     568           0 :             return NULL;
     569             :         }
     570         516 :         if ((arg != NULL && (!PyTuple_Check(arg) ||
     571         258 :                              PyTuple_Size(arg) != 0))
     572         258 :             || (kw != NULL && (!PyDict_Check(kw) ||
     573           0 :                               PyDict_Size(kw) != 0))) {
     574           0 :             PyErr_SetString(PyExc_TypeError,
     575             :                        "this constructor takes no arguments");
     576           0 :             Py_DECREF(inst);
     577           0 :             inst = NULL;
     578             :         }
     579             :     }
     580             :     else {
     581        5073 :         PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
     582        5073 :         Py_DECREF(init);
     583        5073 :         if (res == NULL) {
     584           0 :             Py_DECREF(inst);
     585           0 :             inst = NULL;
     586             :         }
     587             :         else {
     588        5073 :             if (res != Py_None) {
     589           0 :                 PyErr_SetString(PyExc_TypeError,
     590             :                            "__init__() should return None");
     591           0 :                 Py_DECREF(inst);
     592           0 :                 inst = NULL;
     593             :             }
     594        5073 :             Py_DECREF(res);
     595             :         }
     596             :     }
     597        5331 :     return (PyObject *)inst;
     598             : }
     599             : 
     600             : /* Instance methods */
     601             : 
     602             : PyDoc_STRVAR(instance_doc,
     603             : "instance(class[, dict])\n\
     604             : \n\
     605             : Create an instance without calling its __init__() method.\n\
     606             : The class must be a classic class.\n\
     607             : If present, dict must be a dictionary or None.");
     608             : 
     609             : static PyObject *
     610           0 : instance_new(PyTypeObject* type, PyObject* args, PyObject *kw)
     611             : {
     612             :     PyObject *klass;
     613           0 :     PyObject *dict = Py_None;
     614             : 
     615           0 :     if (!PyArg_ParseTuple(args, "O!|O:instance",
     616             :                           &PyClass_Type, &klass, &dict))
     617           0 :         return NULL;
     618             : 
     619           0 :     if (dict == Py_None)
     620           0 :         dict = NULL;
     621           0 :     else if (!PyDict_Check(dict)) {
     622           0 :         PyErr_SetString(PyExc_TypeError,
     623             :               "instance() second arg must be dictionary or None");
     624           0 :         return NULL;
     625             :     }
     626           0 :     return PyInstance_NewRaw(klass, dict);
     627             : }
     628             : 
     629             : 
     630             : static void
     631        3900 : instance_dealloc(register PyInstanceObject *inst)
     632             : {
     633             :     PyObject *error_type, *error_value, *error_traceback;
     634             :     PyObject *del;
     635             :     static PyObject *delstr;
     636             : 
     637        3900 :     _PyObject_GC_UNTRACK(inst);
     638        3900 :     if (inst->in_weakreflist != NULL)
     639           0 :         PyObject_ClearWeakRefs((PyObject *) inst);
     640             : 
     641             :     /* Temporarily resurrect the object. */
     642             :     assert(inst->ob_type == &PyInstance_Type);
     643             :     assert(inst->ob_refcnt == 0);
     644        3900 :     inst->ob_refcnt = 1;
     645             : 
     646             :     /* Save the current exception, if any. */
     647        3900 :     PyErr_Fetch(&error_type, &error_value, &error_traceback);
     648             :     /* Execute __del__ method, if any. */
     649        3900 :     if (delstr == NULL) {
     650           3 :         delstr = PyString_InternFromString("__del__");
     651           3 :         if (delstr == NULL)
     652           0 :             PyErr_WriteUnraisable((PyObject*)inst);
     653             :     }
     654        3900 :     if (delstr && (del = instance_getattr2(inst, delstr)) != NULL) {
     655           0 :         PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
     656           0 :         if (res == NULL)
     657           0 :             PyErr_WriteUnraisable(del);
     658             :         else
     659           0 :             Py_DECREF(res);
     660           0 :         Py_DECREF(del);
     661             :     }
     662             :     /* Restore the saved exception. */
     663        3900 :     PyErr_Restore(error_type, error_value, error_traceback);
     664             : 
     665             :     /* Undo the temporary resurrection; can't use DECREF here, it would
     666             :      * cause a recursive call.
     667             :      */
     668             :     assert(inst->ob_refcnt > 0);
     669        3900 :     if (--inst->ob_refcnt == 0) {
     670             : 
     671             :         /* New weakrefs could be created during the finalizer call.
     672             :             If this occurs, clear them out without calling their
     673             :             finalizers since they might rely on part of the object
     674             :             being finalized that has already been destroyed. */
     675        7800 :         while (inst->in_weakreflist != NULL) {
     676           0 :             _PyWeakref_ClearRef((PyWeakReference *)
     677           0 :                                 (inst->in_weakreflist));
     678             :         }
     679             : 
     680        3900 :         Py_DECREF(inst->in_class);
     681        3900 :         Py_XDECREF(inst->in_dict);
     682        3900 :         PyObject_GC_Del(inst);
     683             :     }
     684             :     else {
     685           0 :         Py_ssize_t refcnt = inst->ob_refcnt;
     686             :         /* __del__ resurrected it!  Make it look like the original
     687             :          * Py_DECREF never happened.
     688             :          */
     689           0 :         _Py_NewReference((PyObject *)inst);
     690           0 :         inst->ob_refcnt = refcnt;
     691           0 :         _PyObject_GC_TRACK(inst);
     692             :         /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
     693             :          * we need to undo that. */
     694             :         _Py_DEC_REFTOTAL;
     695             :         /* If Py_TRACE_REFS, _Py_NewReference re-added self to the
     696             :          * object chain, so no more to do there.
     697             :          * If COUNT_ALLOCS, the original decref bumped tp_frees, and
     698             :          * _Py_NewReference bumped tp_allocs: both of those need to be
     699             :          * undone.
     700             :          */
     701             : #ifdef COUNT_ALLOCS
     702             :         --inst->ob_type->tp_frees;
     703             :         --inst->ob_type->tp_allocs;
     704             : #endif
     705             :     }
     706        3900 : }
     707             : 
     708             : static PyObject *
     709      178278 : instance_getattr1(register PyInstanceObject *inst, PyObject *name)
     710             : {
     711             :     register PyObject *v;
     712             :     register char *sname;
     713             : 
     714      178278 :     if (!PyString_Check(name)) {
     715           0 :         PyErr_SetString(PyExc_TypeError, "attribute name must be a string");
     716           0 :         return NULL;
     717             :     }
     718             : 
     719      178278 :     sname = PyString_AsString(name);
     720      178278 :     if (sname[0] == '_' && sname[1] == '_') {
     721       15936 :         if (strcmp(sname, "__dict__") == 0) {
     722           0 :             if (PyEval_GetRestricted()) {
     723           0 :                 PyErr_SetString(PyExc_RuntimeError,
     724             :             "instance.__dict__ not accessible in restricted mode");
     725           0 :                 return NULL;
     726             :             }
     727           0 :             Py_INCREF(inst->in_dict);
     728           0 :             return inst->in_dict;
     729             :         }
     730       15936 :         if (strcmp(sname, "__class__") == 0) {
     731         864 :             Py_INCREF(inst->in_class);
     732         864 :             return (PyObject *)inst->in_class;
     733             :         }
     734             :     }
     735      177414 :     v = instance_getattr2(inst, name);
     736      177414 :     if (v == NULL && !PyErr_Occurred()) {
     737        4062 :         PyErr_Format(PyExc_AttributeError,
     738             :                      "%.50s instance has no attribute '%.400s'",
     739        4062 :                      PyString_AS_STRING(inst->in_class->cl_name), sname);
     740             :     }
     741      177414 :     return v;
     742             : }
     743             : 
     744             : static PyObject *
     745      186681 : instance_getattr2(register PyInstanceObject *inst, PyObject *name)
     746             : {
     747             :     register PyObject *v;
     748             :     PyClassObject *klass;
     749             :     descrgetfunc f;
     750             : 
     751      186681 :     v = PyDict_GetItem(inst->in_dict, name);
     752      186681 :     if (v != NULL) {
     753      135793 :         Py_INCREF(v);
     754      135793 :         return v;
     755             :     }
     756       50888 :     v = class_lookup(inst->in_class, name, &klass);
     757       50888 :     if (v != NULL) {
     758       42632 :         Py_INCREF(v);
     759       42632 :         f = TP_DESCR_GET(v->ob_type);
     760       42632 :         if (f != NULL) {
     761       41909 :             PyObject *w = f(v, (PyObject *)inst,
     762       41909 :                             (PyObject *)(inst->in_class));
     763       41909 :             Py_DECREF(v);
     764       41909 :             v = w;
     765             :         }
     766             :     }
     767       50888 :     return v;
     768             : }
     769             : 
     770             : static PyObject *
     771      178278 : instance_getattr(register PyInstanceObject *inst, PyObject *name)
     772             : {
     773             :     register PyObject *func, *res;
     774      178278 :     res = instance_getattr1(inst, name);
     775      178278 :     if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
     776             :         PyObject *args;
     777           0 :         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
     778           0 :             return NULL;
     779           0 :         PyErr_Clear();
     780           0 :         args = PyTuple_Pack(2, inst, name);
     781           0 :         if (args == NULL)
     782           0 :             return NULL;
     783           0 :         res = PyEval_CallObject(func, args);
     784           0 :         Py_DECREF(args);
     785             :     }
     786      178278 :     return res;
     787             : }
     788             : 
     789             : /* See classobject.h comments:  this only does dict lookups, and is always
     790             :  * safe to call.
     791             :  */
     792             : PyObject *
     793          60 : _PyInstance_Lookup(PyObject *pinst, PyObject *name)
     794             : {
     795             :     PyObject *v;
     796             :     PyClassObject *klass;
     797             :     PyInstanceObject *inst;     /* pinst cast to the right type */
     798             : 
     799             :     assert(PyInstance_Check(pinst));
     800          60 :     inst = (PyInstanceObject *)pinst;
     801             : 
     802             :     assert(PyString_Check(name));
     803             : 
     804          60 :     v = PyDict_GetItem(inst->in_dict, name);
     805          60 :     if (v == NULL)
     806          60 :         v = class_lookup(inst->in_class, name, &klass);
     807          60 :     return v;
     808             : }
     809             : 
     810             : static int
     811       43575 : instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
     812             : {
     813       43575 :     if (v == NULL) {
     814           0 :         int rv = PyDict_DelItem(inst->in_dict, name);
     815           0 :         if (rv < 0)
     816           0 :             PyErr_Format(PyExc_AttributeError,
     817             :                          "%.50s instance has no attribute '%.400s'",
     818           0 :                          PyString_AS_STRING(inst->in_class->cl_name),
     819           0 :                          PyString_AS_STRING(name));
     820           0 :         return rv;
     821             :     }
     822             :     else
     823       43575 :         return PyDict_SetItem(inst->in_dict, name, v);
     824             : }
     825             : 
     826             : static int
     827       43575 : instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
     828             : {
     829             :     PyObject *func, *args, *res, *tmp;
     830             :     char *sname;
     831             : 
     832       43575 :     if (!PyString_Check(name)) {
     833           0 :         PyErr_SetString(PyExc_TypeError, "attribute name must be a string");
     834           0 :         return -1;
     835             :     }
     836             : 
     837       43575 :     sname = PyString_AsString(name);
     838       43575 :     if (sname[0] == '_' && sname[1] == '_') {
     839           0 :         Py_ssize_t n = PyString_Size(name);
     840           0 :         if (sname[n-1] == '_' && sname[n-2] == '_') {
     841           0 :             if (strcmp(sname, "__dict__") == 0) {
     842           0 :                 if (PyEval_GetRestricted()) {
     843           0 :                     PyErr_SetString(PyExc_RuntimeError,
     844             :                  "__dict__ not accessible in restricted mode");
     845           0 :                     return -1;
     846             :                 }
     847           0 :                 if (v == NULL || !PyDict_Check(v)) {
     848           0 :                     PyErr_SetString(PyExc_TypeError,
     849             :                        "__dict__ must be set to a dictionary");
     850           0 :                     return -1;
     851             :                 }
     852           0 :                 tmp = inst->in_dict;
     853           0 :                 Py_INCREF(v);
     854           0 :                 inst->in_dict = v;
     855           0 :                 Py_DECREF(tmp);
     856           0 :                 return 0;
     857             :             }
     858           0 :             if (strcmp(sname, "__class__") == 0) {
     859           0 :                 if (PyEval_GetRestricted()) {
     860           0 :                     PyErr_SetString(PyExc_RuntimeError,
     861             :                 "__class__ not accessible in restricted mode");
     862           0 :                     return -1;
     863             :                 }
     864           0 :                 if (v == NULL || !PyClass_Check(v)) {
     865           0 :                     PyErr_SetString(PyExc_TypeError,
     866             :                        "__class__ must be set to a class");
     867           0 :                     return -1;
     868             :                 }
     869           0 :                 tmp = (PyObject *)(inst->in_class);
     870           0 :                 Py_INCREF(v);
     871           0 :                 inst->in_class = (PyClassObject *)v;
     872           0 :                 Py_DECREF(tmp);
     873           0 :                 return 0;
     874             :             }
     875             :         }
     876             :     }
     877       43575 :     if (v == NULL)
     878           0 :         func = inst->in_class->cl_delattr;
     879             :     else
     880       43575 :         func = inst->in_class->cl_setattr;
     881       43575 :     if (func == NULL)
     882       43575 :         return instance_setattr1(inst, name, v);
     883           0 :     if (v == NULL)
     884           0 :         args = PyTuple_Pack(2, inst, name);
     885             :     else
     886           0 :         args = PyTuple_Pack(3, inst, name, v);
     887           0 :     if (args == NULL)
     888           0 :         return -1;
     889           0 :     res = PyEval_CallObject(func, args);
     890           0 :     Py_DECREF(args);
     891           0 :     if (res == NULL)
     892           0 :         return -1;
     893           0 :     Py_DECREF(res);
     894           0 :     return 0;
     895             : }
     896             : 
     897             : static PyObject *
     898           0 : instance_repr(PyInstanceObject *inst)
     899             : {
     900             :     PyObject *func;
     901             :     PyObject *res;
     902             :     static PyObject *reprstr;
     903             : 
     904           0 :     if (reprstr == NULL) {
     905           0 :         reprstr = PyString_InternFromString("__repr__");
     906           0 :         if (reprstr == NULL)
     907           0 :             return NULL;
     908             :     }
     909           0 :     func = instance_getattr(inst, reprstr);
     910           0 :     if (func == NULL) {
     911             :         PyObject *classname, *mod;
     912             :         char *cname;
     913           0 :         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
     914           0 :             return NULL;
     915           0 :         PyErr_Clear();
     916           0 :         classname = inst->in_class->cl_name;
     917           0 :         mod = PyDict_GetItemString(inst->in_class->cl_dict,
     918             :                                    "__module__");
     919           0 :         if (classname != NULL && PyString_Check(classname))
     920           0 :             cname = PyString_AsString(classname);
     921             :         else
     922           0 :             cname = "?";
     923           0 :         if (mod == NULL || !PyString_Check(mod))
     924           0 :             return PyString_FromFormat("<?.%s instance at %p>",
     925             :                                        cname, inst);
     926             :         else
     927           0 :             return PyString_FromFormat("<%s.%s instance at %p>",
     928             :                                        PyString_AsString(mod),
     929             :                                        cname, inst);
     930             :     }
     931           0 :     res = PyEval_CallObject(func, (PyObject *)NULL);
     932           0 :     Py_DECREF(func);
     933           0 :     return res;
     934             : }
     935             : 
     936             : static PyObject *
     937           0 : instance_str(PyInstanceObject *inst)
     938             : {
     939             :     PyObject *func;
     940             :     PyObject *res;
     941             :     static PyObject *strstr;
     942             : 
     943           0 :     if (strstr == NULL) {
     944           0 :         strstr = PyString_InternFromString("__str__");
     945           0 :         if (strstr == NULL)
     946           0 :             return NULL;
     947             :     }
     948           0 :     func = instance_getattr(inst, strstr);
     949           0 :     if (func == NULL) {
     950           0 :         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
     951           0 :             return NULL;
     952           0 :         PyErr_Clear();
     953           0 :         return instance_repr(inst);
     954             :     }
     955           0 :     res = PyEval_CallObject(func, (PyObject *)NULL);
     956           0 :     Py_DECREF(func);
     957           0 :     return res;
     958             : }
     959             : 
     960             : static long
     961           0 : instance_hash(PyInstanceObject *inst)
     962             : {
     963             :     PyObject *func;
     964             :     PyObject *res;
     965             :     long outcome;
     966             :     static PyObject *hashstr, *eqstr, *cmpstr;
     967             : 
     968           0 :     if (hashstr == NULL) {
     969           0 :         hashstr = PyString_InternFromString("__hash__");
     970           0 :         if (hashstr == NULL)
     971           0 :             return -1;
     972             :     }
     973           0 :     func = instance_getattr(inst, hashstr);
     974           0 :     if (func == NULL) {
     975           0 :         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
     976           0 :             return -1;
     977           0 :         PyErr_Clear();
     978             :         /* If there is no __eq__ and no __cmp__ method, we hash on the
     979             :            address.  If an __eq__ or __cmp__ method exists, there must
     980             :            be a __hash__. */
     981           0 :         if (eqstr == NULL) {
     982           0 :             eqstr = PyString_InternFromString("__eq__");
     983           0 :             if (eqstr == NULL)
     984           0 :                 return -1;
     985             :         }
     986           0 :         func = instance_getattr(inst, eqstr);
     987           0 :         if (func == NULL) {
     988           0 :             if (!PyErr_ExceptionMatches(PyExc_AttributeError))
     989           0 :                 return -1;
     990           0 :             PyErr_Clear();
     991           0 :             if (cmpstr == NULL) {
     992           0 :                 cmpstr = PyString_InternFromString("__cmp__");
     993           0 :                 if (cmpstr == NULL)
     994           0 :                     return -1;
     995             :             }
     996           0 :             func = instance_getattr(inst, cmpstr);
     997           0 :             if (func == NULL) {
     998           0 :                 if (!PyErr_ExceptionMatches(
     999             :                     PyExc_AttributeError))
    1000           0 :                     return -1;
    1001           0 :                 PyErr_Clear();
    1002           0 :                 return _Py_HashPointer(inst);
    1003             :             }
    1004             :         }
    1005           0 :         Py_XDECREF(func);
    1006           0 :         PyErr_SetString(PyExc_TypeError, "unhashable instance");
    1007           0 :         return -1;
    1008             :     }
    1009           0 :     res = PyEval_CallObject(func, (PyObject *)NULL);
    1010           0 :     Py_DECREF(func);
    1011           0 :     if (res == NULL)
    1012           0 :         return -1;
    1013           0 :     if (PyInt_Check(res) || PyLong_Check(res))
    1014             :         /* This already converts a -1 result to -2. */
    1015           0 :         outcome = res->ob_type->tp_hash(res);
    1016             :     else {
    1017           0 :         PyErr_SetString(PyExc_TypeError,
    1018             :                         "__hash__() should return an int");
    1019           0 :         outcome = -1;
    1020             :     }
    1021           0 :     Py_DECREF(res);
    1022           0 :     return outcome;
    1023             : }
    1024             : 
    1025             : static int
    1026        9578 : instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
    1027             : {
    1028        9578 :     Py_VISIT(o->in_class);
    1029        9578 :     Py_VISIT(o->in_dict);
    1030        9578 :     return 0;
    1031             : }
    1032             : 
    1033             : static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
    1034             : static PyObject *iterstr, *nextstr;
    1035             : 
    1036             : static Py_ssize_t
    1037        1284 : instance_length(PyInstanceObject *inst)
    1038             : {
    1039             :     PyObject *func;
    1040             :     PyObject *res;
    1041             :     Py_ssize_t outcome;
    1042             : 
    1043        1284 :     if (lenstr == NULL) {
    1044           0 :         lenstr = PyString_InternFromString("__len__");
    1045           0 :         if (lenstr == NULL)
    1046           0 :             return -1;
    1047             :     }
    1048        1284 :     func = instance_getattr(inst, lenstr);
    1049        1284 :     if (func == NULL)
    1050           0 :         return -1;
    1051        1284 :     res = PyEval_CallObject(func, (PyObject *)NULL);
    1052        1284 :     Py_DECREF(func);
    1053        1284 :     if (res == NULL)
    1054           0 :         return -1;
    1055        1284 :     if (PyInt_Check(res)) {
    1056        1284 :         outcome = PyInt_AsSsize_t(res);
    1057        1284 :         if (outcome == -1 && PyErr_Occurred()) {
    1058           0 :             Py_DECREF(res);
    1059           0 :             return -1;
    1060             :         }
    1061             : #if SIZEOF_SIZE_T < SIZEOF_INT
    1062             :         /* Overflow check -- range of PyInt is more than C int */
    1063             :         if (outcome != (int)outcome) {
    1064             :             PyErr_SetString(PyExc_OverflowError,
    1065             :              "__len__() should return 0 <= outcome < 2**31");
    1066             :             outcome = -1;
    1067             :         }
    1068             :         else
    1069             : #endif
    1070        1284 :         if (outcome < 0) {
    1071           0 :             PyErr_SetString(PyExc_ValueError,
    1072             :                             "__len__() should return >= 0");
    1073           0 :             outcome = -1;
    1074             :         }
    1075             :     }
    1076             :     else {
    1077           0 :         PyErr_SetString(PyExc_TypeError,
    1078             :                         "__len__() should return an int");
    1079           0 :         outcome = -1;
    1080             :     }
    1081        1284 :     Py_DECREF(res);
    1082        1284 :     return outcome;
    1083             : }
    1084             : 
    1085             : static PyObject *
    1086        2007 : instance_subscript(PyInstanceObject *inst, PyObject *key)
    1087             : {
    1088             :     PyObject *func;
    1089             :     PyObject *arg;
    1090             :     PyObject *res;
    1091             : 
    1092        2007 :     if (getitemstr == NULL) {
    1093           0 :         getitemstr = PyString_InternFromString("__getitem__");
    1094           0 :         if (getitemstr == NULL)
    1095           0 :             return NULL;
    1096             :     }
    1097        2007 :     func = instance_getattr(inst, getitemstr);
    1098        2007 :     if (func == NULL)
    1099           0 :         return NULL;
    1100        2007 :     arg = PyTuple_Pack(1, key);
    1101        2007 :     if (arg == NULL) {
    1102           0 :         Py_DECREF(func);
    1103           0 :         return NULL;
    1104             :     }
    1105        2007 :     res = PyEval_CallObject(func, arg);
    1106        2007 :     Py_DECREF(func);
    1107        2007 :     Py_DECREF(arg);
    1108        2007 :     return res;
    1109             : }
    1110             : 
    1111             : static int
    1112         570 : instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
    1113             : {
    1114             :     PyObject *func;
    1115             :     PyObject *arg;
    1116             :     PyObject *res;
    1117             : 
    1118         570 :     if (value == NULL) {
    1119           0 :         if (delitemstr == NULL) {
    1120           0 :             delitemstr = PyString_InternFromString("__delitem__");
    1121           0 :             if (delitemstr == NULL)
    1122           0 :                 return -1;
    1123             :         }
    1124           0 :         func = instance_getattr(inst, delitemstr);
    1125             :     }
    1126             :     else {
    1127         570 :         if (setitemstr == NULL) {
    1128           3 :             setitemstr = PyString_InternFromString("__setitem__");
    1129           3 :             if (setitemstr == NULL)
    1130           0 :                 return -1;
    1131             :         }
    1132         570 :         func = instance_getattr(inst, setitemstr);
    1133             :     }
    1134         570 :     if (func == NULL)
    1135           0 :         return -1;
    1136         570 :     if (value == NULL)
    1137           0 :         arg = PyTuple_Pack(1, key);
    1138             :     else
    1139         570 :         arg = PyTuple_Pack(2, key, value);
    1140         570 :     if (arg == NULL) {
    1141           0 :         Py_DECREF(func);
    1142           0 :         return -1;
    1143             :     }
    1144         570 :     res = PyEval_CallObject(func, arg);
    1145         570 :     Py_DECREF(func);
    1146         570 :     Py_DECREF(arg);
    1147         570 :     if (res == NULL)
    1148           0 :         return -1;
    1149         570 :     Py_DECREF(res);
    1150         570 :     return 0;
    1151             : }
    1152             : 
    1153             : static PyMappingMethods instance_as_mapping = {
    1154             :     (lenfunc)instance_length,                   /* mp_length */
    1155             :     (binaryfunc)instance_subscript,             /* mp_subscript */
    1156             :     (objobjargproc)instance_ass_subscript,      /* mp_ass_subscript */
    1157             : };
    1158             : 
    1159             : static PyObject *
    1160        2841 : instance_item(PyInstanceObject *inst, Py_ssize_t i)
    1161             : {
    1162             :     PyObject *func, *res;
    1163             : 
    1164        2841 :     if (getitemstr == NULL) {
    1165           0 :         getitemstr = PyString_InternFromString("__getitem__");
    1166           0 :         if (getitemstr == NULL)
    1167           0 :             return NULL;
    1168             :     }
    1169        2841 :     func = instance_getattr(inst, getitemstr);
    1170        2841 :     if (func == NULL)
    1171           0 :         return NULL;
    1172        2841 :     res = PyObject_CallFunction(func, "n", i);
    1173        2841 :     Py_DECREF(func);
    1174        2841 :     return res;
    1175             : }
    1176             : 
    1177             : static PyObject *
    1178         570 : instance_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j)
    1179             : {
    1180             :     PyObject *func, *arg, *res;
    1181             :     static PyObject *getslicestr;
    1182             : 
    1183         570 :     if (getslicestr == NULL) {
    1184           3 :         getslicestr = PyString_InternFromString("__getslice__");
    1185           3 :         if (getslicestr == NULL)
    1186           0 :             return NULL;
    1187             :     }
    1188         570 :     func = instance_getattr(inst, getslicestr);
    1189             : 
    1190         570 :     if (func == NULL) {
    1191         570 :         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
    1192           0 :             return NULL;
    1193         570 :         PyErr_Clear();
    1194             : 
    1195         570 :         if (getitemstr == NULL) {
    1196           3 :             getitemstr = PyString_InternFromString("__getitem__");
    1197           3 :             if (getitemstr == NULL)
    1198           0 :                 return NULL;
    1199             :         }
    1200         570 :         func = instance_getattr(inst, getitemstr);
    1201         570 :         if (func == NULL)
    1202           0 :             return NULL;
    1203         570 :         arg = Py_BuildValue("(N)", _PySlice_FromIndices(i, j));
    1204             :     }
    1205             :     else {
    1206           0 :         if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
    1207           0 :                            "use __getitem__", 1) < 0) {
    1208           0 :             Py_DECREF(func);
    1209           0 :             return NULL;
    1210             :         }
    1211           0 :         arg = Py_BuildValue("(nn)", i, j);
    1212             :     }
    1213             : 
    1214         570 :     if (arg == NULL) {
    1215           0 :         Py_DECREF(func);
    1216           0 :         return NULL;
    1217             :     }
    1218         570 :     res = PyEval_CallObject(func, arg);
    1219         570 :     Py_DECREF(func);
    1220         570 :     Py_DECREF(arg);
    1221         570 :     return res;
    1222             : }
    1223             : 
    1224             : static int
    1225           0 : instance_ass_item(PyInstanceObject *inst, Py_ssize_t i, PyObject *item)
    1226             : {
    1227             :     PyObject *func, *arg, *res;
    1228             : 
    1229           0 :     if (item == NULL) {
    1230           0 :         if (delitemstr == NULL) {
    1231           0 :             delitemstr = PyString_InternFromString("__delitem__");
    1232           0 :             if (delitemstr == NULL)
    1233           0 :                 return -1;
    1234             :         }
    1235           0 :         func = instance_getattr(inst, delitemstr);
    1236             :     }
    1237             :     else {
    1238           0 :         if (setitemstr == NULL) {
    1239           0 :             setitemstr = PyString_InternFromString("__setitem__");
    1240           0 :             if (setitemstr == NULL)
    1241           0 :                 return -1;
    1242             :         }
    1243           0 :         func = instance_getattr(inst, setitemstr);
    1244             :     }
    1245           0 :     if (func == NULL)
    1246           0 :         return -1;
    1247           0 :     if (item == NULL)
    1248           0 :         arg = Py_BuildValue("(n)", i);
    1249             :     else
    1250           0 :         arg = Py_BuildValue("(nO)", i, item);
    1251           0 :     if (arg == NULL) {
    1252           0 :         Py_DECREF(func);
    1253           0 :         return -1;
    1254             :     }
    1255           0 :     res = PyEval_CallObject(func, arg);
    1256           0 :     Py_DECREF(func);
    1257           0 :     Py_DECREF(arg);
    1258           0 :     if (res == NULL)
    1259           0 :         return -1;
    1260           0 :     Py_DECREF(res);
    1261           0 :     return 0;
    1262             : }
    1263             : 
    1264             : static int
    1265           0 : instance_ass_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j, PyObject *value)
    1266             : {
    1267             :     PyObject *func, *arg, *res;
    1268             :     static PyObject *setslicestr, *delslicestr;
    1269             : 
    1270           0 :     if (value == NULL) {
    1271           0 :         if (delslicestr == NULL) {
    1272           0 :             delslicestr =
    1273           0 :                 PyString_InternFromString("__delslice__");
    1274           0 :             if (delslicestr == NULL)
    1275           0 :                 return -1;
    1276             :         }
    1277           0 :         func = instance_getattr(inst, delslicestr);
    1278           0 :         if (func == NULL) {
    1279           0 :             if (!PyErr_ExceptionMatches(PyExc_AttributeError))
    1280           0 :                 return -1;
    1281           0 :             PyErr_Clear();
    1282           0 :             if (delitemstr == NULL) {
    1283           0 :                 delitemstr =
    1284           0 :                     PyString_InternFromString("__delitem__");
    1285           0 :                 if (delitemstr == NULL)
    1286           0 :                     return -1;
    1287             :             }
    1288           0 :             func = instance_getattr(inst, delitemstr);
    1289           0 :             if (func == NULL)
    1290           0 :                 return -1;
    1291             : 
    1292           0 :             arg = Py_BuildValue("(N)",
    1293             :                                 _PySlice_FromIndices(i, j));
    1294             :         }
    1295             :         else {
    1296           0 :             if (PyErr_WarnPy3k("in 3.x, __delslice__ has been "
    1297           0 :                                 "removed; use __delitem__", 1) < 0) {
    1298           0 :                 Py_DECREF(func);
    1299           0 :                 return -1;
    1300             :             }
    1301           0 :             arg = Py_BuildValue("(nn)", i, j);
    1302             :         }
    1303             :     }
    1304             :     else {
    1305           0 :         if (setslicestr == NULL) {
    1306           0 :             setslicestr =
    1307           0 :                 PyString_InternFromString("__setslice__");
    1308           0 :             if (setslicestr == NULL)
    1309           0 :                 return -1;
    1310             :         }
    1311           0 :         func = instance_getattr(inst, setslicestr);
    1312           0 :         if (func == NULL) {
    1313           0 :             if (!PyErr_ExceptionMatches(PyExc_AttributeError))
    1314           0 :                 return -1;
    1315           0 :             PyErr_Clear();
    1316           0 :             if (setitemstr == NULL) {
    1317           0 :                 setitemstr =
    1318           0 :                     PyString_InternFromString("__setitem__");
    1319           0 :                 if (setitemstr == NULL)
    1320           0 :                     return -1;
    1321             :             }
    1322           0 :             func = instance_getattr(inst, setitemstr);
    1323           0 :             if (func == NULL)
    1324           0 :                 return -1;
    1325             : 
    1326           0 :             arg = Py_BuildValue("(NO)",
    1327             :                                 _PySlice_FromIndices(i, j), value);
    1328             :         }
    1329             :         else {
    1330           0 :             if (PyErr_WarnPy3k("in 3.x, __setslice__ has been "
    1331           0 :                                "removed; use __setitem__", 1) < 0) {
    1332           0 :                 Py_DECREF(func);
    1333           0 :                 return -1;
    1334             :             }
    1335           0 :             arg = Py_BuildValue("(nnO)", i, j, value);
    1336             :         }
    1337             :     }
    1338           0 :     if (arg == NULL) {
    1339           0 :         Py_DECREF(func);
    1340           0 :         return -1;
    1341             :     }
    1342           0 :     res = PyEval_CallObject(func, arg);
    1343           0 :     Py_DECREF(func);
    1344           0 :     Py_DECREF(arg);
    1345           0 :     if (res == NULL)
    1346           0 :         return -1;
    1347           0 :     Py_DECREF(res);
    1348           0 :     return 0;
    1349             : }
    1350             : 
    1351             : static int
    1352          18 : instance_contains(PyInstanceObject *inst, PyObject *member)
    1353             : {
    1354             :     static PyObject *__contains__;
    1355             :     PyObject *func;
    1356             : 
    1357             :     /* Try __contains__ first.
    1358             :      * If that can't be done, try iterator-based searching.
    1359             :      */
    1360             : 
    1361          18 :     if(__contains__ == NULL) {
    1362           3 :         __contains__ = PyString_InternFromString("__contains__");
    1363           3 :         if(__contains__ == NULL)
    1364           0 :             return -1;
    1365             :     }
    1366          18 :     func = instance_getattr(inst, __contains__);
    1367          18 :     if (func) {
    1368             :         PyObject *res;
    1369             :         int ret;
    1370          18 :         PyObject *arg = PyTuple_Pack(1, member);
    1371          18 :         if(arg == NULL) {
    1372           0 :             Py_DECREF(func);
    1373           0 :             return -1;
    1374             :         }
    1375          18 :         res = PyEval_CallObject(func, arg);
    1376          18 :         Py_DECREF(func);
    1377          18 :         Py_DECREF(arg);
    1378          18 :         if(res == NULL)
    1379           0 :             return -1;
    1380          18 :         ret = PyObject_IsTrue(res);
    1381          18 :         Py_DECREF(res);
    1382          18 :         return ret;
    1383             :     }
    1384             : 
    1385             :     /* Couldn't find __contains__. */
    1386           0 :     if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
    1387             :         Py_ssize_t rc;
    1388             :         /* Assume the failure was simply due to that there is no
    1389             :          * __contains__ attribute, and try iterating instead.
    1390             :          */
    1391           0 :         PyErr_Clear();
    1392           0 :         rc = _PySequence_IterSearch((PyObject *)inst, member,
    1393             :                                     PY_ITERSEARCH_CONTAINS);
    1394           0 :         if (rc >= 0)
    1395           0 :             return rc > 0;
    1396             :     }
    1397           0 :     return -1;
    1398             : }
    1399             : 
    1400             : static PySequenceMethods
    1401             : instance_as_sequence = {
    1402             :     (lenfunc)instance_length,                   /* sq_length */
    1403             :     0,                                          /* sq_concat */
    1404             :     0,                                          /* sq_repeat */
    1405             :     (ssizeargfunc)instance_item,                /* sq_item */
    1406             :     (ssizessizeargfunc)instance_slice,          /* sq_slice */
    1407             :     (ssizeobjargproc)instance_ass_item,         /* sq_ass_item */
    1408             :     (ssizessizeobjargproc)instance_ass_slice,/* sq_ass_slice */
    1409             :     (objobjproc)instance_contains,              /* sq_contains */
    1410             : };
    1411             : 
    1412             : static PyObject *
    1413           0 : generic_unary_op(PyInstanceObject *self, PyObject *methodname)
    1414             : {
    1415             :     PyObject *func, *res;
    1416             : 
    1417           0 :     if ((func = instance_getattr(self, methodname)) == NULL)
    1418           0 :         return NULL;
    1419           0 :     res = PyEval_CallObject(func, (PyObject *)NULL);
    1420           0 :     Py_DECREF(func);
    1421           0 :     return res;
    1422             : }
    1423             : 
    1424             : static PyObject *
    1425           0 : generic_binary_op(PyObject *v, PyObject *w, char *opname)
    1426             : {
    1427             :     PyObject *result;
    1428             :     PyObject *args;
    1429           0 :     PyObject *func = PyObject_GetAttrString(v, opname);
    1430           0 :     if (func == NULL) {
    1431           0 :         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
    1432           0 :             return NULL;
    1433           0 :         PyErr_Clear();
    1434           0 :         Py_INCREF(Py_NotImplemented);
    1435           0 :         return Py_NotImplemented;
    1436             :     }
    1437           0 :     args = PyTuple_Pack(1, w);
    1438           0 :     if (args == NULL) {
    1439           0 :         Py_DECREF(func);
    1440           0 :         return NULL;
    1441             :     }
    1442           0 :     result = PyEval_CallObject(func, args);
    1443           0 :     Py_DECREF(args);
    1444           0 :     Py_DECREF(func);
    1445           0 :     return result;
    1446             : }
    1447             : 
    1448             : 
    1449             : static PyObject *coerce_obj;
    1450             : 
    1451             : /* Try one half of a binary operator involving a class instance. */
    1452             : static PyObject *
    1453           0 : half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
    1454             :                 int swapped)
    1455             : {
    1456             :     PyObject *args;
    1457             :     PyObject *coercefunc;
    1458           0 :     PyObject *coerced = NULL;
    1459             :     PyObject *v1;
    1460             :     PyObject *result;
    1461             : 
    1462           0 :     if (!PyInstance_Check(v)) {
    1463           0 :         Py_INCREF(Py_NotImplemented);
    1464           0 :         return Py_NotImplemented;
    1465             :     }
    1466             : 
    1467           0 :     if (coerce_obj == NULL) {
    1468           0 :         coerce_obj = PyString_InternFromString("__coerce__");
    1469           0 :         if (coerce_obj == NULL)
    1470           0 :             return NULL;
    1471             :     }
    1472           0 :     coercefunc = PyObject_GetAttr(v, coerce_obj);
    1473           0 :     if (coercefunc == NULL) {
    1474           0 :         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
    1475           0 :             return NULL;
    1476           0 :         PyErr_Clear();
    1477           0 :         return generic_binary_op(v, w, opname);
    1478             :     }
    1479             : 
    1480           0 :     args = PyTuple_Pack(1, w);
    1481           0 :     if (args == NULL) {
    1482           0 :         Py_DECREF(coercefunc);
    1483           0 :         return NULL;
    1484             :     }
    1485           0 :     coerced = PyEval_CallObject(coercefunc, args);
    1486           0 :     Py_DECREF(args);
    1487           0 :     Py_DECREF(coercefunc);
    1488           0 :     if (coerced == NULL) {
    1489           0 :         return NULL;
    1490             :     }
    1491           0 :     if (coerced == Py_None || coerced == Py_NotImplemented) {
    1492           0 :         Py_DECREF(coerced);
    1493           0 :         return generic_binary_op(v, w, opname);
    1494             :     }
    1495           0 :     if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
    1496           0 :         Py_DECREF(coerced);
    1497           0 :         PyErr_SetString(PyExc_TypeError,
    1498             :                         "coercion should return None or 2-tuple");
    1499           0 :         return NULL;
    1500             :     }
    1501           0 :     v1 = PyTuple_GetItem(coerced, 0);
    1502           0 :     w = PyTuple_GetItem(coerced, 1);
    1503           0 :     if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
    1504             :         /* prevent recursion if __coerce__ returns self as the first
    1505             :          * argument */
    1506           0 :         result = generic_binary_op(v1, w, opname);
    1507             :     } else {
    1508           0 :         if (Py_EnterRecursiveCall(" after coercion"))
    1509           0 :             return NULL;
    1510           0 :         if (swapped)
    1511           0 :             result = (thisfunc)(w, v1);
    1512             :         else
    1513           0 :             result = (thisfunc)(v1, w);
    1514           0 :         Py_LeaveRecursiveCall();
    1515             :     }
    1516           0 :     Py_DECREF(coerced);
    1517           0 :     return result;
    1518             : }
    1519             : 
    1520             : /* Implement a binary operator involving at least one class instance. */
    1521             : static PyObject *
    1522           0 : do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
    1523             :                    binaryfunc thisfunc)
    1524             : {
    1525           0 :     PyObject *result = half_binop(v, w, opname, thisfunc, 0);
    1526           0 :     if (result == Py_NotImplemented) {
    1527           0 :         Py_DECREF(result);
    1528           0 :         result = half_binop(w, v, ropname, thisfunc, 1);
    1529             :     }
    1530           0 :     return result;
    1531             : }
    1532             : 
    1533             : static PyObject *
    1534           0 : do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
    1535             :                         char *ropname, binaryfunc thisfunc)
    1536             : {
    1537           0 :     PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
    1538           0 :     if (result == Py_NotImplemented) {
    1539           0 :         Py_DECREF(result);
    1540           0 :         result = do_binop(v, w, opname, ropname, thisfunc);
    1541             :     }
    1542           0 :     return result;
    1543             : }
    1544             : 
    1545             : static int
    1546          18 : instance_coerce(PyObject **pv, PyObject **pw)
    1547             : {
    1548          18 :     PyObject *v = *pv;
    1549          18 :     PyObject *w = *pw;
    1550             :     PyObject *coercefunc;
    1551             :     PyObject *args;
    1552             :     PyObject *coerced;
    1553             : 
    1554          18 :     if (coerce_obj == NULL) {
    1555           3 :         coerce_obj = PyString_InternFromString("__coerce__");
    1556           3 :         if (coerce_obj == NULL)
    1557           0 :             return -1;
    1558             :     }
    1559          18 :     coercefunc = PyObject_GetAttr(v, coerce_obj);
    1560          18 :     if (coercefunc == NULL) {
    1561             :         /* No __coerce__ method */
    1562          18 :         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
    1563           0 :             return -1;
    1564          18 :         PyErr_Clear();
    1565          18 :         return 1;
    1566             :     }
    1567             :     /* Has __coerce__ method: call it */
    1568           0 :     args = PyTuple_Pack(1, w);
    1569           0 :     if (args == NULL) {
    1570           0 :         return -1;
    1571             :     }
    1572           0 :     coerced = PyEval_CallObject(coercefunc, args);
    1573           0 :     Py_DECREF(args);
    1574           0 :     Py_DECREF(coercefunc);
    1575           0 :     if (coerced == NULL) {
    1576             :         /* __coerce__ call raised an exception */
    1577           0 :         return -1;
    1578             :     }
    1579           0 :     if (coerced == Py_None || coerced == Py_NotImplemented) {
    1580             :         /* __coerce__ says "I can't do it" */
    1581           0 :         Py_DECREF(coerced);
    1582           0 :         return 1;
    1583             :     }
    1584           0 :     if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
    1585             :         /* __coerce__ return value is malformed */
    1586           0 :         Py_DECREF(coerced);
    1587           0 :         PyErr_SetString(PyExc_TypeError,
    1588             :                    "coercion should return None or 2-tuple");
    1589           0 :         return -1;
    1590             :     }
    1591             :     /* __coerce__ returned two new values */
    1592           0 :     *pv = PyTuple_GetItem(coerced, 0);
    1593           0 :     *pw = PyTuple_GetItem(coerced, 1);
    1594           0 :     Py_INCREF(*pv);
    1595           0 :     Py_INCREF(*pw);
    1596           0 :     Py_DECREF(coerced);
    1597           0 :     return 0;
    1598             : }
    1599             : 
    1600             : #define UNARY(funcname, methodname) \
    1601             : static PyObject *funcname(PyInstanceObject *self) { \
    1602             :     static PyObject *o; \
    1603             :     if (o == NULL) { o = PyString_InternFromString(methodname); \
    1604             :                      if (o == NULL) return NULL; } \
    1605             :     return generic_unary_op(self, o); \
    1606             : }
    1607             : 
    1608             : /* unary function with a fallback */
    1609             : #define UNARY_FB(funcname, methodname, funcname_fb) \
    1610             : static PyObject *funcname(PyInstanceObject *self) { \
    1611             :     static PyObject *o; \
    1612             :     if (o == NULL) { o = PyString_InternFromString(methodname); \
    1613             :                      if (o == NULL) return NULL; } \
    1614             :     if (PyObject_HasAttr((PyObject*)self, o)) \
    1615             :         return generic_unary_op(self, o); \
    1616             :     else \
    1617             :         return funcname_fb(self); \
    1618             : }
    1619             : 
    1620             : #define BINARY(f, m, n) \
    1621             : static PyObject *f(PyObject *v, PyObject *w) { \
    1622             :     return do_binop(v, w, "__" m "__", "__r" m "__", n); \
    1623             : }
    1624             : 
    1625             : #define BINARY_INPLACE(f, m, n) \
    1626             : static PyObject *f(PyObject *v, PyObject *w) { \
    1627             :     return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
    1628             :                     "__r" m "__", n); \
    1629             : }
    1630             : 
    1631           0 : UNARY(instance_neg, "__neg__")
    1632           0 : UNARY(instance_pos, "__pos__")
    1633           0 : UNARY(instance_abs, "__abs__")
    1634             : 
    1635           0 : BINARY(instance_or, "or", PyNumber_Or)
    1636           0 : BINARY(instance_and, "and", PyNumber_And)
    1637           0 : BINARY(instance_xor, "xor", PyNumber_Xor)
    1638           0 : BINARY(instance_lshift, "lshift", PyNumber_Lshift)
    1639           0 : BINARY(instance_rshift, "rshift", PyNumber_Rshift)
    1640           0 : BINARY(instance_add, "add", PyNumber_Add)
    1641           0 : BINARY(instance_sub, "sub", PyNumber_Subtract)
    1642           0 : BINARY(instance_mul, "mul", PyNumber_Multiply)
    1643           0 : BINARY(instance_div, "div", PyNumber_Divide)
    1644           0 : BINARY(instance_mod, "mod", PyNumber_Remainder)
    1645           0 : BINARY(instance_divmod, "divmod", PyNumber_Divmod)
    1646           0 : BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
    1647           0 : BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
    1648             : 
    1649           0 : BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
    1650           0 : BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
    1651           0 : BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
    1652           0 : BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
    1653           0 : BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
    1654           0 : BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
    1655           0 : BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
    1656           0 : BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
    1657           0 : BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
    1658           0 : BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
    1659           0 : BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
    1660           0 : BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
    1661             : 
    1662             : /* Try a 3-way comparison, returning an int; v is an instance.  Return:
    1663             :    -2 for an exception;
    1664             :    -1 if v < w;
    1665             :    0 if v == w;
    1666             :    1 if v > w;
    1667             :    2 if this particular 3-way comparison is not implemented or undefined.
    1668             : */
    1669             : static int
    1670          18 : half_cmp(PyObject *v, PyObject *w)
    1671             : {
    1672             :     static PyObject *cmp_obj;
    1673             :     PyObject *args;
    1674             :     PyObject *cmp_func;
    1675             :     PyObject *result;
    1676             :     long l;
    1677             : 
    1678             :     assert(PyInstance_Check(v));
    1679             : 
    1680          18 :     if (cmp_obj == NULL) {
    1681           3 :         cmp_obj = PyString_InternFromString("__cmp__");
    1682           3 :         if (cmp_obj == NULL)
    1683           0 :             return -2;
    1684             :     }
    1685             : 
    1686          18 :     cmp_func = PyObject_GetAttr(v, cmp_obj);
    1687          18 :     if (cmp_func == NULL) {
    1688          18 :         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
    1689           0 :             return -2;
    1690          18 :         PyErr_Clear();
    1691          18 :         return 2;
    1692             :     }
    1693             : 
    1694           0 :     args = PyTuple_Pack(1, w);
    1695           0 :     if (args == NULL) {
    1696           0 :         Py_DECREF(cmp_func);
    1697           0 :         return -2;
    1698             :     }
    1699             : 
    1700           0 :     result = PyEval_CallObject(cmp_func, args);
    1701           0 :     Py_DECREF(args);
    1702           0 :     Py_DECREF(cmp_func);
    1703             : 
    1704           0 :     if (result == NULL)
    1705           0 :         return -2;
    1706             : 
    1707           0 :     if (result == Py_NotImplemented) {
    1708           0 :         Py_DECREF(result);
    1709           0 :         return 2;
    1710             :     }
    1711             : 
    1712           0 :     l = PyInt_AsLong(result);
    1713           0 :     Py_DECREF(result);
    1714           0 :     if (l == -1 && PyErr_Occurred()) {
    1715           0 :         PyErr_SetString(PyExc_TypeError,
    1716             :                      "comparison did not return an int");
    1717           0 :         return -2;
    1718             :     }
    1719             : 
    1720           0 :     return l < 0 ? -1 : l > 0 ? 1 : 0;
    1721             : }
    1722             : 
    1723             : /* Try a 3-way comparison, returning an int; either v or w is an instance.
    1724             :    We first try a coercion.  Return:
    1725             :    -2 for an exception;
    1726             :    -1 if v < w;
    1727             :    0 if v == w;
    1728             :    1 if v > w;
    1729             :    2 if this particular 3-way comparison is not implemented or undefined.
    1730             :    THIS IS ONLY CALLED FROM object.c!
    1731             : */
    1732             : static int
    1733           9 : instance_compare(PyObject *v, PyObject *w)
    1734             : {
    1735             :     int c;
    1736             : 
    1737           9 :     c = PyNumber_CoerceEx(&v, &w);
    1738           9 :     if (c < 0)
    1739           0 :         return -2;
    1740           9 :     if (c == 0) {
    1741             :         /* If neither is now an instance, use regular comparison */
    1742           0 :         if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
    1743           0 :             c = PyObject_Compare(v, w);
    1744           0 :             Py_DECREF(v);
    1745           0 :             Py_DECREF(w);
    1746           0 :             if (PyErr_Occurred())
    1747           0 :                 return -2;
    1748           0 :             return c < 0 ? -1 : c > 0 ? 1 : 0;
    1749             :         }
    1750             :     }
    1751             :     else {
    1752             :         /* The coercion didn't do anything.
    1753             :            Treat this the same as returning v and w unchanged. */
    1754           9 :         Py_INCREF(v);
    1755           9 :         Py_INCREF(w);
    1756             :     }
    1757             : 
    1758           9 :     if (PyInstance_Check(v)) {
    1759           9 :         c = half_cmp(v, w);
    1760           9 :         if (c <= 1) {
    1761           0 :             Py_DECREF(v);
    1762           0 :             Py_DECREF(w);
    1763           0 :             return c;
    1764             :         }
    1765             :     }
    1766           9 :     if (PyInstance_Check(w)) {
    1767           9 :         c = half_cmp(w, v);
    1768           9 :         if (c <= 1) {
    1769           0 :             Py_DECREF(v);
    1770           0 :             Py_DECREF(w);
    1771           0 :             if (c >= -1)
    1772           0 :                 c = -c;
    1773           0 :             return c;
    1774             :         }
    1775             :     }
    1776           9 :     Py_DECREF(v);
    1777           9 :     Py_DECREF(w);
    1778           9 :     return 2;
    1779             : }
    1780             : 
    1781             : static int
    1782        1851 : instance_nonzero(PyInstanceObject *self)
    1783             : {
    1784             :     PyObject *func, *res;
    1785             :     long outcome;
    1786             :     static PyObject *nonzerostr;
    1787             : 
    1788        1851 :     if (nonzerostr == NULL) {
    1789           3 :         nonzerostr = PyString_InternFromString("__nonzero__");
    1790           3 :         if (nonzerostr == NULL)
    1791           0 :             return -1;
    1792             :     }
    1793        1851 :     if ((func = instance_getattr(self, nonzerostr)) == NULL) {
    1794        1851 :         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
    1795           0 :             return -1;
    1796        1851 :         PyErr_Clear();
    1797        1851 :         if (lenstr == NULL) {
    1798           3 :             lenstr = PyString_InternFromString("__len__");
    1799           3 :             if (lenstr == NULL)
    1800           0 :                 return -1;
    1801             :         }
    1802        1851 :         if ((func = instance_getattr(self, lenstr)) == NULL) {
    1803         447 :             if (!PyErr_ExceptionMatches(PyExc_AttributeError))
    1804           0 :                 return -1;
    1805         447 :             PyErr_Clear();
    1806             :             /* Fall back to the default behavior:
    1807             :                all instances are nonzero */
    1808         447 :             return 1;
    1809             :         }
    1810             :     }
    1811        1404 :     res = PyEval_CallObject(func, (PyObject *)NULL);
    1812        1404 :     Py_DECREF(func);
    1813        1404 :     if (res == NULL)
    1814           0 :         return -1;
    1815        1404 :     if (!PyInt_Check(res)) {
    1816           0 :         Py_DECREF(res);
    1817           0 :         PyErr_SetString(PyExc_TypeError,
    1818             :                         "__nonzero__ should return an int");
    1819           0 :         return -1;
    1820             :     }
    1821        1404 :     outcome = PyInt_AsLong(res);
    1822        1404 :     Py_DECREF(res);
    1823        1404 :     if (outcome < 0) {
    1824           0 :         PyErr_SetString(PyExc_ValueError,
    1825             :                         "__nonzero__ should return >= 0");
    1826           0 :         return -1;
    1827             :     }
    1828        1404 :     return outcome > 0;
    1829             : }
    1830             : 
    1831             : static PyObject *
    1832           0 : instance_index(PyInstanceObject *self)
    1833             : {
    1834             :     PyObject *func, *res;
    1835             :     static PyObject *indexstr = NULL;
    1836             : 
    1837           0 :     if (indexstr == NULL) {
    1838           0 :         indexstr = PyString_InternFromString("__index__");
    1839           0 :         if (indexstr == NULL)
    1840           0 :             return NULL;
    1841             :     }
    1842           0 :     if ((func = instance_getattr(self, indexstr)) == NULL) {
    1843           0 :         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
    1844           0 :             return NULL;
    1845           0 :         PyErr_Clear();
    1846           0 :         PyErr_SetString(PyExc_TypeError,
    1847             :                         "object cannot be interpreted as an index");
    1848           0 :         return NULL;
    1849             :     }
    1850           0 :     res = PyEval_CallObject(func, (PyObject *)NULL);
    1851           0 :     Py_DECREF(func);
    1852           0 :     return res;
    1853             : }
    1854             : 
    1855             : 
    1856           0 : UNARY(instance_invert, "__invert__")
    1857           0 : UNARY(_instance_trunc, "__trunc__")
    1858             : 
    1859             : static PyObject *
    1860           0 : instance_int(PyInstanceObject *self)
    1861             : {
    1862             :     PyObject *truncated;
    1863             :     static PyObject *int_name;
    1864           0 :     if (int_name == NULL) {
    1865           0 :         int_name = PyString_InternFromString("__int__");
    1866           0 :         if (int_name == NULL)
    1867           0 :             return NULL;
    1868             :     }
    1869           0 :     if (PyObject_HasAttr((PyObject*)self, int_name))
    1870           0 :         return generic_unary_op(self, int_name);
    1871             : 
    1872           0 :     truncated = _instance_trunc(self);
    1873             :     /* __trunc__ is specified to return an Integral type, but
    1874             :        int() needs to return an int. */
    1875           0 :     return _PyNumber_ConvertIntegralToInt(
    1876             :         truncated,
    1877             :         "__trunc__ returned non-Integral (type %.200s)");
    1878             : }
    1879             : 
    1880           0 : UNARY_FB(instance_long, "__long__", instance_int)
    1881           0 : UNARY(instance_float, "__float__")
    1882           0 : UNARY(instance_oct, "__oct__")
    1883           0 : UNARY(instance_hex, "__hex__")
    1884             : 
    1885             : static PyObject *
    1886           0 : bin_power(PyObject *v, PyObject *w)
    1887             : {
    1888           0 :     return PyNumber_Power(v, w, Py_None);
    1889             : }
    1890             : 
    1891             : /* This version is for ternary calls only (z != None) */
    1892             : static PyObject *
    1893           0 : instance_pow(PyObject *v, PyObject *w, PyObject *z)
    1894             : {
    1895           0 :     if (z == Py_None) {
    1896           0 :         return do_binop(v, w, "__pow__", "__rpow__", bin_power);
    1897             :     }
    1898             :     else {
    1899             :         PyObject *func;
    1900             :         PyObject *args;
    1901             :         PyObject *result;
    1902             : 
    1903             :         /* XXX Doesn't do coercions... */
    1904           0 :         func = PyObject_GetAttrString(v, "__pow__");
    1905           0 :         if (func == NULL)
    1906           0 :             return NULL;
    1907           0 :         args = PyTuple_Pack(2, w, z);
    1908           0 :         if (args == NULL) {
    1909           0 :             Py_DECREF(func);
    1910           0 :             return NULL;
    1911             :         }
    1912           0 :         result = PyEval_CallObject(func, args);
    1913           0 :         Py_DECREF(func);
    1914           0 :         Py_DECREF(args);
    1915           0 :         return result;
    1916             :     }
    1917             : }
    1918             : 
    1919             : static PyObject *
    1920           0 : bin_inplace_power(PyObject *v, PyObject *w)
    1921             : {
    1922           0 :     return PyNumber_InPlacePower(v, w, Py_None);
    1923             : }
    1924             : 
    1925             : 
    1926             : static PyObject *
    1927           0 : instance_ipow(PyObject *v, PyObject *w, PyObject *z)
    1928             : {
    1929           0 :     if (z == Py_None) {
    1930           0 :         return do_binop_inplace(v, w, "__ipow__", "__pow__",
    1931             :             "__rpow__", bin_inplace_power);
    1932             :     }
    1933             :     else {
    1934             :         /* XXX Doesn't do coercions... */
    1935             :         PyObject *func;
    1936             :         PyObject *args;
    1937             :         PyObject *result;
    1938             : 
    1939           0 :         func = PyObject_GetAttrString(v, "__ipow__");
    1940           0 :         if (func == NULL) {
    1941           0 :             if (!PyErr_ExceptionMatches(PyExc_AttributeError))
    1942           0 :                 return NULL;
    1943           0 :             PyErr_Clear();
    1944           0 :             return instance_pow(v, w, z);
    1945             :         }
    1946           0 :         args = PyTuple_Pack(2, w, z);
    1947           0 :         if (args == NULL) {
    1948           0 :             Py_DECREF(func);
    1949           0 :             return NULL;
    1950             :         }
    1951           0 :         result = PyEval_CallObject(func, args);
    1952           0 :         Py_DECREF(func);
    1953           0 :         Py_DECREF(args);
    1954           0 :         return result;
    1955             :     }
    1956             : }
    1957             : 
    1958             : 
    1959             : /* Map rich comparison operators to their __xx__ namesakes */
    1960             : #define NAME_OPS 6
    1961             : static PyObject **name_op = NULL;
    1962             : 
    1963             : static int
    1964           3 : init_name_op(void)
    1965             : {
    1966             :     int i;
    1967           3 :     char *_name_op[] = {
    1968             :         "__lt__",
    1969             :         "__le__",
    1970             :         "__eq__",
    1971             :         "__ne__",
    1972             :         "__gt__",
    1973             :         "__ge__",
    1974             :     };
    1975             : 
    1976           3 :     name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
    1977           3 :     if (name_op == NULL)
    1978           0 :         return -1;
    1979          21 :     for (i = 0; i < NAME_OPS; ++i) {
    1980          18 :         name_op[i] = PyString_InternFromString(_name_op[i]);
    1981          18 :         if (name_op[i] == NULL)
    1982           0 :             return -1;
    1983             :     }
    1984           3 :     return 0;
    1985             : }
    1986             : 
    1987             : static PyObject *
    1988          36 : half_richcompare(PyObject *v, PyObject *w, int op)
    1989             : {
    1990             :     PyObject *method;
    1991             :     PyObject *args;
    1992             :     PyObject *res;
    1993             : 
    1994             :     assert(PyInstance_Check(v));
    1995             : 
    1996          36 :     if (name_op == NULL) {
    1997           3 :         if (init_name_op() < 0)
    1998           0 :             return NULL;
    1999             :     }
    2000             :     /* If the instance doesn't define an __getattr__ method, use
    2001             :        instance_getattr2 directly because it will not set an
    2002             :        exception on failure. */
    2003          36 :     if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL)
    2004          36 :         method = instance_getattr2((PyInstanceObject *)v,
    2005          36 :                                    name_op[op]);
    2006             :     else
    2007           0 :         method = PyObject_GetAttr(v, name_op[op]);
    2008          36 :     if (method == NULL) {
    2009          36 :         if (PyErr_Occurred()) {
    2010           0 :             if (!PyErr_ExceptionMatches(PyExc_AttributeError))
    2011           0 :                 return NULL;
    2012           0 :             PyErr_Clear();
    2013             :         }
    2014          36 :         res = Py_NotImplemented;
    2015          36 :         Py_INCREF(res);
    2016          36 :         return res;
    2017             :     }
    2018             : 
    2019           0 :     args = PyTuple_Pack(1, w);
    2020           0 :     if (args == NULL) {
    2021           0 :         Py_DECREF(method);
    2022           0 :         return NULL;
    2023             :     }
    2024             : 
    2025           0 :     res = PyEval_CallObject(method, args);
    2026           0 :     Py_DECREF(args);
    2027           0 :     Py_DECREF(method);
    2028             : 
    2029           0 :     return res;
    2030             : }
    2031             : 
    2032             : static PyObject *
    2033          18 : instance_richcompare(PyObject *v, PyObject *w, int op)
    2034             : {
    2035             :     PyObject *res;
    2036             : 
    2037          18 :     if (PyInstance_Check(v)) {
    2038          18 :         res = half_richcompare(v, w, op);
    2039          18 :         if (res != Py_NotImplemented)
    2040           0 :             return res;
    2041          18 :         Py_DECREF(res);
    2042             :     }
    2043             : 
    2044          18 :     if (PyInstance_Check(w)) {
    2045          18 :         res = half_richcompare(w, v, _Py_SwappedOp[op]);
    2046          18 :         if (res != Py_NotImplemented)
    2047           0 :             return res;
    2048          18 :         Py_DECREF(res);
    2049             :     }
    2050             : 
    2051          18 :     Py_INCREF(Py_NotImplemented);
    2052          18 :     return Py_NotImplemented;
    2053             : }
    2054             : 
    2055             : 
    2056             : /* Get the iterator */
    2057             : static PyObject *
    2058        1158 : instance_getiter(PyInstanceObject *self)
    2059             : {
    2060             :     PyObject *func;
    2061             : 
    2062        1158 :     if (iterstr == NULL) {
    2063           3 :         iterstr = PyString_InternFromString("__iter__");
    2064           3 :         if (iterstr == NULL)
    2065           0 :             return NULL;
    2066             :     }
    2067        1158 :     if (getitemstr == NULL) {
    2068           0 :         getitemstr = PyString_InternFromString("__getitem__");
    2069           0 :         if (getitemstr == NULL)
    2070           0 :             return NULL;
    2071             :     }
    2072             : 
    2073        1158 :     if ((func = instance_getattr(self, iterstr)) != NULL) {
    2074           0 :         PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
    2075           0 :         Py_DECREF(func);
    2076           0 :         if (res != NULL && !PyIter_Check(res)) {
    2077           0 :             PyErr_Format(PyExc_TypeError,
    2078             :                          "__iter__ returned non-iterator "
    2079             :                          "of type '%.100s'",
    2080           0 :                          res->ob_type->tp_name);
    2081           0 :             Py_DECREF(res);
    2082           0 :             res = NULL;
    2083             :         }
    2084           0 :         return res;
    2085             :     }
    2086        1158 :     if (!PyErr_ExceptionMatches(PyExc_AttributeError))
    2087           0 :         return NULL;
    2088        1158 :     PyErr_Clear();
    2089        1158 :     if ((func = instance_getattr(self, getitemstr)) == NULL) {
    2090           0 :         PyErr_SetString(PyExc_TypeError,
    2091             :                         "iteration over non-sequence");
    2092           0 :         return NULL;
    2093             :     }
    2094        1158 :     Py_DECREF(func);
    2095        1158 :     return PySeqIter_New((PyObject *)self);
    2096             : }
    2097             : 
    2098             : 
    2099             : /* Call the iterator's next */
    2100             : static PyObject *
    2101           0 : instance_iternext(PyInstanceObject *self)
    2102             : {
    2103             :     PyObject *func;
    2104             : 
    2105           0 :     if (nextstr == NULL) {
    2106           0 :         nextstr = PyString_InternFromString("next");
    2107           0 :         if (nextstr == NULL)
    2108           0 :             return NULL;
    2109             :     }
    2110             : 
    2111           0 :     if ((func = instance_getattr(self, nextstr)) != NULL) {
    2112           0 :         PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
    2113           0 :         Py_DECREF(func);
    2114           0 :         if (res != NULL) {
    2115           0 :             return res;
    2116             :         }
    2117           0 :         if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
    2118           0 :             PyErr_Clear();
    2119           0 :             return NULL;
    2120             :         }
    2121           0 :         return NULL;
    2122             :     }
    2123           0 :     PyErr_SetString(PyExc_TypeError, "instance has no next() method");
    2124           0 :     return NULL;
    2125             : }
    2126             : 
    2127             : static PyObject *
    2128           0 : instance_call(PyObject *func, PyObject *arg, PyObject *kw)
    2129             : {
    2130           0 :     PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
    2131           0 :     if (call == NULL) {
    2132           0 :         PyInstanceObject *inst = (PyInstanceObject*) func;
    2133           0 :         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
    2134           0 :             return NULL;
    2135           0 :         PyErr_Clear();
    2136           0 :         PyErr_Format(PyExc_AttributeError,
    2137             :                      "%.200s instance has no __call__ method",
    2138           0 :                      PyString_AsString(inst->in_class->cl_name));
    2139           0 :         return NULL;
    2140             :     }
    2141             :     /* We must check and increment the recursion depth here. Scenario:
    2142             :            class A:
    2143             :            pass
    2144             :            A.__call__ = A() # that's right
    2145             :            a = A() # ok
    2146             :            a() # infinite recursion
    2147             :        This bounces between instance_call() and PyObject_Call() without
    2148             :        ever hitting eval_frame() (which has the main recursion check). */
    2149           0 :     if (Py_EnterRecursiveCall(" in __call__")) {
    2150           0 :         res = NULL;
    2151             :     }
    2152             :     else {
    2153           0 :         res = PyObject_Call(call, arg, kw);
    2154           0 :         Py_LeaveRecursiveCall();
    2155             :     }
    2156           0 :     Py_DECREF(call);
    2157           0 :     return res;
    2158             : }
    2159             : 
    2160             : 
    2161             : static PyNumberMethods instance_as_number = {
    2162             :     instance_add,                       /* nb_add */
    2163             :     instance_sub,                       /* nb_subtract */
    2164             :     instance_mul,                       /* nb_multiply */
    2165             :     instance_div,                       /* nb_divide */
    2166             :     instance_mod,                       /* nb_remainder */
    2167             :     instance_divmod,                    /* nb_divmod */
    2168             :     instance_pow,                       /* nb_power */
    2169             :     (unaryfunc)instance_neg,            /* nb_negative */
    2170             :     (unaryfunc)instance_pos,            /* nb_positive */
    2171             :     (unaryfunc)instance_abs,            /* nb_absolute */
    2172             :     (inquiry)instance_nonzero,          /* nb_nonzero */
    2173             :     (unaryfunc)instance_invert,         /* nb_invert */
    2174             :     instance_lshift,                    /* nb_lshift */
    2175             :     instance_rshift,                    /* nb_rshift */
    2176             :     instance_and,                       /* nb_and */
    2177             :     instance_xor,                       /* nb_xor */
    2178             :     instance_or,                        /* nb_or */
    2179             :     instance_coerce,                    /* nb_coerce */
    2180             :     (unaryfunc)instance_int,            /* nb_int */
    2181             :     (unaryfunc)instance_long,           /* nb_long */
    2182             :     (unaryfunc)instance_float,          /* nb_float */
    2183             :     (unaryfunc)instance_oct,            /* nb_oct */
    2184             :     (unaryfunc)instance_hex,            /* nb_hex */
    2185             :     instance_iadd,                      /* nb_inplace_add */
    2186             :     instance_isub,                      /* nb_inplace_subtract */
    2187             :     instance_imul,                      /* nb_inplace_multiply */
    2188             :     instance_idiv,                      /* nb_inplace_divide */
    2189             :     instance_imod,                      /* nb_inplace_remainder */
    2190             :     instance_ipow,                      /* nb_inplace_power */
    2191             :     instance_ilshift,                   /* nb_inplace_lshift */
    2192             :     instance_irshift,                   /* nb_inplace_rshift */
    2193             :     instance_iand,                      /* nb_inplace_and */
    2194             :     instance_ixor,                      /* nb_inplace_xor */
    2195             :     instance_ior,                       /* nb_inplace_or */
    2196             :     instance_floordiv,                  /* nb_floor_divide */
    2197             :     instance_truediv,                   /* nb_true_divide */
    2198             :     instance_ifloordiv,                 /* nb_inplace_floor_divide */
    2199             :     instance_itruediv,                  /* nb_inplace_true_divide */
    2200             :     (unaryfunc)instance_index,          /* nb_index */
    2201             : };
    2202             : 
    2203             : PyTypeObject PyInstance_Type = {
    2204             :     PyObject_HEAD_INIT(&PyType_Type)
    2205             :     0,
    2206             :     "instance",
    2207             :     sizeof(PyInstanceObject),
    2208             :     0,
    2209             :     (destructor)instance_dealloc,               /* tp_dealloc */
    2210             :     0,                                          /* tp_print */
    2211             :     0,                                          /* tp_getattr */
    2212             :     0,                                          /* tp_setattr */
    2213             :     instance_compare,                           /* tp_compare */
    2214             :     (reprfunc)instance_repr,                    /* tp_repr */
    2215             :     &instance_as_number,                        /* tp_as_number */
    2216             :     &instance_as_sequence,                      /* tp_as_sequence */
    2217             :     &instance_as_mapping,                       /* tp_as_mapping */
    2218             :     (hashfunc)instance_hash,                    /* tp_hash */
    2219             :     instance_call,                              /* tp_call */
    2220             :     (reprfunc)instance_str,                     /* tp_str */
    2221             :     (getattrofunc)instance_getattr,             /* tp_getattro */
    2222             :     (setattrofunc)instance_setattr,             /* tp_setattro */
    2223             :     0,                                          /* tp_as_buffer */
    2224             :     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
    2225             :     instance_doc,                               /* tp_doc */
    2226             :     (traverseproc)instance_traverse,            /* tp_traverse */
    2227             :     0,                                          /* tp_clear */
    2228             :     instance_richcompare,                       /* tp_richcompare */
    2229             :     offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
    2230             :     (getiterfunc)instance_getiter,              /* tp_iter */
    2231             :     (iternextfunc)instance_iternext,            /* tp_iternext */
    2232             :     0,                                          /* tp_methods */
    2233             :     0,                                          /* tp_members */
    2234             :     0,                                          /* tp_getset */
    2235             :     0,                                          /* tp_base */
    2236             :     0,                                          /* tp_dict */
    2237             :     0,                                          /* tp_descr_get */
    2238             :     0,                                          /* tp_descr_set */
    2239             :     0,                                          /* tp_dictoffset */
    2240             :     0,                                          /* tp_init */
    2241             :     0,                                          /* tp_alloc */
    2242             :     instance_new,                               /* tp_new */
    2243             : };
    2244             : 
    2245             : 
    2246             : /* Instance method objects are used for two purposes:
    2247             :    (a) as bound instance methods (returned by instancename.methodname)
    2248             :    (b) as unbound methods (returned by ClassName.methodname)
    2249             :    In case (b), im_self is NULL
    2250             : */
    2251             : 
    2252             : PyObject *
    2253       49625 : PyMethod_New(PyObject *func, PyObject *self, PyObject *klass)
    2254             : {
    2255             :     register PyMethodObject *im;
    2256       49625 :     im = free_list;
    2257       49625 :     if (im != NULL) {
    2258       49484 :         free_list = (PyMethodObject *)(im->im_self);
    2259       49484 :         (void)PyObject_INIT(im, &PyMethod_Type);
    2260       49484 :         numfree--;
    2261             :     }
    2262             :     else {
    2263         141 :         im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
    2264         141 :         if (im == NULL)
    2265           0 :             return NULL;
    2266             :     }
    2267       49625 :     im->im_weakreflist = NULL;
    2268       49625 :     Py_INCREF(func);
    2269       49625 :     im->im_func = func;
    2270       49625 :     Py_XINCREF(self);
    2271       49625 :     im->im_self = self;
    2272       49625 :     Py_XINCREF(klass);
    2273       49625 :     im->im_class = klass;
    2274       49625 :     _PyObject_GC_TRACK(im);
    2275       49625 :     return (PyObject *)im;
    2276             : }
    2277             : 
    2278             : /* Descriptors for PyMethod attributes */
    2279             : 
    2280             : /* im_class, im_func and im_self are stored in the PyMethod object */
    2281             : 
    2282             : #define OFF(x) offsetof(PyMethodObject, x)
    2283             : 
    2284             : static PyMemberDef instancemethod_memberlist[] = {
    2285             :     {"im_class",        T_OBJECT,       OFF(im_class),  READONLY|RESTRICTED,
    2286             :      "the class associated with a method"},
    2287             :     {"im_func",         T_OBJECT,       OFF(im_func),   READONLY|RESTRICTED,
    2288             :      "the function (or other callable) implementing a method"},
    2289             :     {"__func__",        T_OBJECT,       OFF(im_func),   READONLY|RESTRICTED,
    2290             :      "the function (or other callable) implementing a method"},
    2291             :     {"im_self",         T_OBJECT,       OFF(im_self),   READONLY|RESTRICTED,
    2292             :      "the instance to which a method is bound; None for unbound methods"},
    2293             :     {"__self__",        T_OBJECT,       OFF(im_self),   READONLY|RESTRICTED,
    2294             :      "the instance to which a method is bound; None for unbound methods"},
    2295             :     {NULL}      /* Sentinel */
    2296             : };
    2297             : 
    2298             : /* Christian Tismer argued convincingly that method attributes should
    2299             :    (nearly) always override function attributes.
    2300             :    The one exception is __doc__; there's a default __doc__ which
    2301             :    should only be used for the class, not for instances */
    2302             : 
    2303             : static PyObject *
    2304           0 : instancemethod_get_doc(PyMethodObject *im, void *context)
    2305             : {
    2306             :     static PyObject *docstr;
    2307           0 :     if (docstr == NULL) {
    2308           0 :         docstr= PyString_InternFromString("__doc__");
    2309           0 :         if (docstr == NULL)
    2310           0 :             return NULL;
    2311             :     }
    2312           0 :     return PyObject_GetAttr(im->im_func, docstr);
    2313             : }
    2314             : 
    2315             : static PyGetSetDef instancemethod_getset[] = {
    2316             :     {"__doc__", (getter)instancemethod_get_doc, NULL, NULL},
    2317             :     {0}
    2318             : };
    2319             : 
    2320             : static PyObject *
    2321          75 : instancemethod_getattro(PyObject *obj, PyObject *name)
    2322             : {
    2323          75 :     PyMethodObject *im = (PyMethodObject *)obj;
    2324          75 :     PyTypeObject *tp = obj->ob_type;
    2325          75 :     PyObject *descr = NULL;
    2326             : 
    2327          75 :     if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
    2328          75 :         if (tp->tp_dict == NULL) {
    2329           0 :             if (PyType_Ready(tp) < 0)
    2330           0 :                 return NULL;
    2331             :         }
    2332          75 :         descr = _PyType_Lookup(tp, name);
    2333             :     }
    2334             : 
    2335          75 :     if (descr != NULL) {
    2336           0 :         descrgetfunc f = TP_DESCR_GET(descr->ob_type);
    2337           0 :         if (f != NULL)
    2338           0 :             return f(descr, obj, (PyObject *)obj->ob_type);
    2339             :         else {
    2340           0 :             Py_INCREF(descr);
    2341           0 :             return descr;
    2342             :         }
    2343             :     }
    2344             : 
    2345          75 :     return PyObject_GetAttr(im->im_func, name);
    2346             : }
    2347             : 
    2348             : PyDoc_STRVAR(instancemethod_doc,
    2349             : "instancemethod(function, instance, class)\n\
    2350             : \n\
    2351             : Create an instance method object.");
    2352             : 
    2353             : static PyObject *
    2354           0 : instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
    2355             : {
    2356             :     PyObject *func;
    2357             :     PyObject *self;
    2358           0 :     PyObject *classObj = NULL;
    2359             : 
    2360           0 :     if (!_PyArg_NoKeywords("instancemethod", kw))
    2361           0 :         return NULL;
    2362           0 :     if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3,
    2363             :                           &func, &self, &classObj))
    2364           0 :         return NULL;
    2365           0 :     if (!PyCallable_Check(func)) {
    2366           0 :         PyErr_SetString(PyExc_TypeError,
    2367             :                         "first argument must be callable");
    2368           0 :         return NULL;
    2369             :     }
    2370           0 :     if (self == Py_None)
    2371           0 :         self = NULL;
    2372           0 :     if (self == NULL && classObj == NULL) {
    2373           0 :         PyErr_SetString(PyExc_TypeError,
    2374             :             "unbound methods must have non-NULL im_class");
    2375           0 :         return NULL;
    2376             :     }
    2377             : 
    2378           0 :     return PyMethod_New(func, self, classObj);
    2379             : }
    2380             : 
    2381             : static void
    2382       49622 : instancemethod_dealloc(register PyMethodObject *im)
    2383             : {
    2384       49622 :     _PyObject_GC_UNTRACK(im);
    2385       49622 :     if (im->im_weakreflist != NULL)
    2386           0 :         PyObject_ClearWeakRefs((PyObject *)im);
    2387       49622 :     Py_DECREF(im->im_func);
    2388       49622 :     Py_XDECREF(im->im_self);
    2389       49622 :     Py_XDECREF(im->im_class);
    2390       49622 :     if (numfree < PyMethod_MAXFREELIST) {
    2391       49622 :         im->im_self = (PyObject *)free_list;
    2392       49622 :         free_list = im;
    2393       49622 :         numfree++;
    2394             :     }
    2395             :     else {
    2396           0 :         PyObject_GC_Del(im);
    2397             :     }
    2398       49622 : }
    2399             : 
    2400             : static int
    2401           0 : instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
    2402             : {
    2403             :     int cmp;
    2404           0 :     cmp = PyObject_Compare(a->im_func, b->im_func);
    2405           0 :     if (cmp)
    2406           0 :         return cmp;
    2407             : 
    2408           0 :     if (a->im_self == b->im_self)
    2409           0 :         return 0;
    2410           0 :     if (a->im_self == NULL || b->im_self == NULL)
    2411           0 :         return (a->im_self < b->im_self) ? -1 : 1;
    2412             :     else
    2413           0 :         return PyObject_Compare(a->im_self, b->im_self);
    2414             : }
    2415             : 
    2416             : static PyObject *
    2417           0 : instancemethod_repr(PyMethodObject *a)
    2418             : {
    2419           0 :     PyObject *self = a->im_self;
    2420           0 :     PyObject *func = a->im_func;
    2421           0 :     PyObject *klass = a->im_class;
    2422           0 :     PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
    2423           0 :     char *sfuncname = "?", *sklassname = "?";
    2424             : 
    2425           0 :     funcname = PyObject_GetAttrString(func, "__name__");
    2426           0 :     if (funcname == NULL) {
    2427           0 :         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
    2428           0 :             return NULL;
    2429           0 :         PyErr_Clear();
    2430             :     }
    2431           0 :     else if (!PyString_Check(funcname)) {
    2432           0 :         Py_DECREF(funcname);
    2433           0 :         funcname = NULL;
    2434             :     }
    2435             :     else
    2436           0 :         sfuncname = PyString_AS_STRING(funcname);
    2437           0 :     if (klass == NULL)
    2438           0 :         klassname = NULL;
    2439             :     else {
    2440           0 :         klassname = PyObject_GetAttrString(klass, "__name__");
    2441           0 :         if (klassname == NULL) {
    2442           0 :             if (!PyErr_ExceptionMatches(PyExc_AttributeError))
    2443           0 :                 return NULL;
    2444           0 :             PyErr_Clear();
    2445             :         }
    2446           0 :         else if (!PyString_Check(klassname)) {
    2447           0 :             Py_DECREF(klassname);
    2448           0 :             klassname = NULL;
    2449             :         }
    2450             :         else
    2451           0 :             sklassname = PyString_AS_STRING(klassname);
    2452             :     }
    2453           0 :     if (self == NULL)
    2454           0 :         result = PyString_FromFormat("<unbound method %s.%s>",
    2455             :                                      sklassname, sfuncname);
    2456             :     else {
    2457             :         /* XXX Shouldn't use repr() here! */
    2458           0 :         PyObject *selfrepr = PyObject_Repr(self);
    2459           0 :         if (selfrepr == NULL)
    2460           0 :             goto fail;
    2461           0 :         if (!PyString_Check(selfrepr)) {
    2462           0 :             Py_DECREF(selfrepr);
    2463           0 :             goto fail;
    2464             :         }
    2465           0 :         result = PyString_FromFormat("<bound method %s.%s of %s>",
    2466             :                                      sklassname, sfuncname,
    2467           0 :                                      PyString_AS_STRING(selfrepr));
    2468           0 :         Py_DECREF(selfrepr);
    2469             :     }
    2470             :   fail:
    2471           0 :     Py_XDECREF(funcname);
    2472           0 :     Py_XDECREF(klassname);
    2473           0 :     return result;
    2474             : }
    2475             : 
    2476             : static long
    2477           0 : instancemethod_hash(PyMethodObject *a)
    2478             : {
    2479             :     long x, y;
    2480           0 :     if (a->im_self == NULL)
    2481           0 :         x = PyObject_Hash(Py_None);
    2482             :     else
    2483           0 :         x = PyObject_Hash(a->im_self);
    2484           0 :     if (x == -1)
    2485           0 :         return -1;
    2486           0 :     y = PyObject_Hash(a->im_func);
    2487           0 :     if (y == -1)
    2488           0 :         return -1;
    2489           0 :     x = x ^ y;
    2490           0 :     if (x == -1)
    2491           0 :         x = -2;
    2492           0 :     return x;
    2493             : }
    2494             : 
    2495             : static int
    2496         524 : instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
    2497             : {
    2498         524 :     Py_VISIT(im->im_func);
    2499         524 :     Py_VISIT(im->im_self);
    2500         524 :     Py_VISIT(im->im_class);
    2501         524 :     return 0;
    2502             : }
    2503             : 
    2504             : static void
    2505           0 : getclassname(PyObject *klass, char *buf, int bufsize)
    2506             : {
    2507             :     PyObject *name;
    2508             : 
    2509             :     assert(bufsize > 1);
    2510           0 :     strcpy(buf, "?"); /* Default outcome */
    2511           0 :     if (klass == NULL)
    2512           0 :         return;
    2513           0 :     name = PyObject_GetAttrString(klass, "__name__");
    2514           0 :     if (name == NULL) {
    2515             :         /* This function cannot return an exception */
    2516           0 :         PyErr_Clear();
    2517           0 :         return;
    2518             :     }
    2519           0 :     if (PyString_Check(name)) {
    2520           0 :         strncpy(buf, PyString_AS_STRING(name), bufsize);
    2521           0 :         buf[bufsize-1] = '\0';
    2522             :     }
    2523           0 :     Py_DECREF(name);
    2524             : }
    2525             : 
    2526             : static void
    2527           0 : getinstclassname(PyObject *inst, char *buf, int bufsize)
    2528             : {
    2529             :     PyObject *klass;
    2530             : 
    2531           0 :     if (inst == NULL) {
    2532             :         assert(bufsize > 0 && (size_t)bufsize > strlen("nothing"));
    2533           0 :         strcpy(buf, "nothing");
    2534           0 :         return;
    2535             :     }
    2536             : 
    2537           0 :     klass = PyObject_GetAttrString(inst, "__class__");
    2538           0 :     if (klass == NULL) {
    2539             :         /* This function cannot return an exception */
    2540           0 :         PyErr_Clear();
    2541           0 :         klass = (PyObject *)(inst->ob_type);
    2542           0 :         Py_INCREF(klass);
    2543             :     }
    2544           0 :     getclassname(klass, buf, bufsize);
    2545           0 :     Py_XDECREF(klass);
    2546             : }
    2547             : 
    2548             : static PyObject *
    2549       17650 : instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
    2550             : {
    2551       17650 :     PyObject *self = PyMethod_GET_SELF(func);
    2552       17650 :     PyObject *klass = PyMethod_GET_CLASS(func);
    2553             :     PyObject *result;
    2554             : 
    2555       17650 :     func = PyMethod_GET_FUNCTION(func);
    2556       17650 :     if (self == NULL) {
    2557             :         /* Unbound methods must be called with an instance of
    2558             :            the class (or a derived class) as first argument */
    2559             :         int ok;
    2560          18 :         if (PyTuple_Size(arg) >= 1)
    2561          18 :             self = PyTuple_GET_ITEM(arg, 0);
    2562          18 :         if (self == NULL)
    2563           0 :             ok = 0;
    2564             :         else {
    2565          18 :             ok = PyObject_IsInstance(self, klass);
    2566          18 :             if (ok < 0)
    2567           0 :                 return NULL;
    2568             :         }
    2569          18 :         if (!ok) {
    2570             :             char clsbuf[256];
    2571             :             char instbuf[256];
    2572           0 :             getclassname(klass, clsbuf, sizeof(clsbuf));
    2573           0 :             getinstclassname(self, instbuf, sizeof(instbuf));
    2574           0 :             PyErr_Format(PyExc_TypeError,
    2575             :                          "unbound method %s%s must be called with "
    2576             :                          "%s instance as first argument "
    2577             :                          "(got %s%s instead)",
    2578             :                          PyEval_GetFuncName(func),
    2579             :                          PyEval_GetFuncDesc(func),
    2580             :                          clsbuf,
    2581             :                          instbuf,
    2582             :                          self == NULL ? "" : " instance");
    2583           0 :             return NULL;
    2584             :         }
    2585          18 :         Py_INCREF(arg);
    2586             :     }
    2587             :     else {
    2588       17632 :         Py_ssize_t argcount = PyTuple_Size(arg);
    2589       17632 :         PyObject *newarg = PyTuple_New(argcount + 1);
    2590             :         int i;
    2591       17632 :         if (newarg == NULL)
    2592           0 :             return NULL;
    2593       17632 :         Py_INCREF(self);
    2594       17632 :         PyTuple_SET_ITEM(newarg, 0, self);
    2595       33294 :         for (i = 0; i < argcount; i++) {
    2596       15662 :             PyObject *v = PyTuple_GET_ITEM(arg, i);
    2597       15662 :             Py_XINCREF(v);
    2598       15662 :             PyTuple_SET_ITEM(newarg, i+1, v);
    2599             :         }
    2600       17632 :         arg = newarg;
    2601             :     }
    2602       17650 :     result = PyObject_Call((PyObject *)func, arg, kw);
    2603       17650 :     Py_DECREF(arg);
    2604       17650 :     return result;
    2605             : }
    2606             : 
    2607             : static PyObject *
    2608           0 : instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls)
    2609             : {
    2610             :     /* Don't rebind an already bound method, or an unbound method
    2611             :        of a class that's not a base class of cls. */
    2612             : 
    2613           0 :     if (PyMethod_GET_SELF(meth) != NULL) {
    2614             :         /* Already bound */
    2615           0 :         Py_INCREF(meth);
    2616           0 :         return meth;
    2617             :     }
    2618             :     /* No, it is an unbound method */
    2619           0 :     if (PyMethod_GET_CLASS(meth) != NULL && cls != NULL) {
    2620             :         /* Do subclass test.  If it fails, return meth unchanged. */
    2621           0 :         int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth));
    2622           0 :         if (ok < 0)
    2623           0 :             return NULL;
    2624           0 :         if (!ok) {
    2625           0 :             Py_INCREF(meth);
    2626           0 :             return meth;
    2627             :         }
    2628             :     }
    2629             :     /* Bind it to obj */
    2630           0 :     return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls);
    2631             : }
    2632             : 
    2633             : PyTypeObject PyMethod_Type = {
    2634             :     PyObject_HEAD_INIT(&PyType_Type)
    2635             :     0,
    2636             :     "instancemethod",
    2637             :     sizeof(PyMethodObject),
    2638             :     0,
    2639             :     (destructor)instancemethod_dealloc,         /* tp_dealloc */
    2640             :     0,                                          /* tp_print */
    2641             :     0,                                          /* tp_getattr */
    2642             :     0,                                          /* tp_setattr */
    2643             :     (cmpfunc)instancemethod_compare,            /* tp_compare */
    2644             :     (reprfunc)instancemethod_repr,              /* tp_repr */
    2645             :     0,                                          /* tp_as_number */
    2646             :     0,                                          /* tp_as_sequence */
    2647             :     0,                                          /* tp_as_mapping */
    2648             :     (hashfunc)instancemethod_hash,              /* tp_hash */
    2649             :     instancemethod_call,                        /* tp_call */
    2650             :     0,                                          /* tp_str */
    2651             :     instancemethod_getattro,                    /* tp_getattro */
    2652             :     PyObject_GenericSetAttr,                    /* tp_setattro */
    2653             :     0,                                          /* tp_as_buffer */
    2654             :     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC  | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
    2655             :     instancemethod_doc,                         /* tp_doc */
    2656             :     (traverseproc)instancemethod_traverse,      /* tp_traverse */
    2657             :     0,                                          /* tp_clear */
    2658             :     0,                                          /* tp_richcompare */
    2659             :     offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
    2660             :     0,                                          /* tp_iter */
    2661             :     0,                                          /* tp_iternext */
    2662             :     0,                                          /* tp_methods */
    2663             :     instancemethod_memberlist,                  /* tp_members */
    2664             :     instancemethod_getset,                      /* tp_getset */
    2665             :     0,                                          /* tp_base */
    2666             :     0,                                          /* tp_dict */
    2667             :     instancemethod_descr_get,                   /* tp_descr_get */
    2668             :     0,                                          /* tp_descr_set */
    2669             :     0,                                          /* tp_dictoffset */
    2670             :     0,                                          /* tp_init */
    2671             :     0,                                          /* tp_alloc */
    2672             :     instancemethod_new,                         /* tp_new */
    2673             : };
    2674             : 
    2675             : /* Clear out the free list */
    2676             : 
    2677             : int
    2678           6 : PyMethod_ClearFreeList(void)
    2679             : {
    2680           6 :     int freelist_size = numfree;
    2681             : 
    2682         150 :     while (free_list) {
    2683         138 :         PyMethodObject *im = free_list;
    2684         138 :         free_list = (PyMethodObject *)(im->im_self);
    2685         138 :         PyObject_GC_Del(im);
    2686         138 :         numfree--;
    2687             :     }
    2688             :     assert(numfree == 0);
    2689           6 :     return freelist_size;
    2690             : }
    2691             : 
    2692             : void
    2693           3 : PyMethod_Fini(void)
    2694             : {
    2695           3 :     (void)PyMethod_ClearFreeList();
    2696           3 : }

Generated by: LCOV version 1.10