classobject.c revision 3202c6fac875615efae017c6f6219a498f6fc90e
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	/* Temporarily resurrect the object. */
519#ifdef Py_TRACE_REFS
520#ifndef Py_REF_DEBUG
521#   error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
522#endif
523	/* much too complicated if Py_TRACE_REFS defined */
524	inst->ob_type = &PyInstance_Type;
525	_Py_NewReference((PyObject *)inst);
526#ifdef COUNT_ALLOCS
527	/* compensate for boost in _Py_NewReference; note that
528	 * _Py_RefTotal was also boosted; we'll knock that down later.
529	 */
530	inst->ob_type->tp_alloc--;
531#endif
532#else /* !Py_TRACE_REFS */
533	/* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
534	Py_INCREF(inst);
535#endif /* !Py_TRACE_REFS */
536
537	/* Save the current exception, if any. */
538	PyErr_Fetch(&error_type, &error_value, &error_traceback);
539	/* Execute __del__ method, if any. */
540	if (delstr == NULL)
541		delstr = PyString_InternFromString("__del__");
542	if ((del = instance_getattr2(inst, delstr)) != NULL) {
543		PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
544		if (res == NULL)
545			PyErr_WriteUnraisable(del);
546		else
547			Py_DECREF(res);
548		Py_DECREF(del);
549	}
550	/* Restore the saved exception. */
551	PyErr_Restore(error_type, error_value, error_traceback);
552	/* Undo the temporary resurrection; can't use DECREF here, it would
553	 * cause a recursive call.
554	 */
555#ifdef Py_REF_DEBUG
556	/* _Py_RefTotal was boosted either by _Py_NewReference or
557	 * Py_INCREF above.
558	 */
559	_Py_RefTotal--;
560#endif
561	if (--inst->ob_refcnt > 0) {
562#ifdef COUNT_ALLOCS
563		inst->ob_type->tp_free--;
564#endif
565		return; /* __del__ added a reference; don't delete now */
566	}
567#ifdef Py_TRACE_REFS
568	_Py_ForgetReference((PyObject *)inst);
569#ifdef COUNT_ALLOCS
570	/* compensate for increment in _Py_ForgetReference */
571	inst->ob_type->tp_free--;
572#endif
573#ifndef WITH_CYCLE_GC
574	inst->ob_type = NULL;
575#endif
576#endif
577	PyObject_GC_Fini(inst);
578	Py_DECREF(inst->in_class);
579	Py_XDECREF(inst->in_dict);
580	inst = (PyInstanceObject *) PyObject_AS_GC(inst);
581	PyObject_DEL(inst);
582}
583
584static PyObject *
585instance_getattr1(register PyInstanceObject *inst, PyObject *name)
586{
587	register PyObject *v;
588	register char *sname = PyString_AsString(name);
589	if (sname[0] == '_' && sname[1] == '_') {
590		if (strcmp(sname, "__dict__") == 0) {
591			if (PyEval_GetRestricted()) {
592				PyErr_SetString(PyExc_RuntimeError,
593			"instance.__dict__ not accessible in restricted mode");
594				return NULL;
595			}
596			Py_INCREF(inst->in_dict);
597			return inst->in_dict;
598		}
599		if (strcmp(sname, "__class__") == 0) {
600			Py_INCREF(inst->in_class);
601			return (PyObject *)inst->in_class;
602		}
603	}
604	v = instance_getattr2(inst, name);
605	if (v == NULL) {
606		PyErr_Format(PyExc_AttributeError,
607			     "%.50s instance has no attribute '%.400s'",
608			     PyString_AS_STRING(inst->in_class->cl_name), sname);
609	}
610	return v;
611}
612
613static PyObject *
614instance_getattr2(register PyInstanceObject *inst, PyObject *name)
615{
616	register PyObject *v;
617	PyClassObject *class;
618	class = NULL;
619	v = PyDict_GetItem(inst->in_dict, name);
620	if (v == NULL) {
621		v = class_lookup(inst->in_class, name, &class);
622		if (v == NULL)
623			return v;
624	}
625	Py_INCREF(v);
626	if (class != NULL) {
627		if (PyFunction_Check(v)) {
628			PyObject *w = PyMethod_New(v, (PyObject *)inst,
629						   (PyObject *)class);
630			Py_DECREF(v);
631			v = w;
632		}
633		else if (PyMethod_Check(v)) {
634			PyObject *im_class = PyMethod_Class(v);
635			/* Only if classes are compatible */
636			if (PyClass_IsSubclass((PyObject *)class, im_class)) {
637				PyObject *im_func = PyMethod_Function(v);
638				PyObject *w = PyMethod_New(im_func,
639						(PyObject *)inst, im_class);
640				Py_DECREF(v);
641				v = w;
642			}
643		}
644	}
645	return v;
646}
647
648static PyObject *
649instance_getattr(register PyInstanceObject *inst, PyObject *name)
650{
651	register PyObject *func, *res;
652	res = instance_getattr1(inst, name);
653	if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
654		PyObject *args;
655		PyErr_Clear();
656		args = Py_BuildValue("(OO)", inst, name);
657		if (args == NULL)
658			return NULL;
659		res = PyEval_CallObject(func, args);
660		Py_DECREF(args);
661	}
662	return res;
663}
664
665static int
666instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
667{
668	if (v == NULL) {
669		int rv = PyDict_DelItem(inst->in_dict, name);
670		if (rv < 0)
671			PyErr_Format(PyExc_AttributeError,
672				     "%.50s instance has no attribute '%.400s'",
673				     PyString_AS_STRING(inst->in_class->cl_name),
674				     PyString_AS_STRING(name));
675		return rv;
676	}
677	else
678		return PyDict_SetItem(inst->in_dict, name, v);
679}
680
681static int
682instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
683{
684	PyObject *func, *args, *res, *tmp;
685	char *sname = PyString_AsString(name);
686	if (sname[0] == '_' && sname[1] == '_') {
687		int n = PyString_Size(name);
688		if (sname[n-1] == '_' && sname[n-2] == '_') {
689			if (strcmp(sname, "__dict__") == 0) {
690				if (PyEval_GetRestricted()) {
691					PyErr_SetString(PyExc_RuntimeError,
692				 "__dict__ not accessible in restricted mode");
693					return -1;
694				}
695				if (v == NULL || !PyDict_Check(v)) {
696				    PyErr_SetString(PyExc_TypeError,
697				       "__dict__ must be set to a dictionary");
698				    return -1;
699				}
700				tmp = inst->in_dict;
701				Py_INCREF(v);
702				inst->in_dict = v;
703				Py_DECREF(tmp);
704				return 0;
705			}
706			if (strcmp(sname, "__class__") == 0) {
707				if (PyEval_GetRestricted()) {
708					PyErr_SetString(PyExc_RuntimeError,
709				"__class__ not accessible in restricted mode");
710					return -1;
711				}
712				if (v == NULL || !PyClass_Check(v)) {
713					PyErr_SetString(PyExc_TypeError,
714					   "__class__ must be set to a class");
715					return -1;
716				}
717				tmp = (PyObject *)(inst->in_class);
718				Py_INCREF(v);
719				inst->in_class = (PyClassObject *)v;
720				Py_DECREF(tmp);
721				return 0;
722			}
723		}
724	}
725	if (v == NULL)
726		func = inst->in_class->cl_delattr;
727	else
728		func = inst->in_class->cl_setattr;
729	if (func == NULL)
730		return instance_setattr1(inst, name, v);
731	if (v == NULL)
732		args = Py_BuildValue("(OO)", inst, name);
733	else
734		args = Py_BuildValue("(OOO)", inst, name, v);
735	if (args == NULL)
736		return -1;
737	res = PyEval_CallObject(func, args);
738	Py_DECREF(args);
739	if (res == NULL)
740		return -1;
741	Py_DECREF(res);
742	return 0;
743}
744
745static PyObject *
746instance_repr(PyInstanceObject *inst)
747{
748	PyObject *func;
749	PyObject *res;
750	static PyObject *reprstr;
751
752	if (reprstr == NULL)
753		reprstr = PyString_InternFromString("__repr__");
754	func = instance_getattr(inst, reprstr);
755	if (func == NULL) {
756		char buf[140];
757		PyObject *classname = inst->in_class->cl_name;
758		PyObject *mod = PyDict_GetItemString(
759			inst->in_class->cl_dict, "__module__");
760		char *cname;
761		if (classname != NULL && PyString_Check(classname))
762			cname = PyString_AsString(classname);
763		else
764			cname = "?";
765		PyErr_Clear();
766		if (mod == NULL || !PyString_Check(mod))
767			sprintf(buf, "<?.%.100s instance at %p>",
768				cname, inst);
769		else
770			sprintf(buf, "<%.50s.%.50s instance at %p>",
771				PyString_AsString(mod),
772				cname, inst);
773		return PyString_FromString(buf);
774	}
775	res = PyEval_CallObject(func, (PyObject *)NULL);
776	Py_DECREF(func);
777	return res;
778}
779
780static long
781instance_hash(PyInstanceObject *inst)
782{
783	PyObject *func;
784	PyObject *res;
785	long outcome;
786	static PyObject *hashstr, *eqstr, *cmpstr;
787
788	if (hashstr == NULL)
789		hashstr = PyString_InternFromString("__hash__");
790	func = instance_getattr(inst, hashstr);
791	if (func == NULL) {
792		/* If there is no __eq__ and no __cmp__ method, we hash on the
793		   address.  If an __eq__ or __cmp__ method exists, there must
794		   be a __hash__. */
795		PyErr_Clear();
796		if (eqstr == NULL)
797			eqstr = PyString_InternFromString("__eq__");
798		func = instance_getattr(inst, eqstr);
799		if (func == NULL) {
800			PyErr_Clear();
801			if (cmpstr == NULL)
802				cmpstr = PyString_InternFromString("__cmp__");
803			func = instance_getattr(inst, cmpstr);
804			if (func == NULL) {
805				PyErr_Clear();
806				return _Py_HashPointer(inst);
807			}
808		}
809		PyErr_SetString(PyExc_TypeError, "unhashable instance");
810		return -1;
811	}
812	res = PyEval_CallObject(func, (PyObject *)NULL);
813	Py_DECREF(func);
814	if (res == NULL)
815		return -1;
816	if (PyInt_Check(res)) {
817		outcome = PyInt_AsLong(res);
818		if (outcome == -1)
819			outcome = -2;
820	}
821	else {
822		PyErr_SetString(PyExc_TypeError,
823				"__hash__() should return an int");
824		outcome = -1;
825	}
826	Py_DECREF(res);
827	return outcome;
828}
829
830static int
831instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
832{
833	int err;
834	if (o->in_class) {
835		err = visit((PyObject *)(o->in_class), arg);
836		if (err)
837			return err;
838	}
839	if (o->in_dict) {
840		err = visit(o->in_dict, arg);
841		if (err)
842			return err;
843	}
844	return 0;
845}
846
847static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
848
849static int
850instance_length(PyInstanceObject *inst)
851{
852	PyObject *func;
853	PyObject *res;
854	int outcome;
855
856	if (lenstr == NULL)
857		lenstr = PyString_InternFromString("__len__");
858	func = instance_getattr(inst, lenstr);
859	if (func == NULL)
860		return -1;
861	res = PyEval_CallObject(func, (PyObject *)NULL);
862	Py_DECREF(func);
863	if (res == NULL)
864		return -1;
865	if (PyInt_Check(res)) {
866		outcome = PyInt_AsLong(res);
867		if (outcome < 0)
868			PyErr_SetString(PyExc_ValueError,
869					"__len__() should return >= 0");
870	}
871	else {
872		PyErr_SetString(PyExc_TypeError,
873				"__len__() should return an int");
874		outcome = -1;
875	}
876	Py_DECREF(res);
877	return outcome;
878}
879
880static PyObject *
881instance_subscript(PyInstanceObject *inst, PyObject *key)
882{
883	PyObject *func;
884	PyObject *arg;
885	PyObject *res;
886
887	if (getitemstr == NULL)
888		getitemstr = PyString_InternFromString("__getitem__");
889	func = instance_getattr(inst, getitemstr);
890	if (func == NULL)
891		return NULL;
892	arg = Py_BuildValue("(O)", key);
893	if (arg == NULL) {
894		Py_DECREF(func);
895		return NULL;
896	}
897	res = PyEval_CallObject(func, arg);
898	Py_DECREF(func);
899	Py_DECREF(arg);
900	return res;
901}
902
903static int
904instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
905{
906	PyObject *func;
907	PyObject *arg;
908	PyObject *res;
909
910	if (value == NULL) {
911		if (delitemstr == NULL)
912			delitemstr = PyString_InternFromString("__delitem__");
913		func = instance_getattr(inst, delitemstr);
914	}
915	else {
916		if (setitemstr == NULL)
917			setitemstr = PyString_InternFromString("__setitem__");
918		func = instance_getattr(inst, setitemstr);
919	}
920	if (func == NULL)
921		return -1;
922	if (value == NULL)
923		arg = Py_BuildValue("(O)", key);
924	else
925		arg = Py_BuildValue("(OO)", key, value);
926	if (arg == NULL) {
927		Py_DECREF(func);
928		return -1;
929	}
930	res = PyEval_CallObject(func, arg);
931	Py_DECREF(func);
932	Py_DECREF(arg);
933	if (res == NULL)
934		return -1;
935	Py_DECREF(res);
936	return 0;
937}
938
939static PyMappingMethods instance_as_mapping = {
940	(inquiry)instance_length,		/* mp_length */
941	(binaryfunc)instance_subscript,		/* mp_subscript */
942	(objobjargproc)instance_ass_subscript,	/* mp_ass_subscript */
943};
944
945static PyObject *
946instance_item(PyInstanceObject *inst, int i)
947{
948	PyObject *func, *arg, *res;
949
950	if (getitemstr == NULL)
951		getitemstr = PyString_InternFromString("__getitem__");
952	func = instance_getattr(inst, getitemstr);
953	if (func == NULL)
954		return NULL;
955	arg = Py_BuildValue("(i)", i);
956	if (arg == NULL) {
957		Py_DECREF(func);
958		return NULL;
959	}
960	res = PyEval_CallObject(func, arg);
961	Py_DECREF(func);
962	Py_DECREF(arg);
963	return res;
964}
965
966static PyObject *
967sliceobj_from_intint(int i, int j)
968{
969	PyObject *start, *end, *res;
970
971	start = PyInt_FromLong((long)i);
972	if (!start)
973		return NULL;
974
975	end = PyInt_FromLong((long)j);
976	if (!end) {
977		Py_DECREF(start);
978		return NULL;
979	}
980	res = PySlice_New(start, end, NULL);
981	Py_DECREF(start);
982	Py_DECREF(end);
983	return res;
984}
985
986
987static PyObject *
988instance_slice(PyInstanceObject *inst, int i, int j)
989{
990	PyObject *func, *arg, *res;
991	static PyObject *getslicestr;
992
993	if (getslicestr == NULL)
994		getslicestr = PyString_InternFromString("__getslice__");
995	func = instance_getattr(inst, getslicestr);
996
997	if (func == NULL) {
998		PyErr_Clear();
999
1000		if (getitemstr == NULL)
1001			getitemstr = PyString_InternFromString("__getitem__");
1002		func = instance_getattr(inst, getitemstr);
1003		if (func == NULL)
1004			return NULL;
1005		arg = Py_BuildValue("(N)", sliceobj_from_intint(i, j));
1006	} else
1007		arg = Py_BuildValue("(ii)", i, j);
1008
1009	if (arg == NULL) {
1010		Py_DECREF(func);
1011		return NULL;
1012	}
1013	res = PyEval_CallObject(func, arg);
1014	Py_DECREF(func);
1015	Py_DECREF(arg);
1016	return res;
1017}
1018
1019static int
1020instance_ass_item(PyInstanceObject *inst, int i, PyObject *item)
1021{
1022	PyObject *func, *arg, *res;
1023
1024	if (item == NULL) {
1025		if (delitemstr == NULL)
1026			delitemstr = PyString_InternFromString("__delitem__");
1027		func = instance_getattr(inst, delitemstr);
1028	}
1029	else {
1030		if (setitemstr == NULL)
1031			setitemstr = PyString_InternFromString("__setitem__");
1032		func = instance_getattr(inst, setitemstr);
1033	}
1034	if (func == NULL)
1035		return -1;
1036	if (item == NULL)
1037		arg = Py_BuildValue("i", i);
1038	else
1039		arg = Py_BuildValue("(iO)", i, item);
1040	if (arg == NULL) {
1041		Py_DECREF(func);
1042		return -1;
1043	}
1044	res = PyEval_CallObject(func, arg);
1045	Py_DECREF(func);
1046	Py_DECREF(arg);
1047	if (res == NULL)
1048		return -1;
1049	Py_DECREF(res);
1050	return 0;
1051}
1052
1053static int
1054instance_ass_slice(PyInstanceObject *inst, int i, int j, PyObject *value)
1055{
1056	PyObject *func, *arg, *res;
1057	static PyObject *setslicestr, *delslicestr;
1058
1059	if (value == NULL) {
1060		if (delslicestr == NULL)
1061			delslicestr =
1062				PyString_InternFromString("__delslice__");
1063		func = instance_getattr(inst, delslicestr);
1064		if (func == NULL) {
1065			PyErr_Clear();
1066			if (delitemstr == NULL)
1067				delitemstr =
1068				    PyString_InternFromString("__delitem__");
1069			func = instance_getattr(inst, delitemstr);
1070			if (func == NULL)
1071				return -1;
1072
1073			arg = Py_BuildValue("(N)",
1074					    sliceobj_from_intint(i, j));
1075		} else
1076			arg = Py_BuildValue("(ii)", i, j);
1077	}
1078	else {
1079		if (setslicestr == NULL)
1080			setslicestr =
1081				PyString_InternFromString("__setslice__");
1082		func = instance_getattr(inst, setslicestr);
1083		if (func == NULL) {
1084			PyErr_Clear();
1085			if (setitemstr == NULL)
1086				setitemstr =
1087				    PyString_InternFromString("__setitem__");
1088			func = instance_getattr(inst, setitemstr);
1089			if (func == NULL)
1090				return -1;
1091
1092			arg = Py_BuildValue("(NO)",
1093					    sliceobj_from_intint(i, j), value);
1094		} else
1095			arg = Py_BuildValue("(iiO)", i, j, value);
1096	}
1097	if (arg == NULL) {
1098		Py_DECREF(func);
1099		return -1;
1100	}
1101	res = PyEval_CallObject(func, arg);
1102	Py_DECREF(func);
1103	Py_DECREF(arg);
1104	if (res == NULL)
1105		return -1;
1106	Py_DECREF(res);
1107	return 0;
1108}
1109
1110static int instance_contains(PyInstanceObject *inst, PyObject *member)
1111{
1112	static PyObject *__contains__;
1113	PyObject *func, *arg, *res;
1114	int ret;
1115
1116	if(__contains__ == NULL) {
1117		__contains__ = PyString_InternFromString("__contains__");
1118		if(__contains__ == NULL)
1119			return -1;
1120	}
1121	func = instance_getattr(inst, __contains__);
1122	if(func == NULL) {
1123		/* fall back to previous behavior */
1124		int i, cmp_res;
1125
1126		if(!PyErr_ExceptionMatches(PyExc_AttributeError))
1127			return -1;
1128		PyErr_Clear();
1129		for(i=0;;i++) {
1130			PyObject *obj = instance_item(inst, i);
1131			int ret = 0;
1132
1133			if(obj == NULL) {
1134				if(!PyErr_ExceptionMatches(PyExc_IndexError))
1135					return -1;
1136				PyErr_Clear();
1137				return 0;
1138			}
1139			if(PyObject_Cmp(obj, member, &cmp_res) == -1)
1140				ret = -1;
1141			if(cmp_res == 0)
1142				ret = 1;
1143			Py_DECREF(obj);
1144			if(ret)
1145				return ret;
1146		}
1147	}
1148	arg = Py_BuildValue("(O)", member);
1149	if(arg == NULL) {
1150		Py_DECREF(func);
1151		return -1;
1152	}
1153	res = PyEval_CallObject(func, arg);
1154	Py_DECREF(func);
1155	Py_DECREF(arg);
1156	if(res == NULL)
1157		return -1;
1158	ret = PyObject_IsTrue(res);
1159	Py_DECREF(res);
1160	return ret;
1161}
1162
1163static PySequenceMethods
1164instance_as_sequence = {
1165	(inquiry)instance_length,		/* sq_length */
1166	0,					/* sq_concat */
1167	0,					/* sq_repeat */
1168	(intargfunc)instance_item,		/* sq_item */
1169	(intintargfunc)instance_slice,		/* sq_slice */
1170	(intobjargproc)instance_ass_item,	/* sq_ass_item */
1171	(intintobjargproc)instance_ass_slice,	/* sq_ass_slice */
1172	(objobjproc)instance_contains,		/* sq_contains */
1173};
1174
1175static PyObject *
1176generic_unary_op(PyInstanceObject *self, PyObject *methodname)
1177{
1178	PyObject *func, *res;
1179
1180	if ((func = instance_getattr(self, methodname)) == NULL)
1181		return NULL;
1182	res = PyEval_CallObject(func, (PyObject *)NULL);
1183	Py_DECREF(func);
1184	return res;
1185}
1186
1187static PyObject *
1188generic_binary_op(PyObject *v, PyObject *w, char *opname)
1189{
1190	PyObject *result;
1191	PyObject *args;
1192	PyObject *func = PyObject_GetAttrString(v, opname);
1193	if (func == NULL) {
1194		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1195			return NULL;
1196		PyErr_Clear();
1197		Py_INCREF(Py_NotImplemented);
1198		return Py_NotImplemented;
1199	}
1200	args = Py_BuildValue("(O)", w);
1201	if (args == NULL) {
1202		Py_DECREF(func);
1203		return NULL;
1204	}
1205	result = PyEval_CallObject(func, args);
1206	Py_DECREF(args);
1207	Py_DECREF(func);
1208	return result;
1209}
1210
1211
1212static PyObject *coerce_obj;
1213
1214/* Try one half of a binary operator involving a class instance. */
1215static PyObject *
1216half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
1217		int swapped)
1218{
1219	PyObject *args;
1220	PyObject *coercefunc;
1221	PyObject *coerced = NULL;
1222	PyObject *v1;
1223	PyObject *result;
1224
1225	if (!PyInstance_Check(v)) {
1226		Py_INCREF(Py_NotImplemented);
1227		return Py_NotImplemented;
1228	}
1229
1230	if (coerce_obj == NULL) {
1231		coerce_obj = PyString_InternFromString("__coerce__");
1232		if (coerce_obj == NULL)
1233			return NULL;
1234	}
1235	coercefunc = PyObject_GetAttr(v, coerce_obj);
1236	if (coercefunc == NULL) {
1237		PyErr_Clear();
1238		return generic_binary_op(v, w, opname);
1239	}
1240
1241	args = Py_BuildValue("(O)", w);
1242	if (args == NULL) {
1243		return NULL;
1244	}
1245	coerced = PyEval_CallObject(coercefunc, args);
1246	Py_DECREF(args);
1247	Py_DECREF(coercefunc);
1248	if (coerced == NULL) {
1249		return NULL;
1250	}
1251	if (coerced == Py_None || coerced == Py_NotImplemented) {
1252		Py_DECREF(coerced);
1253		return generic_binary_op(v, w, opname);
1254	}
1255	if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1256		Py_DECREF(coerced);
1257		PyErr_SetString(PyExc_TypeError,
1258				"coercion should return None or 2-tuple");
1259		return NULL;
1260	}
1261	v1 = PyTuple_GetItem(coerced, 0);
1262	w = PyTuple_GetItem(coerced, 1);
1263	if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
1264		/* prevent recursion if __coerce__ returns self as the first
1265		 * argument */
1266		result = generic_binary_op(v1, w, opname);
1267	} else {
1268		if (swapped)
1269			result = (thisfunc)(w, v1);
1270		else
1271			result = (thisfunc)(v1, w);
1272	}
1273	Py_DECREF(coerced);
1274	return result;
1275}
1276
1277/* Implement a binary operator involving at least one class instance. */
1278static PyObject *
1279do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1280                   binaryfunc thisfunc)
1281{
1282	PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1283	if (result == Py_NotImplemented) {
1284		Py_DECREF(result);
1285		result = half_binop(w, v, ropname, thisfunc, 1);
1286	}
1287	return result;
1288}
1289
1290static PyObject *
1291do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
1292			char *ropname, binaryfunc thisfunc)
1293{
1294	PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1295	if (result == Py_NotImplemented) {
1296		Py_DECREF(result);
1297		result = do_binop(v, w, opname, ropname, thisfunc);
1298	}
1299	return result;
1300}
1301
1302static int
1303instance_coerce(PyObject **pv, PyObject **pw)
1304{
1305	PyObject *v = *pv;
1306	PyObject *w = *pw;
1307	PyObject *coercefunc;
1308	PyObject *args;
1309	PyObject *coerced;
1310
1311	if (coerce_obj == NULL) {
1312		coerce_obj = PyString_InternFromString("__coerce__");
1313		if (coerce_obj == NULL)
1314			return -1;
1315	}
1316	coercefunc = PyObject_GetAttr(v, coerce_obj);
1317	if (coercefunc == NULL) {
1318		/* No __coerce__ method */
1319		PyErr_Clear();
1320		return 1;
1321	}
1322	/* Has __coerce__ method: call it */
1323	args = Py_BuildValue("(O)", w);
1324	if (args == NULL) {
1325		return -1;
1326	}
1327	coerced = PyEval_CallObject(coercefunc, args);
1328	Py_DECREF(args);
1329	Py_DECREF(coercefunc);
1330	if (coerced == NULL) {
1331		/* __coerce__ call raised an exception */
1332		return -1;
1333	}
1334	if (coerced == Py_None || coerced == Py_NotImplemented) {
1335		/* __coerce__ says "I can't do it" */
1336		Py_DECREF(coerced);
1337		return 1;
1338	}
1339	if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1340		/* __coerce__ return value is malformed */
1341		Py_DECREF(coerced);
1342		PyErr_SetString(PyExc_TypeError,
1343			   "coercion should return None or 2-tuple");
1344		return -1;
1345	}
1346	/* __coerce__ returned two new values */
1347	*pv = PyTuple_GetItem(coerced, 0);
1348	*pw = PyTuple_GetItem(coerced, 1);
1349	Py_INCREF(*pv);
1350	Py_INCREF(*pw);
1351	Py_DECREF(coerced);
1352	return 0;
1353}
1354
1355#define UNARY(funcname, methodname) \
1356static PyObject *funcname(PyInstanceObject *self) { \
1357	static PyObject *o; \
1358	if (o == NULL) o = PyString_InternFromString(methodname); \
1359	return generic_unary_op(self, o); \
1360}
1361
1362#define BINARY(f, m, n) \
1363static PyObject *f(PyObject *v, PyObject *w) { \
1364	return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1365}
1366
1367#define BINARY_INPLACE(f, m, n) \
1368static PyObject *f(PyObject *v, PyObject *w) { \
1369	return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1370			"__r" m "__", n); \
1371}
1372
1373UNARY(instance_neg, "__neg__")
1374UNARY(instance_pos, "__pos__")
1375UNARY(instance_abs, "__abs__")
1376
1377BINARY(instance_or, "or", PyNumber_Or)
1378BINARY(instance_and, "and", PyNumber_And)
1379BINARY(instance_xor, "xor", PyNumber_Xor)
1380BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1381BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1382BINARY(instance_add, "add", PyNumber_Add)
1383BINARY(instance_sub, "sub", PyNumber_Subtract)
1384BINARY(instance_mul, "mul", PyNumber_Multiply)
1385BINARY(instance_div, "div", PyNumber_Divide)
1386BINARY(instance_mod, "mod", PyNumber_Remainder)
1387BINARY(instance_divmod, "divmod", PyNumber_Divmod)
1388
1389BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1390BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1391BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1392BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1393BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1394BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1395BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1396BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1397BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1398BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
1399
1400/* Try a 3-way comparison, returning an int; v is an instance.  Return:
1401   -2 for an exception;
1402   -1 if v < w;
1403   0 if v == w;
1404   1 if v > w;
1405   2 if this particular 3-way comparison is not implemented or undefined.
1406*/
1407static int
1408half_cmp(PyObject *v, PyObject *w)
1409{
1410	static PyObject *cmp_obj;
1411	PyObject *args;
1412	PyObject *cmp_func;
1413	PyObject *result;
1414	long l;
1415
1416	assert(PyInstance_Check(v));
1417
1418	if (cmp_obj == NULL) {
1419		cmp_obj = PyString_InternFromString("__cmp__");
1420		if (cmp_obj == NULL)
1421			return -2;
1422	}
1423
1424	cmp_func = PyObject_GetAttr(v, cmp_obj);
1425	if (cmp_func == NULL) {
1426		PyErr_Clear();
1427		return 2;
1428	}
1429
1430	args = Py_BuildValue("(O)", w);
1431	if (args == NULL)
1432		return -2;
1433
1434	result = PyEval_CallObject(cmp_func, args);
1435	Py_DECREF(args);
1436	Py_DECREF(cmp_func);
1437
1438	if (result == NULL)
1439		return -2;
1440
1441	if (result == Py_NotImplemented) {
1442		Py_DECREF(result);
1443		return 2;
1444	}
1445
1446	l = PyInt_AsLong(result);
1447	Py_DECREF(result);
1448	if (l == -1 && PyErr_Occurred()) {
1449		PyErr_SetString(PyExc_TypeError,
1450			     "comparison did not return an int");
1451		return -2;
1452	}
1453
1454	return l < 0 ? -1 : l > 0 ? 1 : 0;
1455}
1456
1457/* Try a 3-way comparison, returning an int; either v or w is an instance.
1458   We first try a coercion.  Return:
1459   -2 for an exception;
1460   -1 if v < w;
1461   0 if v == w;
1462   1 if v > w;
1463   2 if this particular 3-way comparison is not implemented or undefined.
1464   THIS IS ONLY CALLED FROM object.c!
1465*/
1466static int
1467instance_compare(PyObject *v, PyObject *w)
1468{
1469	int c;
1470
1471	c = PyNumber_CoerceEx(&v, &w);
1472	if (c < 0)
1473		return -2;
1474	if (c == 0) {
1475		/* If neither is now an instance, use regular comparison */
1476		if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1477			c = PyObject_Compare(v, w);
1478			Py_DECREF(v);
1479			Py_DECREF(w);
1480			if (PyErr_Occurred())
1481				return -2;
1482			return c < 0 ? -1 : c > 0 ? 1 : 0;
1483		}
1484	}
1485	else {
1486		/* The coercion didn't do anything.
1487		   Treat this the same as returning v and w unchanged. */
1488		Py_INCREF(v);
1489		Py_INCREF(w);
1490	}
1491
1492	if (PyInstance_Check(v)) {
1493		c = half_cmp(v, w);
1494		if (c <= 1) {
1495			Py_DECREF(v);
1496			Py_DECREF(w);
1497			return c;
1498		}
1499	}
1500	if (PyInstance_Check(w)) {
1501		c = half_cmp(w, v);
1502		if (c <= 1) {
1503			Py_DECREF(v);
1504			Py_DECREF(w);
1505			if (c >= -1)
1506				c = -c;
1507			return c;
1508		}
1509	}
1510	Py_DECREF(v);
1511	Py_DECREF(w);
1512	return 2;
1513}
1514
1515static int
1516instance_nonzero(PyInstanceObject *self)
1517{
1518	PyObject *func, *res;
1519	long outcome;
1520	static PyObject *nonzerostr;
1521
1522	if (nonzerostr == NULL)
1523		nonzerostr = PyString_InternFromString("__nonzero__");
1524	if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1525		PyErr_Clear();
1526		if (lenstr == NULL)
1527			lenstr = PyString_InternFromString("__len__");
1528		if ((func = instance_getattr(self, lenstr)) == NULL) {
1529			PyErr_Clear();
1530			/* Fall back to the default behavior:
1531			   all instances are nonzero */
1532			return 1;
1533		}
1534	}
1535	res = PyEval_CallObject(func, (PyObject *)NULL);
1536	Py_DECREF(func);
1537	if (res == NULL)
1538		return -1;
1539	if (!PyInt_Check(res)) {
1540		Py_DECREF(res);
1541		PyErr_SetString(PyExc_TypeError,
1542				"__nonzero__ should return an int");
1543		return -1;
1544	}
1545	outcome = PyInt_AsLong(res);
1546	Py_DECREF(res);
1547	if (outcome < 0) {
1548		PyErr_SetString(PyExc_ValueError,
1549				"__nonzero__ should return >= 0");
1550		return -1;
1551	}
1552	return outcome > 0;
1553}
1554
1555UNARY(instance_invert, "__invert__")
1556UNARY(instance_int, "__int__")
1557UNARY(instance_long, "__long__")
1558UNARY(instance_float, "__float__")
1559UNARY(instance_oct, "__oct__")
1560UNARY(instance_hex, "__hex__")
1561
1562static PyObject *
1563bin_power(PyObject *v, PyObject *w)
1564{
1565	return PyNumber_Power(v, w, Py_None);
1566}
1567
1568/* This version is for ternary calls only (z != None) */
1569static PyObject *
1570instance_pow(PyObject *v, PyObject *w, PyObject *z)
1571{
1572	if (z == Py_None) {
1573		return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1574	}
1575	else {
1576		PyObject *func;
1577		PyObject *args;
1578		PyObject *result;
1579
1580		/* XXX Doesn't do coercions... */
1581		func = PyObject_GetAttrString(v, "__pow__");
1582		if (func == NULL)
1583			return NULL;
1584		args = Py_BuildValue("(OO)", w, z);
1585		if (args == NULL) {
1586			Py_DECREF(func);
1587			return NULL;
1588		}
1589		result = PyEval_CallObject(func, args);
1590		Py_DECREF(func);
1591		Py_DECREF(args);
1592		return result;
1593	}
1594}
1595
1596static PyObject *
1597bin_inplace_power(PyObject *v, PyObject *w)
1598{
1599	return PyNumber_InPlacePower(v, w, Py_None);
1600}
1601
1602
1603static PyObject *
1604instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1605{
1606	if (z == Py_None) {
1607		return do_binop_inplace(v, w, "__ipow__", "__pow__",
1608			"__rpow__", bin_inplace_power);
1609	}
1610	else {
1611		/* XXX Doesn't do coercions... */
1612		PyObject *func;
1613		PyObject *args;
1614		PyObject *result;
1615
1616		func = PyObject_GetAttrString(v, "__ipow__");
1617		if (func == NULL) {
1618			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1619				return NULL;
1620			PyErr_Clear();
1621			return instance_pow(v, w, z);
1622		}
1623		args = Py_BuildValue("(OO)", w, z);
1624		if (args == NULL) {
1625			Py_DECREF(func);
1626			return NULL;
1627		}
1628		result = PyEval_CallObject(func, args);
1629		Py_DECREF(func);
1630		Py_DECREF(args);
1631		return result;
1632	}
1633}
1634
1635
1636/* Map rich comparison operators to their __xx__ namesakes */
1637static char *name_op[] = {
1638	"__lt__",
1639	"__le__",
1640	"__eq__",
1641	"__ne__",
1642	"__gt__",
1643	"__ge__",
1644};
1645
1646static PyObject *
1647half_richcompare(PyObject *v, PyObject *w, int op)
1648{
1649	PyObject *name;
1650	PyObject *method;
1651	PyObject *args;
1652	PyObject *res;
1653
1654	assert(PyInstance_Check(v));
1655
1656	name = PyString_InternFromString(name_op[op]);
1657	if (name == NULL)
1658		return NULL;
1659
1660	method = PyObject_GetAttr(v, name);
1661	Py_DECREF(name);
1662	if (method == NULL) {
1663		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1664			return NULL;
1665		PyErr_Clear();
1666		res = Py_NotImplemented;
1667		Py_INCREF(res);
1668		return res;
1669	}
1670
1671	args = Py_BuildValue("(O)", w);
1672	if (args == NULL) {
1673		Py_DECREF(method);
1674		return NULL;
1675	}
1676
1677	res = PyEval_CallObject(method, args);
1678	Py_DECREF(args);
1679	Py_DECREF(method);
1680
1681	return res;
1682}
1683
1684/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
1685static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
1686
1687static PyObject *
1688instance_richcompare(PyObject *v, PyObject *w, int op)
1689{
1690	PyObject *res;
1691
1692	if (PyInstance_Check(v)) {
1693		res = half_richcompare(v, w, op);
1694		if (res != Py_NotImplemented)
1695			return res;
1696		Py_DECREF(res);
1697	}
1698
1699	if (PyInstance_Check(w)) {
1700		res = half_richcompare(w, v, swapped_op[op]);
1701		if (res != Py_NotImplemented)
1702			return res;
1703		Py_DECREF(res);
1704	}
1705
1706	Py_INCREF(Py_NotImplemented);
1707	return Py_NotImplemented;
1708}
1709
1710
1711static PyNumberMethods instance_as_number = {
1712	(binaryfunc)instance_add,		/* nb_add */
1713	(binaryfunc)instance_sub,		/* nb_subtract */
1714	(binaryfunc)instance_mul,		/* nb_multiply */
1715	(binaryfunc)instance_div,		/* nb_divide */
1716	(binaryfunc)instance_mod,		/* nb_remainder */
1717	(binaryfunc)instance_divmod,		/* nb_divmod */
1718	(ternaryfunc)instance_pow,		/* nb_power */
1719	(unaryfunc)instance_neg,		/* nb_negative */
1720	(unaryfunc)instance_pos,		/* nb_positive */
1721	(unaryfunc)instance_abs,		/* nb_absolute */
1722	(inquiry)instance_nonzero,		/* nb_nonzero */
1723	(unaryfunc)instance_invert,		/* nb_invert */
1724	(binaryfunc)instance_lshift,		/* nb_lshift */
1725	(binaryfunc)instance_rshift,		/* nb_rshift */
1726	(binaryfunc)instance_and,		/* nb_and */
1727	(binaryfunc)instance_xor,		/* nb_xor */
1728	(binaryfunc)instance_or,		/* nb_or */
1729	(coercion)instance_coerce,		/* nb_coerce */
1730	(unaryfunc)instance_int,		/* nb_int */
1731	(unaryfunc)instance_long,		/* nb_long */
1732	(unaryfunc)instance_float,		/* nb_float */
1733	(unaryfunc)instance_oct,		/* nb_oct */
1734	(unaryfunc)instance_hex,		/* nb_hex */
1735	(binaryfunc)instance_iadd,		/* nb_inplace_add */
1736	(binaryfunc)instance_isub,		/* nb_inplace_subtract */
1737	(binaryfunc)instance_imul,		/* nb_inplace_multiply */
1738	(binaryfunc)instance_idiv,		/* nb_inplace_divide */
1739	(binaryfunc)instance_imod,		/* nb_inplace_remainder */
1740	(ternaryfunc)instance_ipow,		/* nb_inplace_power */
1741	(binaryfunc)instance_ilshift,		/* nb_inplace_lshift */
1742	(binaryfunc)instance_irshift,		/* nb_inplace_rshift */
1743	(binaryfunc)instance_iand,		/* nb_inplace_and */
1744	(binaryfunc)instance_ixor,		/* nb_inplace_xor */
1745	(binaryfunc)instance_ior,		/* nb_inplace_or */
1746};
1747
1748PyTypeObject PyInstance_Type = {
1749	PyObject_HEAD_INIT(&PyType_Type)
1750	0,
1751	"instance",
1752	sizeof(PyInstanceObject) + PyGC_HEAD_SIZE,
1753	0,
1754	(destructor)instance_dealloc,		/* tp_dealloc */
1755	0,					/* tp_print */
1756	0,					/* tp_getattr */
1757	0,					/* tp_setattr */
1758	instance_compare,			/* tp_compare */
1759	(reprfunc)instance_repr,		/* tp_repr */
1760	&instance_as_number,			/* tp_as_number */
1761	&instance_as_sequence,			/* tp_as_sequence */
1762	&instance_as_mapping,			/* tp_as_mapping */
1763	(hashfunc)instance_hash,		/* tp_hash */
1764	0,					/* tp_call */
1765	0,					/* tp_str */
1766	(getattrofunc)instance_getattr,		/* tp_getattro */
1767	(setattrofunc)instance_setattr,		/* tp_setattro */
1768	0,					/* tp_as_buffer */
1769	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
1770	0,					/* tp_doc */
1771	(traverseproc)instance_traverse,	/* tp_traverse */
1772	0,					/* tp_clear */
1773	instance_richcompare,			/* tp_richcompare */
1774};
1775
1776
1777/* Instance method objects are used for two purposes:
1778   (a) as bound instance methods (returned by instancename.methodname)
1779   (b) as unbound methods (returned by ClassName.methodname)
1780   In case (b), im_self is NULL
1781*/
1782
1783static PyMethodObject *free_list;
1784
1785PyObject *
1786PyMethod_New(PyObject *func, PyObject *self, PyObject *class)
1787{
1788	register PyMethodObject *im;
1789	if (!PyCallable_Check(func)) {
1790		PyErr_BadInternalCall();
1791		return NULL;
1792	}
1793	im = free_list;
1794	if (im != NULL) {
1795		free_list = (PyMethodObject *)(im->im_self);
1796		PyObject_INIT(im, &PyMethod_Type);
1797	}
1798	else {
1799		im = PyObject_NEW(PyMethodObject, &PyMethod_Type);
1800		if (im == NULL)
1801			return NULL;
1802	}
1803	Py_INCREF(func);
1804	im->im_func = func;
1805	Py_XINCREF(self);
1806	im->im_self = self;
1807	Py_INCREF(class);
1808	im->im_class = class;
1809	PyObject_GC_Init(im);
1810	return (PyObject *)im;
1811}
1812
1813PyObject *
1814PyMethod_Function(register PyObject *im)
1815{
1816	if (!PyMethod_Check(im)) {
1817		PyErr_BadInternalCall();
1818		return NULL;
1819	}
1820	return ((PyMethodObject *)im)->im_func;
1821}
1822
1823PyObject *
1824PyMethod_Self(register PyObject *im)
1825{
1826	if (!PyMethod_Check(im)) {
1827		PyErr_BadInternalCall();
1828		return NULL;
1829	}
1830	return ((PyMethodObject *)im)->im_self;
1831}
1832
1833PyObject *
1834PyMethod_Class(register PyObject *im)
1835{
1836	if (!PyMethod_Check(im)) {
1837		PyErr_BadInternalCall();
1838		return NULL;
1839	}
1840	return ((PyMethodObject *)im)->im_class;
1841}
1842
1843/* Class method methods */
1844
1845#define OFF(x) offsetof(PyMethodObject, x)
1846
1847static struct memberlist instancemethod_memberlist[] = {
1848	{"im_func",	T_OBJECT,	OFF(im_func)},
1849	{"im_self",	T_OBJECT,	OFF(im_self)},
1850	{"im_class",	T_OBJECT,	OFF(im_class)},
1851	/* Dummies that are not handled by getattr() except for __members__ */
1852	{"__doc__",	T_INT,		0},
1853	{"__name__",	T_INT,		0},
1854	{"__dict__",    T_OBJECT,       0},
1855	{NULL}	/* Sentinel */
1856};
1857
1858static int
1859instancemethod_setattro(register PyMethodObject *im, PyObject *name,
1860			PyObject *v)
1861{
1862	char *sname = PyString_AsString(name);
1863
1864	if (PyEval_GetRestricted() ||
1865	    strcmp(sname, "im_func") == 0 ||
1866	    strcmp(sname, "im_self") == 0 ||
1867	    strcmp(sname, "im_class") == 0)
1868	{
1869		PyErr_Format(PyExc_TypeError, "read-only attribute: %s",
1870			     sname);
1871		return -1;
1872	}
1873	if (im->im_self != NULL) {
1874		PyErr_Format(PyExc_TypeError,
1875			     "cannot set attributes through bound methods");
1876		return -1;
1877	}
1878	return PyObject_SetAttr(im->im_func, name, v);
1879}
1880
1881
1882static PyObject *
1883instancemethod_getattro(register PyMethodObject *im, PyObject *name)
1884{
1885	PyObject *rtn;
1886	char *sname = PyString_AsString(name);
1887	if (sname[0] == '_') {
1888		/* Inherit __name__ and __doc__ from the callable object
1889		   implementing the method */
1890	        if (strcmp(sname, "__name__") == 0 ||
1891		    strcmp(sname, "__doc__") == 0)
1892			return PyObject_GetAttr(im->im_func, name);
1893	}
1894	if (PyEval_GetRestricted()) {
1895		PyErr_SetString(PyExc_RuntimeError,
1896	    "instance-method attributes not accessible in restricted mode");
1897		return NULL;
1898	}
1899	if (sname[0] == '_' && strcmp(sname, "__dict__") == 0)
1900		return PyObject_GetAttr(im->im_func, name);
1901
1902	rtn = PyMember_Get((char *)im, instancemethod_memberlist, sname);
1903	if (rtn == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1904		PyErr_Clear();
1905		rtn = PyObject_GetAttr(im->im_func, name);
1906	}
1907	return rtn;
1908}
1909
1910static void
1911instancemethod_dealloc(register PyMethodObject *im)
1912{
1913	PyObject_GC_Fini(im);
1914	Py_DECREF(im->im_func);
1915	Py_XDECREF(im->im_self);
1916	Py_DECREF(im->im_class);
1917	im->im_self = (PyObject *)free_list;
1918	free_list = im;
1919}
1920
1921static int
1922instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
1923{
1924	if (a->im_self != b->im_self)
1925		return (a->im_self < b->im_self) ? -1 : 1;
1926	return PyObject_Compare(a->im_func, b->im_func);
1927}
1928
1929static PyObject *
1930instancemethod_repr(PyMethodObject *a)
1931{
1932	char buf[240];
1933	PyInstanceObject *self = (PyInstanceObject *)(a->im_self);
1934	PyObject *func = a->im_func;
1935	PyClassObject *class = (PyClassObject *)(a->im_class);
1936	PyObject *fclassname, *iclassname, *funcname;
1937	char *fcname, *icname, *fname;
1938	fclassname = class->cl_name;
1939	if (PyFunction_Check(func)) {
1940		funcname = ((PyFunctionObject *)func)->func_name;
1941		Py_INCREF(funcname);
1942	}
1943	else {
1944		funcname = PyObject_GetAttrString(func,"__name__");
1945		if (funcname == NULL)
1946			PyErr_Clear();
1947	}
1948	if (funcname != NULL && PyString_Check(funcname))
1949		fname = PyString_AS_STRING(funcname);
1950	else
1951		fname = "?";
1952	if (fclassname != NULL && PyString_Check(fclassname))
1953		fcname = PyString_AsString(fclassname);
1954	else
1955		fcname = "?";
1956	if (self == NULL)
1957		sprintf(buf, "<unbound method %.100s.%.100s>", fcname, fname);
1958	else {
1959		iclassname = self->in_class->cl_name;
1960		if (iclassname != NULL && PyString_Check(iclassname))
1961			icname = PyString_AsString(iclassname);
1962		else
1963			icname = "?";
1964		sprintf(buf, "<method %.60s.%.60s of %.60s instance at %p>",
1965			fcname, fname, icname, self);
1966	}
1967	Py_XDECREF(funcname);
1968	return PyString_FromString(buf);
1969}
1970
1971static long
1972instancemethod_hash(PyMethodObject *a)
1973{
1974	long x, y;
1975	if (a->im_self == NULL)
1976		x = PyObject_Hash(Py_None);
1977	else
1978		x = PyObject_Hash(a->im_self);
1979	if (x == -1)
1980		return -1;
1981	y = PyObject_Hash(a->im_func);
1982	if (y == -1)
1983		return -1;
1984	return x ^ y;
1985}
1986
1987static int
1988instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
1989{
1990	int err;
1991	if (im->im_func) {
1992		err = visit(im->im_func, arg);
1993		if (err)
1994			return err;
1995	}
1996	if (im->im_self) {
1997		err = visit(im->im_self, arg);
1998		if (err)
1999			return err;
2000	}
2001	if (im->im_class) {
2002		err = visit(im->im_class, arg);
2003		if (err)
2004			return err;
2005	}
2006	return 0;
2007}
2008
2009PyTypeObject PyMethod_Type = {
2010	PyObject_HEAD_INIT(&PyType_Type)
2011	0,
2012	"instance method",
2013	sizeof(PyMethodObject) + PyGC_HEAD_SIZE,
2014	0,
2015	(destructor)instancemethod_dealloc,	/* tp_dealloc */
2016	0,					/* tp_print */
2017	0,					/* tp_getattr */
2018	0,					/* tp_setattr */
2019	(cmpfunc)instancemethod_compare,	/* tp_compare */
2020	(reprfunc)instancemethod_repr,		/* tp_repr */
2021	0,					/* tp_as_number */
2022	0,					/* tp_as_sequence */
2023	0,					/* tp_as_mapping */
2024	(hashfunc)instancemethod_hash,		/* tp_hash */
2025	0,					/* tp_call */
2026	0,					/* tp_str */
2027	(getattrofunc)instancemethod_getattro,	/* tp_getattro */
2028	(setattrofunc)instancemethod_setattro,	/* tp_setattro */
2029	0,					/* tp_as_buffer */
2030	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC,	/* tp_flags */
2031	0,					/* tp_doc */
2032	(traverseproc)instancemethod_traverse,	/* tp_traverse */
2033};
2034
2035/* Clear out the free list */
2036
2037void
2038PyMethod_Fini(void)
2039{
2040	while (free_list) {
2041		PyMethodObject *im = free_list;
2042		free_list = (PyMethodObject *)(im->im_self);
2043		im = (PyMethodObject *) PyObject_AS_GC(im);
2044		PyObject_DEL(im);
2045	}
2046}
2047