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