classobject.c revision 45ec02aed14685c353e55841b5acbc0dadee76f8
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
619	_PyObject_GC_UNTRACK(inst);
620	if (inst->in_weakreflist != NULL)
621		PyObject_ClearWeakRefs((PyObject *) inst);
622
623	/* Temporarily resurrect the object. */
624	assert(inst->ob_type == &PyInstance_Type);
625	assert(inst->ob_refcnt == 0);
626	inst->ob_refcnt = 1;
627
628	/* Save the current exception, if any. */
629	PyErr_Fetch(&error_type, &error_value, &error_traceback);
630	/* Execute __del__ method, if any. */
631	if (delstr == NULL)
632		delstr = PyString_InternFromString("__del__");
633	if ((del = instance_getattr2(inst, delstr)) != NULL) {
634		PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
635		if (res == NULL)
636			PyErr_WriteUnraisable(del);
637		else
638			Py_DECREF(res);
639		Py_DECREF(del);
640	}
641	/* Restore the saved exception. */
642	PyErr_Restore(error_type, error_value, error_traceback);
643
644	/* Undo the temporary resurrection; can't use DECREF here, it would
645	 * cause a recursive call.
646	 */
647	assert(inst->ob_refcnt > 0);
648	if (--inst->ob_refcnt == 0) {
649		Py_DECREF(inst->in_class);
650		Py_XDECREF(inst->in_dict);
651		PyObject_GC_Del(inst);
652	}
653	else {
654		int refcnt = inst->ob_refcnt;
655		/* __del__ resurrected it!  Make it look like the original
656		 * Py_DECREF never happened.
657		 */
658		_Py_NewReference((PyObject *)inst);
659		inst->ob_refcnt = refcnt;
660		_PyObject_GC_TRACK(inst);
661		/* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal,
662		 * but _Py_NewReference bumped it again, so that's a wash.
663		 * If Py_TRACE_REFS, _Py_NewReference re-added self to the
664		 * object chain, so no more to do there either.
665		 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
666		 * _Py_NewReference bumped tp_allocs:  both of those need to
667		 * be undone.
668		 */
669#ifdef COUNT_ALLOCS
670		--inst->ob_type->tp_frees;
671		--inst->ob_type->tp_allocs;
672#endif
673	}
674}
675
676static PyObject *
677instance_getattr1(register PyInstanceObject *inst, PyObject *name)
678{
679	register PyObject *v;
680	register char *sname = PyString_AsString(name);
681	if (sname[0] == '_' && sname[1] == '_') {
682		if (strcmp(sname, "__dict__") == 0) {
683			if (PyEval_GetRestricted()) {
684				PyErr_SetString(PyExc_RuntimeError,
685			"instance.__dict__ not accessible in restricted mode");
686				return NULL;
687			}
688			Py_INCREF(inst->in_dict);
689			return inst->in_dict;
690		}
691		if (strcmp(sname, "__class__") == 0) {
692			Py_INCREF(inst->in_class);
693			return (PyObject *)inst->in_class;
694		}
695	}
696	v = instance_getattr2(inst, name);
697	if (v == NULL) {
698		PyErr_Format(PyExc_AttributeError,
699			     "%.50s instance has no attribute '%.400s'",
700			     PyString_AS_STRING(inst->in_class->cl_name), sname);
701	}
702	return v;
703}
704
705static PyObject *
706instance_getattr2(register PyInstanceObject *inst, PyObject *name)
707{
708	register PyObject *v;
709	PyClassObject *class;
710	descrgetfunc f;
711
712	v = PyDict_GetItem(inst->in_dict, name);
713	if (v != NULL) {
714		Py_INCREF(v);
715		return v;
716	}
717	v = class_lookup(inst->in_class, name, &class);
718	if (v != NULL) {
719		Py_INCREF(v);
720		f = TP_DESCR_GET(v->ob_type);
721		if (f != NULL) {
722			PyObject *w = f(v, (PyObject *)inst,
723					(PyObject *)(inst->in_class));
724			Py_DECREF(v);
725			v = w;
726		}
727	}
728	return v;
729}
730
731static PyObject *
732instance_getattr(register PyInstanceObject *inst, PyObject *name)
733{
734	register PyObject *func, *res;
735	res = instance_getattr1(inst, name);
736	if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
737		PyObject *args;
738		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
739			return NULL;
740		PyErr_Clear();
741		args = Py_BuildValue("(OO)", inst, name);
742		if (args == NULL)
743			return NULL;
744		res = PyEval_CallObject(func, args);
745		Py_DECREF(args);
746	}
747	return res;
748}
749
750static int
751instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
752{
753	if (v == NULL) {
754		int rv = PyDict_DelItem(inst->in_dict, name);
755		if (rv < 0)
756			PyErr_Format(PyExc_AttributeError,
757				     "%.50s instance has no attribute '%.400s'",
758				     PyString_AS_STRING(inst->in_class->cl_name),
759				     PyString_AS_STRING(name));
760		return rv;
761	}
762	else
763		return PyDict_SetItem(inst->in_dict, name, v);
764}
765
766static int
767instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
768{
769	PyObject *func, *args, *res, *tmp;
770	char *sname = PyString_AsString(name);
771	if (sname[0] == '_' && sname[1] == '_') {
772		int n = PyString_Size(name);
773		if (sname[n-1] == '_' && sname[n-2] == '_') {
774			if (strcmp(sname, "__dict__") == 0) {
775				if (PyEval_GetRestricted()) {
776					PyErr_SetString(PyExc_RuntimeError,
777				 "__dict__ not accessible in restricted mode");
778					return -1;
779				}
780				if (v == NULL || !PyDict_Check(v)) {
781				    PyErr_SetString(PyExc_TypeError,
782				       "__dict__ must be set to a dictionary");
783				    return -1;
784				}
785				tmp = inst->in_dict;
786				Py_INCREF(v);
787				inst->in_dict = v;
788				Py_DECREF(tmp);
789				return 0;
790			}
791			if (strcmp(sname, "__class__") == 0) {
792				if (PyEval_GetRestricted()) {
793					PyErr_SetString(PyExc_RuntimeError,
794				"__class__ not accessible in restricted mode");
795					return -1;
796				}
797				if (v == NULL || !PyClass_Check(v)) {
798					PyErr_SetString(PyExc_TypeError,
799					   "__class__ must be set to a class");
800					return -1;
801				}
802				tmp = (PyObject *)(inst->in_class);
803				Py_INCREF(v);
804				inst->in_class = (PyClassObject *)v;
805				Py_DECREF(tmp);
806				return 0;
807			}
808		}
809	}
810	if (v == NULL)
811		func = inst->in_class->cl_delattr;
812	else
813		func = inst->in_class->cl_setattr;
814	if (func == NULL)
815		return instance_setattr1(inst, name, v);
816	if (v == NULL)
817		args = Py_BuildValue("(OO)", inst, name);
818	else
819		args = Py_BuildValue("(OOO)", inst, name, v);
820	if (args == NULL)
821		return -1;
822	res = PyEval_CallObject(func, args);
823	Py_DECREF(args);
824	if (res == NULL)
825		return -1;
826	Py_DECREF(res);
827	return 0;
828}
829
830static PyObject *
831instance_repr(PyInstanceObject *inst)
832{
833	PyObject *func;
834	PyObject *res;
835	static PyObject *reprstr;
836
837	if (reprstr == NULL)
838		reprstr = PyString_InternFromString("__repr__");
839	func = instance_getattr(inst, reprstr);
840	if (func == NULL) {
841		PyObject *classname, *mod;
842		char *cname;
843		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
844			return NULL;
845		PyErr_Clear();
846		classname = inst->in_class->cl_name;
847		mod = PyDict_GetItemString(inst->in_class->cl_dict,
848					   "__module__");
849		if (classname != NULL && PyString_Check(classname))
850			cname = PyString_AsString(classname);
851		else
852			cname = "?";
853		if (mod == NULL || !PyString_Check(mod))
854			return PyString_FromFormat("<?.%s instance at %p>",
855						   cname, inst);
856		else
857			return PyString_FromFormat("<%s.%s instance at %p>",
858						   PyString_AsString(mod),
859						   cname, inst);
860	}
861	res = PyEval_CallObject(func, (PyObject *)NULL);
862	Py_DECREF(func);
863	return res;
864}
865
866static PyObject *
867instance_str(PyInstanceObject *inst)
868{
869	PyObject *func;
870	PyObject *res;
871	static PyObject *strstr;
872
873	if (strstr == NULL)
874		strstr = PyString_InternFromString("__str__");
875	func = instance_getattr(inst, strstr);
876	if (func == NULL) {
877		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
878			return NULL;
879		PyErr_Clear();
880		return instance_repr(inst);
881	}
882	res = PyEval_CallObject(func, (PyObject *)NULL);
883	Py_DECREF(func);
884	return res;
885}
886
887static long
888instance_hash(PyInstanceObject *inst)
889{
890	PyObject *func;
891	PyObject *res;
892	long outcome;
893	static PyObject *hashstr, *eqstr, *cmpstr;
894
895	if (hashstr == NULL)
896		hashstr = PyString_InternFromString("__hash__");
897	func = instance_getattr(inst, hashstr);
898	if (func == NULL) {
899		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
900			return -1;
901		PyErr_Clear();
902		/* If there is no __eq__ and no __cmp__ method, we hash on the
903		   address.  If an __eq__ or __cmp__ method exists, there must
904		   be a __hash__. */
905		if (eqstr == NULL)
906			eqstr = PyString_InternFromString("__eq__");
907		func = instance_getattr(inst, eqstr);
908		if (func == NULL) {
909			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
910				return -1;
911			PyErr_Clear();
912			if (cmpstr == NULL)
913				cmpstr = PyString_InternFromString("__cmp__");
914			func = instance_getattr(inst, cmpstr);
915			if (func == NULL) {
916				if (!PyErr_ExceptionMatches(
917					PyExc_AttributeError))
918					return -1;
919				PyErr_Clear();
920				return _Py_HashPointer(inst);
921			}
922		}
923		PyErr_SetString(PyExc_TypeError, "unhashable instance");
924		return -1;
925	}
926	res = PyEval_CallObject(func, (PyObject *)NULL);
927	Py_DECREF(func);
928	if (res == NULL)
929		return -1;
930	if (PyInt_Check(res)) {
931		outcome = PyInt_AsLong(res);
932		if (outcome == -1)
933			outcome = -2;
934	}
935	else {
936		PyErr_SetString(PyExc_TypeError,
937				"__hash__() should return an int");
938		outcome = -1;
939	}
940	Py_DECREF(res);
941	return outcome;
942}
943
944static int
945instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
946{
947	int err;
948	if (o->in_class) {
949		err = visit((PyObject *)(o->in_class), arg);
950		if (err)
951			return err;
952	}
953	if (o->in_dict) {
954		err = visit(o->in_dict, arg);
955		if (err)
956			return err;
957	}
958	return 0;
959}
960
961static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
962static PyObject *iterstr, *nextstr;
963
964static int
965instance_length(PyInstanceObject *inst)
966{
967	PyObject *func;
968	PyObject *res;
969	int outcome;
970
971	if (lenstr == NULL)
972		lenstr = PyString_InternFromString("__len__");
973	func = instance_getattr(inst, lenstr);
974	if (func == NULL)
975		return -1;
976	res = PyEval_CallObject(func, (PyObject *)NULL);
977	Py_DECREF(func);
978	if (res == NULL)
979		return -1;
980	if (PyInt_Check(res)) {
981		outcome = PyInt_AsLong(res);
982		if (outcome < 0)
983			PyErr_SetString(PyExc_ValueError,
984					"__len__() should return >= 0");
985	}
986	else {
987		PyErr_SetString(PyExc_TypeError,
988				"__len__() should return an int");
989		outcome = -1;
990	}
991	Py_DECREF(res);
992	return outcome;
993}
994
995static PyObject *
996instance_subscript(PyInstanceObject *inst, PyObject *key)
997{
998	PyObject *func;
999	PyObject *arg;
1000	PyObject *res;
1001
1002	if (getitemstr == NULL)
1003		getitemstr = PyString_InternFromString("__getitem__");
1004	func = instance_getattr(inst, getitemstr);
1005	if (func == NULL)
1006		return NULL;
1007	arg = Py_BuildValue("(O)", key);
1008	if (arg == NULL) {
1009		Py_DECREF(func);
1010		return NULL;
1011	}
1012	res = PyEval_CallObject(func, arg);
1013	Py_DECREF(func);
1014	Py_DECREF(arg);
1015	return res;
1016}
1017
1018static int
1019instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
1020{
1021	PyObject *func;
1022	PyObject *arg;
1023	PyObject *res;
1024
1025	if (value == NULL) {
1026		if (delitemstr == NULL)
1027			delitemstr = PyString_InternFromString("__delitem__");
1028		func = instance_getattr(inst, delitemstr);
1029	}
1030	else {
1031		if (setitemstr == NULL)
1032			setitemstr = PyString_InternFromString("__setitem__");
1033		func = instance_getattr(inst, setitemstr);
1034	}
1035	if (func == NULL)
1036		return -1;
1037	if (value == NULL)
1038		arg = Py_BuildValue("(O)", key);
1039	else
1040		arg = Py_BuildValue("(OO)", key, value);
1041	if (arg == NULL) {
1042		Py_DECREF(func);
1043		return -1;
1044	}
1045	res = PyEval_CallObject(func, arg);
1046	Py_DECREF(func);
1047	Py_DECREF(arg);
1048	if (res == NULL)
1049		return -1;
1050	Py_DECREF(res);
1051	return 0;
1052}
1053
1054static PyMappingMethods instance_as_mapping = {
1055	(inquiry)instance_length,		/* mp_length */
1056	(binaryfunc)instance_subscript,		/* mp_subscript */
1057	(objobjargproc)instance_ass_subscript,	/* mp_ass_subscript */
1058};
1059
1060static PyObject *
1061instance_item(PyInstanceObject *inst, int i)
1062{
1063	PyObject *func, *arg, *res;
1064
1065	if (getitemstr == NULL)
1066		getitemstr = PyString_InternFromString("__getitem__");
1067	func = instance_getattr(inst, getitemstr);
1068	if (func == NULL)
1069		return NULL;
1070	arg = Py_BuildValue("(i)", i);
1071	if (arg == NULL) {
1072		Py_DECREF(func);
1073		return NULL;
1074	}
1075	res = PyEval_CallObject(func, arg);
1076	Py_DECREF(func);
1077	Py_DECREF(arg);
1078	return res;
1079}
1080
1081static PyObject *
1082sliceobj_from_intint(int i, int j)
1083{
1084	PyObject *start, *end, *res;
1085
1086	start = PyInt_FromLong((long)i);
1087	if (!start)
1088		return NULL;
1089
1090	end = PyInt_FromLong((long)j);
1091	if (!end) {
1092		Py_DECREF(start);
1093		return NULL;
1094	}
1095	res = PySlice_New(start, end, NULL);
1096	Py_DECREF(start);
1097	Py_DECREF(end);
1098	return res;
1099}
1100
1101
1102static PyObject *
1103instance_slice(PyInstanceObject *inst, int i, int j)
1104{
1105	PyObject *func, *arg, *res;
1106	static PyObject *getslicestr;
1107
1108	if (getslicestr == NULL)
1109		getslicestr = PyString_InternFromString("__getslice__");
1110	func = instance_getattr(inst, getslicestr);
1111
1112	if (func == NULL) {
1113		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1114			return NULL;
1115		PyErr_Clear();
1116
1117		if (getitemstr == NULL)
1118			getitemstr = PyString_InternFromString("__getitem__");
1119		func = instance_getattr(inst, getitemstr);
1120		if (func == NULL)
1121			return NULL;
1122		arg = Py_BuildValue("(N)", sliceobj_from_intint(i, j));
1123	} else
1124		arg = Py_BuildValue("(ii)", i, j);
1125
1126	if (arg == NULL) {
1127		Py_DECREF(func);
1128		return NULL;
1129	}
1130	res = PyEval_CallObject(func, arg);
1131	Py_DECREF(func);
1132	Py_DECREF(arg);
1133	return res;
1134}
1135
1136static int
1137instance_ass_item(PyInstanceObject *inst, int i, PyObject *item)
1138{
1139	PyObject *func, *arg, *res;
1140
1141	if (item == NULL) {
1142		if (delitemstr == NULL)
1143			delitemstr = PyString_InternFromString("__delitem__");
1144		func = instance_getattr(inst, delitemstr);
1145	}
1146	else {
1147		if (setitemstr == NULL)
1148			setitemstr = PyString_InternFromString("__setitem__");
1149		func = instance_getattr(inst, setitemstr);
1150	}
1151	if (func == NULL)
1152		return -1;
1153	if (item == NULL)
1154		arg = Py_BuildValue("i", i);
1155	else
1156		arg = Py_BuildValue("(iO)", i, item);
1157	if (arg == NULL) {
1158		Py_DECREF(func);
1159		return -1;
1160	}
1161	res = PyEval_CallObject(func, arg);
1162	Py_DECREF(func);
1163	Py_DECREF(arg);
1164	if (res == NULL)
1165		return -1;
1166	Py_DECREF(res);
1167	return 0;
1168}
1169
1170static int
1171instance_ass_slice(PyInstanceObject *inst, int i, int j, PyObject *value)
1172{
1173	PyObject *func, *arg, *res;
1174	static PyObject *setslicestr, *delslicestr;
1175
1176	if (value == NULL) {
1177		if (delslicestr == NULL)
1178			delslicestr =
1179				PyString_InternFromString("__delslice__");
1180		func = instance_getattr(inst, delslicestr);
1181		if (func == NULL) {
1182			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1183				return -1;
1184			PyErr_Clear();
1185			if (delitemstr == NULL)
1186				delitemstr =
1187				    PyString_InternFromString("__delitem__");
1188			func = instance_getattr(inst, delitemstr);
1189			if (func == NULL)
1190				return -1;
1191
1192			arg = Py_BuildValue("(N)",
1193					    sliceobj_from_intint(i, j));
1194		} else
1195			arg = Py_BuildValue("(ii)", i, j);
1196	}
1197	else {
1198		if (setslicestr == NULL)
1199			setslicestr =
1200				PyString_InternFromString("__setslice__");
1201		func = instance_getattr(inst, setslicestr);
1202		if (func == NULL) {
1203			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1204				return -1;
1205			PyErr_Clear();
1206			if (setitemstr == NULL)
1207				setitemstr =
1208				    PyString_InternFromString("__setitem__");
1209			func = instance_getattr(inst, setitemstr);
1210			if (func == NULL)
1211				return -1;
1212
1213			arg = Py_BuildValue("(NO)",
1214					    sliceobj_from_intint(i, j), value);
1215		} else
1216			arg = Py_BuildValue("(iiO)", i, j, value);
1217	}
1218	if (arg == NULL) {
1219		Py_DECREF(func);
1220		return -1;
1221	}
1222	res = PyEval_CallObject(func, arg);
1223	Py_DECREF(func);
1224	Py_DECREF(arg);
1225	if (res == NULL)
1226		return -1;
1227	Py_DECREF(res);
1228	return 0;
1229}
1230
1231static int
1232instance_contains(PyInstanceObject *inst, PyObject *member)
1233{
1234	static PyObject *__contains__;
1235	PyObject *func;
1236
1237	/* Try __contains__ first.
1238	 * If that can't be done, try iterator-based searching.
1239	 */
1240
1241	if(__contains__ == NULL) {
1242		__contains__ = PyString_InternFromString("__contains__");
1243		if(__contains__ == NULL)
1244			return -1;
1245	}
1246	func = instance_getattr(inst, __contains__);
1247	if (func) {
1248		PyObject *res;
1249		int ret;
1250		PyObject *arg = Py_BuildValue("(O)", member);
1251		if(arg == NULL) {
1252			Py_DECREF(func);
1253			return -1;
1254		}
1255		res = PyEval_CallObject(func, arg);
1256		Py_DECREF(func);
1257		Py_DECREF(arg);
1258		if(res == NULL)
1259			return -1;
1260		ret = PyObject_IsTrue(res);
1261		Py_DECREF(res);
1262		return ret;
1263	}
1264
1265	/* Couldn't find __contains__. */
1266	if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
1267		/* Assume the failure was simply due to that there is no
1268		 * __contains__ attribute, and try iterating instead.
1269		 */
1270		PyErr_Clear();
1271		return _PySequence_IterSearch((PyObject *)inst, member,
1272					      PY_ITERSEARCH_CONTAINS);
1273	}
1274	else
1275		return -1;
1276}
1277
1278static PySequenceMethods
1279instance_as_sequence = {
1280	(inquiry)instance_length,		/* sq_length */
1281	0,					/* sq_concat */
1282	0,					/* sq_repeat */
1283	(intargfunc)instance_item,		/* sq_item */
1284	(intintargfunc)instance_slice,		/* sq_slice */
1285	(intobjargproc)instance_ass_item,	/* sq_ass_item */
1286	(intintobjargproc)instance_ass_slice,	/* sq_ass_slice */
1287	(objobjproc)instance_contains,		/* sq_contains */
1288};
1289
1290static PyObject *
1291generic_unary_op(PyInstanceObject *self, PyObject *methodname)
1292{
1293	PyObject *func, *res;
1294
1295	if ((func = instance_getattr(self, methodname)) == NULL)
1296		return NULL;
1297	res = PyEval_CallObject(func, (PyObject *)NULL);
1298	Py_DECREF(func);
1299	return res;
1300}
1301
1302static PyObject *
1303generic_binary_op(PyObject *v, PyObject *w, char *opname)
1304{
1305	PyObject *result;
1306	PyObject *args;
1307	PyObject *func = PyObject_GetAttrString(v, opname);
1308	if (func == NULL) {
1309		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1310			return NULL;
1311		PyErr_Clear();
1312		Py_INCREF(Py_NotImplemented);
1313		return Py_NotImplemented;
1314	}
1315	args = Py_BuildValue("(O)", w);
1316	if (args == NULL) {
1317		Py_DECREF(func);
1318		return NULL;
1319	}
1320	result = PyEval_CallObject(func, args);
1321	Py_DECREF(args);
1322	Py_DECREF(func);
1323	return result;
1324}
1325
1326
1327static PyObject *coerce_obj;
1328
1329/* Try one half of a binary operator involving a class instance. */
1330static PyObject *
1331half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
1332		int swapped)
1333{
1334	PyObject *args;
1335	PyObject *coercefunc;
1336	PyObject *coerced = NULL;
1337	PyObject *v1;
1338	PyObject *result;
1339
1340	if (!PyInstance_Check(v)) {
1341		Py_INCREF(Py_NotImplemented);
1342		return Py_NotImplemented;
1343	}
1344
1345	if (coerce_obj == NULL) {
1346		coerce_obj = PyString_InternFromString("__coerce__");
1347		if (coerce_obj == NULL)
1348			return NULL;
1349	}
1350	coercefunc = PyObject_GetAttr(v, coerce_obj);
1351	if (coercefunc == NULL) {
1352		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1353			return NULL;
1354		PyErr_Clear();
1355		return generic_binary_op(v, w, opname);
1356	}
1357
1358	args = Py_BuildValue("(O)", w);
1359	if (args == NULL) {
1360		return NULL;
1361	}
1362	coerced = PyEval_CallObject(coercefunc, args);
1363	Py_DECREF(args);
1364	Py_DECREF(coercefunc);
1365	if (coerced == NULL) {
1366		return NULL;
1367	}
1368	if (coerced == Py_None || coerced == Py_NotImplemented) {
1369		Py_DECREF(coerced);
1370		return generic_binary_op(v, w, opname);
1371	}
1372	if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1373		Py_DECREF(coerced);
1374		PyErr_SetString(PyExc_TypeError,
1375				"coercion should return None or 2-tuple");
1376		return NULL;
1377	}
1378	v1 = PyTuple_GetItem(coerced, 0);
1379	w = PyTuple_GetItem(coerced, 1);
1380	if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
1381		/* prevent recursion if __coerce__ returns self as the first
1382		 * argument */
1383		result = generic_binary_op(v1, w, opname);
1384	} else {
1385		if (swapped)
1386			result = (thisfunc)(w, v1);
1387		else
1388			result = (thisfunc)(v1, w);
1389	}
1390	Py_DECREF(coerced);
1391	return result;
1392}
1393
1394/* Implement a binary operator involving at least one class instance. */
1395static PyObject *
1396do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1397                   binaryfunc thisfunc)
1398{
1399	PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1400	if (result == Py_NotImplemented) {
1401		Py_DECREF(result);
1402		result = half_binop(w, v, ropname, thisfunc, 1);
1403	}
1404	return result;
1405}
1406
1407static PyObject *
1408do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
1409			char *ropname, binaryfunc thisfunc)
1410{
1411	PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1412	if (result == Py_NotImplemented) {
1413		Py_DECREF(result);
1414		result = do_binop(v, w, opname, ropname, thisfunc);
1415	}
1416	return result;
1417}
1418
1419static int
1420instance_coerce(PyObject **pv, PyObject **pw)
1421{
1422	PyObject *v = *pv;
1423	PyObject *w = *pw;
1424	PyObject *coercefunc;
1425	PyObject *args;
1426	PyObject *coerced;
1427
1428	if (coerce_obj == NULL) {
1429		coerce_obj = PyString_InternFromString("__coerce__");
1430		if (coerce_obj == NULL)
1431			return -1;
1432	}
1433	coercefunc = PyObject_GetAttr(v, coerce_obj);
1434	if (coercefunc == NULL) {
1435		/* No __coerce__ method */
1436		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1437			return -1;
1438		PyErr_Clear();
1439		return 1;
1440	}
1441	/* Has __coerce__ method: call it */
1442	args = Py_BuildValue("(O)", w);
1443	if (args == NULL) {
1444		return -1;
1445	}
1446	coerced = PyEval_CallObject(coercefunc, args);
1447	Py_DECREF(args);
1448	Py_DECREF(coercefunc);
1449	if (coerced == NULL) {
1450		/* __coerce__ call raised an exception */
1451		return -1;
1452	}
1453	if (coerced == Py_None || coerced == Py_NotImplemented) {
1454		/* __coerce__ says "I can't do it" */
1455		Py_DECREF(coerced);
1456		return 1;
1457	}
1458	if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1459		/* __coerce__ return value is malformed */
1460		Py_DECREF(coerced);
1461		PyErr_SetString(PyExc_TypeError,
1462			   "coercion should return None or 2-tuple");
1463		return -1;
1464	}
1465	/* __coerce__ returned two new values */
1466	*pv = PyTuple_GetItem(coerced, 0);
1467	*pw = PyTuple_GetItem(coerced, 1);
1468	Py_INCREF(*pv);
1469	Py_INCREF(*pw);
1470	Py_DECREF(coerced);
1471	return 0;
1472}
1473
1474#define UNARY(funcname, methodname) \
1475static PyObject *funcname(PyInstanceObject *self) { \
1476	static PyObject *o; \
1477	if (o == NULL) o = PyString_InternFromString(methodname); \
1478	return generic_unary_op(self, o); \
1479}
1480
1481#define BINARY(f, m, n) \
1482static PyObject *f(PyObject *v, PyObject *w) { \
1483	return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1484}
1485
1486#define BINARY_INPLACE(f, m, n) \
1487static PyObject *f(PyObject *v, PyObject *w) { \
1488	return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1489			"__r" m "__", n); \
1490}
1491
1492UNARY(instance_neg, "__neg__")
1493UNARY(instance_pos, "__pos__")
1494UNARY(instance_abs, "__abs__")
1495
1496BINARY(instance_or, "or", PyNumber_Or)
1497BINARY(instance_and, "and", PyNumber_And)
1498BINARY(instance_xor, "xor", PyNumber_Xor)
1499BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1500BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1501BINARY(instance_add, "add", PyNumber_Add)
1502BINARY(instance_sub, "sub", PyNumber_Subtract)
1503BINARY(instance_mul, "mul", PyNumber_Multiply)
1504BINARY(instance_div, "div", PyNumber_Divide)
1505BINARY(instance_mod, "mod", PyNumber_Remainder)
1506BINARY(instance_divmod, "divmod", PyNumber_Divmod)
1507BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
1508BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
1509
1510BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1511BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1512BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1513BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1514BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1515BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1516BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1517BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1518BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1519BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
1520BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
1521BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
1522
1523/* Try a 3-way comparison, returning an int; v is an instance.  Return:
1524   -2 for an exception;
1525   -1 if v < w;
1526   0 if v == w;
1527   1 if v > w;
1528   2 if this particular 3-way comparison is not implemented or undefined.
1529*/
1530static int
1531half_cmp(PyObject *v, PyObject *w)
1532{
1533	static PyObject *cmp_obj;
1534	PyObject *args;
1535	PyObject *cmp_func;
1536	PyObject *result;
1537	long l;
1538
1539	assert(PyInstance_Check(v));
1540
1541	if (cmp_obj == NULL) {
1542		cmp_obj = PyString_InternFromString("__cmp__");
1543		if (cmp_obj == NULL)
1544			return -2;
1545	}
1546
1547	cmp_func = PyObject_GetAttr(v, cmp_obj);
1548	if (cmp_func == NULL) {
1549		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1550			return -2;
1551		PyErr_Clear();
1552		return 2;
1553	}
1554
1555	args = Py_BuildValue("(O)", w);
1556	if (args == NULL)
1557		return -2;
1558
1559	result = PyEval_CallObject(cmp_func, args);
1560	Py_DECREF(args);
1561	Py_DECREF(cmp_func);
1562
1563	if (result == NULL)
1564		return -2;
1565
1566	if (result == Py_NotImplemented) {
1567		Py_DECREF(result);
1568		return 2;
1569	}
1570
1571	l = PyInt_AsLong(result);
1572	Py_DECREF(result);
1573	if (l == -1 && PyErr_Occurred()) {
1574		PyErr_SetString(PyExc_TypeError,
1575			     "comparison did not return an int");
1576		return -2;
1577	}
1578
1579	return l < 0 ? -1 : l > 0 ? 1 : 0;
1580}
1581
1582/* Try a 3-way comparison, returning an int; either v or w is an instance.
1583   We first try a coercion.  Return:
1584   -2 for an exception;
1585   -1 if v < w;
1586   0 if v == w;
1587   1 if v > w;
1588   2 if this particular 3-way comparison is not implemented or undefined.
1589   THIS IS ONLY CALLED FROM object.c!
1590*/
1591static int
1592instance_compare(PyObject *v, PyObject *w)
1593{
1594	int c;
1595
1596	c = PyNumber_CoerceEx(&v, &w);
1597	if (c < 0)
1598		return -2;
1599	if (c == 0) {
1600		/* If neither is now an instance, use regular comparison */
1601		if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1602			c = PyObject_Compare(v, w);
1603			Py_DECREF(v);
1604			Py_DECREF(w);
1605			if (PyErr_Occurred())
1606				return -2;
1607			return c < 0 ? -1 : c > 0 ? 1 : 0;
1608		}
1609	}
1610	else {
1611		/* The coercion didn't do anything.
1612		   Treat this the same as returning v and w unchanged. */
1613		Py_INCREF(v);
1614		Py_INCREF(w);
1615	}
1616
1617	if (PyInstance_Check(v)) {
1618		c = half_cmp(v, w);
1619		if (c <= 1) {
1620			Py_DECREF(v);
1621			Py_DECREF(w);
1622			return c;
1623		}
1624	}
1625	if (PyInstance_Check(w)) {
1626		c = half_cmp(w, v);
1627		if (c <= 1) {
1628			Py_DECREF(v);
1629			Py_DECREF(w);
1630			if (c >= -1)
1631				c = -c;
1632			return c;
1633		}
1634	}
1635	Py_DECREF(v);
1636	Py_DECREF(w);
1637	return 2;
1638}
1639
1640static int
1641instance_nonzero(PyInstanceObject *self)
1642{
1643	PyObject *func, *res;
1644	long outcome;
1645	static PyObject *nonzerostr;
1646
1647	if (nonzerostr == NULL)
1648		nonzerostr = PyString_InternFromString("__nonzero__");
1649	if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1650		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1651			return -1;
1652		PyErr_Clear();
1653		if (lenstr == NULL)
1654			lenstr = PyString_InternFromString("__len__");
1655		if ((func = instance_getattr(self, lenstr)) == NULL) {
1656			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1657				return -1;
1658			PyErr_Clear();
1659			/* Fall back to the default behavior:
1660			   all instances are nonzero */
1661			return 1;
1662		}
1663	}
1664	res = PyEval_CallObject(func, (PyObject *)NULL);
1665	Py_DECREF(func);
1666	if (res == NULL)
1667		return -1;
1668	if (!PyInt_Check(res)) {
1669		Py_DECREF(res);
1670		PyErr_SetString(PyExc_TypeError,
1671				"__nonzero__ should return an int");
1672		return -1;
1673	}
1674	outcome = PyInt_AsLong(res);
1675	Py_DECREF(res);
1676	if (outcome < 0) {
1677		PyErr_SetString(PyExc_ValueError,
1678				"__nonzero__ should return >= 0");
1679		return -1;
1680	}
1681	return outcome > 0;
1682}
1683
1684UNARY(instance_invert, "__invert__")
1685UNARY(instance_int, "__int__")
1686UNARY(instance_long, "__long__")
1687UNARY(instance_float, "__float__")
1688UNARY(instance_oct, "__oct__")
1689UNARY(instance_hex, "__hex__")
1690
1691static PyObject *
1692bin_power(PyObject *v, PyObject *w)
1693{
1694	return PyNumber_Power(v, w, Py_None);
1695}
1696
1697/* This version is for ternary calls only (z != None) */
1698static PyObject *
1699instance_pow(PyObject *v, PyObject *w, PyObject *z)
1700{
1701	if (z == Py_None) {
1702		return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1703	}
1704	else {
1705		PyObject *func;
1706		PyObject *args;
1707		PyObject *result;
1708
1709		/* XXX Doesn't do coercions... */
1710		func = PyObject_GetAttrString(v, "__pow__");
1711		if (func == NULL)
1712			return NULL;
1713		args = Py_BuildValue("(OO)", w, z);
1714		if (args == NULL) {
1715			Py_DECREF(func);
1716			return NULL;
1717		}
1718		result = PyEval_CallObject(func, args);
1719		Py_DECREF(func);
1720		Py_DECREF(args);
1721		return result;
1722	}
1723}
1724
1725static PyObject *
1726bin_inplace_power(PyObject *v, PyObject *w)
1727{
1728	return PyNumber_InPlacePower(v, w, Py_None);
1729}
1730
1731
1732static PyObject *
1733instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1734{
1735	if (z == Py_None) {
1736		return do_binop_inplace(v, w, "__ipow__", "__pow__",
1737			"__rpow__", bin_inplace_power);
1738	}
1739	else {
1740		/* XXX Doesn't do coercions... */
1741		PyObject *func;
1742		PyObject *args;
1743		PyObject *result;
1744
1745		func = PyObject_GetAttrString(v, "__ipow__");
1746		if (func == NULL) {
1747			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1748				return NULL;
1749			PyErr_Clear();
1750			return instance_pow(v, w, z);
1751		}
1752		args = Py_BuildValue("(OO)", w, z);
1753		if (args == NULL) {
1754			Py_DECREF(func);
1755			return NULL;
1756		}
1757		result = PyEval_CallObject(func, args);
1758		Py_DECREF(func);
1759		Py_DECREF(args);
1760		return result;
1761	}
1762}
1763
1764
1765/* Map rich comparison operators to their __xx__ namesakes */
1766#define NAME_OPS 6
1767static PyObject **name_op = NULL;
1768
1769static int
1770init_name_op(void)
1771{
1772	int i;
1773	char *_name_op[] = {
1774		"__lt__",
1775		"__le__",
1776		"__eq__",
1777		"__ne__",
1778		"__gt__",
1779		"__ge__",
1780	};
1781
1782	name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
1783	if (name_op == NULL)
1784		return -1;
1785	for (i = 0; i < NAME_OPS; ++i) {
1786		name_op[i] = PyString_InternFromString(_name_op[i]);
1787		if (name_op[i] == NULL)
1788			return -1;
1789	}
1790	return 0;
1791}
1792
1793static PyObject *
1794half_richcompare(PyObject *v, PyObject *w, int op)
1795{
1796	PyObject *method;
1797	PyObject *args;
1798	PyObject *res;
1799
1800	assert(PyInstance_Check(v));
1801
1802	if (name_op == NULL) {
1803		if (init_name_op() < 0)
1804			return NULL;
1805	}
1806	/* If the instance doesn't define an __getattr__ method, use
1807	   instance_getattr2 directly because it will not set an
1808	   exception on failure. */
1809	if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL) {
1810		method = instance_getattr2((PyInstanceObject *)v,
1811					   name_op[op]);
1812		if (method == NULL) {
1813			assert(!PyErr_Occurred());
1814			res = Py_NotImplemented;
1815			Py_INCREF(res);
1816			return res;
1817		}
1818	} else {
1819		method = PyObject_GetAttr(v, name_op[op]);
1820		if (method == NULL) {
1821			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1822				return NULL;
1823			PyErr_Clear();
1824			res = Py_NotImplemented;
1825			Py_INCREF(res);
1826			return res;
1827		}
1828	}
1829
1830	args = Py_BuildValue("(O)", w);
1831	if (args == NULL) {
1832		Py_DECREF(method);
1833		return NULL;
1834	}
1835
1836	res = PyEval_CallObject(method, args);
1837	Py_DECREF(args);
1838	Py_DECREF(method);
1839
1840	return res;
1841}
1842
1843/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
1844static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
1845
1846static PyObject *
1847instance_richcompare(PyObject *v, PyObject *w, int op)
1848{
1849	PyObject *res;
1850
1851	if (PyInstance_Check(v)) {
1852		res = half_richcompare(v, w, op);
1853		if (res != Py_NotImplemented)
1854			return res;
1855		Py_DECREF(res);
1856	}
1857
1858	if (PyInstance_Check(w)) {
1859		res = half_richcompare(w, v, swapped_op[op]);
1860		if (res != Py_NotImplemented)
1861			return res;
1862		Py_DECREF(res);
1863	}
1864
1865	Py_INCREF(Py_NotImplemented);
1866	return Py_NotImplemented;
1867}
1868
1869
1870/* Get the iterator */
1871static PyObject *
1872instance_getiter(PyInstanceObject *self)
1873{
1874	PyObject *func;
1875
1876	if (iterstr == NULL) {
1877		iterstr = PyString_InternFromString("__iter__");
1878		if (iterstr == NULL)
1879			return NULL;
1880	}
1881	if (getitemstr == NULL) {
1882		getitemstr = PyString_InternFromString("__getitem__");
1883		if (getitemstr == NULL)
1884			return NULL;
1885	}
1886
1887	if ((func = instance_getattr(self, iterstr)) != NULL) {
1888		PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
1889		Py_DECREF(func);
1890		if (res != NULL && !PyIter_Check(res)) {
1891			PyErr_Format(PyExc_TypeError,
1892				     "__iter__ returned non-iterator "
1893				     "of type '%.100s'",
1894				     res->ob_type->tp_name);
1895			Py_DECREF(res);
1896			res = NULL;
1897		}
1898		return res;
1899	}
1900	if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1901		return NULL;
1902	PyErr_Clear();
1903	if ((func = instance_getattr(self, getitemstr)) == NULL) {
1904		PyErr_SetString(PyExc_TypeError,
1905				"iteration over non-sequence");
1906		return NULL;
1907	}
1908	Py_DECREF(func);
1909	return PySeqIter_New((PyObject *)self);
1910}
1911
1912
1913/* Call the iterator's next */
1914static PyObject *
1915instance_iternext(PyInstanceObject *self)
1916{
1917	PyObject *func;
1918
1919	if (nextstr == NULL)
1920		nextstr = PyString_InternFromString("next");
1921
1922	if ((func = instance_getattr(self, nextstr)) != NULL) {
1923		PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
1924		Py_DECREF(func);
1925		if (res != NULL) {
1926			return res;
1927		}
1928		if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
1929			PyErr_Clear();
1930			return NULL;
1931		}
1932		return NULL;
1933	}
1934	PyErr_SetString(PyExc_TypeError, "instance has no next() method");
1935	return NULL;
1936}
1937
1938static PyObject *
1939instance_call(PyObject *func, PyObject *arg, PyObject *kw)
1940{
1941	PyThreadState *tstate = PyThreadState_GET();
1942	PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
1943	if (call == NULL) {
1944		PyInstanceObject *inst = (PyInstanceObject*) func;
1945		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1946			return NULL;
1947		PyErr_Clear();
1948		PyErr_Format(PyExc_AttributeError,
1949			     "%.200s instance has no __call__ method",
1950			     PyString_AsString(inst->in_class->cl_name));
1951		return NULL;
1952	}
1953	/* We must check and increment the recursion depth here. Scenario:
1954	       class A:
1955	           pass
1956	       A.__call__ = A() # that's right
1957	       a = A() # ok
1958	       a() # infinite recursion
1959	   This bounces between instance_call() and PyObject_Call() without
1960	   ever hitting eval_frame() (which has the main recursion check). */
1961	if (tstate->recursion_depth++ > Py_GetRecursionLimit()) {
1962		PyErr_SetString(PyExc_RuntimeError,
1963				"maximum __call__ recursion depth exceeded");
1964		res = NULL;
1965	}
1966	else
1967		res = PyObject_Call(call, arg, kw);
1968	tstate->recursion_depth--;
1969	Py_DECREF(call);
1970	return res;
1971}
1972
1973
1974static PyNumberMethods instance_as_number = {
1975	(binaryfunc)instance_add,		/* nb_add */
1976	(binaryfunc)instance_sub,		/* nb_subtract */
1977	(binaryfunc)instance_mul,		/* nb_multiply */
1978	(binaryfunc)instance_div,		/* nb_divide */
1979	(binaryfunc)instance_mod,		/* nb_remainder */
1980	(binaryfunc)instance_divmod,		/* nb_divmod */
1981	(ternaryfunc)instance_pow,		/* nb_power */
1982	(unaryfunc)instance_neg,		/* nb_negative */
1983	(unaryfunc)instance_pos,		/* nb_positive */
1984	(unaryfunc)instance_abs,		/* nb_absolute */
1985	(inquiry)instance_nonzero,		/* nb_nonzero */
1986	(unaryfunc)instance_invert,		/* nb_invert */
1987	(binaryfunc)instance_lshift,		/* nb_lshift */
1988	(binaryfunc)instance_rshift,		/* nb_rshift */
1989	(binaryfunc)instance_and,		/* nb_and */
1990	(binaryfunc)instance_xor,		/* nb_xor */
1991	(binaryfunc)instance_or,		/* nb_or */
1992	(coercion)instance_coerce,		/* nb_coerce */
1993	(unaryfunc)instance_int,		/* nb_int */
1994	(unaryfunc)instance_long,		/* nb_long */
1995	(unaryfunc)instance_float,		/* nb_float */
1996	(unaryfunc)instance_oct,		/* nb_oct */
1997	(unaryfunc)instance_hex,		/* nb_hex */
1998	(binaryfunc)instance_iadd,		/* nb_inplace_add */
1999	(binaryfunc)instance_isub,		/* nb_inplace_subtract */
2000	(binaryfunc)instance_imul,		/* nb_inplace_multiply */
2001	(binaryfunc)instance_idiv,		/* nb_inplace_divide */
2002	(binaryfunc)instance_imod,		/* nb_inplace_remainder */
2003	(ternaryfunc)instance_ipow,		/* nb_inplace_power */
2004	(binaryfunc)instance_ilshift,		/* nb_inplace_lshift */
2005	(binaryfunc)instance_irshift,		/* nb_inplace_rshift */
2006	(binaryfunc)instance_iand,		/* nb_inplace_and */
2007	(binaryfunc)instance_ixor,		/* nb_inplace_xor */
2008	(binaryfunc)instance_ior,		/* nb_inplace_or */
2009	(binaryfunc)instance_floordiv,		/* nb_floor_divide */
2010	(binaryfunc)instance_truediv,		/* nb_true_divide */
2011	(binaryfunc)instance_ifloordiv,		/* nb_inplace_floor_divide */
2012	(binaryfunc)instance_itruediv,		/* nb_inplace_true_divide */
2013};
2014
2015PyTypeObject PyInstance_Type = {
2016	PyObject_HEAD_INIT(&PyType_Type)
2017	0,
2018	"instance",
2019	sizeof(PyInstanceObject),
2020	0,
2021	(destructor)instance_dealloc,		/* tp_dealloc */
2022	0,					/* tp_print */
2023	0,					/* tp_getattr */
2024	0,					/* tp_setattr */
2025	instance_compare,			/* tp_compare */
2026	(reprfunc)instance_repr,		/* tp_repr */
2027	&instance_as_number,			/* tp_as_number */
2028	&instance_as_sequence,			/* tp_as_sequence */
2029	&instance_as_mapping,			/* tp_as_mapping */
2030	(hashfunc)instance_hash,		/* tp_hash */
2031	instance_call,				/* tp_call */
2032	(reprfunc)instance_str,			/* tp_str */
2033	(getattrofunc)instance_getattr,		/* tp_getattro */
2034	(setattrofunc)instance_setattr,		/* tp_setattro */
2035	0,					/* tp_as_buffer */
2036	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
2037	instance_doc,				/* tp_doc */
2038	(traverseproc)instance_traverse,	/* tp_traverse */
2039	0,					/* tp_clear */
2040	instance_richcompare,			/* tp_richcompare */
2041 	offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
2042	(getiterfunc)instance_getiter,		/* tp_iter */
2043	(iternextfunc)instance_iternext,	/* tp_iternext */
2044	0,					/* tp_methods */
2045	0,					/* tp_members */
2046	0,					/* tp_getset */
2047	0,					/* tp_base */
2048	0,					/* tp_dict */
2049	0,					/* tp_descr_get */
2050	0,					/* tp_descr_set */
2051	0,					/* tp_dictoffset */
2052	0,					/* tp_init */
2053	0,					/* tp_alloc */
2054	instance_new,				/* tp_new */
2055};
2056
2057
2058/* Instance method objects are used for two purposes:
2059   (a) as bound instance methods (returned by instancename.methodname)
2060   (b) as unbound methods (returned by ClassName.methodname)
2061   In case (b), im_self is NULL
2062*/
2063
2064static PyMethodObject *free_list;
2065
2066PyObject *
2067PyMethod_New(PyObject *func, PyObject *self, PyObject *class)
2068{
2069	register PyMethodObject *im;
2070	if (!PyCallable_Check(func)) {
2071		PyErr_BadInternalCall();
2072		return NULL;
2073	}
2074	im = free_list;
2075	if (im != NULL) {
2076		free_list = (PyMethodObject *)(im->im_self);
2077		PyObject_INIT(im, &PyMethod_Type);
2078	}
2079	else {
2080		im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
2081		if (im == NULL)
2082			return NULL;
2083	}
2084	im->im_weakreflist = NULL;
2085	Py_INCREF(func);
2086	im->im_func = func;
2087	Py_XINCREF(self);
2088	im->im_self = self;
2089	Py_XINCREF(class);
2090	im->im_class = class;
2091	_PyObject_GC_TRACK(im);
2092	return (PyObject *)im;
2093}
2094
2095/* Descriptors for PyMethod attributes */
2096
2097/* im_class, im_func and im_self are stored in the PyMethod object */
2098
2099#define OFF(x) offsetof(PyMethodObject, x)
2100
2101static PyMemberDef instancemethod_memberlist[] = {
2102	{"im_class",	T_OBJECT,	OFF(im_class),	READONLY|RESTRICTED,
2103	 "the class associated with a method"},
2104	{"im_func",	T_OBJECT,	OFF(im_func),	READONLY|RESTRICTED,
2105	 "the function (or other callable) implementing a method"},
2106	{"im_self",	T_OBJECT,	OFF(im_self),	READONLY|RESTRICTED,
2107	 "the instance to which a method is bound; None for unbound methods"},
2108	{NULL}	/* Sentinel */
2109};
2110
2111/* The getattr() implementation for PyMethod objects is similar to
2112   PyObject_GenericGetAttr(), but instead of looking in __dict__ it
2113   asks im_self for the attribute.  Then the error handling is a bit
2114   different because we want to preserve the exception raised by the
2115   delegate, unless we have an alternative from our class. */
2116
2117static PyObject *
2118instancemethod_getattro(PyObject *obj, PyObject *name)
2119{
2120	PyMethodObject *im = (PyMethodObject *)obj;
2121	PyTypeObject *tp = obj->ob_type;
2122	PyObject *descr = NULL, *res;
2123	descrgetfunc f = NULL;
2124
2125	if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
2126		if (tp->tp_dict == NULL) {
2127			if (PyType_Ready(tp) < 0)
2128				return NULL;
2129		}
2130		descr = _PyType_Lookup(tp, name);
2131	}
2132
2133	f = NULL;
2134	if (descr != NULL) {
2135		f = TP_DESCR_GET(descr->ob_type);
2136		if (f != NULL && PyDescr_IsData(descr))
2137			return f(descr, obj, (PyObject *)obj->ob_type);
2138	}
2139
2140	res = PyObject_GetAttr(im->im_func, name);
2141	if (res != NULL || !PyErr_ExceptionMatches(PyExc_AttributeError))
2142		return res;
2143
2144	if (f != NULL) {
2145		PyErr_Clear();
2146		return f(descr, obj, (PyObject *)obj->ob_type);
2147	}
2148
2149	if (descr != NULL) {
2150		PyErr_Clear();
2151		Py_INCREF(descr);
2152		return descr;
2153	}
2154
2155	assert(PyErr_Occurred());
2156	return NULL;
2157}
2158
2159PyDoc_STRVAR(instancemethod_doc,
2160"instancemethod(function, instance, class)\n\
2161\n\
2162Create an instance method object.");
2163
2164static PyObject *
2165instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
2166{
2167	PyObject *func;
2168	PyObject *self;
2169	PyObject *classObj;
2170
2171	if (!PyArg_ParseTuple(args, "OOO:instancemethod",
2172			      &func, &self, &classObj))
2173		return NULL;
2174	if (!PyCallable_Check(func)) {
2175		PyErr_SetString(PyExc_TypeError,
2176				"first argument must be callable");
2177		return NULL;
2178	}
2179	if (self == Py_None)
2180		self = NULL;
2181	return PyMethod_New(func, self, classObj);
2182}
2183
2184static void
2185instancemethod_dealloc(register PyMethodObject *im)
2186{
2187	_PyObject_GC_UNTRACK(im);
2188	if (im->im_weakreflist != NULL)
2189		PyObject_ClearWeakRefs((PyObject *)im);
2190	Py_DECREF(im->im_func);
2191	Py_XDECREF(im->im_self);
2192	Py_XDECREF(im->im_class);
2193	im->im_self = (PyObject *)free_list;
2194	free_list = im;
2195}
2196
2197static int
2198instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
2199{
2200	if (a->im_self != b->im_self)
2201		return (a->im_self < b->im_self) ? -1 : 1;
2202	return PyObject_Compare(a->im_func, b->im_func);
2203}
2204
2205static PyObject *
2206instancemethod_repr(PyMethodObject *a)
2207{
2208	PyObject *self = a->im_self;
2209	PyObject *func = a->im_func;
2210	PyObject *klass = a->im_class;
2211	PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
2212	char *sfuncname = "?", *sklassname = "?";
2213
2214	funcname = PyObject_GetAttrString(func, "__name__");
2215	if (funcname == NULL) {
2216		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2217			return NULL;
2218		PyErr_Clear();
2219	}
2220	else if (!PyString_Check(funcname)) {
2221		Py_DECREF(funcname);
2222		funcname = NULL;
2223	}
2224	else
2225		sfuncname = PyString_AS_STRING(funcname);
2226	if (klass == NULL)
2227		klassname = NULL;
2228	else {
2229		klassname = PyObject_GetAttrString(klass, "__name__");
2230		if (klassname == NULL) {
2231			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2232				return NULL;
2233			PyErr_Clear();
2234		}
2235		else if (!PyString_Check(klassname)) {
2236			Py_DECREF(klassname);
2237			klassname = NULL;
2238		}
2239		else
2240			sklassname = PyString_AS_STRING(klassname);
2241	}
2242	if (self == NULL)
2243		result = PyString_FromFormat("<unbound method %s.%s>",
2244					     sklassname, sfuncname);
2245	else {
2246		/* XXX Shouldn't use repr() here! */
2247		PyObject *selfrepr = PyObject_Repr(self);
2248		if (selfrepr == NULL)
2249			goto fail;
2250		if (!PyString_Check(selfrepr)) {
2251			Py_DECREF(selfrepr);
2252			goto fail;
2253		}
2254		result = PyString_FromFormat("<bound method %s.%s of %s>",
2255					     sklassname, sfuncname,
2256					     PyString_AS_STRING(selfrepr));
2257		Py_DECREF(selfrepr);
2258	}
2259  fail:
2260	Py_XDECREF(funcname);
2261	Py_XDECREF(klassname);
2262	return result;
2263}
2264
2265static long
2266instancemethod_hash(PyMethodObject *a)
2267{
2268	long x, y;
2269	if (a->im_self == NULL)
2270		x = PyObject_Hash(Py_None);
2271	else
2272		x = PyObject_Hash(a->im_self);
2273	if (x == -1)
2274		return -1;
2275	y = PyObject_Hash(a->im_func);
2276	if (y == -1)
2277		return -1;
2278	return x ^ y;
2279}
2280
2281static int
2282instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
2283{
2284	int err;
2285	if (im->im_func) {
2286		err = visit(im->im_func, arg);
2287		if (err)
2288			return err;
2289	}
2290	if (im->im_self) {
2291		err = visit(im->im_self, arg);
2292		if (err)
2293			return err;
2294	}
2295	if (im->im_class) {
2296		err = visit(im->im_class, arg);
2297		if (err)
2298			return err;
2299	}
2300	return 0;
2301}
2302
2303static void
2304getclassname(PyObject *class, char *buf, int bufsize)
2305{
2306	PyObject *name;
2307
2308	assert(bufsize > 1);
2309	strcpy(buf, "?"); /* Default outcome */
2310	if (class == NULL)
2311		return;
2312	name = PyObject_GetAttrString(class, "__name__");
2313	if (name == NULL) {
2314		/* This function cannot return an exception */
2315		PyErr_Clear();
2316		return;
2317	}
2318	if (PyString_Check(name)) {
2319		strncpy(buf, PyString_AS_STRING(name), bufsize);
2320		buf[bufsize-1] = '\0';
2321	}
2322	Py_DECREF(name);
2323}
2324
2325static void
2326getinstclassname(PyObject *inst, char *buf, int bufsize)
2327{
2328	PyObject *class;
2329
2330	if (inst == NULL) {
2331		assert(bufsize > strlen("nothing"));
2332		strcpy(buf, "nothing");
2333		return;
2334	}
2335
2336	class = PyObject_GetAttrString(inst, "__class__");
2337	if (class == NULL) {
2338		/* This function cannot return an exception */
2339		PyErr_Clear();
2340		class = (PyObject *)(inst->ob_type);
2341		Py_INCREF(class);
2342	}
2343	getclassname(class, buf, bufsize);
2344	Py_XDECREF(class);
2345}
2346
2347static PyObject *
2348instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
2349{
2350	PyObject *self = PyMethod_GET_SELF(func);
2351	PyObject *class = PyMethod_GET_CLASS(func);
2352	PyObject *result;
2353
2354	func = PyMethod_GET_FUNCTION(func);
2355	if (self == NULL) {
2356		/* Unbound methods must be called with an instance of
2357		   the class (or a derived class) as first argument */
2358		int ok;
2359		if (PyTuple_Size(arg) >= 1)
2360			self = PyTuple_GET_ITEM(arg, 0);
2361		if (self == NULL)
2362			ok = 0;
2363		else {
2364			ok = PyObject_IsInstance(self, class);
2365			if (ok < 0)
2366				return NULL;
2367		}
2368		if (!ok) {
2369			char clsbuf[256];
2370			char instbuf[256];
2371			getclassname(class, clsbuf, sizeof(clsbuf));
2372			getinstclassname(self, instbuf, sizeof(instbuf));
2373			PyErr_Format(PyExc_TypeError,
2374				     "unbound method %s%s must be called with "
2375				     "%s instance as first argument "
2376				     "(got %s%s instead)",
2377				     PyEval_GetFuncName(func),
2378				     PyEval_GetFuncDesc(func),
2379				     clsbuf,
2380				     instbuf,
2381				     self == NULL ? "" : " instance");
2382			return NULL;
2383		}
2384		Py_INCREF(arg);
2385	}
2386	else {
2387		int argcount = PyTuple_Size(arg);
2388		PyObject *newarg = PyTuple_New(argcount + 1);
2389		int i;
2390		if (newarg == NULL)
2391			return NULL;
2392		Py_INCREF(self);
2393		PyTuple_SET_ITEM(newarg, 0, self);
2394		for (i = 0; i < argcount; i++) {
2395			PyObject *v = PyTuple_GET_ITEM(arg, i);
2396			Py_XINCREF(v);
2397			PyTuple_SET_ITEM(newarg, i+1, v);
2398		}
2399		arg = newarg;
2400	}
2401	result = PyObject_Call((PyObject *)func, arg, kw);
2402	Py_DECREF(arg);
2403	return result;
2404}
2405
2406static PyObject *
2407instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *class)
2408{
2409	/* Don't rebind an already bound method, or an unbound method
2410	   of a class that's not a base class of class */
2411	if (PyMethod_GET_SELF(meth) != NULL ||
2412	    (PyMethod_GET_CLASS(meth) != NULL &&
2413	     !PyObject_IsSubclass(class,  PyMethod_GET_CLASS(meth)))) {
2414		Py_INCREF(meth);
2415		return meth;
2416	}
2417	if (obj == Py_None)
2418		obj = NULL;
2419	return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, class);
2420}
2421
2422PyTypeObject PyMethod_Type = {
2423	PyObject_HEAD_INIT(&PyType_Type)
2424	0,
2425	"instancemethod",
2426	sizeof(PyMethodObject),
2427	0,
2428	(destructor)instancemethod_dealloc,	/* tp_dealloc */
2429	0,					/* tp_print */
2430	0,					/* tp_getattr */
2431	0,					/* tp_setattr */
2432	(cmpfunc)instancemethod_compare,	/* tp_compare */
2433	(reprfunc)instancemethod_repr,		/* tp_repr */
2434	0,					/* tp_as_number */
2435	0,					/* tp_as_sequence */
2436	0,					/* tp_as_mapping */
2437	(hashfunc)instancemethod_hash,		/* tp_hash */
2438	instancemethod_call,			/* tp_call */
2439	0,					/* tp_str */
2440	(getattrofunc)instancemethod_getattro,	/* tp_getattro */
2441	PyObject_GenericSetAttr,		/* tp_setattro */
2442	0,					/* tp_as_buffer */
2443	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2444	instancemethod_doc,			/* tp_doc */
2445	(traverseproc)instancemethod_traverse,	/* tp_traverse */
2446	0,					/* tp_clear */
2447	0,					/* tp_richcompare */
2448 	offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
2449	0,					/* tp_iter */
2450	0,					/* tp_iternext */
2451	0,					/* tp_methods */
2452	instancemethod_memberlist,		/* tp_members */
2453	0,					/* tp_getset */
2454	0,					/* tp_base */
2455	0,					/* tp_dict */
2456	instancemethod_descr_get,		/* tp_descr_get */
2457	0,					/* tp_descr_set */
2458	0,					/* tp_dictoffset */
2459	0,					/* tp_init */
2460	0,					/* tp_alloc */
2461	instancemethod_new,			/* tp_new */
2462};
2463
2464/* Clear out the free list */
2465
2466void
2467PyMethod_Fini(void)
2468{
2469	while (free_list) {
2470		PyMethodObject *im = free_list;
2471		free_list = (PyMethodObject *)(im->im_self);
2472		PyObject_GC_Del(im);
2473	}
2474}
2475