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