Python-2.7.3/Objects/classobject.c

No issues found

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