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