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