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