home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / Languages / Python 1.1 / Objects / classobject.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-09-28  |  25.3 KB  |  1,203 lines  |  [TEXT/KAHL]

  1. /***********************************************************
  2. Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
  3. Amsterdam, 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 not be used in advertising or publicity pertaining to
  13. distribution of the software without specific, written prior permission.
  14.  
  15. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  16. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17. FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  18. FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  19. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  20. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  21. OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  22.  
  23. ******************************************************************/
  24.  
  25. /* Class object implementation */
  26.  
  27. #include "allobjects.h"
  28. #include "structmember.h"
  29.  
  30. /* Forward */
  31. static object *class_lookup PROTO((classobject *, char *, classobject **));
  32. static object *instance_getattr1 PROTO((instanceobject *, char *));
  33.  
  34. object *
  35. newclassobject(bases, dict, name)
  36.     object *bases; /* NULL or tuple of classobjects! */
  37.     object *dict;
  38.     object *name; /* String; NULL if unknown */
  39. {
  40.     int pos;
  41.     object *key, *value;
  42.     classobject *op, *dummy;
  43.     if (bases == NULL) {
  44.         bases = newtupleobject(0);
  45.         if (bases == NULL)
  46.             return NULL;
  47.     }
  48.     else
  49.         INCREF(bases);
  50.     op = NEWOBJ(classobject, &Classtype);
  51.     if (op == NULL) {
  52.         DECREF(bases);
  53.         return NULL;
  54.     }
  55.     op->cl_bases = bases;
  56.     INCREF(dict);
  57.     op->cl_dict = dict;
  58.     XINCREF(name);
  59.     op->cl_name = name;
  60.     op->cl_getattr = class_lookup(op, "__getattr__", &dummy);
  61.     op->cl_setattr = class_lookup(op, "__setattr__", &dummy);
  62.     op->cl_delattr = class_lookup(op, "__delattr__", &dummy);
  63.     XINCREF(op->cl_getattr);
  64.     XINCREF(op->cl_setattr);
  65.     XINCREF(op->cl_delattr);
  66.     pos = 0;
  67.     while (mappinggetnext(dict, &pos, &key, &value)) {
  68.         if (is_accessobject(value))
  69.             setaccessowner(value, (object *)op);
  70.     }
  71.     return (object *) op;
  72. }
  73.  
  74. /* Class methods */
  75.  
  76. static void
  77. class_dealloc(op)
  78.     classobject *op;
  79. {
  80.     DECREF(op->cl_bases);
  81.     DECREF(op->cl_dict);
  82.     XDECREF(op->cl_name);
  83.     free((ANY *)op);
  84. }
  85.  
  86. static object *
  87. class_lookup(cp, name, pclass)
  88.     classobject *cp;
  89.     char *name;
  90.     classobject **pclass;
  91. {
  92.     int i, n;
  93.     object *value = dictlookup(cp->cl_dict, name);
  94.     if (value != NULL) {
  95.         *pclass = cp;
  96.         return value;
  97.     }
  98.     n = gettuplesize(cp->cl_bases);
  99.     for (i = 0; i < n; i++) {
  100.         object *v = class_lookup((classobject *)
  101.                  gettupleitem(cp->cl_bases, i), name, pclass);
  102.         if (v != NULL)
  103.             return v;
  104.     }
  105.     return NULL;
  106. }
  107.  
  108. static object *
  109. class_getattr(op, name)
  110.     register classobject *op;
  111.     register char *name;
  112. {
  113.     register object *v;
  114.     classobject *class;
  115.     if (strcmp(name, "__dict__") == 0) {
  116.         INCREF(op->cl_dict);
  117.         return op->cl_dict;
  118.     }
  119.     if (strcmp(name, "__bases__") == 0) {
  120.         INCREF(op->cl_bases);
  121.         return op->cl_bases;
  122.     }
  123.     if (strcmp(name, "__name__") == 0) {
  124.         if (op->cl_name == NULL)
  125.             v = None;
  126.         else
  127.             v = op->cl_name;
  128.         INCREF(v);
  129.         return v;
  130.     }
  131.     v = class_lookup(op, name, &class);
  132.     if (v == NULL) {
  133.         err_setstr(AttributeError, name);
  134.         return NULL;
  135.     }
  136.     if (is_accessobject(v)) {
  137.         v = getaccessvalue(v, getowner());
  138.         if (v == NULL)
  139.             return NULL;
  140.     }
  141.     else
  142.         INCREF(v);
  143.     if (is_funcobject(v)) {
  144.         object *w = newinstancemethodobject(v, (object *)NULL,
  145.                             (object *)class);
  146.         DECREF(v);
  147.         v = w;
  148.     }
  149.     return v;
  150. }
  151.  
  152. static int
  153. class_setattr(op, name, v)
  154.     classobject *op;
  155.     char *name;
  156.     object *v;
  157. {
  158.     object *ac;
  159.     if (name[0] == '_' && name[1] == '_') {
  160.         int n = strlen(name);
  161.         if (name[n-1] == '_' && name[n-2] == '_') {
  162.             err_setstr(TypeError, "read-only special attribute");
  163.             return -1;
  164.         }
  165.     }
  166.     ac = dictlookup(op->cl_dict, name);
  167.     if (ac != NULL && is_accessobject(ac))
  168.         return setaccessvalue(ac, getowner(), v);
  169.     if (v == NULL) {
  170.         int rv = dictremove(op->cl_dict, name);
  171.         if (rv < 0)
  172.             err_setstr(AttributeError,
  173.                    "delete non-existing class attribute");
  174.         return rv;
  175.     }
  176.     else
  177.         return dictinsert(op->cl_dict, name, v);
  178. }
  179.  
  180. static object *
  181. class_repr(op)
  182.     classobject *op;
  183. {
  184.     char buf[140];
  185.     char *name;
  186.     if (op->cl_name == NULL || !is_stringobject(op->cl_name))
  187.         name = "?";
  188.     else
  189.         name = getstringvalue(op->cl_name);
  190.     sprintf(buf, "<class %.100s at %lx>", name, (long)op);
  191.     return newstringobject(buf);
  192. }
  193.  
  194. typeobject Classtype = {
  195.     OB_HEAD_INIT(&Typetype)
  196.     0,
  197.     "class",
  198.     sizeof(classobject),
  199.     0,
  200.     (destructor)class_dealloc, /*tp_dealloc*/
  201.     0,        /*tp_print*/
  202.     (getattrfunc)class_getattr, /*tp_getattr*/
  203.     (setattrfunc)class_setattr, /*tp_setattr*/
  204.     0,        /*tp_compare*/
  205.     (reprfunc)class_repr, /*tp_repr*/
  206.     0,        /*tp_as_number*/
  207.     0,        /*tp_as_sequence*/
  208.     0,        /*tp_as_mapping*/
  209. };
  210.  
  211. int
  212. issubclass(class, base)
  213.     object *class;
  214.     object *base;
  215. {
  216.     int i, n;
  217.     classobject *cp;
  218.     if (class == base)
  219.         return 1;
  220.     if (class == NULL || !is_classobject(class))
  221.         return 0;
  222.     cp = (classobject *)class;
  223.     n = gettuplesize(cp->cl_bases);
  224.     for (i = 0; i < n; i++) {
  225.         if (issubclass(gettupleitem(cp->cl_bases, i), base))
  226.             return 1;
  227.     }
  228.     return 0;
  229. }
  230.  
  231.  
  232. /* Instance objects */
  233.  
  234. static int
  235. addaccess(class, inst)
  236.     classobject *class;
  237.     instanceobject *inst;
  238. {
  239.     int i, n, pos, ret;
  240.     object *key, *value, *ac;
  241.     
  242.     n = gettuplesize(class->cl_bases);
  243.     for (i = 0; i < n; i++) {
  244.         if (addaccess((classobject *)gettupleitem(class->cl_bases, i), inst) < 0)
  245.             return -1;
  246.     }
  247.     
  248.     pos = 0;
  249.     while (mappinggetnext(class->cl_dict, &pos, &key, &value)) {
  250.         object *v;
  251.         if (!is_accessobject(value))
  252.             continue;
  253.         if (hasaccessvalue(value))
  254.             continue;
  255.         ac = dict2lookup(inst->in_dict, key);
  256.         if (ac != NULL && is_accessobject(ac)) {
  257.             err_setval(ConflictError, key);
  258.             return -1;
  259.         }
  260.         ac = cloneaccessobject(value);
  261.         if (ac == NULL)
  262.             return -1;
  263.         ret = dict2insert(inst->in_dict, key, ac);
  264.         DECREF(ac);
  265.         if (ret != 0)
  266.             return -1;
  267.         }
  268.     return 0;
  269. }
  270.  
  271. object *
  272. newinstanceobject(class, arg)
  273.     object *class;
  274.     object *arg;
  275. {
  276.     register instanceobject *inst;
  277.     object *v;
  278.     object *init;
  279.     if (!is_classobject(class)) {
  280.         err_badcall();
  281.         return NULL;
  282.     }
  283.     inst = NEWOBJ(instanceobject, &Instancetype);
  284.     if (inst == NULL)
  285.         return NULL;
  286.     INCREF(class);
  287.     inst->in_class = (classobject *)class;
  288.     inst->in_dict = newdictobject();
  289.     if (inst->in_dict == NULL ||
  290.         addaccess((classobject *)class, inst) != 0) {
  291.         DECREF(inst);
  292.         return NULL;
  293.     }
  294.     init = instance_getattr1(inst, "__init__");
  295.     if (init == NULL) {
  296.         err_clear();
  297.         if (arg != NULL && !(is_tupleobject(arg) &&
  298.                      gettuplesize(arg) == 0)) {
  299.             err_setstr(TypeError,
  300.                 "this classobject() takes no arguments");
  301.             DECREF(inst);
  302.             inst = NULL;
  303.         }
  304.     }
  305.     else {
  306.         object *res = call_object(init, arg);
  307.         DECREF(init);
  308.         if (res == NULL) {
  309.             DECREF(inst);
  310.             inst = NULL;
  311.         }
  312.         else {
  313.             if (res != None) {
  314.                 err_setstr(TypeError,
  315.                        "__init__() should return None");
  316.                 DECREF(inst);
  317.                 inst = NULL;
  318.             }
  319.             DECREF(res);
  320.         }
  321.     }
  322.     return (object *)inst;
  323. }
  324.  
  325. /* Instance methods */
  326.  
  327. static void
  328. instance_dealloc(inst)
  329.     register instanceobject *inst;
  330. {
  331.     object *error_type, *error_value;
  332.     object *del;
  333.     /* Call the __del__ method if it exists.  First temporarily
  334.        revive the object and save the current exception, if any. */
  335.     INCREF(inst);
  336.     err_get(&error_type, &error_value);
  337.     if ((del = instance_getattr1(inst, "__del__")) != NULL) {
  338.         object *args = newtupleobject(0);
  339.         object *res = args;
  340.         if (res != NULL)
  341.             res = call_object(del, args);
  342.         XDECREF(args);
  343.         DECREF(del);
  344.         XDECREF(res);
  345.         /* XXX If __del__ raised an exception, it is ignored! */
  346.     }
  347.     /* Restore the saved exception and undo the temporary revival */
  348.     err_setval(error_type, error_value);
  349.     /* Can't use DECREF here, it would cause a recursive call */
  350.     if (--inst->ob_refcnt > 0)
  351.         return; /* __del__ added a reference; don't delete now */
  352.     DECREF(inst->in_class);
  353.     XDECREF(inst->in_dict);
  354.     free((ANY *)inst);
  355. }
  356.  
  357. static object *
  358. instance_getattr1(inst, name)
  359.     register instanceobject *inst;
  360.     register char *name;
  361. {
  362.     register object *v;
  363.     classobject *class;
  364.     if (name[0] == '_' && name[1] == '_') {
  365.         if (strcmp(name, "__dict__") == 0) {
  366.             INCREF(inst->in_dict);
  367.             return inst->in_dict;
  368.         }
  369.         if (strcmp(name, "__class__") == 0) {
  370.             INCREF(inst->in_class);
  371.             return (object *)inst->in_class;
  372.         }
  373.     }
  374.     class = NULL;
  375.     v = dictlookup(inst->in_dict, name);
  376.     if (v == NULL) {
  377.         v = class_lookup(inst->in_class, name, &class);
  378.         if (v == NULL) {
  379.             err_setstr(AttributeError, name);
  380.             return NULL;
  381.         }
  382.     }
  383.     if (is_accessobject(v)) {
  384.         v = getaccessvalue(v, getowner());
  385.         if (v == NULL)
  386.             return NULL;
  387.     }
  388.     else
  389.         INCREF(v);
  390.     if (class != NULL) {
  391.         if (is_funcobject(v)) {
  392.             object *w = newinstancemethodobject(v, (object *)inst,
  393.                                 (object *)class);
  394.             DECREF(v);
  395.             v = w;
  396.         }
  397.         else if (is_instancemethodobject(v)) {
  398.             object *im_class = instancemethodgetclass(v);
  399.             /* Only if classes are compatible */
  400.             if (issubclass((object *)class, im_class)) {
  401.                 object *im_func = instancemethodgetfunc(v);
  402.                 object *w = newinstancemethodobject(im_func,
  403.                         (object *)inst, im_class);
  404.                 DECREF(v);
  405.                 v = w;
  406.             }
  407.         }
  408.     }
  409.     return v;
  410. }
  411.  
  412. static object *
  413. instance_getattr(inst, name)
  414.     register instanceobject *inst;
  415.     register char *name;
  416. {
  417.     register object *func, *res;
  418.     res = instance_getattr1(inst, name);
  419.     if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
  420.         object *args;
  421. #if 0
  422.         if (name[0] == '_' && name[1] == '_') {
  423.             int n = strlen(name);
  424.             if (name[n-1] == '_' && name[n-2] == '_') {
  425.                 /* Don't mess with system attributes */
  426.                 return NULL;
  427.             }
  428.         }
  429. #endif
  430.         args = mkvalue("(Os)", inst, name);
  431.         if (args == NULL)
  432.             return NULL;
  433.         res = call_object(func, args);
  434.         DECREF(args);
  435.     }
  436.     return res;
  437. }
  438.  
  439. static int
  440. instance_setattr1(inst, name, v)
  441.     instanceobject *inst;
  442.     char *name;
  443.     object *v;
  444. {
  445.     object *ac;
  446.     ac = dictlookup(inst->in_dict, name);
  447.     if (ac != NULL && is_accessobject(ac))
  448.         return setaccessvalue(ac, getowner(), v);
  449.     if (v == NULL) {
  450.         int rv = dictremove(inst->in_dict, name);
  451.         if (rv < 0)
  452.             err_setstr(AttributeError,
  453.                    "delete non-existing instance attribute");
  454.         return rv;
  455.     }
  456.     else
  457.         return dictinsert(inst->in_dict, name, v);
  458. }
  459.  
  460. static int
  461. instance_setattr(inst, name, v)
  462.     instanceobject *inst;
  463.     char *name;
  464.     object *v;
  465. {
  466.     object *func, *args, *res;
  467.     if (name[0] == '_' && name[1] == '_') {
  468.         int n = strlen(name);
  469.         if (name[n-1] == '_' && name[n-2] == '_') {
  470.             err_setstr(TypeError, "read-only special attribute");
  471.             return -1;
  472.         }
  473.     }
  474.     if (v == NULL)
  475.         func = inst->in_class->cl_delattr;
  476.     else
  477.         func = inst->in_class->cl_setattr;
  478.     if (func == NULL)
  479.         return instance_setattr1(inst, name, v);
  480.     if (v == NULL)
  481.         args = mkvalue("(Os)", inst, name);
  482.     else
  483.         args = mkvalue("(OsO)", inst, name, v);
  484.     if (args == NULL)
  485.         return -1;
  486.     res = call_object(func, args);
  487.     DECREF(args);
  488.     if (res == NULL)
  489.         return -1;
  490.     DECREF(res);
  491.     return 0;
  492. }
  493.  
  494. static object *
  495. instance_repr(inst)
  496.     instanceobject *inst;
  497. {
  498.     object *func;
  499.     object *res;
  500.  
  501.     func = instance_getattr(inst, "__repr__");
  502.     if (func == NULL) {
  503.         char buf[140];
  504.         object *classname = inst->in_class->cl_name;
  505.         char *cname;
  506.         if (classname != NULL && is_stringobject(classname))
  507.             cname = getstringvalue(classname);
  508.         else
  509.             cname = "?";
  510.         err_clear();
  511.         sprintf(buf, "<%.100s instance at %lx>", cname, (long)inst);
  512.         return newstringobject(buf);
  513.     }
  514.     res = call_object(func, (object *)NULL);
  515.     DECREF(func);
  516.     return res;
  517. }
  518.  
  519. static int
  520. instance_compare(inst, other)
  521.     object *inst, *other;
  522. {
  523.     object *result;
  524.     int outcome;
  525.     result  = instancebinop(inst, other, "__cmp__", "__rcmp__");
  526.     if (result == NULL)
  527.         return -2;
  528.     outcome = getintvalue(result);
  529.     DECREF(result);
  530.     if (outcome == -1 && err_occurred())
  531.         return -2;
  532.     if (outcome < 0)
  533.         return -1;
  534.     else if (outcome > 0)
  535.         return 1;
  536.     return 0;
  537. }
  538.  
  539. static long
  540. instance_hash(inst)
  541.     instanceobject *inst;
  542. {
  543.     object *func;
  544.     object *res;
  545.     long outcome;
  546.  
  547.     func = instance_getattr(inst, "__hash__");
  548.     if (func == NULL) {
  549.         /* If there is no __cmp__ method, we hash on the address.
  550.            If a __cmp__ method exists, there must be a __hash__. */
  551.         err_clear();
  552.         func = instance_getattr(inst, "__cmp__");
  553.         if (func == NULL) {
  554.             err_clear();
  555.             outcome = (long)inst;
  556.             if (outcome == -1)
  557.                 outcome = -2;
  558.             return outcome;
  559.         }
  560.         err_setstr(TypeError, "unhashable instance");
  561.         return -1;
  562.     }
  563.     res = call_object(func, (object *)NULL);
  564.     DECREF(func);
  565.     if (res == NULL)
  566.         return -1;
  567.     if (is_intobject(res)) {
  568.         outcome = getintvalue(res);
  569.         if (outcome == -1)
  570.             outcome = -2;
  571.     }
  572.     else {
  573.         err_setstr(TypeError, "__hash__() should return an int");
  574.         outcome = -1;
  575.     }
  576.     DECREF(res);
  577.     return outcome;
  578. }
  579.  
  580. static int
  581. instance_length(inst)
  582.     instanceobject *inst;
  583. {
  584.     object *func;
  585.     object *res;
  586.     int outcome;
  587.  
  588.     func = instance_getattr(inst, "__len__");
  589.     if (func == NULL)
  590.         return -1;
  591.     res = call_object(func, (object *)NULL);
  592.     DECREF(func);
  593.     if (res == NULL)
  594.         return -1;
  595.     if (is_intobject(res)) {
  596.         outcome = getintvalue(res);
  597.         if (outcome < 0)
  598.             err_setstr(ValueError, "__len__() should return >= 0");
  599.     }
  600.     else {
  601.         err_setstr(TypeError, "__len__() should return an int");
  602.         outcome = -1;
  603.     }
  604.     DECREF(res);
  605.     return outcome;
  606. }
  607.  
  608. static object *
  609. instance_subscript(inst, key)
  610.     instanceobject *inst;
  611.     object *key;
  612. {
  613.     object *func;
  614.     object *arg;
  615.     object *res;
  616.  
  617.     func = instance_getattr(inst, "__getitem__");
  618.     if (func == NULL)
  619.         return NULL;
  620.     arg = mkvalue("(O)", key);
  621.     if (arg == NULL) {
  622.         DECREF(func);
  623.         return NULL;
  624.     }
  625.     res = call_object(func, arg);
  626.     DECREF(func);
  627.     DECREF(arg);
  628.     return res;
  629. }
  630.  
  631. static int
  632. instance_ass_subscript(inst, key, value)
  633.     instanceobject*inst;
  634.     object *key;
  635.     object *value;
  636. {
  637.     object *func;
  638.     object *arg;
  639.     object *res;
  640.  
  641.     if (value == NULL)
  642.         func = instance_getattr(inst, "__delitem__");
  643.     else
  644.         func = instance_getattr(inst, "__setitem__");
  645.     if (func == NULL)
  646.         return -1;
  647.     if (value == NULL)
  648.         arg = mkvalue("(O)", key);
  649.     else
  650.         arg = mkvalue("(OO)", key, value);
  651.     if (arg == NULL) {
  652.         DECREF(func);
  653.         return -1;
  654.     }
  655.     res = call_object(func, arg);
  656.     DECREF(func);
  657.     DECREF(arg);
  658.     if (res == NULL)
  659.         return -1;
  660.     DECREF(res);
  661.     return 0;
  662. }
  663.  
  664. static mapping_methods instance_as_mapping = {
  665.     (inquiry)instance_length, /*mp_length*/
  666.     (binaryfunc)instance_subscript, /*mp_subscript*/
  667.     (objobjargproc)instance_ass_subscript, /*mp_ass_subscript*/
  668. };
  669.  
  670. static object *
  671. instance_item(inst, i)
  672.     instanceobject *inst;
  673.     int i;
  674. {
  675.     object *func, *arg, *res;
  676.  
  677.     func = instance_getattr(inst, "__getitem__");
  678.     if (func == NULL)
  679.         return NULL;
  680.     arg = newintobject((long)i);
  681.     if (arg == NULL) {
  682.         DECREF(func);
  683.         return NULL;
  684.     }
  685.     res = call_object(func, arg);
  686.     DECREF(func);
  687.     DECREF(arg);
  688.     return res;
  689. }
  690.  
  691. static object *
  692. instance_slice(inst, i, j)
  693.     instanceobject *inst;
  694.     int i, j;
  695. {
  696.     object *func, *arg, *res;
  697.  
  698.     func = instance_getattr(inst, "__getslice__");
  699.     if (func == NULL)
  700.         return NULL;
  701.     arg = mkvalue("(ii)", i, j);
  702.     if (arg == NULL) {
  703.         DECREF(func);
  704.         return NULL;
  705.     }
  706.     res = call_object(func, arg);
  707.     DECREF(func);
  708.     DECREF(arg);
  709.     return res;
  710. }
  711.  
  712. static int
  713. instance_ass_item(inst, i, item)
  714.     instanceobject *inst;
  715.     int i;
  716.     object *item;
  717. {
  718.     object *func, *arg, *res;
  719.  
  720.     if (item == NULL)
  721.         func = instance_getattr(inst, "__delitem__");
  722.     else
  723.         func = instance_getattr(inst, "__setitem__");
  724.     if (func == NULL)
  725.         return -1;
  726.     if (item == NULL)
  727.         arg = mkvalue("i", i);
  728.     else
  729.         arg = mkvalue("(iO)", i, item);
  730.     if (arg == NULL) {
  731.         DECREF(func);
  732.         return -1;
  733.     }
  734.     res = call_object(func, arg);
  735.     DECREF(func);
  736.     DECREF(arg);
  737.     if (res == NULL)
  738.         return -1;
  739.     DECREF(res);
  740.     return 0;
  741. }
  742.  
  743. static int
  744. instance_ass_slice(inst, i, j, value)
  745.     instanceobject *inst;
  746.     int i, j;
  747.     object *value;
  748. {
  749.     object *func, *arg, *res;
  750.  
  751.     if (value == NULL)
  752.         func = instance_getattr(inst, "__delslice__");
  753.     else
  754.         func = instance_getattr(inst, "__setslice__");
  755.     if (func == NULL)
  756.         return -1;
  757.     if (value == NULL)
  758.         arg = mkvalue("(ii)", i, j);
  759.     else
  760.         arg = mkvalue("(iiO)", i, j, value);
  761.     if (arg == NULL) {
  762.         DECREF(func);
  763.         return -1;
  764.     }
  765.     res = call_object(func, arg);
  766.     DECREF(func);
  767.     DECREF(arg);
  768.     if (res == NULL)
  769.         return -1;
  770.     DECREF(res);
  771.     return 0;
  772. }
  773.  
  774. static sequence_methods instance_as_sequence = {
  775.     (inquiry)instance_length, /*sq_length*/
  776.     0, /*sq_concat*/
  777.     0, /*sq_repeat*/
  778.     (intargfunc)instance_item, /*sq_item*/
  779.     (intintargfunc)instance_slice, /*sq_slice*/
  780.     (intobjargproc)instance_ass_item, /*sq_ass_item*/
  781.     (intintobjargproc)instance_ass_slice, /*sq_ass_slice*/
  782. };
  783.  
  784. static object *
  785. generic_unary_op(self, methodname)
  786.     instanceobject *self;
  787.     char *methodname;
  788. {
  789.     object *func, *res;
  790.  
  791.     if ((func = instance_getattr(self, methodname)) == NULL)
  792.         return NULL;
  793.     res = call_object(func, (object *)NULL);
  794.     DECREF(func);
  795.     return res;
  796. }
  797.  
  798.  
  799. /* Forward */
  800. static int halfbinop PROTO((object *, object *, char *, object **));
  801.  
  802.  
  803. /* Implement a binary operator involving at least one class instance. */
  804.  
  805. object *
  806. instancebinop(v, w, opname, ropname)
  807.     object *v;
  808.     object *w;
  809.     char *opname;
  810.     char *ropname;
  811. {
  812.     char buf[256];
  813.     object *result = NULL;
  814.     if (halfbinop(v, w, opname, &result) <= 0)
  815.         return result;
  816.     if (halfbinop(w, v, ropname, &result) <= 0)
  817.         return result;
  818.     sprintf(buf, "%s nor %s defined for these operands", opname, ropname);
  819.     err_setstr(TypeError, buf);
  820.     return NULL;
  821. }
  822.  
  823.  
  824. /* Try one half of a binary operator involving a class instance.
  825.    Return value:
  826.    -1 if an exception is to be reported right away
  827.    0  if we have a valid result
  828.    1  if we could try another operation
  829. */
  830.  
  831. static int
  832. halfbinop(v, w, opname, r_result)
  833.     object *v;
  834.     object *w;
  835.     char *opname;
  836.     object **r_result;
  837. {
  838.     object *func;
  839.     object *args;
  840.     object *coerce;
  841.     object *coerced = NULL;
  842.     object *v1;
  843.     
  844.     if (!is_instanceobject(v))
  845.         return 1;
  846.     func = getattr(v, opname);
  847.     if (func == NULL) {
  848.         if (err_occurred() != AttributeError)
  849.             return -1;
  850.         err_clear();
  851.         return 1;
  852.     }
  853.     coerce = getattr(v, "__coerce__");
  854.     if (coerce == NULL) {
  855.         err_clear();
  856.     }
  857.     else {
  858.         args = mkvalue("(O)", w);
  859.         if (args == NULL) {
  860.             DECREF(func);
  861.             return -1;
  862.         }
  863.         coerced = call_object(coerce, args);
  864.         DECREF(args);
  865.         DECREF(coerce);
  866.         if (coerced == NULL) {
  867.             DECREF(func);
  868.             return -1;
  869.         }
  870.         if (coerced == None) {
  871.             DECREF(coerced);
  872.             DECREF(func);
  873.             return 1;
  874.         }
  875.         if (!is_tupleobject(coerced) || gettuplesize(coerced) != 2) {
  876.             DECREF(coerced);
  877.             DECREF(func);
  878.             err_setstr(TypeError, "coercion should return None or 2-tuple");
  879.             return -1;
  880.         }
  881.         v1 = gettupleitem(coerced, 0);
  882.         if (v1 != v) {
  883.             v = v1;
  884.             DECREF(func);
  885.             func = getattr(v, opname);
  886.             if (func == NULL) {
  887.                 XDECREF(coerced);
  888.                 return -1;
  889.             }
  890.         }
  891.         w = gettupleitem(coerced, 1);
  892.     }
  893.     args = mkvalue("(O)", w);
  894.     if (args == NULL) {
  895.         DECREF(func);
  896.         XDECREF(coerced);
  897.         return -1;
  898.     }
  899.     *r_result = call_object(func, args);
  900.     DECREF(args);
  901.     DECREF(func);
  902.     XDECREF(coerced);
  903.     return *r_result == NULL ? -1 : 0;
  904. }
  905.  
  906.  
  907. #define UNARY(funcname, methodname) \
  908. static object *funcname(self) instanceobject *self; { \
  909.     return generic_unary_op(self, methodname); \
  910. }
  911.  
  912. UNARY(instance_neg, "__neg__")
  913. UNARY(instance_pos, "__pos__")
  914. UNARY(instance_abs, "__abs__")
  915.  
  916. static int
  917. instance_nonzero(self)
  918.     instanceobject *self;
  919. {
  920.     object *func, *res;
  921.     long outcome;
  922.  
  923.     if ((func = instance_getattr(self, "__nonzero__")) == NULL) {
  924.         err_clear();
  925.         if ((func = instance_getattr(self, "__len__")) == NULL) {
  926.             err_clear();
  927.             /* Fall back to the default behavior:
  928.                all instances are nonzero */
  929.             return 1;
  930.         }
  931.     }
  932.     res = call_object(func, (object *)NULL);
  933.     DECREF(func);
  934.     if (res == NULL)
  935.         return -1;
  936.     if (!is_intobject(res)) {
  937.         DECREF(res);
  938.         err_setstr(TypeError, "__nonzero__ should return an int");
  939.         return -1;
  940.     }
  941.     outcome = getintvalue(res);
  942.     DECREF(res);
  943.     if (outcome < 0) {
  944.         err_setstr(ValueError, "__nonzero__ should return >= 0");
  945.         return -1;
  946.     }
  947.     return outcome > 0;
  948. }
  949.  
  950. UNARY(instance_invert, "__invert__")
  951. UNARY(instance_int, "__int__")
  952. UNARY(instance_long, "__long__")
  953. UNARY(instance_float, "__float__")
  954. UNARY(instance_oct, "__oct__")
  955. UNARY(instance_hex, "__hex__")
  956.  
  957. /* This version is for ternary calls only (z != None) */
  958. static object *
  959. instance_pow(v, w, z)
  960.     object *v;
  961.     object *w;
  962.     object *z;
  963. {
  964.     /* XXX Doesn't do coercions... */
  965.     object *func;
  966.     object *args;
  967.     object *result;
  968.     func = getattr(v, "__pow__");
  969.     if (func == NULL)
  970.         return NULL;
  971.     args = mkvalue("(OO)", w, z);
  972.     if (args == NULL) {
  973.         DECREF(func);
  974.         return NULL;
  975.     }
  976.     result = call_object(func, args);
  977.     DECREF(func);
  978.     DECREF(args);
  979.     return result;
  980. }
  981.  
  982. static number_methods instance_as_number = {
  983.     0, /*nb_add*/
  984.     0, /*nb_subtract*/
  985.     0, /*nb_multiply*/
  986.     0, /*nb_divide*/
  987.     0, /*nb_remainder*/
  988.     0, /*nb_divmod*/
  989.     (ternaryfunc)instance_pow, /*nb_power*/
  990.     (unaryfunc)instance_neg, /*nb_negative*/
  991.     (unaryfunc)instance_pos, /*nb_positive*/
  992.     (unaryfunc)instance_abs, /*nb_absolute*/
  993.     (inquiry)instance_nonzero, /*nb_nonzero*/
  994.     (unaryfunc)instance_invert, /*nb_invert*/
  995.     0, /*nb_lshift*/
  996.     0, /*nb_rshift*/
  997.     0, /*nb_and*/
  998.     0, /*nb_xor*/
  999.     0, /*nb_or*/
  1000.     0, /*nb_coerce*/
  1001.     (unaryfunc)instance_int, /*nb_int*/
  1002.     (unaryfunc)instance_long, /*nb_long*/
  1003.     (unaryfunc)instance_float, /*nb_float*/
  1004.     (unaryfunc)instance_oct, /*nb_oct*/
  1005.     (unaryfunc)instance_hex, /*nb_hex*/
  1006. };
  1007.  
  1008. typeobject Instancetype = {
  1009.     OB_HEAD_INIT(&Typetype)
  1010.     0,
  1011.     "instance",
  1012.     sizeof(instanceobject),
  1013.     0,
  1014.     (destructor)instance_dealloc, /*tp_dealloc*/
  1015.     0,            /*tp_print*/
  1016.     (getattrfunc)instance_getattr, /*tp_getattr*/
  1017.     (setattrfunc)instance_setattr, /*tp_setattr*/
  1018.     instance_compare, /*tp_compare*/
  1019.     (reprfunc)instance_repr, /*tp_repr*/
  1020.     &instance_as_number,    /*tp_as_number*/
  1021.     &instance_as_sequence,    /*tp_as_sequence*/
  1022.     &instance_as_mapping,    /*tp_as_mapping*/
  1023.     (hashfunc)instance_hash, /*tp_hash*/
  1024. };
  1025.  
  1026.  
  1027. /* Instance method objects are used for two purposes:
  1028.    (a) as bound instance methods (returned by instancename.methodname)
  1029.    (b) as unbound methods (returned by ClassName.methodname)
  1030.    In case (b), im_self is NULL
  1031. */
  1032.  
  1033. typedef struct {
  1034.     OB_HEAD
  1035.     object    *im_func;    /* The function implementing the method */
  1036.     object    *im_self;    /* The instance it is bound to, or NULL */
  1037.     object    *im_class;    /* The class that defined the method */
  1038. } instancemethodobject;
  1039.  
  1040. object *
  1041. newinstancemethodobject(func, self, class)
  1042.     object *func;
  1043.     object *self;
  1044.     object *class;
  1045. {
  1046.     register instancemethodobject *im;
  1047.     if (!is_funcobject(func)) {
  1048.         err_badcall();
  1049.         return NULL;
  1050.     }
  1051.     im = NEWOBJ(instancemethodobject, &Instancemethodtype);
  1052.     if (im == NULL)
  1053.         return NULL;
  1054.     INCREF(func);
  1055.     im->im_func = func;
  1056.     XINCREF(self);
  1057.     im->im_self = self;
  1058.     INCREF(class);
  1059.     im->im_class = class;
  1060.     return (object *)im;
  1061. }
  1062.  
  1063. object *
  1064. instancemethodgetfunc(im)
  1065.     register object *im;
  1066. {
  1067.     if (!is_instancemethodobject(im)) {
  1068.         err_badcall();
  1069.         return NULL;
  1070.     }
  1071.     return ((instancemethodobject *)im)->im_func;
  1072. }
  1073.  
  1074. object *
  1075. instancemethodgetself(im)
  1076.     register object *im;
  1077. {
  1078.     if (!is_instancemethodobject(im)) {
  1079.         err_badcall();
  1080.         return NULL;
  1081.     }
  1082.     return ((instancemethodobject *)im)->im_self;
  1083. }
  1084.  
  1085. object *
  1086. instancemethodgetclass(im)
  1087.     register object *im;
  1088. {
  1089.     if (!is_instancemethodobject(im)) {
  1090.         err_badcall();
  1091.         return NULL;
  1092.     }
  1093.     return ((instancemethodobject *)im)->im_class;
  1094. }
  1095.  
  1096. /* Class method methods */
  1097.  
  1098. #define OFF(x) offsetof(instancemethodobject, x)
  1099.  
  1100. static struct memberlist instancemethod_memberlist[] = {
  1101.     {"im_func",    T_OBJECT,    OFF(im_func)},
  1102.     {"im_self",    T_OBJECT,    OFF(im_self)},
  1103.     {"im_class",    T_OBJECT,    OFF(im_class)},
  1104.     {NULL}    /* Sentinel */
  1105. };
  1106.  
  1107. static object *
  1108. instancemethod_getattr(im, name)
  1109.     register instancemethodobject *im;
  1110.     char *name;
  1111. {
  1112.     return getmember((char *)im, instancemethod_memberlist, name);
  1113. }
  1114.  
  1115. static void
  1116. instancemethod_dealloc(im)
  1117.     register instancemethodobject *im;
  1118. {
  1119.     DECREF(im->im_func);
  1120.     XDECREF(im->im_self);
  1121.     DECREF(im->im_class);
  1122.     free((ANY *)im);
  1123. }
  1124.  
  1125. static int
  1126. instancemethod_compare(a, b)
  1127.     instancemethodobject *a, *b;
  1128. {
  1129.     int cmp = cmpobject(a->im_self, b->im_self);
  1130.     if (cmp == 0)
  1131.         cmp = cmpobject(a->im_func, b->im_func);
  1132.     return cmp;
  1133. }
  1134.  
  1135. static object *
  1136. instancemethod_repr(a)
  1137.     instancemethodobject *a;
  1138. {
  1139.     char buf[240];
  1140.     instanceobject *self = (instanceobject *)(a->im_self);
  1141.     funcobject *func = (funcobject *)(a->im_func);
  1142.     classobject *class = (classobject *)(a->im_class);
  1143.     object *fclassname, *iclassname, *funcname;
  1144.     char *fcname, *icname, *fname;
  1145.     fclassname = class->cl_name;
  1146.     funcname = func->func_name;
  1147.     if (fclassname != NULL && is_stringobject(fclassname))
  1148.         fcname = getstringvalue(fclassname);
  1149.     else
  1150.         fcname = "?";
  1151.     if (funcname != NULL && is_stringobject(funcname))
  1152.         fname = getstringvalue(funcname);
  1153.     else
  1154.         fname = "?";
  1155.     if (self == NULL)
  1156.         sprintf(buf, "<unbound method %.100s.%.100s>", fcname, fname);
  1157.     else {
  1158.         iclassname = self->in_class->cl_name;
  1159.         if (iclassname != NULL && is_stringobject(iclassname))
  1160.             icname = getstringvalue(iclassname);
  1161.         else
  1162.             icname = "?";
  1163.         sprintf(buf, "<method %.60s.%.60s of %.60s instance at %lx>",
  1164.             fcname, fname, icname, (long)self);
  1165.     }
  1166.     return newstringobject(buf);
  1167. }
  1168.  
  1169. static long
  1170. instancemethod_hash(a)
  1171.     instancemethodobject *a;
  1172. {
  1173.     long x, y;
  1174.     if (a->im_self == NULL)
  1175.         x = hashobject(None);
  1176.     else
  1177.         x = hashobject(a->im_self);
  1178.     if (x == -1)
  1179.         return -1;
  1180.     y = hashobject(a->im_func);
  1181.     if (y == -1)
  1182.         return -1;
  1183.     return x ^ y;
  1184. }
  1185.  
  1186. typeobject Instancemethodtype = {
  1187.     OB_HEAD_INIT(&Typetype)
  1188.     0,
  1189.     "instance method",
  1190.     sizeof(instancemethodobject),
  1191.     0,
  1192.     (destructor)instancemethod_dealloc, /*tp_dealloc*/
  1193.     0,            /*tp_print*/
  1194.     (getattrfunc)instancemethod_getattr, /*tp_getattr*/
  1195.     0,            /*tp_setattr*/
  1196.     (cmpfunc)instancemethod_compare, /*tp_compare*/
  1197.     (reprfunc)instancemethod_repr, /*tp_repr*/
  1198.     0,            /*tp_as_number*/
  1199.     0,            /*tp_as_sequence*/
  1200.     0,            /*tp_as_mapping*/
  1201.     (hashfunc)instancemethod_hash, /*tp_hash*/
  1202. };
  1203.