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