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