home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / py2s152.zip / Objects / classobject.c < prev    next >
C/C++ Source or Header  |  1999-06-27  |  40KB  |  1,631 lines

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