home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Objects / classobject.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-25  |  40.7 KB  |  1,765 lines

  1.  
  2. /* Class object implementation */
  3.  
  4. #include "Python.h"
  5. #include "structmember.h"
  6.  
  7. /* Forward */
  8. static PyObject *class_lookup(PyClassObject *, PyObject *,
  9.                   PyClassObject **);
  10. static PyObject *instance_getattr1(PyInstanceObject *, PyObject *);
  11. static PyObject *instance_getattr2(PyInstanceObject *, PyObject *);
  12.  
  13. static PyObject *getattrstr, *setattrstr, *delattrstr;
  14.  
  15.  
  16. PyObject *
  17. PyClass_New(PyObject *bases, PyObject *dict, PyObject *name)
  18.      /* bases is NULL or tuple of classobjects! */
  19. {
  20.     PyClassObject *op, *dummy;
  21.     static PyObject *docstr, *modstr, *namestr;
  22.     if (docstr == NULL) {
  23.         docstr= PyString_InternFromString("__doc__");
  24.         if (docstr == NULL)
  25.             return NULL;
  26.     }
  27.     if (modstr == NULL) {
  28.         modstr= PyString_InternFromString("__module__");
  29.         if (modstr == NULL)
  30.             return NULL;
  31.     }
  32.     if (namestr == NULL) {
  33.         namestr= PyString_InternFromString("__name__");
  34.         if (namestr == NULL)
  35.             return NULL;
  36.     }
  37.     if (name == NULL || !PyString_Check(name)) {
  38.         PyErr_SetString(PyExc_SystemError,
  39.                 "PyClass_New: name must be a string");
  40.         return NULL;
  41.     }
  42.     if (dict == NULL || !PyDict_Check(dict)) {
  43.         PyErr_SetString(PyExc_SystemError,
  44.                 "PyClass_New: dict must be a dictionary");
  45.         return NULL;
  46.     }
  47.     if (PyDict_GetItem(dict, docstr) == NULL) {
  48.         if (PyDict_SetItem(dict, docstr, Py_None) < 0)
  49.             return NULL;
  50.     }
  51.     if (PyDict_GetItem(dict, modstr) == NULL) {
  52.         PyObject *globals = PyEval_GetGlobals();
  53.         if (globals != NULL) {
  54.             PyObject *modname = PyDict_GetItem(globals, namestr);
  55.             if (modname != NULL) {
  56.                 if (PyDict_SetItem(dict, modstr, modname) < 0)
  57.                     return NULL;
  58.             }
  59.         }
  60.     }
  61.     if (bases == NULL) {
  62.         bases = PyTuple_New(0);
  63.         if (bases == NULL)
  64.             return NULL;
  65.     }
  66.     else {
  67.         int i;
  68.         if (!PyTuple_Check(bases)) {
  69.             PyErr_SetString(PyExc_SystemError,
  70.                     "PyClass_New: bases must be a tuple");
  71.             return NULL;
  72.         }
  73.         i = PyTuple_Size(bases);
  74.         while (--i >= 0) {
  75.             if (!PyClass_Check(PyTuple_GetItem(bases, i))) {
  76.                 PyErr_SetString(PyExc_SystemError,
  77.                     "PyClass_New: base must be a class");
  78.                 return NULL;
  79.             }
  80.         }
  81.         Py_INCREF(bases);
  82.     }
  83.     op = PyObject_NEW(PyClassObject, &PyClass_Type);
  84.     if (op == NULL) {
  85.         Py_DECREF(bases);
  86.         return NULL;
  87.     }
  88.     op->cl_bases = bases;
  89.     Py_INCREF(dict);
  90.     op->cl_dict = dict;
  91.     Py_XINCREF(name);
  92.     op->cl_name = name;
  93.     if (getattrstr == NULL) {
  94.         getattrstr = PyString_InternFromString("__getattr__");
  95.         setattrstr = PyString_InternFromString("__setattr__");
  96.         delattrstr = PyString_InternFromString("__delattr__");
  97.     }
  98.     op->cl_getattr = class_lookup(op, getattrstr, &dummy);
  99.     op->cl_setattr = class_lookup(op, setattrstr, &dummy);
  100.     op->cl_delattr = class_lookup(op, delattrstr, &dummy);
  101.     Py_XINCREF(op->cl_getattr);
  102.     Py_XINCREF(op->cl_setattr);
  103.     Py_XINCREF(op->cl_delattr);
  104.     PyObject_GC_Init(op);
  105.     return (PyObject *) op;
  106. }
  107.  
  108. /* Class methods */
  109.  
  110. static void
  111. class_dealloc(PyClassObject *op)
  112. {
  113.     PyObject_GC_Fini(op);
  114.     Py_DECREF(op->cl_bases);
  115.     Py_DECREF(op->cl_dict);
  116.     Py_XDECREF(op->cl_name);
  117.     Py_XDECREF(op->cl_getattr);
  118.     Py_XDECREF(op->cl_setattr);
  119.     Py_XDECREF(op->cl_delattr);
  120.     op = (PyClassObject *) PyObject_AS_GC(op);
  121.     PyObject_DEL(op);
  122. }
  123.  
  124. static PyObject *
  125. class_lookup(PyClassObject *cp, PyObject *name, PyClassObject **pclass)
  126. {
  127.     int i, n;
  128.     PyObject *value = PyDict_GetItem(cp->cl_dict, name);
  129.     if (value != NULL) {
  130.         *pclass = cp;
  131.         return value;
  132.     }
  133.     n = PyTuple_Size(cp->cl_bases);
  134.     for (i = 0; i < n; i++) {
  135.         /* XXX What if one of the bases is not a class? */
  136.         PyObject *v = class_lookup(
  137.             (PyClassObject *)
  138.             PyTuple_GetItem(cp->cl_bases, i), name, pclass);
  139.         if (v != NULL)
  140.             return v;
  141.     }
  142.     return NULL;
  143. }
  144.  
  145. static PyObject *
  146. class_getattr(register PyClassObject *op, PyObject *name)
  147. {
  148.     register PyObject *v;
  149.     register char *sname = PyString_AsString(name);
  150.     PyClassObject *class;
  151.     if (sname[0] == '_' && sname[1] == '_') {
  152.         if (strcmp(sname, "__dict__") == 0) {
  153.             if (PyEval_GetRestricted()) {
  154.                 PyErr_SetString(PyExc_RuntimeError,
  155.                "class.__dict__ not accessible in restricted mode");
  156.                 return NULL;
  157.             }
  158.             Py_INCREF(op->cl_dict);
  159.             return op->cl_dict;
  160.         }
  161.         if (strcmp(sname, "__bases__") == 0) {
  162.             Py_INCREF(op->cl_bases);
  163.             return op->cl_bases;
  164.         }
  165.         if (strcmp(sname, "__name__") == 0) {
  166.             if (op->cl_name == NULL)
  167.                 v = Py_None;
  168.             else
  169.                 v = op->cl_name;
  170.             Py_INCREF(v);
  171.             return v;
  172.         }
  173.     }
  174.     v = class_lookup(op, name, &class);
  175.     if (v == NULL) {
  176.         PyErr_SetObject(PyExc_AttributeError, name);
  177.         return NULL;
  178.     }
  179.     Py_INCREF(v);
  180.     if (PyFunction_Check(v)) {
  181.         PyObject *w = PyMethod_New(v, (PyObject *)NULL,
  182.                             (PyObject *)class);
  183.         Py_DECREF(v);
  184.         v = w;
  185.     }
  186.     return v;
  187. }
  188.  
  189. static void
  190. set_slot(PyObject **slot, PyObject *v)
  191. {
  192.     PyObject *temp = *slot;
  193.     Py_XINCREF(v);
  194.     *slot = v;
  195.     Py_XDECREF(temp);
  196. }
  197.  
  198. static void
  199. set_attr_slots(PyClassObject *c)
  200. {
  201.     PyClassObject *dummy;
  202.  
  203.     set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy));
  204.     set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy));
  205.     set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy));
  206. }
  207.  
  208. static char *
  209. set_dict(PyClassObject *c, PyObject *v)
  210. {
  211.     if (v == NULL || !PyDict_Check(v))
  212.         return "__dict__ must be a dictionary object";
  213.     set_slot(&c->cl_dict, v);
  214.     set_attr_slots(c);
  215.     return "";
  216. }
  217.  
  218. static char *
  219. set_bases(PyClassObject *c, PyObject *v)
  220. {
  221.     int i, n;
  222.  
  223.     if (v == NULL || !PyTuple_Check(v))
  224.         return "__bases__ must be a tuple object";
  225.     n = PyTuple_Size(v);
  226.     for (i = 0; i < n; i++) {
  227.         PyObject *x = PyTuple_GET_ITEM(v, i);
  228.         if (!PyClass_Check(x))
  229.             return "__bases__ items must be classes";
  230.         if (PyClass_IsSubclass(x, (PyObject *)c))
  231.             return "a __bases__ item causes an inheritance cycle";
  232.     }
  233.     set_slot(&c->cl_bases, v);
  234.     set_attr_slots(c);
  235.     return "";
  236. }
  237.  
  238. static char *
  239. set_name(PyClassObject *c, PyObject *v)
  240. {
  241.     if (v == NULL || !PyString_Check(v))
  242.         return "__name__ must be a string object";
  243.     if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v))
  244.         return "__name__ must not contain null bytes";
  245.     set_slot(&c->cl_name, v);
  246.     return "";
  247. }
  248.  
  249. static int
  250. class_setattr(PyClassObject *op, PyObject *name, PyObject *v)
  251. {
  252.     char *sname;
  253.     if (PyEval_GetRestricted()) {
  254.         PyErr_SetString(PyExc_RuntimeError,
  255.                "classes are read-only in restricted mode");
  256.         return -1;
  257.     }
  258.     sname = PyString_AsString(name);
  259.     if (sname[0] == '_' && sname[1] == '_') {
  260.         int n = PyString_Size(name);
  261.         if (sname[n-1] == '_' && sname[n-2] == '_') {
  262.             char *err = NULL;
  263.             if (strcmp(sname, "__dict__") == 0)
  264.                 err = set_dict(op, v);
  265.             else if (strcmp(sname, "__bases__") == 0)
  266.                 err = set_bases(op, v);
  267.             else if (strcmp(sname, "__name__") == 0)
  268.                 err = set_name(op, v);
  269.             else if (strcmp(sname, "__getattr__") == 0)
  270.                 set_slot(&op->cl_getattr, v);
  271.             else if (strcmp(sname, "__setattr__") == 0)
  272.                 set_slot(&op->cl_setattr, v);
  273.             else if (strcmp(sname, "__delattr__") == 0)
  274.                 set_slot(&op->cl_delattr, v);
  275.             /* For the last three, we fall through to update the
  276.                dictionary as well. */
  277.             if (err != NULL) {
  278.                 if (*err == '\0')
  279.                     return 0;
  280.                 PyErr_SetString(PyExc_TypeError, err);
  281.                 return -1;
  282.             }
  283.         }
  284.     }
  285.     if (v == NULL) {
  286.         int rv = PyDict_DelItem(op->cl_dict, name);
  287.         if (rv < 0)
  288.             PyErr_SetString(PyExc_AttributeError,
  289.                    "delete non-existing class attribute");
  290.         return rv;
  291.     }
  292.     else
  293.         return PyDict_SetItem(op->cl_dict, name, v);
  294. }
  295.  
  296. static PyObject *
  297. class_repr(PyClassObject *op)
  298. {
  299.     PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
  300.     char buf[140];
  301.     char *name;
  302.     if (op->cl_name == NULL || !PyString_Check(op->cl_name))
  303.         name = "?";
  304.     else
  305.         name = PyString_AsString(op->cl_name);
  306.     if (mod == NULL || !PyString_Check(mod))
  307.         sprintf(buf, "<class ?.%.100s at %p>", name, op);
  308.     else
  309.         sprintf(buf, "<class %.50s.%.50s at %p>",
  310.             PyString_AsString(mod),
  311.             name, op);
  312.     return PyString_FromString(buf);
  313. }
  314.  
  315. static PyObject *
  316. class_str(PyClassObject *op)
  317. {
  318.     PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
  319.     PyObject *name = op->cl_name;
  320.     PyObject *res;
  321.     int m, n;
  322.  
  323.     if (name == NULL || !PyString_Check(name))
  324.         return class_repr(op);
  325.     if (mod == NULL || !PyString_Check(mod)) {
  326.         Py_INCREF(name);
  327.         return name;
  328.     }
  329.     m = PyString_Size(mod);
  330.     n = PyString_Size(name);
  331.     res = PyString_FromStringAndSize((char *)NULL, m+1+n);
  332.     if (res != NULL) {
  333.         char *s = PyString_AsString(res);
  334.         memcpy(s, PyString_AsString(mod), m);
  335.         s += m;
  336.         *s++ = '.';
  337.         memcpy(s, PyString_AsString(name), n);
  338.     }
  339.     return res;
  340. }
  341.  
  342. static int
  343. class_traverse(PyClassObject *o, visitproc visit, void *arg)
  344. {
  345.     int err;
  346.     if (o->cl_bases) {
  347.         err = visit(o->cl_bases, arg);
  348.         if (err)
  349.             return err;
  350.     }
  351.     if (o->cl_dict) {
  352.         err = visit(o->cl_dict, arg);
  353.         if (err)
  354.             return err;
  355.     }
  356.     if (o->cl_name) {
  357.         err = visit(o->cl_name, arg);
  358.         if (err)
  359.             return err;
  360.     }
  361.     if (o->cl_getattr) {
  362.         err = visit(o->cl_getattr, arg);
  363.         if (err)
  364.             return err;
  365.     }
  366.     if (o->cl_setattr) {
  367.         err = visit(o->cl_setattr, arg);
  368.         if (err)
  369.             return err;
  370.     }
  371.     if (o->cl_delattr) {
  372.         err = visit(o->cl_delattr, arg);
  373.         if (err)
  374.             return err;
  375.     }
  376.     return 0;
  377. }
  378.  
  379. PyTypeObject PyClass_Type = {
  380.     PyObject_HEAD_INIT(&PyType_Type)
  381.     0,
  382.     "class",
  383.     sizeof(PyClassObject) + PyGC_HEAD_SIZE,
  384.     0,
  385.     (destructor)class_dealloc, /*tp_dealloc*/
  386.     0,        /*tp_print*/
  387.     0,        /*tp_getattr*/
  388.     0,        /*tp_setattr*/
  389.     0,        /*tp_compare*/
  390.     (reprfunc)class_repr, /*tp_repr*/
  391.     0,        /*tp_as_number*/
  392.     0,        /*tp_as_sequence*/
  393.     0,        /*tp_as_mapping*/
  394.     0,        /*tp_hash*/
  395.     0,        /*tp_call*/
  396.     (reprfunc)class_str, /*tp_str*/
  397.     (getattrofunc)class_getattr, /*tp_getattro*/
  398.     (setattrofunc)class_setattr, /*tp_setattro*/
  399.     0,        /* tp_as_buffer */
  400.     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
  401.     0,        /* tp_doc */
  402.     (traverseproc)class_traverse,    /* tp_traverse */
  403. };
  404.  
  405. int
  406. PyClass_IsSubclass(PyObject *class, PyObject *base)
  407. {
  408.     int i, n;
  409.     PyClassObject *cp;
  410.     if (class == base)
  411.         return 1;
  412.     if (class == NULL || !PyClass_Check(class))
  413.         return 0;
  414.     cp = (PyClassObject *)class;
  415.     n = PyTuple_Size(cp->cl_bases);
  416.     for (i = 0; i < n; i++) {
  417.         if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
  418.             return 1;
  419.     }
  420.     return 0;
  421. }
  422.  
  423.  
  424. /* Instance objects */
  425.  
  426. PyObject *
  427. PyInstance_New(PyObject *class, PyObject *arg, PyObject *kw)
  428. {
  429.     register PyInstanceObject *inst;
  430.     PyObject *init;
  431.     static PyObject *initstr;
  432.     if (!PyClass_Check(class)) {
  433.         PyErr_BadInternalCall();
  434.         return NULL;
  435.     }
  436.     inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type);
  437.     if (inst == NULL)
  438.         return NULL;
  439.     inst->in_dict = PyDict_New();
  440.     if (inst->in_dict == NULL) {
  441.         inst = (PyInstanceObject *) PyObject_AS_GC(inst);
  442.         PyObject_DEL(inst);
  443.         return NULL;
  444.     }
  445.     Py_INCREF(class);
  446.     inst->in_class = (PyClassObject *)class;
  447.     PyObject_GC_Init(inst);
  448.     if (initstr == NULL)
  449.         initstr = PyString_InternFromString("__init__");
  450.     init = instance_getattr2(inst, initstr);
  451.     if (init == NULL) {
  452.         if ((arg != NULL && (!PyTuple_Check(arg) ||
  453.                      PyTuple_Size(arg) != 0))
  454.             || (kw != NULL && (!PyDict_Check(kw) ||
  455.                       PyDict_Size(kw) != 0))) {
  456.             PyErr_SetString(PyExc_TypeError,
  457.                    "this constructor takes no arguments");
  458.             Py_DECREF(inst);
  459.             inst = NULL;
  460.         }
  461.     }
  462.     else {
  463.         PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
  464.         Py_DECREF(init);
  465.         if (res == NULL) {
  466.             Py_DECREF(inst);
  467.             inst = NULL;
  468.         }
  469.         else {
  470.             if (res != Py_None) {
  471.                 PyErr_SetString(PyExc_TypeError,
  472.                        "__init__() should return None");
  473.                 Py_DECREF(inst);
  474.                 inst = NULL;
  475.             }
  476.             Py_DECREF(res);
  477.         }
  478.     }
  479.     return (PyObject *)inst;
  480. }
  481.  
  482. /* Instance methods */
  483.  
  484. static void
  485. instance_dealloc(register PyInstanceObject *inst)
  486. {
  487.     PyObject *error_type, *error_value, *error_traceback;
  488.     PyObject *del;
  489.     static PyObject *delstr;
  490. #ifdef Py_REF_DEBUG
  491.     extern long _Py_RefTotal;
  492. #endif
  493.     /* Temporarily resurrect the object. */
  494. #ifdef Py_TRACE_REFS
  495. #ifndef Py_REF_DEBUG
  496. #   error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
  497. #endif
  498.     /* much too complicated if Py_TRACE_REFS defined */
  499.     inst->ob_type = &PyInstance_Type;
  500.     _Py_NewReference((PyObject *)inst);
  501. #ifdef COUNT_ALLOCS
  502.     /* compensate for boost in _Py_NewReference; note that
  503.      * _Py_RefTotal was also boosted; we'll knock that down later.
  504.      */
  505.     inst->ob_type->tp_alloc--;
  506. #endif
  507. #else /* !Py_TRACE_REFS */
  508.     /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
  509.     Py_INCREF(inst);
  510. #endif /* !Py_TRACE_REFS */
  511.  
  512.     /* Save the current exception, if any. */
  513.     PyErr_Fetch(&error_type, &error_value, &error_traceback);
  514.     /* Execute __del__ method, if any. */
  515.     if (delstr == NULL)
  516.         delstr = PyString_InternFromString("__del__");
  517.     if ((del = instance_getattr2(inst, delstr)) != NULL) {
  518.         PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
  519.         if (res == NULL)
  520.             PyErr_WriteUnraisable(del);
  521.         else
  522.             Py_DECREF(res);
  523.         Py_DECREF(del);
  524.     }
  525.     /* Restore the saved exception. */
  526.     PyErr_Restore(error_type, error_value, error_traceback);
  527.     /* Undo the temporary resurrection; can't use DECREF here, it would
  528.      * cause a recursive call.
  529.      */
  530. #ifdef Py_REF_DEBUG
  531.     /* _Py_RefTotal was boosted either by _Py_NewReference or
  532.      * Py_INCREF above.
  533.      */
  534.     _Py_RefTotal--;
  535. #endif
  536.     if (--inst->ob_refcnt > 0) {
  537. #ifdef COUNT_ALLOCS
  538.         inst->ob_type->tp_free--;
  539. #endif
  540.         return; /* __del__ added a reference; don't delete now */
  541.     }
  542. #ifdef Py_TRACE_REFS
  543.     _Py_ForgetReference((PyObject *)inst);
  544. #ifdef COUNT_ALLOCS
  545.     /* compensate for increment in _Py_ForgetReference */
  546.     inst->ob_type->tp_free--;
  547. #endif
  548. #ifndef WITH_CYCLE_GC
  549.     inst->ob_type = NULL;
  550. #endif
  551. #endif
  552.     PyObject_GC_Fini(inst);
  553.     Py_DECREF(inst->in_class);
  554.     Py_XDECREF(inst->in_dict);
  555.     inst = (PyInstanceObject *) PyObject_AS_GC(inst);
  556.     PyObject_DEL(inst);
  557. }
  558.  
  559. static PyObject *
  560. instance_getattr1(register PyInstanceObject *inst, PyObject *name)
  561. {
  562.     register PyObject *v;
  563.     register char *sname = PyString_AsString(name);
  564.     if (sname[0] == '_' && sname[1] == '_') {
  565.         if (strcmp(sname, "__dict__") == 0) {
  566.             if (PyEval_GetRestricted()) {
  567.                 PyErr_SetString(PyExc_RuntimeError,
  568.             "instance.__dict__ not accessible in restricted mode");
  569.                 return NULL;
  570.             }
  571.             Py_INCREF(inst->in_dict);
  572.             return inst->in_dict;
  573.         }
  574.         if (strcmp(sname, "__class__") == 0) {
  575.             Py_INCREF(inst->in_class);
  576.             return (PyObject *)inst->in_class;
  577.         }
  578.     }
  579.     v = instance_getattr2(inst, name);
  580.     if (v == NULL) {
  581.         PyErr_Format(PyExc_AttributeError,"'%.50s' instance has no attribute '%.400s'",
  582.                  PyString_AS_STRING(inst->in_class->cl_name), sname);
  583.     }
  584.     return v;
  585. }
  586.  
  587. static PyObject *
  588. instance_getattr2(register PyInstanceObject *inst, PyObject *name)
  589. {
  590.     register PyObject *v;
  591.     PyClassObject *class;
  592.     class = NULL;
  593.     v = PyDict_GetItem(inst->in_dict, name);
  594.     if (v == NULL) {
  595.         v = class_lookup(inst->in_class, name, &class);
  596.         if (v == NULL)
  597.             return v;
  598.     }
  599.     Py_INCREF(v);
  600.     if (class != NULL) {
  601.         if (PyFunction_Check(v)) {
  602.             PyObject *w = PyMethod_New(v, (PyObject *)inst,
  603.                                 (PyObject *)class);
  604.             Py_DECREF(v);
  605.             v = w;
  606.         }
  607.         else if (PyMethod_Check(v)) {
  608.             PyObject *im_class = PyMethod_Class(v);
  609.             /* Only if classes are compatible */
  610.             if (PyClass_IsSubclass((PyObject *)class, im_class)) {
  611.                 PyObject *im_func = PyMethod_Function(v);
  612.                 PyObject *w = PyMethod_New(im_func,
  613.                         (PyObject *)inst, im_class);
  614.                 Py_DECREF(v);
  615.                 v = w;
  616.             }
  617.         }
  618.     }
  619.     return v;
  620. }
  621.  
  622. static PyObject *
  623. instance_getattr(register PyInstanceObject *inst, PyObject *name)
  624. {
  625.     register PyObject *func, *res;
  626.     res = instance_getattr1(inst, name);
  627.     if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
  628.         PyObject *args;
  629.         PyErr_Clear();
  630.         args = Py_BuildValue("(OO)", inst, name);
  631.         if (args == NULL)
  632.             return NULL;
  633.         res = PyEval_CallObject(func, args);
  634.         Py_DECREF(args);
  635.     }
  636.     return res;
  637. }
  638.  
  639. static int
  640. instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
  641. {
  642.     if (v == NULL) {
  643.         int rv = PyDict_DelItem(inst->in_dict, name);
  644.         if (rv < 0)
  645.             PyErr_SetString(PyExc_AttributeError,
  646.                    "delete non-existing instance attribute");
  647.         return rv;
  648.     }
  649.     else
  650.         return PyDict_SetItem(inst->in_dict, name, v);
  651. }
  652.  
  653. static int
  654. instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
  655. {
  656.     PyObject *func, *args, *res, *tmp;
  657.     char *sname = PyString_AsString(name);
  658.     if (sname[0] == '_' && sname[1] == '_') {
  659.         int n = PyString_Size(name);
  660.         if (sname[n-1] == '_' && sname[n-2] == '_') {
  661.             if (strcmp(sname, "__dict__") == 0) {
  662.                 if (PyEval_GetRestricted()) {
  663.                     PyErr_SetString(PyExc_RuntimeError,
  664.                  "__dict__ not accessible in restricted mode");
  665.                     return -1;
  666.                 }
  667.                 if (v == NULL || !PyDict_Check(v)) {
  668.                     PyErr_SetString(PyExc_TypeError,
  669.                        "__dict__ must be set to a dictionary");
  670.                     return -1;
  671.                 }
  672.                 tmp = inst->in_dict;
  673.                 Py_INCREF(v);
  674.                 inst->in_dict = v;
  675.                 Py_DECREF(tmp);
  676.                 return 0;
  677.             }
  678.             if (strcmp(sname, "__class__") == 0) {
  679.                 if (PyEval_GetRestricted()) {
  680.                     PyErr_SetString(PyExc_RuntimeError,
  681.                 "__class__ not accessible in restricted mode");
  682.                     return -1;
  683.                 }
  684.                 if (v == NULL || !PyClass_Check(v)) {
  685.                     PyErr_SetString(PyExc_TypeError,
  686.                        "__class__ must be set to a class");
  687.                     return -1;
  688.                 }
  689.                 tmp = (PyObject *)(inst->in_class);
  690.                 Py_INCREF(v);
  691.                 inst->in_class = (PyClassObject *)v;
  692.                 Py_DECREF(tmp);
  693.                 return 0;
  694.             }
  695.         }
  696.     }
  697.     if (v == NULL)
  698.         func = inst->in_class->cl_delattr;
  699.     else
  700.         func = inst->in_class->cl_setattr;
  701.     if (func == NULL)
  702.         return instance_setattr1(inst, name, v);
  703.     if (v == NULL)
  704.         args = Py_BuildValue("(OO)", inst, name);
  705.     else
  706.         args = Py_BuildValue("(OOO)", inst, name, v);
  707.     if (args == NULL)
  708.         return -1;
  709.     res = PyEval_CallObject(func, args);
  710.     Py_DECREF(args);
  711.     if (res == NULL)
  712.         return -1;
  713.     Py_DECREF(res);
  714.     return 0;
  715. }
  716.  
  717. static PyObject *
  718. instance_repr(PyInstanceObject *inst)
  719. {
  720.     PyObject *func;
  721.     PyObject *res;
  722.     static PyObject *reprstr;
  723.  
  724.     if (reprstr == NULL)
  725.         reprstr = PyString_InternFromString("__repr__");
  726.     func = instance_getattr(inst, reprstr);
  727.     if (func == NULL) {
  728.         char buf[140];
  729.         PyObject *classname = inst->in_class->cl_name;
  730.         PyObject *mod = PyDict_GetItemString(
  731.             inst->in_class->cl_dict, "__module__");
  732.         char *cname;
  733.         if (classname != NULL && PyString_Check(classname))
  734.             cname = PyString_AsString(classname);
  735.         else
  736.             cname = "?";
  737.         PyErr_Clear();
  738.         if (mod == NULL || !PyString_Check(mod))
  739.             sprintf(buf, "<?.%.100s instance at %p>",
  740.                 cname, inst);
  741.         else
  742.             sprintf(buf, "<%.50s.%.50s instance at %p>",
  743.                 PyString_AsString(mod),
  744.                 cname, inst);
  745.         return PyString_FromString(buf);
  746.     }
  747.     res = PyEval_CallObject(func, (PyObject *)NULL);
  748.     Py_DECREF(func);
  749.     return res;
  750. }
  751.  
  752. static PyObject *
  753. instance_compare1(PyObject *inst, PyObject *other)
  754. {
  755.     return PyInstance_DoBinOp(inst, other, "__cmp__", "__rcmp__",
  756.                  instance_compare1);
  757. }
  758.  
  759. static int
  760. instance_compare(PyObject *inst, PyObject *other)
  761. {
  762.     PyObject *result;
  763.     long outcome;
  764.     result = instance_compare1(inst, other);
  765.     if (result == NULL)
  766.         return -1;
  767.     if (!PyInt_Check(result)) {
  768.         Py_DECREF(result);
  769.         PyErr_SetString(PyExc_TypeError,
  770.                 "comparison did not return an int");
  771.         return -1;
  772.     }
  773.     outcome = PyInt_AsLong(result);
  774.     Py_DECREF(result);
  775.     if (outcome < 0)
  776.         return -1;
  777.     else if (outcome > 0)
  778.         return 1;
  779.     return 0;
  780. }
  781.  
  782. static long
  783. instance_hash(PyInstanceObject *inst)
  784. {
  785.     PyObject *func;
  786.     PyObject *res;
  787.     long outcome;
  788.     static PyObject *hashstr, *cmpstr;
  789.  
  790.     if (hashstr == NULL)
  791.         hashstr = PyString_InternFromString("__hash__");
  792.     func = instance_getattr(inst, hashstr);
  793.     if (func == NULL) {
  794.         /* If there is no __cmp__ method, we hash on the address.
  795.            If a __cmp__ method exists, there must be a __hash__. */
  796.         PyErr_Clear();
  797.         if (cmpstr == NULL)
  798.             cmpstr = PyString_InternFromString("__cmp__");
  799.         func = instance_getattr(inst, cmpstr);
  800.         if (func == NULL) {
  801.             PyErr_Clear();
  802.             return _Py_HashPointer(inst);
  803.         }
  804.         PyErr_SetString(PyExc_TypeError, "unhashable instance");
  805.         return -1;
  806.     }
  807.     res = PyEval_CallObject(func, (PyObject *)NULL);
  808.     Py_DECREF(func);
  809.     if (res == NULL)
  810.         return -1;
  811.     if (PyInt_Check(res)) {
  812.         outcome = PyInt_AsLong(res);
  813.         if (outcome == -1)
  814.             outcome = -2;
  815.     }
  816.     else {
  817.         PyErr_SetString(PyExc_TypeError,
  818.                 "__hash__() should return an int");
  819.         outcome = -1;
  820.     }
  821.     Py_DECREF(res);
  822.     return outcome;
  823. }
  824.  
  825. static int
  826. instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
  827. {
  828.     int err;
  829.     if (o->in_class) {
  830.         err = visit((PyObject *)(o->in_class), arg);
  831.         if (err)
  832.             return err;
  833.     }
  834.     if (o->in_dict) {
  835.         err = visit(o->in_dict, arg);
  836.         if (err)
  837.             return err;
  838.     }
  839.     return 0;
  840. }
  841.  
  842. static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
  843.  
  844. static int
  845. instance_length(PyInstanceObject *inst)
  846. {
  847.     PyObject *func;
  848.     PyObject *res;
  849.     int outcome;
  850.  
  851.     if (lenstr == NULL)
  852.         lenstr = PyString_InternFromString("__len__");
  853.     func = instance_getattr(inst, lenstr);
  854.     if (func == NULL)
  855.         return -1;
  856.     res = PyEval_CallObject(func, (PyObject *)NULL);
  857.     Py_DECREF(func);
  858.     if (res == NULL)
  859.         return -1;
  860.     if (PyInt_Check(res)) {
  861.         outcome = PyInt_AsLong(res);
  862.         if (outcome < 0)
  863.             PyErr_SetString(PyExc_ValueError,
  864.                     "__len__() should return >= 0");
  865.     }
  866.     else {
  867.         PyErr_SetString(PyExc_TypeError,
  868.                 "__len__() should return an int");
  869.         outcome = -1;
  870.     }
  871.     Py_DECREF(res);
  872.     return outcome;
  873. }
  874.  
  875. static PyObject *
  876. instance_subscript(PyInstanceObject *inst, PyObject *key)
  877. {
  878.     PyObject *func;
  879.     PyObject *arg;
  880.     PyObject *res;
  881.  
  882.     if (getitemstr == NULL)
  883.         getitemstr = PyString_InternFromString("__getitem__");
  884.     func = instance_getattr(inst, getitemstr);
  885.     if (func == NULL)
  886.         return NULL;
  887.     arg = Py_BuildValue("(O)", key);
  888.     if (arg == NULL) {
  889.         Py_DECREF(func);
  890.         return NULL;
  891.     }
  892.     res = PyEval_CallObject(func, arg);
  893.     Py_DECREF(func);
  894.     Py_DECREF(arg);
  895.     return res;
  896. }
  897.  
  898. static int
  899. instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
  900. {
  901.     PyObject *func;
  902.     PyObject *arg;
  903.     PyObject *res;
  904.  
  905.     if (value == NULL) {
  906.         if (delitemstr == NULL)
  907.             delitemstr = PyString_InternFromString("__delitem__");
  908.         func = instance_getattr(inst, delitemstr);
  909.     }
  910.     else {
  911.         if (setitemstr == NULL)
  912.             setitemstr = PyString_InternFromString("__setitem__");
  913.         func = instance_getattr(inst, setitemstr);
  914.     }
  915.     if (func == NULL)
  916.         return -1;
  917.     if (value == NULL)
  918.         arg = Py_BuildValue("(O)", key);
  919.     else
  920.         arg = Py_BuildValue("(OO)", key, value);
  921.     if (arg == NULL) {
  922.         Py_DECREF(func);
  923.         return -1;
  924.     }
  925.     res = PyEval_CallObject(func, arg);
  926.     Py_DECREF(func);
  927.     Py_DECREF(arg);
  928.     if (res == NULL)
  929.         return -1;
  930.     Py_DECREF(res);
  931.     return 0;
  932. }
  933.  
  934. static PyMappingMethods instance_as_mapping = {
  935.     (inquiry)instance_length, /*mp_length*/
  936.     (binaryfunc)instance_subscript, /*mp_subscript*/
  937.     (objobjargproc)instance_ass_subscript, /*mp_ass_subscript*/
  938. };
  939.  
  940. static PyObject *
  941. instance_item(PyInstanceObject *inst, int i)
  942. {
  943.     PyObject *func, *arg, *res;
  944.  
  945.     if (getitemstr == NULL)
  946.         getitemstr = PyString_InternFromString("__getitem__");
  947.     func = instance_getattr(inst, getitemstr);
  948.     if (func == NULL)
  949.         return NULL;
  950.     arg = Py_BuildValue("(i)", i);
  951.     if (arg == NULL) {
  952.         Py_DECREF(func);
  953.         return NULL;
  954.     }
  955.     res = PyEval_CallObject(func, arg);
  956.     Py_DECREF(func);
  957.     Py_DECREF(arg);
  958.     return res;
  959. }
  960.  
  961. static PyObject *
  962. sliceobj_from_intint(int i, int j)
  963. {
  964.     PyObject *start, *end, *res;
  965.  
  966.     start = PyInt_FromLong((long)i);
  967.     if (!start)
  968.         return NULL;
  969.     
  970.     end = PyInt_FromLong((long)j);
  971.     if (!end) {
  972.         Py_DECREF(start);
  973.         return NULL;
  974.     }
  975.     res = PySlice_New(start, end, NULL);
  976.     Py_DECREF(start);
  977.     Py_DECREF(end);
  978.     return res;
  979. }
  980.  
  981.  
  982. static PyObject *
  983. instance_slice(PyInstanceObject *inst, int i, int j)
  984. {
  985.     PyObject *func, *arg, *res;
  986.     static PyObject *getslicestr;
  987.  
  988.     if (getslicestr == NULL)
  989.         getslicestr = PyString_InternFromString("__getslice__");
  990.     func = instance_getattr(inst, getslicestr);
  991.  
  992.     if (func == NULL) {
  993.         PyErr_Clear();
  994.  
  995.         if (getitemstr == NULL)
  996.             getitemstr = PyString_InternFromString("__getitem__");
  997.         func = instance_getattr(inst, getitemstr);
  998.         if (func == NULL)
  999.             return NULL;
  1000.         arg = Py_BuildValue("(N)", sliceobj_from_intint(i, j));
  1001.     } else 
  1002.         arg = Py_BuildValue("(ii)", i, j);
  1003.         
  1004.     if (arg == NULL) {
  1005.         Py_DECREF(func);
  1006.         return NULL;
  1007.     }
  1008.     res = PyEval_CallObject(func, arg);
  1009.     Py_DECREF(func);
  1010.     Py_DECREF(arg);
  1011.     return res;
  1012. }
  1013.  
  1014. static int
  1015. instance_ass_item(PyInstanceObject *inst, int i, PyObject *item)
  1016. {
  1017.     PyObject *func, *arg, *res;
  1018.  
  1019.     if (item == NULL) {
  1020.         if (delitemstr == NULL)
  1021.             delitemstr = PyString_InternFromString("__delitem__");
  1022.         func = instance_getattr(inst, delitemstr);
  1023.     }
  1024.     else {
  1025.         if (setitemstr == NULL)
  1026.             setitemstr = PyString_InternFromString("__setitem__");
  1027.         func = instance_getattr(inst, setitemstr);
  1028.     }
  1029.     if (func == NULL)
  1030.         return -1;
  1031.     if (item == NULL)
  1032.         arg = Py_BuildValue("i", i);
  1033.     else
  1034.         arg = Py_BuildValue("(iO)", i, item);
  1035.     if (arg == NULL) {
  1036.         Py_DECREF(func);
  1037.         return -1;
  1038.     }
  1039.     res = PyEval_CallObject(func, arg);
  1040.     Py_DECREF(func);
  1041.     Py_DECREF(arg);
  1042.     if (res == NULL)
  1043.         return -1;
  1044.     Py_DECREF(res);
  1045.     return 0;
  1046. }
  1047.  
  1048. static int
  1049. instance_ass_slice(PyInstanceObject *inst, int i, int j, PyObject *value)
  1050. {
  1051.     PyObject *func, *arg, *res;
  1052.     static PyObject *setslicestr, *delslicestr;
  1053.  
  1054.     if (value == NULL) {
  1055.         if (delslicestr == NULL)
  1056.             delslicestr =
  1057.                 PyString_InternFromString("__delslice__");
  1058.         func = instance_getattr(inst, delslicestr);
  1059.         if (func == NULL) {
  1060.             PyErr_Clear();
  1061.             if (delitemstr == NULL)
  1062.                 delitemstr =
  1063.                     PyString_InternFromString("__delitem__");
  1064.             func = instance_getattr(inst, delitemstr);
  1065.             if (func == NULL)
  1066.                 return -1;
  1067.  
  1068.             arg = Py_BuildValue("(N)",
  1069.                         sliceobj_from_intint(i, j));
  1070.         } else
  1071.             arg = Py_BuildValue("(ii)", i, j);
  1072.     }
  1073.     else {
  1074.         if (setslicestr == NULL)
  1075.             setslicestr =
  1076.                 PyString_InternFromString("__setslice__");
  1077.         func = instance_getattr(inst, setslicestr);
  1078.         if (func == NULL) {
  1079.             PyErr_Clear();
  1080.             if (setitemstr == NULL)
  1081.                 setitemstr =
  1082.                     PyString_InternFromString("__setitem__");
  1083.             func = instance_getattr(inst, setitemstr);
  1084.             if (func == NULL)
  1085.                 return -1;
  1086.  
  1087.             arg = Py_BuildValue("(NO)",
  1088.                         sliceobj_from_intint(i, j), value);
  1089.         } else
  1090.             arg = Py_BuildValue("(iiO)", i, j, value);
  1091.     }
  1092.     if (arg == NULL) {
  1093.         Py_DECREF(func);
  1094.         return -1;
  1095.     }
  1096.     res = PyEval_CallObject(func, arg);
  1097.     Py_DECREF(func);
  1098.     Py_DECREF(arg);
  1099.     if (res == NULL)
  1100.         return -1;
  1101.     Py_DECREF(res);
  1102.     return 0;
  1103. }
  1104.  
  1105. static int instance_contains(PyInstanceObject *inst, PyObject *member)
  1106. {
  1107.     static PyObject *__contains__;
  1108.     PyObject *func, *arg, *res;
  1109.     int ret;
  1110.  
  1111.     if(__contains__ == NULL) {
  1112.         __contains__ = PyString_InternFromString("__contains__");
  1113.         if(__contains__ == NULL)
  1114.             return -1;
  1115.     }
  1116.     func = instance_getattr(inst, __contains__);
  1117.     if(func == NULL) {
  1118.         /* fall back to previous behavior */
  1119.         int i, cmp_res;
  1120.  
  1121.         if(!PyErr_ExceptionMatches(PyExc_AttributeError))
  1122.             return -1;
  1123.         PyErr_Clear();
  1124.         for(i=0;;i++) {
  1125.             PyObject *obj = instance_item(inst, i);
  1126.             int ret = 0;
  1127.  
  1128.             if(obj == NULL) {
  1129.                 if(!PyErr_ExceptionMatches(PyExc_IndexError))
  1130.                     return -1;
  1131.                 PyErr_Clear();
  1132.                 return 0;
  1133.             }
  1134.             if(PyObject_Cmp(obj, member, &cmp_res) == -1)
  1135.                 ret = -1;
  1136.             if(cmp_res == 0) 
  1137.                 ret = 1;
  1138.             Py_DECREF(obj);
  1139.             if(ret)
  1140.                 return ret;
  1141.         }
  1142.     }
  1143.     arg = Py_BuildValue("(O)", member);
  1144.     if(arg == NULL) {
  1145.         Py_DECREF(func);
  1146.         return -1;
  1147.     }
  1148.     res = PyEval_CallObject(func, arg);
  1149.     Py_DECREF(func);
  1150.     Py_DECREF(arg);
  1151.     if(res == NULL) 
  1152.         return -1;
  1153.     ret = PyObject_IsTrue(res);
  1154.     Py_DECREF(res);
  1155.     return ret;
  1156. }
  1157.  
  1158. static PySequenceMethods
  1159. instance_as_sequence = {
  1160.     (inquiry)instance_length, /*sq_length*/
  1161.     0, /*sq_concat*/
  1162.     0, /*sq_repeat*/
  1163.     (intargfunc)instance_item, /*sq_item*/
  1164.     (intintargfunc)instance_slice, /*sq_slice*/
  1165.     (intobjargproc)instance_ass_item, /*sq_ass_item*/
  1166.     (intintobjargproc)instance_ass_slice, /*sq_ass_slice*/
  1167.     (objobjproc)instance_contains, /* sq_contains */
  1168. };
  1169.  
  1170. static PyObject *
  1171. generic_unary_op(PyInstanceObject *self, PyObject *methodname)
  1172. {
  1173.     PyObject *func, *res;
  1174.  
  1175.     if ((func = instance_getattr(self, methodname)) == NULL)
  1176.         return NULL;
  1177.     res = PyEval_CallObject(func, (PyObject *)NULL);
  1178.     Py_DECREF(func);
  1179.     return res;
  1180. }
  1181.  
  1182.  
  1183. /* Implement a binary operator involving at least one class instance. */
  1184.  
  1185. PyObject *
  1186. PyInstance_DoBinOp(PyObject *v, PyObject *w, char *opname, char *ropname,
  1187.                    PyObject * (*thisfunc)(PyObject *, PyObject *))
  1188. {
  1189.     char buf[256];
  1190.     PyObject *result = NULL;
  1191.  
  1192.     if (PyInstance_HalfBinOp(v, w, opname, &result, thisfunc, 0) <= 0)
  1193.         return result;
  1194.     if (PyInstance_HalfBinOp(w, v, ropname, &result, thisfunc, 1) <= 0)
  1195.         return result;
  1196.     /* Sigh -- special case for comparisons */
  1197.     if (strcmp(opname, "__cmp__") == 0) {
  1198.         Py_uintptr_t iv = (Py_uintptr_t)v;
  1199.         Py_uintptr_t iw = (Py_uintptr_t)w;
  1200.         long c = (iv < iw) ? -1 : (iv > iw) ? 1 : 0;
  1201.         return PyInt_FromLong(c);
  1202.     }
  1203.     sprintf(buf, "%s nor %s defined for these operands", opname, ropname);
  1204.     PyErr_SetString(PyExc_TypeError, buf);
  1205.     return NULL;
  1206. }
  1207.  
  1208.  
  1209. /* Try one half of a binary operator involving a class instance.
  1210.    Return value:
  1211.    -1 if an exception is to be reported right away
  1212.    0  if we have a valid result
  1213.    1  if we could try another operation
  1214. */
  1215.  
  1216. static PyObject *coerce_obj;
  1217.  
  1218. int
  1219. PyInstance_HalfBinOp(PyObject *v, PyObject *w, char *opname, PyObject **r_result,
  1220.              PyObject * (*thisfunc)(PyObject *, PyObject *), int swapped)
  1221. {
  1222.     PyObject *func;
  1223.     PyObject *args;
  1224.     PyObject *coercefunc;
  1225.     PyObject *coerced = NULL;
  1226.     PyObject *v1;
  1227.     
  1228.     if (!PyInstance_Check(v))
  1229.         return 1;
  1230.     if (coerce_obj == NULL) {
  1231.         coerce_obj = PyString_InternFromString("__coerce__");
  1232.         if (coerce_obj == NULL)
  1233.             return -1;
  1234.     }
  1235.     coercefunc = PyObject_GetAttr(v, coerce_obj);
  1236.     if (coercefunc == NULL) {
  1237.         PyErr_Clear();
  1238.     }
  1239.     else {
  1240.         args = Py_BuildValue("(O)", w);
  1241.         if (args == NULL) {
  1242.             return -1;
  1243.         }
  1244.         coerced = PyEval_CallObject(coercefunc, args);
  1245.         Py_DECREF(args);
  1246.         Py_DECREF(coercefunc);
  1247.         if (coerced == NULL) {
  1248.             return -1;
  1249.         }
  1250.         if (coerced == Py_None) {
  1251.             Py_DECREF(coerced);
  1252.             return 1;
  1253.         }
  1254.         if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
  1255.             Py_DECREF(coerced);
  1256.             PyErr_SetString(PyExc_TypeError,
  1257.                    "coercion should return None or 2-tuple");
  1258.             return -1;
  1259.         }
  1260.         v1 = PyTuple_GetItem(coerced, 0);
  1261.         w = PyTuple_GetItem(coerced, 1);
  1262.         if (v1 != v) {
  1263.             v = v1;
  1264.             if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
  1265.                 if (swapped)
  1266.                     *r_result = (*thisfunc)(w, v);
  1267.                 else
  1268.                     *r_result = (*thisfunc)(v, w);
  1269.                 Py_DECREF(coerced);
  1270.                 return *r_result == NULL ? -1 : 0;
  1271.             }
  1272.         }
  1273.     }
  1274.     func = PyObject_GetAttrString(v, opname);
  1275.     if (func == NULL) {
  1276.         Py_XDECREF(coerced);
  1277.         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1278.             return -1;
  1279.         PyErr_Clear();
  1280.         return 1;
  1281.     }
  1282.     args = Py_BuildValue("(O)", w);
  1283.     if (args == NULL) {
  1284.         Py_DECREF(func);
  1285.         Py_XDECREF(coerced);
  1286.         return -1;
  1287.     }
  1288.     *r_result = PyEval_CallObject(func, args);
  1289.     Py_DECREF(args);
  1290.     Py_DECREF(func);
  1291.     Py_XDECREF(coerced);
  1292.     return *r_result == NULL ? -1 : 0;
  1293. }
  1294.  
  1295. static int
  1296. instance_coerce(PyObject **pv, PyObject **pw)
  1297. {
  1298.     PyObject *v = *pv;
  1299.     PyObject *w = *pw;
  1300.     PyObject *coercefunc;
  1301.     PyObject *args;
  1302.     PyObject *coerced;
  1303.  
  1304.     if (coerce_obj == NULL) {
  1305.         coerce_obj = PyString_InternFromString("__coerce__");
  1306.         if (coerce_obj == NULL)
  1307.             return -1;
  1308.     }
  1309.     coercefunc = PyObject_GetAttr(v, coerce_obj);
  1310.     if (coercefunc == NULL) {
  1311.         /* No __coerce__ method: always OK */
  1312.         PyErr_Clear();
  1313.         Py_INCREF(v);
  1314.         Py_INCREF(w);
  1315.         return 0;
  1316.     }
  1317.     /* Has __coerce__ method: call it */
  1318.     args = Py_BuildValue("(O)", w);
  1319.     if (args == NULL) {
  1320.         return -1;
  1321.     }
  1322.     coerced = PyEval_CallObject(coercefunc, args);
  1323.     Py_DECREF(args);
  1324.     Py_DECREF(coercefunc);
  1325.     if (coerced == NULL) {
  1326.         /* __coerce__ call raised an exception */
  1327.         return -1;
  1328.     }
  1329.     if (coerced == Py_None) {
  1330.         /* __coerce__ says "I can't do it" */
  1331.         Py_DECREF(coerced);
  1332.         return 1;
  1333.     }
  1334.     if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
  1335.         /* __coerce__ return value is malformed */
  1336.         Py_DECREF(coerced);
  1337.         PyErr_SetString(PyExc_TypeError,
  1338.                "coercion should return None or 2-tuple");
  1339.         return -1;
  1340.     }
  1341.     /* __coerce__ returned two new values */
  1342.     *pv = PyTuple_GetItem(coerced, 0);
  1343.     *pw = PyTuple_GetItem(coerced, 1);
  1344.     Py_INCREF(*pv);
  1345.     Py_INCREF(*pw);
  1346.     Py_DECREF(coerced);
  1347.     return 0;
  1348. }
  1349.  
  1350.  
  1351. #define UNARY(funcname, methodname) \
  1352. static PyObject *funcname(PyInstanceObject *self) { \
  1353.     static PyObject *o; \
  1354.     if (o == NULL) o = PyString_InternFromString(methodname); \
  1355.     return generic_unary_op(self, o); \
  1356. }
  1357.  
  1358. UNARY(instance_neg, "__neg__")
  1359. UNARY(instance_pos, "__pos__")
  1360. UNARY(instance_abs, "__abs__")
  1361.  
  1362. static int
  1363. instance_nonzero(PyInstanceObject *self)
  1364. {
  1365.     PyObject *func, *res;
  1366.     long outcome;
  1367.     static PyObject *nonzerostr;
  1368.  
  1369.     if (nonzerostr == NULL)
  1370.         nonzerostr = PyString_InternFromString("__nonzero__");
  1371.     if ((func = instance_getattr(self, nonzerostr)) == NULL) {
  1372.         PyErr_Clear();
  1373.         if (lenstr == NULL)
  1374.             lenstr = PyString_InternFromString("__len__");
  1375.         if ((func = instance_getattr(self, lenstr)) == NULL) {
  1376.             PyErr_Clear();
  1377.             /* Fall back to the default behavior:
  1378.                all instances are nonzero */
  1379.             return 1;
  1380.         }
  1381.     }
  1382.     res = PyEval_CallObject(func, (PyObject *)NULL);
  1383.     Py_DECREF(func);
  1384.     if (res == NULL)
  1385.         return -1;
  1386.     if (!PyInt_Check(res)) {
  1387.         Py_DECREF(res);
  1388.         PyErr_SetString(PyExc_TypeError,
  1389.                 "__nonzero__ should return an int");
  1390.         return -1;
  1391.     }
  1392.     outcome = PyInt_AsLong(res);
  1393.     Py_DECREF(res);
  1394.     if (outcome < 0) {
  1395.         PyErr_SetString(PyExc_ValueError,
  1396.                 "__nonzero__ should return >= 0");
  1397.         return -1;
  1398.     }
  1399.     return outcome > 0;
  1400. }
  1401.  
  1402. UNARY(instance_invert, "__invert__")
  1403. UNARY(instance_int, "__int__")
  1404. UNARY(instance_long, "__long__")
  1405. UNARY(instance_float, "__float__")
  1406. UNARY(instance_oct, "__oct__")
  1407. UNARY(instance_hex, "__hex__")
  1408.  
  1409. /* This version is for ternary calls only (z != None) */
  1410. static PyObject *
  1411. instance_pow(PyObject *v, PyObject *w, PyObject *z)
  1412. {
  1413.     /* XXX Doesn't do coercions... */
  1414.     PyObject *func;
  1415.     PyObject *args;
  1416.     PyObject *result;
  1417.     static PyObject *powstr;
  1418.  
  1419.     if (powstr == NULL)
  1420.         powstr = PyString_InternFromString("__pow__");
  1421.     func = PyObject_GetAttr(v, powstr);
  1422.     if (func == NULL)
  1423.         return NULL;
  1424.     args = Py_BuildValue("(OO)", w, z);
  1425.     if (args == NULL) {
  1426.         Py_DECREF(func);
  1427.         return NULL;
  1428.     }
  1429.     result = PyEval_CallObject(func, args);
  1430.     Py_DECREF(func);
  1431.     Py_DECREF(args);
  1432.     return result;
  1433. }
  1434.  
  1435. static PyObject *
  1436. instance_inplace_pow(PyObject *v, PyObject *w, PyObject *z)
  1437. {
  1438.     /* XXX Doesn't do coercions... */
  1439.     PyObject *func;
  1440.     PyObject *args;
  1441.     PyObject *result;
  1442.     static PyObject *ipowstr;
  1443.  
  1444.     if (ipowstr == NULL)
  1445.         ipowstr = PyString_InternFromString("__ipow__");
  1446.     func = PyObject_GetAttr(v, ipowstr);
  1447.     if (func == NULL) {
  1448.         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1449.             return NULL;
  1450.         PyErr_Clear();
  1451.         return instance_pow(v, w, z);
  1452.     }
  1453.     args = Py_BuildValue("(OO)", w, z);
  1454.     if (args == NULL) {
  1455.         Py_DECREF(func);
  1456.         return NULL;
  1457.     }
  1458.     result = PyEval_CallObject(func, args);
  1459.     Py_DECREF(func);
  1460.     Py_DECREF(args);
  1461.     return result;
  1462. }
  1463.  
  1464.  
  1465. static PyNumberMethods instance_as_number = {
  1466.     0, /*nb_add*/
  1467.     0, /*nb_subtract*/
  1468.     0, /*nb_multiply*/
  1469.     0, /*nb_divide*/
  1470.     0, /*nb_remainder*/
  1471.     0, /*nb_divmod*/
  1472.     (ternaryfunc)instance_pow, /*nb_power*/
  1473.     (unaryfunc)instance_neg, /*nb_negative*/
  1474.     (unaryfunc)instance_pos, /*nb_positive*/
  1475.     (unaryfunc)instance_abs, /*nb_absolute*/
  1476.     (inquiry)instance_nonzero, /*nb_nonzero*/
  1477.     (unaryfunc)instance_invert, /*nb_invert*/
  1478.     0, /*nb_lshift*/
  1479.     0, /*nb_rshift*/
  1480.     0, /*nb_and*/
  1481.     0, /*nb_xor*/
  1482.     0, /*nb_or*/
  1483.     (coercion)instance_coerce, /*nb_coerce*/
  1484.     (unaryfunc)instance_int, /*nb_int*/
  1485.     (unaryfunc)instance_long, /*nb_long*/
  1486.     (unaryfunc)instance_float, /*nb_float*/
  1487.     (unaryfunc)instance_oct, /*nb_oct*/
  1488.     (unaryfunc)instance_hex, /*nb_hex*/
  1489.     0, /*nb_inplace_add*/
  1490.     0, /*nb_inplace_subtract*/
  1491.     0, /*nb_inplace_multiply*/
  1492.     0, /*nb_inplace_divide*/
  1493.     0, /*nb_inplace_remainder*/
  1494.     (ternaryfunc)instance_inplace_pow, /*nb_inplace_power*/
  1495.     0, /*nb_inplace_lshift*/
  1496.     0, /*nb_inplace_rshift*/
  1497.     0, /*nb_inplace_and*/
  1498.     0, /*nb_inplace_xor*/
  1499.     0, /*nb_inplace_or*/
  1500. };
  1501.  
  1502. PyTypeObject PyInstance_Type = {
  1503.     PyObject_HEAD_INIT(&PyType_Type)
  1504.     0,
  1505.     "instance",
  1506.     sizeof(PyInstanceObject) + PyGC_HEAD_SIZE,
  1507.     0,
  1508.     (destructor)instance_dealloc, /*tp_dealloc*/
  1509.     0,            /*tp_print*/
  1510.     0,            /*tp_getattr*/
  1511.     0,            /*tp_setattr*/
  1512.     instance_compare,    /*tp_compare*/
  1513.     (reprfunc)instance_repr, /*tp_repr*/
  1514.     &instance_as_number,    /*tp_as_number*/
  1515.     &instance_as_sequence,    /*tp_as_sequence*/
  1516.     &instance_as_mapping,    /*tp_as_mapping*/
  1517.     (hashfunc)instance_hash, /*tp_hash*/
  1518.     0,            /*tp_call*/
  1519.     0,            /*tp_str*/
  1520.     (getattrofunc)instance_getattr, /*tp_getattro*/
  1521.     (setattrofunc)instance_setattr, /*tp_setattro*/
  1522.         0, /* tp_as_buffer */
  1523.     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
  1524.     0,        /* tp_doc */
  1525.     (traverseproc)instance_traverse,    /* tp_traverse */
  1526. };
  1527.  
  1528.  
  1529. /* Instance method objects are used for two purposes:
  1530.    (a) as bound instance methods (returned by instancename.methodname)
  1531.    (b) as unbound methods (returned by ClassName.methodname)
  1532.    In case (b), im_self is NULL
  1533. */
  1534.  
  1535. static PyMethodObject *free_list;
  1536.  
  1537. PyObject *
  1538. PyMethod_New(PyObject *func, PyObject *self, PyObject *class)
  1539. {
  1540.     register PyMethodObject *im;
  1541.     if (!PyCallable_Check(func)) {
  1542.         PyErr_BadInternalCall();
  1543.         return NULL;
  1544.     }
  1545.     im = free_list;
  1546.     if (im != NULL) {
  1547.         free_list = (PyMethodObject *)(im->im_self);
  1548.         PyObject_INIT(im, &PyMethod_Type);
  1549.     }
  1550.     else {
  1551.         im = PyObject_NEW(PyMethodObject, &PyMethod_Type);
  1552.         if (im == NULL)
  1553.             return NULL;
  1554.     }
  1555.     Py_INCREF(func);
  1556.     im->im_func = func;
  1557.     Py_XINCREF(self);
  1558.     im->im_self = self;
  1559.     Py_INCREF(class);
  1560.     im->im_class = class;
  1561.     PyObject_GC_Init(im);
  1562.     return (PyObject *)im;
  1563. }
  1564.  
  1565. PyObject *
  1566. PyMethod_Function(register PyObject *im)
  1567. {
  1568.     if (!PyMethod_Check(im)) {
  1569.         PyErr_BadInternalCall();
  1570.         return NULL;
  1571.     }
  1572.     return ((PyMethodObject *)im)->im_func;
  1573. }
  1574.  
  1575. PyObject *
  1576. PyMethod_Self(register PyObject *im)
  1577. {
  1578.     if (!PyMethod_Check(im)) {
  1579.         PyErr_BadInternalCall();
  1580.         return NULL;
  1581.     }
  1582.     return ((PyMethodObject *)im)->im_self;
  1583. }
  1584.  
  1585. PyObject *
  1586. PyMethod_Class(register PyObject *im)
  1587. {
  1588.     if (!PyMethod_Check(im)) {
  1589.         PyErr_BadInternalCall();
  1590.         return NULL;
  1591.     }
  1592.     return ((PyMethodObject *)im)->im_class;
  1593. }
  1594.  
  1595. /* Class method methods */
  1596.  
  1597. #define OFF(x) offsetof(PyMethodObject, x)
  1598.  
  1599. static struct memberlist instancemethod_memberlist[] = {
  1600.     {"im_func",    T_OBJECT,    OFF(im_func)},
  1601.     {"im_self",    T_OBJECT,    OFF(im_self)},
  1602.     {"im_class",    T_OBJECT,    OFF(im_class)},
  1603.     /* Dummies that are not handled by getattr() except for __members__ */
  1604.     {"__doc__",    T_INT,        0},
  1605.     {"__name__",    T_INT,        0},
  1606.     {NULL}    /* Sentinel */
  1607. };
  1608.  
  1609. static PyObject *
  1610. instancemethod_getattr(register PyMethodObject *im, PyObject *name)
  1611. {
  1612.     char *sname = PyString_AsString(name);
  1613.     if (sname[0] == '_') {
  1614.         /* Inherit __name__ and __doc__ from the callable object
  1615.            implementing the method */
  1616.             if (strcmp(sname, "__name__") == 0 ||
  1617.             strcmp(sname, "__doc__") == 0)
  1618.             return PyObject_GetAttr(im->im_func, name);
  1619.     }
  1620.     if (PyEval_GetRestricted()) {
  1621.         PyErr_SetString(PyExc_RuntimeError,
  1622.         "instance-method attributes not accessible in restricted mode");
  1623.         return NULL;
  1624.     }
  1625.     return PyMember_Get((char *)im, instancemethod_memberlist, sname);
  1626. }
  1627.  
  1628. static void
  1629. instancemethod_dealloc(register PyMethodObject *im)
  1630. {
  1631.     PyObject_GC_Fini(im);
  1632.     Py_DECREF(im->im_func);
  1633.     Py_XDECREF(im->im_self);
  1634.     Py_DECREF(im->im_class);
  1635.     im->im_self = (PyObject *)free_list;
  1636.     free_list = im;
  1637. }
  1638.  
  1639. static int
  1640. instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
  1641. {
  1642.     if (a->im_self != b->im_self)
  1643.         return (a->im_self < b->im_self) ? -1 : 1;
  1644.     return PyObject_Compare(a->im_func, b->im_func);
  1645. }
  1646.  
  1647. static PyObject *
  1648. instancemethod_repr(PyMethodObject *a)
  1649. {
  1650.     char buf[240];
  1651.     PyInstanceObject *self = (PyInstanceObject *)(a->im_self);
  1652.     PyObject *func = a->im_func;
  1653.     PyClassObject *class = (PyClassObject *)(a->im_class);
  1654.     PyObject *fclassname, *iclassname, *funcname;
  1655.     char *fcname, *icname, *fname;
  1656.     fclassname = class->cl_name;
  1657.     if (PyFunction_Check(func)) {
  1658.         funcname = ((PyFunctionObject *)func)->func_name;
  1659.         Py_INCREF(funcname);
  1660.     }
  1661.     else {
  1662.         funcname = PyObject_GetAttrString(func,"__name__");
  1663.         if (funcname == NULL)
  1664.             PyErr_Clear();
  1665.     }
  1666.     if (funcname != NULL && PyString_Check(funcname))
  1667.         fname = PyString_AS_STRING(funcname);
  1668.     else
  1669.         fname = "?";
  1670.     if (fclassname != NULL && PyString_Check(fclassname))
  1671.         fcname = PyString_AsString(fclassname);
  1672.     else
  1673.         fcname = "?";
  1674.     if (self == NULL)
  1675.         sprintf(buf, "<unbound method %.100s.%.100s>", fcname, fname);
  1676.     else {
  1677.         iclassname = self->in_class->cl_name;
  1678.         if (iclassname != NULL && PyString_Check(iclassname))
  1679.             icname = PyString_AsString(iclassname);
  1680.         else
  1681.             icname = "?";
  1682.         sprintf(buf, "<method %.60s.%.60s of %.60s instance at %p>",
  1683.             fcname, fname, icname, self);
  1684.     }
  1685.     Py_XDECREF(funcname);
  1686.     return PyString_FromString(buf);
  1687. }
  1688.  
  1689. static long
  1690. instancemethod_hash(PyMethodObject *a)
  1691. {
  1692.     long x, y;
  1693.     if (a->im_self == NULL)
  1694.         x = PyObject_Hash(Py_None);
  1695.     else
  1696.         x = PyObject_Hash(a->im_self);
  1697.     if (x == -1)
  1698.         return -1;
  1699.     y = PyObject_Hash(a->im_func);
  1700.     if (y == -1)
  1701.         return -1;
  1702.     return x ^ y;
  1703. }
  1704.  
  1705. static int
  1706. instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
  1707. {
  1708.     int err;
  1709.     if (im->im_func) {
  1710.         err = visit(im->im_func, arg);
  1711.         if (err)
  1712.             return err;
  1713.     }
  1714.     if (im->im_self) {
  1715.         err = visit(im->im_self, arg);
  1716.         if (err)
  1717.             return err;
  1718.     }
  1719.     if (im->im_class) {
  1720.         err = visit(im->im_class, arg);
  1721.         if (err)
  1722.             return err;
  1723.     }
  1724.     return 0;
  1725. }
  1726.  
  1727. PyTypeObject PyMethod_Type = {
  1728.     PyObject_HEAD_INIT(&PyType_Type)
  1729.     0,
  1730.     "instance method",
  1731.     sizeof(PyMethodObject) + PyGC_HEAD_SIZE,
  1732.     0,
  1733.     (destructor)instancemethod_dealloc, /*tp_dealloc*/
  1734.     0,            /*tp_print*/
  1735.     0,            /*tp_getattr*/
  1736.     0,            /*tp_setattr*/
  1737.     (cmpfunc)instancemethod_compare, /*tp_compare*/
  1738.     (reprfunc)instancemethod_repr, /*tp_repr*/
  1739.     0,            /*tp_as_number*/
  1740.     0,            /*tp_as_sequence*/
  1741.     0,            /*tp_as_mapping*/
  1742.     (hashfunc)instancemethod_hash, /*tp_hash*/
  1743.     0,            /*tp_call*/
  1744.     0,            /*tp_str*/
  1745.     (getattrofunc)instancemethod_getattr, /*tp_getattro*/
  1746.     0,            /*tp_setattro*/
  1747.     0,            /* tp_as_buffer */
  1748.     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
  1749.     0,            /* tp_doc */
  1750.     (traverseproc)instancemethod_traverse,    /* tp_traverse */
  1751. };
  1752.  
  1753. /* Clear out the free list */
  1754.  
  1755. void
  1756. PyMethod_Fini(void)
  1757. {
  1758.     while (free_list) {
  1759.         PyMethodObject *im = free_list;
  1760.         free_list = (PyMethodObject *)(im->im_self);
  1761.         im = (PyMethodObject *) PyObject_AS_GC(im);
  1762.         PyObject_DEL(im);
  1763.     }
  1764. }
  1765.