typeobject.c revision 8ace1ab53a49d90d66e8a03491a272c70ad4eb46
1/* Type object implementation */
2
3#include "Python.h"
4#include "structmember.h"
5
6static PyMemberDef type_members[] = {
7	{"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
8	{"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
9	{"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
10	{"__weakrefoffset__", T_LONG,
11	 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
12	{"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
13	{"__dictoffset__", T_LONG,
14	 offsetof(PyTypeObject, tp_dictoffset), READONLY},
15	{"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
16	{"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
17	{0}
18};
19
20static PyObject *
21type_name(PyTypeObject *type, void *context)
22{
23	char *s;
24
25	s = strrchr(type->tp_name, '.');
26	if (s == NULL)
27		s = type->tp_name;
28	else
29		s++;
30	return PyString_FromString(s);
31}
32
33static PyObject *
34type_module(PyTypeObject *type, void *context)
35{
36	PyObject *mod;
37	char *s;
38
39	s = strrchr(type->tp_name, '.');
40	if (s != NULL)
41		return PyString_FromStringAndSize(type->tp_name,
42						  (int)(s - type->tp_name));
43	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
44		return PyString_FromString("__builtin__");
45	mod = PyDict_GetItemString(type->tp_dict, "__module__");
46	if (mod != NULL && PyString_Check(mod)) {
47		Py_INCREF(mod);
48		return mod;
49	}
50	PyErr_SetString(PyExc_AttributeError, "__module__");
51	return NULL;
52}
53
54static int
55type_set_module(PyTypeObject *type, PyObject *value, void *context)
56{
57	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
58	    strrchr(type->tp_name, '.')) {
59		PyErr_Format(PyExc_TypeError,
60			     "can't set %s.__module__", type->tp_name);
61		return -1;
62	}
63	if (!value) {
64		PyErr_Format(PyExc_TypeError,
65			     "can't delete %s.__module__", type->tp_name);
66		return -1;
67	}
68	return PyDict_SetItemString(type->tp_dict, "__module__", value);
69}
70
71static PyObject *
72type_dict(PyTypeObject *type, void *context)
73{
74	if (type->tp_dict == NULL) {
75		Py_INCREF(Py_None);
76		return Py_None;
77	}
78	return PyDictProxy_New(type->tp_dict);
79}
80
81static PyObject *
82type_get_doc(PyTypeObject *type, void *context)
83{
84	PyObject *result;
85	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
86		if (type->tp_doc == NULL) {
87			Py_INCREF(Py_None);
88			return Py_None;
89		}
90		return PyString_FromString(type->tp_doc);
91	}
92	result = PyDict_GetItemString(type->tp_dict, "__doc__");
93	Py_INCREF(result);
94	return result;
95}
96
97static PyGetSetDef type_getsets[] = {
98	{"__name__", (getter)type_name, NULL, NULL},
99	{"__module__", (getter)type_module, (setter)type_set_module, NULL},
100	{"__dict__",  (getter)type_dict,  NULL, NULL},
101	{"__doc__", (getter)type_get_doc, NULL, NULL},
102	{0}
103};
104
105static int
106type_compare(PyObject *v, PyObject *w)
107{
108	/* This is called with type objects only. So we
109	   can just compare the addresses. */
110	Py_uintptr_t vv = (Py_uintptr_t)v;
111	Py_uintptr_t ww = (Py_uintptr_t)w;
112	return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
113}
114
115static PyObject *
116type_repr(PyTypeObject *type)
117{
118	PyObject *mod, *name, *rtn;
119	char *kind;
120
121	mod = type_module(type, NULL);
122	if (mod == NULL)
123		PyErr_Clear();
124	else if (!PyString_Check(mod)) {
125		Py_DECREF(mod);
126		mod = NULL;
127	}
128	name = type_name(type, NULL);
129	if (name == NULL)
130		return NULL;
131
132	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
133		kind = "class";
134	else
135		kind = "type";
136
137	if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
138		rtn = PyString_FromFormat("<%s '%s.%s'>",
139					  kind,
140					  PyString_AS_STRING(mod),
141					  PyString_AS_STRING(name));
142	}
143	else
144		rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
145
146	Py_XDECREF(mod);
147	Py_DECREF(name);
148	return rtn;
149}
150
151static PyObject *
152type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
153{
154	PyObject *obj;
155
156	if (type->tp_new == NULL) {
157		PyErr_Format(PyExc_TypeError,
158			     "cannot create '%.100s' instances",
159			     type->tp_name);
160		return NULL;
161	}
162
163	obj = type->tp_new(type, args, kwds);
164	if (obj != NULL) {
165		/* Ugly exception: when the call was type(something),
166		   don't call tp_init on the result. */
167		if (type == &PyType_Type &&
168		    PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
169		    (kwds == NULL ||
170		     (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
171			return obj;
172		/* If the returned object is not an instance of type,
173		   it won't be initialized. */
174		if (!PyType_IsSubtype(obj->ob_type, type))
175			return obj;
176		type = obj->ob_type;
177		if (type->tp_init != NULL &&
178		    type->tp_init(obj, args, kwds) < 0) {
179			Py_DECREF(obj);
180			obj = NULL;
181		}
182	}
183	return obj;
184}
185
186PyObject *
187PyType_GenericAlloc(PyTypeObject *type, int nitems)
188{
189	PyObject *obj;
190	const size_t size = _PyObject_VAR_SIZE(type, nitems);
191
192	if (PyType_IS_GC(type))
193		obj = _PyObject_GC_Malloc(type, nitems);
194	else
195		obj = PyObject_MALLOC(size);
196
197	if (obj == NULL)
198		return PyErr_NoMemory();
199
200	memset(obj, '\0', size);
201
202	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
203		Py_INCREF(type);
204
205	if (type->tp_itemsize == 0)
206		PyObject_INIT(obj, type);
207	else
208		(void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
209
210	if (PyType_IS_GC(type))
211		_PyObject_GC_TRACK(obj);
212	return obj;
213}
214
215PyObject *
216PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
217{
218	return type->tp_alloc(type, 0);
219}
220
221/* Helpers for subtyping */
222
223static int
224subtype_traverse(PyObject *self, visitproc visit, void *arg)
225{
226	PyTypeObject *type, *base;
227	traverseproc f;
228	int err;
229
230	/* Find the nearest base with a different tp_traverse */
231	type = self->ob_type;
232	base = type->tp_base;
233	while ((f = base->tp_traverse) == subtype_traverse) {
234		base = base->tp_base;
235		assert(base);
236	}
237
238	if (type->tp_dictoffset != base->tp_dictoffset) {
239		PyObject **dictptr = _PyObject_GetDictPtr(self);
240		if (dictptr && *dictptr) {
241			err = visit(*dictptr, arg);
242			if (err)
243				return err;
244		}
245	}
246
247	if (f)
248		return f(self, visit, arg);
249	return 0;
250}
251
252staticforward PyObject *lookup_maybe(PyObject *, char *, PyObject **);
253
254static int
255call_finalizer(PyObject *self)
256{
257	static PyObject *del_str = NULL;
258	PyObject *del, *res;
259	PyObject *error_type, *error_value, *error_traceback;
260
261	/* Temporarily resurrect the object. */
262#ifdef Py_TRACE_REFS
263#ifndef Py_REF_DEBUG
264#   error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
265#endif
266	/* much too complicated if Py_TRACE_REFS defined */
267	_Py_NewReference((PyObject *)self);
268#ifdef COUNT_ALLOCS
269	/* compensate for boost in _Py_NewReference; note that
270	 * _Py_RefTotal was also boosted; we'll knock that down later.
271	 */
272	self->ob_type->tp_allocs--;
273#endif
274#else /* !Py_TRACE_REFS */
275	/* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
276	Py_INCREF(self);
277#endif /* !Py_TRACE_REFS */
278
279	/* Save the current exception, if any. */
280	PyErr_Fetch(&error_type, &error_value, &error_traceback);
281
282	/* Execute __del__ method, if any. */
283	del = lookup_maybe(self, "__del__", &del_str);
284	if (del != NULL) {
285		res = PyEval_CallObject(del, NULL);
286		if (res == NULL)
287			PyErr_WriteUnraisable(del);
288		else
289			Py_DECREF(res);
290		Py_DECREF(del);
291	}
292
293	/* Restore the saved exception. */
294	PyErr_Restore(error_type, error_value, error_traceback);
295
296	/* Undo the temporary resurrection; can't use DECREF here, it would
297	 * cause a recursive call.
298	 */
299#ifdef Py_REF_DEBUG
300	/* _Py_RefTotal was boosted either by _Py_NewReference or
301	 * Py_INCREF above.
302	 */
303	_Py_RefTotal--;
304#endif
305	if (--self->ob_refcnt > 0) {
306#ifdef COUNT_ALLOCS
307		self->ob_type->tp_frees--;
308#endif
309		_PyObject_GC_TRACK(self);
310		return -1; /* __del__ added a reference; don't delete now */
311	}
312#ifdef Py_TRACE_REFS
313	_Py_ForgetReference((PyObject *)self);
314#ifdef COUNT_ALLOCS
315	/* compensate for increment in _Py_ForgetReference */
316	self->ob_type->tp_frees--;
317#endif
318#endif
319
320	return 0;
321}
322
323static void
324subtype_dealloc(PyObject *self)
325{
326	PyTypeObject *type, *base;
327	destructor f;
328
329	/* This exists so we can DECREF self->ob_type */
330
331	if (call_finalizer(self) < 0)
332		return;
333
334	/* Find the nearest base with a different tp_dealloc */
335	type = self->ob_type;
336	base = type->tp_base;
337	while ((f = base->tp_dealloc) == subtype_dealloc) {
338		base = base->tp_base;
339		assert(base);
340	}
341
342	/* Clear __slots__ variables */
343	if (type->tp_basicsize != base->tp_basicsize &&
344	    type->tp_itemsize == 0)
345	{
346		char *addr = ((char *)self);
347		char *p = addr + base->tp_basicsize;
348		char *q = addr + type->tp_basicsize;
349		for (; p < q; p += sizeof(PyObject *)) {
350			PyObject **pp;
351			if (p == addr + type->tp_dictoffset ||
352			    p == addr + type->tp_weaklistoffset)
353				continue;
354			pp = (PyObject **)p;
355			if (*pp != NULL) {
356				Py_DECREF(*pp);
357				*pp = NULL;
358			}
359		}
360	}
361
362	/* If we added a dict, DECREF it */
363	if (type->tp_dictoffset && !base->tp_dictoffset) {
364		PyObject **dictptr = _PyObject_GetDictPtr(self);
365		if (dictptr != NULL) {
366			PyObject *dict = *dictptr;
367			if (dict != NULL) {
368				Py_DECREF(dict);
369				*dictptr = NULL;
370			}
371		}
372	}
373
374	/* If we added weaklist, we clear it */
375	if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
376		PyObject_ClearWeakRefs(self);
377
378	/* Finalize GC if the base doesn't do GC and we do */
379	if (PyType_IS_GC(type) && !PyType_IS_GC(base))
380		_PyObject_GC_UNTRACK(self);
381
382	/* Call the base tp_dealloc() */
383	assert(f);
384	f(self);
385
386	/* Can't reference self beyond this point */
387	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
388		Py_DECREF(type);
389	}
390}
391
392staticforward PyTypeObject *solid_base(PyTypeObject *type);
393
394typedef struct {
395	PyTypeObject type;
396	PyNumberMethods as_number;
397	PySequenceMethods as_sequence;
398	PyMappingMethods as_mapping;
399	PyBufferProcs as_buffer;
400	PyObject *name, *slots;
401	PyMemberDef members[1];
402} etype;
403
404/* type test with subclassing support */
405
406int
407PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
408{
409	PyObject *mro;
410
411	if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
412		return b == a || b == &PyBaseObject_Type;
413
414	mro = a->tp_mro;
415	if (mro != NULL) {
416		/* Deal with multiple inheritance without recursion
417		   by walking the MRO tuple */
418		int i, n;
419		assert(PyTuple_Check(mro));
420		n = PyTuple_GET_SIZE(mro);
421		for (i = 0; i < n; i++) {
422			if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
423				return 1;
424		}
425		return 0;
426	}
427	else {
428		/* a is not completely initilized yet; follow tp_base */
429		do {
430			if (a == b)
431				return 1;
432			a = a->tp_base;
433		} while (a != NULL);
434		return b == &PyBaseObject_Type;
435	}
436}
437
438/* Internal routines to do a method lookup in the type
439   without looking in the instance dictionary
440   (so we can't use PyObject_GetAttr) but still binding
441   it to the instance.  The arguments are the object,
442   the method name as a C string, and the address of a
443   static variable used to cache the interned Python string.
444
445   Two variants:
446
447   - lookup_maybe() returns NULL without raising an exception
448     when the _PyType_Lookup() call fails;
449
450   - lookup_method() always raises an exception upon errors.
451*/
452
453static PyObject *
454lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
455{
456	PyObject *res;
457
458	if (*attrobj == NULL) {
459		*attrobj = PyString_InternFromString(attrstr);
460		if (*attrobj == NULL)
461			return NULL;
462	}
463	res = _PyType_Lookup(self->ob_type, *attrobj);
464	if (res != NULL) {
465		descrgetfunc f;
466		if ((f = res->ob_type->tp_descr_get) == NULL)
467			Py_INCREF(res);
468		else
469			res = f(res, self, (PyObject *)(self->ob_type));
470	}
471	return res;
472}
473
474static PyObject *
475lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
476{
477	PyObject *res = lookup_maybe(self, attrstr, attrobj);
478	if (res == NULL && !PyErr_Occurred())
479		PyErr_SetObject(PyExc_AttributeError, *attrobj);
480	return res;
481}
482
483/* A variation of PyObject_CallMethod that uses lookup_method()
484   instead of PyObject_GetAttrString().  This uses the same convention
485   as lookup_method to cache the interned name string object. */
486
487static PyObject *
488call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
489{
490	va_list va;
491	PyObject *args, *func = 0, *retval;
492	va_start(va, format);
493
494	func = lookup_maybe(o, name, nameobj);
495	if (func == NULL) {
496		va_end(va);
497		if (!PyErr_Occurred())
498			PyErr_SetObject(PyExc_AttributeError, *nameobj);
499		return NULL;
500	}
501
502	if (format && *format)
503		args = Py_VaBuildValue(format, va);
504	else
505		args = PyTuple_New(0);
506
507	va_end(va);
508
509	if (args == NULL)
510		return NULL;
511
512	assert(PyTuple_Check(args));
513	retval = PyObject_Call(func, args, NULL);
514
515	Py_DECREF(args);
516	Py_DECREF(func);
517
518	return retval;
519}
520
521/* Clone of call_method() that returns NotImplemented when the lookup fails. */
522
523static PyObject *
524call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
525{
526	va_list va;
527	PyObject *args, *func = 0, *retval;
528	va_start(va, format);
529
530	func = lookup_maybe(o, name, nameobj);
531	if (func == NULL) {
532		va_end(va);
533		if (!PyErr_Occurred()) {
534			Py_INCREF(Py_NotImplemented);
535			return Py_NotImplemented;
536		}
537		return NULL;
538	}
539
540	if (format && *format)
541		args = Py_VaBuildValue(format, va);
542	else
543		args = PyTuple_New(0);
544
545	va_end(va);
546
547	if (args == NULL)
548		return NULL;
549
550	assert(PyTuple_Check(args));
551	retval = PyObject_Call(func, args, NULL);
552
553	Py_DECREF(args);
554	Py_DECREF(func);
555
556	return retval;
557}
558
559/* Method resolution order algorithm from "Putting Metaclasses to Work"
560   by Forman and Danforth (Addison-Wesley 1999). */
561
562static int
563conservative_merge(PyObject *left, PyObject *right)
564{
565	int left_size;
566	int right_size;
567	int i, j, r, ok;
568	PyObject *temp, *rr;
569
570	assert(PyList_Check(left));
571	assert(PyList_Check(right));
572
573  again:
574	left_size = PyList_GET_SIZE(left);
575	right_size = PyList_GET_SIZE(right);
576	for (i = 0; i < left_size; i++) {
577		for (j = 0; j < right_size; j++) {
578			if (PyList_GET_ITEM(left, i) ==
579			    PyList_GET_ITEM(right, j)) {
580				/* found a merge point */
581				temp = PyList_New(0);
582				if (temp == NULL)
583					return -1;
584				for (r = 0; r < j; r++) {
585					rr = PyList_GET_ITEM(right, r);
586					ok = PySequence_Contains(left, rr);
587					if (ok < 0) {
588						Py_DECREF(temp);
589						return -1;
590					}
591					if (!ok) {
592						ok = PyList_Append(temp, rr);
593						if (ok < 0) {
594							Py_DECREF(temp);
595							return -1;
596						}
597					}
598				}
599				ok = PyList_SetSlice(left, i, i, temp);
600				Py_DECREF(temp);
601				if (ok < 0)
602					return -1;
603				ok = PyList_SetSlice(right, 0, j+1, NULL);
604				if (ok < 0)
605					return -1;
606				goto again;
607			}
608		}
609	}
610	return PyList_SetSlice(left, left_size, left_size, right);
611}
612
613static int
614serious_order_disagreements(PyObject *left, PyObject *right)
615{
616	return 0; /* XXX later -- for now, we cheat: "don't do that" */
617}
618
619static int
620fill_classic_mro(PyObject *mro, PyObject *cls)
621{
622	PyObject *bases, *base;
623	int i, n;
624
625	assert(PyList_Check(mro));
626	assert(PyClass_Check(cls));
627	i = PySequence_Contains(mro, cls);
628	if (i < 0)
629		return -1;
630	if (!i) {
631		if (PyList_Append(mro, cls) < 0)
632			return -1;
633	}
634	bases = ((PyClassObject *)cls)->cl_bases;
635	assert(bases && PyTuple_Check(bases));
636	n = PyTuple_GET_SIZE(bases);
637	for (i = 0; i < n; i++) {
638		base = PyTuple_GET_ITEM(bases, i);
639		if (fill_classic_mro(mro, base) < 0)
640			return -1;
641	}
642	return 0;
643}
644
645static PyObject *
646classic_mro(PyObject *cls)
647{
648	PyObject *mro;
649
650	assert(PyClass_Check(cls));
651	mro = PyList_New(0);
652	if (mro != NULL) {
653		if (fill_classic_mro(mro, cls) == 0)
654			return mro;
655		Py_DECREF(mro);
656	}
657	return NULL;
658}
659
660static PyObject *
661mro_implementation(PyTypeObject *type)
662{
663	int i, n, ok;
664	PyObject *bases, *result;
665
666	bases = type->tp_bases;
667	n = PyTuple_GET_SIZE(bases);
668	result = Py_BuildValue("[O]", (PyObject *)type);
669	if (result == NULL)
670		return NULL;
671	for (i = 0; i < n; i++) {
672		PyObject *base = PyTuple_GET_ITEM(bases, i);
673		PyObject *parentMRO;
674		if (PyType_Check(base))
675			parentMRO = PySequence_List(
676				((PyTypeObject*)base)->tp_mro);
677		else
678			parentMRO = classic_mro(base);
679		if (parentMRO == NULL) {
680			Py_DECREF(result);
681			return NULL;
682		}
683		if (serious_order_disagreements(result, parentMRO)) {
684			Py_DECREF(result);
685			return NULL;
686		}
687		ok = conservative_merge(result, parentMRO);
688		Py_DECREF(parentMRO);
689		if (ok < 0) {
690			Py_DECREF(result);
691			return NULL;
692		}
693	}
694	return result;
695}
696
697static PyObject *
698mro_external(PyObject *self)
699{
700	PyTypeObject *type = (PyTypeObject *)self;
701
702	return mro_implementation(type);
703}
704
705static int
706mro_internal(PyTypeObject *type)
707{
708	PyObject *mro, *result, *tuple;
709
710	if (type->ob_type == &PyType_Type) {
711		result = mro_implementation(type);
712	}
713	else {
714		static PyObject *mro_str;
715		mro = lookup_method((PyObject *)type, "mro", &mro_str);
716		if (mro == NULL)
717			return -1;
718		result = PyObject_CallObject(mro, NULL);
719		Py_DECREF(mro);
720	}
721	if (result == NULL)
722		return -1;
723	tuple = PySequence_Tuple(result);
724	Py_DECREF(result);
725	type->tp_mro = tuple;
726	return 0;
727}
728
729
730/* Calculate the best base amongst multiple base classes.
731   This is the first one that's on the path to the "solid base". */
732
733static PyTypeObject *
734best_base(PyObject *bases)
735{
736	int i, n;
737	PyTypeObject *base, *winner, *candidate, *base_i;
738	PyObject *base_proto;
739
740	assert(PyTuple_Check(bases));
741	n = PyTuple_GET_SIZE(bases);
742	assert(n > 0);
743	base = NULL;
744	winner = NULL;
745	for (i = 0; i < n; i++) {
746		base_proto = PyTuple_GET_ITEM(bases, i);
747		if (PyClass_Check(base_proto))
748			continue;
749		if (!PyType_Check(base_proto)) {
750			PyErr_SetString(
751				PyExc_TypeError,
752				"bases must be types");
753			return NULL;
754		}
755		base_i = (PyTypeObject *)base_proto;
756		if (base_i->tp_dict == NULL) {
757			if (PyType_Ready(base_i) < 0)
758				return NULL;
759		}
760		candidate = solid_base(base_i);
761		if (winner == NULL) {
762			winner = candidate;
763			base = base_i;
764		}
765		else if (PyType_IsSubtype(winner, candidate))
766			;
767		else if (PyType_IsSubtype(candidate, winner)) {
768			winner = candidate;
769			base = base_i;
770		}
771		else {
772			PyErr_SetString(
773				PyExc_TypeError,
774				"multiple bases have "
775				"instance lay-out conflict");
776			return NULL;
777		}
778	}
779	if (base == NULL)
780		PyErr_SetString(PyExc_TypeError,
781			"a new-style class can't have only classic bases");
782	return base;
783}
784
785static int
786extra_ivars(PyTypeObject *type, PyTypeObject *base)
787{
788	size_t t_size = type->tp_basicsize;
789	size_t b_size = base->tp_basicsize;
790
791	assert(t_size >= b_size); /* Else type smaller than base! */
792	if (type->tp_itemsize || base->tp_itemsize) {
793		/* If itemsize is involved, stricter rules */
794		return t_size != b_size ||
795			type->tp_itemsize != base->tp_itemsize;
796	}
797	if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
798	    type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
799		t_size -= sizeof(PyObject *);
800	if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
801	    type->tp_dictoffset + sizeof(PyObject *) == t_size)
802		t_size -= sizeof(PyObject *);
803
804	return t_size != b_size;
805}
806
807static PyTypeObject *
808solid_base(PyTypeObject *type)
809{
810	PyTypeObject *base;
811
812	if (type->tp_base)
813		base = solid_base(type->tp_base);
814	else
815		base = &PyBaseObject_Type;
816	if (extra_ivars(type, base))
817		return type;
818	else
819		return base;
820}
821
822staticforward void object_dealloc(PyObject *);
823staticforward int object_init(PyObject *, PyObject *, PyObject *);
824staticforward int update_slot(PyTypeObject *, PyObject *);
825staticforward void fixup_slot_dispatchers(PyTypeObject *);
826
827static PyObject *
828subtype_dict(PyObject *obj, void *context)
829{
830	PyObject **dictptr = _PyObject_GetDictPtr(obj);
831	PyObject *dict;
832
833	if (dictptr == NULL) {
834		PyErr_SetString(PyExc_AttributeError,
835				"This object has no __dict__");
836		return NULL;
837	}
838	dict = *dictptr;
839	if (dict == NULL)
840		*dictptr = dict = PyDict_New();
841	Py_XINCREF(dict);
842	return dict;
843}
844
845static int
846subtype_setdict(PyObject *obj, PyObject *value, void *context)
847{
848	PyObject **dictptr = _PyObject_GetDictPtr(obj);
849	PyObject *dict;
850
851	if (dictptr == NULL) {
852		PyErr_SetString(PyExc_AttributeError,
853				"This object has no __dict__");
854		return -1;
855	}
856	if (value != NULL && !PyDict_Check(value)) {
857		PyErr_SetString(PyExc_TypeError,
858				"__dict__ must be set to a dictionary");
859		return -1;
860	}
861	dict = *dictptr;
862	Py_XINCREF(value);
863	*dictptr = value;
864	Py_XDECREF(dict);
865	return 0;
866}
867
868static PyGetSetDef subtype_getsets[] = {
869	{"__dict__", subtype_dict, subtype_setdict, NULL},
870	{0},
871};
872
873/* bozo: __getstate__ that raises TypeError */
874
875static PyObject *
876bozo_func(PyObject *self, PyObject *args)
877{
878	PyErr_SetString(PyExc_TypeError,
879			"a class that defines __slots__ without "
880			"defining __getstate__ cannot be pickled");
881	return NULL;
882}
883
884static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
885
886static PyObject *bozo_obj = NULL;
887
888static PyObject *
889type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
890{
891	PyObject *name, *bases, *dict;
892	static char *kwlist[] = {"name", "bases", "dict", 0};
893	PyObject *slots, *tmp;
894	PyTypeObject *type, *base, *tmptype, *winner;
895	etype *et;
896	PyMemberDef *mp;
897	int i, nbases, nslots, slotoffset, add_dict, add_weak;
898
899	assert(args != NULL && PyTuple_Check(args));
900	assert(kwds == NULL || PyDict_Check(kwds));
901
902	/* Special case: type(x) should return x->ob_type */
903	{
904		const int nargs = PyTuple_GET_SIZE(args);
905		const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
906
907		if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
908			PyObject *x = PyTuple_GET_ITEM(args, 0);
909			Py_INCREF(x->ob_type);
910			return (PyObject *) x->ob_type;
911		}
912
913		/* SF bug 475327 -- if that didn't trigger, we need 3
914		   arguments. but PyArg_ParseTupleAndKeywords below may give
915		   a msg saying type() needs exactly 3. */
916		if (nargs + nkwds != 3) {
917			PyErr_SetString(PyExc_TypeError,
918					"type() takes 1 or 3 arguments");
919			return NULL;
920		}
921	}
922
923	/* Check arguments: (name, bases, dict) */
924	if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
925					 &name,
926					 &PyTuple_Type, &bases,
927					 &PyDict_Type, &dict))
928		return NULL;
929
930	/* Determine the proper metatype to deal with this,
931	   and check for metatype conflicts while we're at it.
932	   Note that if some other metatype wins to contract,
933	   it's possible that its instances are not types. */
934	nbases = PyTuple_GET_SIZE(bases);
935	winner = metatype;
936	for (i = 0; i < nbases; i++) {
937		tmp = PyTuple_GET_ITEM(bases, i);
938		tmptype = tmp->ob_type;
939		if (tmptype == &PyClass_Type)
940			continue; /* Special case classic classes */
941		if (PyType_IsSubtype(winner, tmptype))
942			continue;
943		if (PyType_IsSubtype(tmptype, winner)) {
944			winner = tmptype;
945			continue;
946		}
947		PyErr_SetString(PyExc_TypeError,
948				"metatype conflict among bases");
949		return NULL;
950	}
951	if (winner != metatype) {
952		if (winner->tp_new != type_new) /* Pass it to the winner */
953			return winner->tp_new(winner, args, kwds);
954		metatype = winner;
955	}
956
957	/* Adjust for empty tuple bases */
958	if (nbases == 0) {
959		bases = Py_BuildValue("(O)", &PyBaseObject_Type);
960		if (bases == NULL)
961			return NULL;
962		nbases = 1;
963	}
964	else
965		Py_INCREF(bases);
966
967	/* XXX From here until type is allocated, "return NULL" leaks bases! */
968
969	/* Calculate best base, and check that all bases are type objects */
970	base = best_base(bases);
971	if (base == NULL)
972		return NULL;
973	if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
974		PyErr_Format(PyExc_TypeError,
975			     "type '%.100s' is not an acceptable base type",
976			     base->tp_name);
977		return NULL;
978	}
979
980	/* Check for a __slots__ sequence variable in dict, and count it */
981	slots = PyDict_GetItemString(dict, "__slots__");
982	nslots = 0;
983	add_dict = 0;
984	add_weak = 0;
985	if (slots != NULL) {
986		/* Make it into a tuple */
987		if (PyString_Check(slots))
988			slots = Py_BuildValue("(O)", slots);
989		else
990			slots = PySequence_Tuple(slots);
991		if (slots == NULL)
992			return NULL;
993		nslots = PyTuple_GET_SIZE(slots);
994		if (nslots > 0 && base->tp_itemsize != 0) {
995			PyErr_Format(PyExc_TypeError,
996				     "nonempty __slots__ "
997				     "not supported for subtype of '%s'",
998				     base->tp_name);
999			return NULL;
1000		}
1001		for (i = 0; i < nslots; i++) {
1002			if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
1003				PyErr_SetString(PyExc_TypeError,
1004				"__slots__ must be a sequence of strings");
1005				Py_DECREF(slots);
1006				return NULL;
1007			}
1008			/* XXX Check against null bytes in name */
1009		}
1010	}
1011	if (slots != NULL) {
1012		/* See if *this* class defines __getstate__ */
1013		PyObject *getstate = PyDict_GetItemString(dict,
1014							  "__getstate__");
1015		if (getstate == NULL) {
1016			/* If not, provide a bozo that raises TypeError */
1017			if (bozo_obj == NULL) {
1018				bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1019				if (bozo_obj == NULL) {
1020					/* XXX decref various things */
1021					return NULL;
1022				}
1023			}
1024			if (PyDict_SetItemString(dict,
1025						 "__getstate__",
1026						 bozo_obj) < 0) {
1027				/* XXX decref various things */
1028				return NULL;
1029			}
1030		}
1031	}
1032	if (slots == NULL && base->tp_dictoffset == 0 &&
1033	    (base->tp_setattro == PyObject_GenericSetAttr ||
1034	     base->tp_setattro == NULL)) {
1035		add_dict++;
1036	}
1037	if (slots == NULL && base->tp_weaklistoffset == 0 &&
1038	    base->tp_itemsize == 0) {
1039		nslots++;
1040		add_weak++;
1041	}
1042
1043	/* XXX From here until type is safely allocated,
1044	   "return NULL" may leak slots! */
1045
1046	/* Allocate the type object */
1047	type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1048	if (type == NULL)
1049		return NULL;
1050
1051	/* Keep name and slots alive in the extended type object */
1052	et = (etype *)type;
1053	Py_INCREF(name);
1054	et->name = name;
1055	et->slots = slots;
1056
1057	/* Initialize tp_flags */
1058	type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1059		Py_TPFLAGS_BASETYPE;
1060	if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1061		type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1062
1063	/* It's a new-style number unless it specifically inherits any
1064	   old-style numeric behavior */
1065	if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1066	    (base->tp_as_number == NULL))
1067		type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1068
1069	/* Initialize essential fields */
1070	type->tp_as_number = &et->as_number;
1071	type->tp_as_sequence = &et->as_sequence;
1072	type->tp_as_mapping = &et->as_mapping;
1073	type->tp_as_buffer = &et->as_buffer;
1074	type->tp_name = PyString_AS_STRING(name);
1075
1076	/* Set tp_base and tp_bases */
1077	type->tp_bases = bases;
1078	Py_INCREF(base);
1079	type->tp_base = base;
1080
1081	/* Initialize tp_dict from passed-in dict */
1082	type->tp_dict = dict = PyDict_Copy(dict);
1083	if (dict == NULL) {
1084		Py_DECREF(type);
1085		return NULL;
1086	}
1087
1088	/* Set __module__ in the dict */
1089	if (PyDict_GetItemString(dict, "__module__") == NULL) {
1090		tmp = PyEval_GetGlobals();
1091		if (tmp != NULL) {
1092			tmp = PyDict_GetItemString(tmp, "__name__");
1093			if (tmp != NULL) {
1094				if (PyDict_SetItemString(dict, "__module__",
1095							 tmp) < 0)
1096					return NULL;
1097			}
1098		}
1099	}
1100
1101	/* Set tp_doc to a copy of dict['__doc__'], if the latter is there
1102	   and is a string.  The __doc__ accessor will first look for tp_doc;
1103	   if that fails, it will still look into __dict__.
1104	*/
1105	{
1106		PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1107		if (doc != NULL && PyString_Check(doc)) {
1108			const size_t n = (size_t)PyString_GET_SIZE(doc);
1109			type->tp_doc = (char *)PyObject_MALLOC(n+1);
1110			if (type->tp_doc == NULL) {
1111				Py_DECREF(type);
1112				return NULL;
1113			}
1114			memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1115		}
1116	}
1117
1118	/* Special-case __new__: if it's a plain function,
1119	   make it a static function */
1120	tmp = PyDict_GetItemString(dict, "__new__");
1121	if (tmp != NULL && PyFunction_Check(tmp)) {
1122		tmp = PyStaticMethod_New(tmp);
1123		if (tmp == NULL) {
1124			Py_DECREF(type);
1125			return NULL;
1126		}
1127		PyDict_SetItemString(dict, "__new__", tmp);
1128		Py_DECREF(tmp);
1129	}
1130
1131	/* Add descriptors for custom slots from __slots__, or for __dict__ */
1132	mp = et->members;
1133	slotoffset = base->tp_basicsize;
1134	if (slots != NULL) {
1135		for (i = 0; i < nslots; i++, mp++) {
1136			mp->name = PyString_AS_STRING(
1137				PyTuple_GET_ITEM(slots, i));
1138			mp->type = T_OBJECT_EX;
1139			mp->offset = slotoffset;
1140			if (base->tp_weaklistoffset == 0 &&
1141			    strcmp(mp->name, "__weakref__") == 0) {
1142				mp->type = T_OBJECT;
1143				type->tp_weaklistoffset = slotoffset;
1144			}
1145			slotoffset += sizeof(PyObject *);
1146		}
1147	}
1148	else {
1149		if (add_dict) {
1150			if (base->tp_itemsize)
1151				type->tp_dictoffset =
1152					-(long)sizeof(PyObject *);
1153			else
1154				type->tp_dictoffset = slotoffset;
1155			slotoffset += sizeof(PyObject *);
1156			type->tp_getset = subtype_getsets;
1157		}
1158		if (add_weak) {
1159			assert(!base->tp_itemsize);
1160			type->tp_weaklistoffset = slotoffset;
1161			mp->name = "__weakref__";
1162			mp->type = T_OBJECT;
1163			mp->offset = slotoffset;
1164			mp->flags = READONLY;
1165			mp++;
1166			slotoffset += sizeof(PyObject *);
1167		}
1168	}
1169	type->tp_basicsize = slotoffset;
1170	type->tp_itemsize = base->tp_itemsize;
1171	type->tp_members = et->members;
1172
1173	/* Special case some slots */
1174	if (type->tp_dictoffset != 0 || nslots > 0) {
1175		if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1176			type->tp_getattro = PyObject_GenericGetAttr;
1177		if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1178			type->tp_setattro = PyObject_GenericSetAttr;
1179	}
1180	type->tp_dealloc = subtype_dealloc;
1181
1182	/* Enable GC unless there are really no instance variables possible */
1183	if (!(type->tp_basicsize == sizeof(PyObject) &&
1184	      type->tp_itemsize == 0))
1185		type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1186
1187	/* Always override allocation strategy to use regular heap */
1188	type->tp_alloc = PyType_GenericAlloc;
1189	if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1190		type->tp_free = _PyObject_GC_Del;
1191		type->tp_traverse = subtype_traverse;
1192		type->tp_clear = base->tp_clear;
1193	}
1194	else
1195		type->tp_free = _PyObject_Del;
1196
1197	/* Initialize the rest */
1198	if (PyType_Ready(type) < 0) {
1199		Py_DECREF(type);
1200		return NULL;
1201	}
1202
1203	/* Put the proper slots in place */
1204	fixup_slot_dispatchers(type);
1205
1206	return (PyObject *)type;
1207}
1208
1209/* Internal API to look for a name through the MRO.
1210   This returns a borrowed reference, and doesn't set an exception! */
1211PyObject *
1212_PyType_Lookup(PyTypeObject *type, PyObject *name)
1213{
1214	int i, n;
1215	PyObject *mro, *res, *base, *dict;
1216
1217	/* Look in tp_dict of types in MRO */
1218	mro = type->tp_mro;
1219	assert(PyTuple_Check(mro));
1220	n = PyTuple_GET_SIZE(mro);
1221	for (i = 0; i < n; i++) {
1222		base = PyTuple_GET_ITEM(mro, i);
1223		if (PyClass_Check(base))
1224			dict = ((PyClassObject *)base)->cl_dict;
1225		else {
1226			assert(PyType_Check(base));
1227			dict = ((PyTypeObject *)base)->tp_dict;
1228		}
1229		assert(dict && PyDict_Check(dict));
1230		res = PyDict_GetItem(dict, name);
1231		if (res != NULL)
1232			return res;
1233	}
1234	return NULL;
1235}
1236
1237/* This is similar to PyObject_GenericGetAttr(),
1238   but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1239static PyObject *
1240type_getattro(PyTypeObject *type, PyObject *name)
1241{
1242	PyTypeObject *metatype = type->ob_type;
1243	PyObject *meta_attribute, *attribute;
1244	descrgetfunc meta_get;
1245
1246	/* Initialize this type (we'll assume the metatype is initialized) */
1247	if (type->tp_dict == NULL) {
1248		if (PyType_Ready(type) < 0)
1249			return NULL;
1250	}
1251
1252	/* No readable descriptor found yet */
1253	meta_get = NULL;
1254
1255	/* Look for the attribute in the metatype */
1256	meta_attribute = _PyType_Lookup(metatype, name);
1257
1258	if (meta_attribute != NULL) {
1259		meta_get = meta_attribute->ob_type->tp_descr_get;
1260
1261		if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1262			/* Data descriptors implement tp_descr_set to intercept
1263			 * writes. Assume the attribute is not overridden in
1264			 * type's tp_dict (and bases): call the descriptor now.
1265			 */
1266			return meta_get(meta_attribute, (PyObject *)type,
1267					(PyObject *)metatype);
1268		}
1269	}
1270
1271	/* No data descriptor found on metatype. Look in tp_dict of this
1272	 * type and its bases */
1273	attribute = _PyType_Lookup(type, name);
1274	if (attribute != NULL) {
1275		/* Implement descriptor functionality, if any */
1276		descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1277		if (local_get != NULL) {
1278			/* NULL 2nd argument indicates the descriptor was
1279			 * found on the target object itself (or a base)  */
1280			return local_get(attribute, (PyObject *)NULL,
1281					 (PyObject *)type);
1282		}
1283
1284		Py_INCREF(attribute);
1285		return attribute;
1286	}
1287
1288	/* No attribute found in local __dict__ (or bases): use the
1289	 * descriptor from the metatype, if any */
1290	if (meta_get != NULL)
1291		return meta_get(meta_attribute, (PyObject *)type,
1292				(PyObject *)metatype);
1293
1294	/* If an ordinary attribute was found on the metatype, return it now */
1295	if (meta_attribute != NULL) {
1296		Py_INCREF(meta_attribute);
1297		return meta_attribute;
1298	}
1299
1300	/* Give up */
1301	PyErr_Format(PyExc_AttributeError,
1302			 "type object '%.50s' has no attribute '%.400s'",
1303			 type->tp_name, PyString_AS_STRING(name));
1304	return NULL;
1305}
1306
1307static int
1308type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1309{
1310	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1311		PyErr_Format(
1312			PyExc_TypeError,
1313			"can't set attributes of built-in/extension type '%s'",
1314			type->tp_name);
1315		return -1;
1316	}
1317	if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1318		return -1;
1319	return update_slot(type, name);
1320}
1321
1322static void
1323type_dealloc(PyTypeObject *type)
1324{
1325	etype *et;
1326
1327	/* Assert this is a heap-allocated type object */
1328	assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
1329	_PyObject_GC_UNTRACK(type);
1330	PyObject_ClearWeakRefs((PyObject *)type);
1331	et = (etype *)type;
1332	Py_XDECREF(type->tp_base);
1333	Py_XDECREF(type->tp_dict);
1334	Py_XDECREF(type->tp_bases);
1335	Py_XDECREF(type->tp_mro);
1336	Py_XDECREF(type->tp_cache);
1337	Py_XDECREF(type->tp_subclasses);
1338	Py_XDECREF(et->name);
1339	Py_XDECREF(et->slots);
1340	type->ob_type->tp_free((PyObject *)type);
1341}
1342
1343static PyObject *
1344type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1345{
1346	PyObject *list, *raw, *ref;
1347	int i, n;
1348
1349	list = PyList_New(0);
1350	if (list == NULL)
1351		return NULL;
1352	raw = type->tp_subclasses;
1353	if (raw == NULL)
1354		return list;
1355	assert(PyList_Check(raw));
1356	n = PyList_GET_SIZE(raw);
1357	for (i = 0; i < n; i++) {
1358		ref = PyList_GET_ITEM(raw, i);
1359		assert(PyWeakref_CheckRef(ref));
1360		ref = PyWeakref_GET_OBJECT(ref);
1361		if (ref != Py_None) {
1362			if (PyList_Append(list, ref) < 0) {
1363				Py_DECREF(list);
1364				return NULL;
1365			}
1366		}
1367	}
1368	return list;
1369}
1370
1371static PyMethodDef type_methods[] = {
1372	{"mro", (PyCFunction)mro_external, METH_NOARGS,
1373	 "mro() -> list\nreturn a type's method resolution order"},
1374	{"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1375	 "__subclasses__() -> list of immediate subclasses"},
1376	{0}
1377};
1378
1379static char type_doc[] =
1380"type(object) -> the object's type\n"
1381"type(name, bases, dict) -> a new type";
1382
1383static int
1384type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1385{
1386	etype *et;
1387	int err;
1388
1389	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1390		return 0;
1391
1392	et = (etype *)type;
1393
1394#define VISIT(SLOT) \
1395	if (SLOT) { \
1396		err = visit((PyObject *)(SLOT), arg); \
1397		if (err) \
1398			return err; \
1399	}
1400
1401	VISIT(type->tp_dict);
1402	VISIT(type->tp_cache);
1403	VISIT(type->tp_mro);
1404	VISIT(type->tp_bases);
1405	VISIT(type->tp_base);
1406	VISIT(type->tp_subclasses);
1407	VISIT(et->slots);
1408
1409#undef VISIT
1410
1411	return 0;
1412}
1413
1414static int
1415type_clear(PyTypeObject *type)
1416{
1417	etype *et;
1418	PyObject *tmp;
1419
1420	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1421		return 0;
1422
1423	et = (etype *)type;
1424
1425#define CLEAR(SLOT) \
1426	if (SLOT) { \
1427		tmp = (PyObject *)(SLOT); \
1428		SLOT = NULL; \
1429		Py_DECREF(tmp); \
1430	}
1431
1432	CLEAR(type->tp_dict);
1433	CLEAR(type->tp_cache);
1434	CLEAR(type->tp_mro);
1435	CLEAR(type->tp_bases);
1436	CLEAR(type->tp_base);
1437	CLEAR(type->tp_subclasses);
1438	CLEAR(et->slots);
1439
1440	if (type->tp_doc != NULL) {
1441		PyObject_FREE(type->tp_doc);
1442		type->tp_doc = NULL;
1443	}
1444
1445#undef CLEAR
1446
1447	return 0;
1448}
1449
1450static int
1451type_is_gc(PyTypeObject *type)
1452{
1453	return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1454}
1455
1456PyTypeObject PyType_Type = {
1457	PyObject_HEAD_INIT(&PyType_Type)
1458	0,					/* ob_size */
1459	"type",					/* tp_name */
1460	sizeof(etype),				/* tp_basicsize */
1461	sizeof(PyMemberDef),			/* tp_itemsize */
1462	(destructor)type_dealloc,		/* tp_dealloc */
1463	0,					/* tp_print */
1464	0,			 		/* tp_getattr */
1465	0,					/* tp_setattr */
1466	type_compare,				/* tp_compare */
1467	(reprfunc)type_repr,			/* tp_repr */
1468	0,					/* tp_as_number */
1469	0,					/* tp_as_sequence */
1470	0,					/* tp_as_mapping */
1471	(hashfunc)_Py_HashPointer,		/* tp_hash */
1472	(ternaryfunc)type_call,			/* tp_call */
1473	0,					/* tp_str */
1474	(getattrofunc)type_getattro,		/* tp_getattro */
1475	(setattrofunc)type_setattro,		/* tp_setattro */
1476	0,					/* tp_as_buffer */
1477	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1478		Py_TPFLAGS_BASETYPE,		/* tp_flags */
1479	type_doc,				/* tp_doc */
1480	(traverseproc)type_traverse,		/* tp_traverse */
1481	(inquiry)type_clear,			/* tp_clear */
1482	0,					/* tp_richcompare */
1483	offsetof(PyTypeObject, tp_weaklist),	/* tp_weaklistoffset */
1484	0,					/* tp_iter */
1485	0,					/* tp_iternext */
1486	type_methods,				/* tp_methods */
1487	type_members,				/* tp_members */
1488	type_getsets,				/* tp_getset */
1489	0,					/* tp_base */
1490	0,					/* tp_dict */
1491	0,					/* tp_descr_get */
1492	0,					/* tp_descr_set */
1493	offsetof(PyTypeObject, tp_dict),	/* tp_dictoffset */
1494	0,					/* tp_init */
1495	0,					/* tp_alloc */
1496	type_new,				/* tp_new */
1497	_PyObject_GC_Del,			/* tp_free */
1498	(inquiry)type_is_gc,			/* tp_is_gc */
1499};
1500
1501
1502/* The base type of all types (eventually)... except itself. */
1503
1504static int
1505object_init(PyObject *self, PyObject *args, PyObject *kwds)
1506{
1507	return 0;
1508}
1509
1510static void
1511object_dealloc(PyObject *self)
1512{
1513	self->ob_type->tp_free(self);
1514}
1515
1516static PyObject *
1517object_repr(PyObject *self)
1518{
1519	PyTypeObject *type;
1520	PyObject *mod, *name, *rtn;
1521
1522	type = self->ob_type;
1523	mod = type_module(type, NULL);
1524	if (mod == NULL)
1525		PyErr_Clear();
1526	else if (!PyString_Check(mod)) {
1527		Py_DECREF(mod);
1528		mod = NULL;
1529	}
1530	name = type_name(type, NULL);
1531	if (name == NULL)
1532		return NULL;
1533	if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
1534		rtn = PyString_FromFormat("<%s.%s object at %p>",
1535					  PyString_AS_STRING(mod),
1536					  PyString_AS_STRING(name),
1537					  self);
1538	else
1539		rtn = PyString_FromFormat("<%s object at %p>",
1540					  type->tp_name, self);
1541	Py_XDECREF(mod);
1542	Py_DECREF(name);
1543	return rtn;
1544}
1545
1546static PyObject *
1547object_str(PyObject *self)
1548{
1549	unaryfunc f;
1550
1551	f = self->ob_type->tp_repr;
1552	if (f == NULL)
1553		f = object_repr;
1554	return f(self);
1555}
1556
1557static long
1558object_hash(PyObject *self)
1559{
1560	return _Py_HashPointer(self);
1561}
1562
1563static PyObject *
1564object_get_class(PyObject *self, void *closure)
1565{
1566	Py_INCREF(self->ob_type);
1567	return (PyObject *)(self->ob_type);
1568}
1569
1570static int
1571equiv_structs(PyTypeObject *a, PyTypeObject *b)
1572{
1573	return a == b ||
1574	       (a != NULL &&
1575		b != NULL &&
1576		a->tp_basicsize == b->tp_basicsize &&
1577		a->tp_itemsize == b->tp_itemsize &&
1578		a->tp_dictoffset == b->tp_dictoffset &&
1579		a->tp_weaklistoffset == b->tp_weaklistoffset &&
1580		((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1581		 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1582}
1583
1584static int
1585same_slots_added(PyTypeObject *a, PyTypeObject *b)
1586{
1587	PyTypeObject *base = a->tp_base;
1588	int size;
1589
1590	if (base != b->tp_base)
1591		return 0;
1592	if (equiv_structs(a, base) && equiv_structs(b, base))
1593		return 1;
1594	size = base->tp_basicsize;
1595	if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1596		size += sizeof(PyObject *);
1597	if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1598		size += sizeof(PyObject *);
1599	return size == a->tp_basicsize && size == b->tp_basicsize;
1600}
1601
1602static int
1603object_set_class(PyObject *self, PyObject *value, void *closure)
1604{
1605	PyTypeObject *old = self->ob_type;
1606	PyTypeObject *new, *newbase, *oldbase;
1607
1608	if (!PyType_Check(value)) {
1609		PyErr_Format(PyExc_TypeError,
1610		  "__class__ must be set to new-style class, not '%s' object",
1611		  value->ob_type->tp_name);
1612		return -1;
1613	}
1614	new = (PyTypeObject *)value;
1615	newbase = new;
1616	oldbase = old;
1617	while (equiv_structs(newbase, newbase->tp_base))
1618		newbase = newbase->tp_base;
1619	while (equiv_structs(oldbase, oldbase->tp_base))
1620		oldbase = oldbase->tp_base;
1621	if (newbase != oldbase &&
1622	    (newbase->tp_base != oldbase->tp_base ||
1623	     !same_slots_added(newbase, oldbase))) {
1624		PyErr_Format(PyExc_TypeError,
1625			     "__class__ assignment: "
1626			     "'%s' object layout differs from '%s'",
1627			     new->tp_name,
1628			     old->tp_name);
1629		return -1;
1630	}
1631	if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1632		Py_INCREF(new);
1633	}
1634	self->ob_type = new;
1635	if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1636		Py_DECREF(old);
1637	}
1638	return 0;
1639}
1640
1641static PyGetSetDef object_getsets[] = {
1642	{"__class__", object_get_class, object_set_class,
1643	 "the object's class"},
1644	{0}
1645};
1646
1647static PyObject *
1648object_reduce(PyObject *self, PyObject *args)
1649{
1650	/* Call copy_reg._reduce(self) */
1651	static PyObject *copy_reg_str;
1652	PyObject *copy_reg, *res;
1653
1654	if (!copy_reg_str) {
1655		copy_reg_str = PyString_InternFromString("copy_reg");
1656		if (copy_reg_str == NULL)
1657			return NULL;
1658	}
1659	copy_reg = PyImport_Import(copy_reg_str);
1660	if (!copy_reg)
1661		return NULL;
1662	res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1663	Py_DECREF(copy_reg);
1664	return res;
1665}
1666
1667static PyMethodDef object_methods[] = {
1668	{"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1669	{0}
1670};
1671
1672PyTypeObject PyBaseObject_Type = {
1673	PyObject_HEAD_INIT(&PyType_Type)
1674 	0,					/* ob_size */
1675	"object",				/* tp_name */
1676	sizeof(PyObject),			/* tp_basicsize */
1677	0,					/* tp_itemsize */
1678	(destructor)object_dealloc,		/* tp_dealloc */
1679	0,					/* tp_print */
1680	0,			 		/* tp_getattr */
1681	0,					/* tp_setattr */
1682	0,					/* tp_compare */
1683	object_repr,				/* tp_repr */
1684	0,					/* tp_as_number */
1685	0,					/* tp_as_sequence */
1686	0,					/* tp_as_mapping */
1687	object_hash,				/* tp_hash */
1688	0,					/* tp_call */
1689	object_str,				/* tp_str */
1690	PyObject_GenericGetAttr,		/* tp_getattro */
1691	PyObject_GenericSetAttr,		/* tp_setattro */
1692	0,					/* tp_as_buffer */
1693	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1694	"The most base type",			/* tp_doc */
1695	0,					/* tp_traverse */
1696	0,					/* tp_clear */
1697	0,					/* tp_richcompare */
1698	0,					/* tp_weaklistoffset */
1699	0,					/* tp_iter */
1700	0,					/* tp_iternext */
1701	object_methods,				/* tp_methods */
1702	0,					/* tp_members */
1703	object_getsets,				/* tp_getset */
1704	0,					/* tp_base */
1705	0,					/* tp_dict */
1706	0,					/* tp_descr_get */
1707	0,					/* tp_descr_set */
1708	0,					/* tp_dictoffset */
1709	object_init,				/* tp_init */
1710	PyType_GenericAlloc,			/* tp_alloc */
1711	PyType_GenericNew,			/* tp_new */
1712	_PyObject_Del,				/* tp_free */
1713};
1714
1715
1716/* Initialize the __dict__ in a type object */
1717
1718static PyObject *
1719create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1720{
1721	PyObject *cfunc;
1722	PyObject *result;
1723
1724	cfunc = PyCFunction_New(meth, NULL);
1725	if (cfunc == NULL)
1726		return NULL;
1727	result = func(cfunc);
1728	Py_DECREF(cfunc);
1729	return result;
1730}
1731
1732static int
1733add_methods(PyTypeObject *type, PyMethodDef *meth)
1734{
1735	PyObject *dict = type->tp_dict;
1736
1737	for (; meth->ml_name != NULL; meth++) {
1738		PyObject *descr;
1739		if (PyDict_GetItemString(dict, meth->ml_name))
1740			continue;
1741		if (meth->ml_flags & METH_CLASS) {
1742			if (meth->ml_flags & METH_STATIC) {
1743				PyErr_SetString(PyExc_ValueError,
1744				     "method cannot be both class and static");
1745				return -1;
1746			}
1747			descr = create_specialmethod(meth, PyClassMethod_New);
1748		}
1749		else if (meth->ml_flags & METH_STATIC) {
1750			descr = create_specialmethod(meth, PyStaticMethod_New);
1751		}
1752		else {
1753			descr = PyDescr_NewMethod(type, meth);
1754		}
1755		if (descr == NULL)
1756			return -1;
1757		if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
1758			return -1;
1759		Py_DECREF(descr);
1760	}
1761	return 0;
1762}
1763
1764static int
1765add_members(PyTypeObject *type, PyMemberDef *memb)
1766{
1767	PyObject *dict = type->tp_dict;
1768
1769	for (; memb->name != NULL; memb++) {
1770		PyObject *descr;
1771		if (PyDict_GetItemString(dict, memb->name))
1772			continue;
1773		descr = PyDescr_NewMember(type, memb);
1774		if (descr == NULL)
1775			return -1;
1776		if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1777			return -1;
1778		Py_DECREF(descr);
1779	}
1780	return 0;
1781}
1782
1783static int
1784add_getset(PyTypeObject *type, PyGetSetDef *gsp)
1785{
1786	PyObject *dict = type->tp_dict;
1787
1788	for (; gsp->name != NULL; gsp++) {
1789		PyObject *descr;
1790		if (PyDict_GetItemString(dict, gsp->name))
1791			continue;
1792		descr = PyDescr_NewGetSet(type, gsp);
1793
1794		if (descr == NULL)
1795			return -1;
1796		if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1797			return -1;
1798		Py_DECREF(descr);
1799	}
1800	return 0;
1801}
1802
1803static void
1804inherit_special(PyTypeObject *type, PyTypeObject *base)
1805{
1806	int oldsize, newsize;
1807
1808	/* Special flag magic */
1809	if (!type->tp_as_buffer && base->tp_as_buffer) {
1810		type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1811		type->tp_flags |=
1812			base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1813	}
1814	if (!type->tp_as_sequence && base->tp_as_sequence) {
1815		type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1816		type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1817	}
1818	if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1819	    (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1820		if ((!type->tp_as_number && base->tp_as_number) ||
1821		    (!type->tp_as_sequence && base->tp_as_sequence)) {
1822			type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1823			if (!type->tp_as_number && !type->tp_as_sequence) {
1824				type->tp_flags |= base->tp_flags &
1825					Py_TPFLAGS_HAVE_INPLACEOPS;
1826			}
1827		}
1828		/* Wow */
1829	}
1830	if (!type->tp_as_number && base->tp_as_number) {
1831		type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1832		type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1833	}
1834
1835	/* Copying basicsize is connected to the GC flags */
1836	oldsize = base->tp_basicsize;
1837	newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1838	if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1839	    (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1840	    (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1841	    (!type->tp_traverse && !type->tp_clear)) {
1842		type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1843		if (type->tp_traverse == NULL)
1844			type->tp_traverse = base->tp_traverse;
1845		if (type->tp_clear == NULL)
1846			type->tp_clear = base->tp_clear;
1847	}
1848	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1849		/* The condition below could use some explanation.
1850		   It appears that tp_new is not inherited for static types
1851		   whose base class is 'object'; this seems to be a precaution
1852		   so that old extension types don't suddenly become
1853		   callable (object.__new__ wouldn't insure the invariants
1854		   that the extension type's own factory function ensures).
1855		   Heap types, of course, are under our control, so they do
1856		   inherit tp_new; static extension types that specify some
1857		   other built-in type as the default are considered
1858		   new-style-aware so they also inherit object.__new__. */
1859		if (base != &PyBaseObject_Type ||
1860		    (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1861			if (type->tp_new == NULL)
1862				type->tp_new = base->tp_new;
1863		}
1864	}
1865	type->tp_basicsize = newsize;
1866
1867	/* Copy other non-function slots */
1868
1869#undef COPYVAL
1870#define COPYVAL(SLOT) \
1871	if (type->SLOT == 0) type->SLOT = base->SLOT
1872
1873	COPYVAL(tp_itemsize);
1874	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1875		COPYVAL(tp_weaklistoffset);
1876	}
1877	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1878		COPYVAL(tp_dictoffset);
1879	}
1880}
1881
1882static void
1883inherit_slots(PyTypeObject *type, PyTypeObject *base)
1884{
1885	PyTypeObject *basebase;
1886
1887#undef SLOTDEFINED
1888#undef COPYSLOT
1889#undef COPYNUM
1890#undef COPYSEQ
1891#undef COPYMAP
1892#undef COPYBUF
1893
1894#define SLOTDEFINED(SLOT) \
1895	(base->SLOT != 0 && \
1896	 (basebase == NULL || base->SLOT != basebase->SLOT))
1897
1898#define COPYSLOT(SLOT) \
1899	if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
1900
1901#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1902#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1903#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1904#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
1905
1906	/* This won't inherit indirect slots (from tp_as_number etc.)
1907	   if type doesn't provide the space. */
1908
1909	if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1910		basebase = base->tp_base;
1911		if (basebase->tp_as_number == NULL)
1912			basebase = NULL;
1913		COPYNUM(nb_add);
1914		COPYNUM(nb_subtract);
1915		COPYNUM(nb_multiply);
1916		COPYNUM(nb_divide);
1917		COPYNUM(nb_remainder);
1918		COPYNUM(nb_divmod);
1919		COPYNUM(nb_power);
1920		COPYNUM(nb_negative);
1921		COPYNUM(nb_positive);
1922		COPYNUM(nb_absolute);
1923		COPYNUM(nb_nonzero);
1924		COPYNUM(nb_invert);
1925		COPYNUM(nb_lshift);
1926		COPYNUM(nb_rshift);
1927		COPYNUM(nb_and);
1928		COPYNUM(nb_xor);
1929		COPYNUM(nb_or);
1930		COPYNUM(nb_coerce);
1931		COPYNUM(nb_int);
1932		COPYNUM(nb_long);
1933		COPYNUM(nb_float);
1934		COPYNUM(nb_oct);
1935		COPYNUM(nb_hex);
1936		COPYNUM(nb_inplace_add);
1937		COPYNUM(nb_inplace_subtract);
1938		COPYNUM(nb_inplace_multiply);
1939		COPYNUM(nb_inplace_divide);
1940		COPYNUM(nb_inplace_remainder);
1941		COPYNUM(nb_inplace_power);
1942		COPYNUM(nb_inplace_lshift);
1943		COPYNUM(nb_inplace_rshift);
1944		COPYNUM(nb_inplace_and);
1945		COPYNUM(nb_inplace_xor);
1946		COPYNUM(nb_inplace_or);
1947		if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1948			COPYNUM(nb_true_divide);
1949			COPYNUM(nb_floor_divide);
1950			COPYNUM(nb_inplace_true_divide);
1951			COPYNUM(nb_inplace_floor_divide);
1952		}
1953	}
1954
1955	if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1956		basebase = base->tp_base;
1957		if (basebase->tp_as_sequence == NULL)
1958			basebase = NULL;
1959		COPYSEQ(sq_length);
1960		COPYSEQ(sq_concat);
1961		COPYSEQ(sq_repeat);
1962		COPYSEQ(sq_item);
1963		COPYSEQ(sq_slice);
1964		COPYSEQ(sq_ass_item);
1965		COPYSEQ(sq_ass_slice);
1966		COPYSEQ(sq_contains);
1967		COPYSEQ(sq_inplace_concat);
1968		COPYSEQ(sq_inplace_repeat);
1969	}
1970
1971	if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1972		basebase = base->tp_base;
1973		if (basebase->tp_as_mapping == NULL)
1974			basebase = NULL;
1975		COPYMAP(mp_length);
1976		COPYMAP(mp_subscript);
1977		COPYMAP(mp_ass_subscript);
1978	}
1979
1980	if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1981		basebase = base->tp_base;
1982		if (basebase->tp_as_buffer == NULL)
1983			basebase = NULL;
1984		COPYBUF(bf_getreadbuffer);
1985		COPYBUF(bf_getwritebuffer);
1986		COPYBUF(bf_getsegcount);
1987		COPYBUF(bf_getcharbuffer);
1988	}
1989
1990	basebase = base->tp_base;
1991
1992	COPYSLOT(tp_dealloc);
1993	COPYSLOT(tp_print);
1994	if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1995		type->tp_getattr = base->tp_getattr;
1996		type->tp_getattro = base->tp_getattro;
1997	}
1998	if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1999		type->tp_setattr = base->tp_setattr;
2000		type->tp_setattro = base->tp_setattro;
2001	}
2002	/* tp_compare see tp_richcompare */
2003	COPYSLOT(tp_repr);
2004	/* tp_hash see tp_richcompare */
2005	COPYSLOT(tp_call);
2006	COPYSLOT(tp_str);
2007	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
2008		if (type->tp_compare == NULL &&
2009		    type->tp_richcompare == NULL &&
2010		    type->tp_hash == NULL)
2011		{
2012			type->tp_compare = base->tp_compare;
2013			type->tp_richcompare = base->tp_richcompare;
2014			type->tp_hash = base->tp_hash;
2015		}
2016	}
2017	else {
2018		COPYSLOT(tp_compare);
2019	}
2020	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2021		COPYSLOT(tp_iter);
2022		COPYSLOT(tp_iternext);
2023	}
2024	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2025		COPYSLOT(tp_descr_get);
2026		COPYSLOT(tp_descr_set);
2027		COPYSLOT(tp_dictoffset);
2028		COPYSLOT(tp_init);
2029		COPYSLOT(tp_alloc);
2030		COPYSLOT(tp_free);
2031		COPYSLOT(tp_is_gc);
2032	}
2033}
2034
2035staticforward int add_operators(PyTypeObject *);
2036staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
2037
2038int
2039PyType_Ready(PyTypeObject *type)
2040{
2041	PyObject *dict, *bases;
2042	PyTypeObject *base;
2043	int i, n;
2044
2045	if (type->tp_flags & Py_TPFLAGS_READY) {
2046		assert(type->tp_dict != NULL);
2047		return 0;
2048	}
2049	assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
2050
2051	type->tp_flags |= Py_TPFLAGS_READYING;
2052
2053	/* Initialize ob_type if NULL.  This means extensions that want to be
2054	   compilable separately on Windows can call PyType_Ready() instead of
2055	   initializing the ob_type field of their type objects. */
2056	if (type->ob_type == NULL)
2057		type->ob_type = &PyType_Type;
2058
2059	/* Initialize tp_base (defaults to BaseObject unless that's us) */
2060	base = type->tp_base;
2061	if (base == NULL && type != &PyBaseObject_Type)
2062		base = type->tp_base = &PyBaseObject_Type;
2063
2064	/* Initialize tp_bases */
2065	bases = type->tp_bases;
2066	if (bases == NULL) {
2067		if (base == NULL)
2068			bases = PyTuple_New(0);
2069		else
2070			bases = Py_BuildValue("(O)", base);
2071		if (bases == NULL)
2072			goto error;
2073		type->tp_bases = bases;
2074	}
2075
2076	/* Initialize the base class */
2077	if (base && base->tp_dict == NULL) {
2078		if (PyType_Ready(base) < 0)
2079			goto error;
2080	}
2081
2082	/* Initialize tp_dict */
2083	dict = type->tp_dict;
2084	if (dict == NULL) {
2085		dict = PyDict_New();
2086		if (dict == NULL)
2087			goto error;
2088		type->tp_dict = dict;
2089	}
2090
2091	/* Add type-specific descriptors to tp_dict */
2092	if (add_operators(type) < 0)
2093		goto error;
2094	if (type->tp_methods != NULL) {
2095		if (add_methods(type, type->tp_methods) < 0)
2096			goto error;
2097	}
2098	if (type->tp_members != NULL) {
2099		if (add_members(type, type->tp_members) < 0)
2100			goto error;
2101	}
2102	if (type->tp_getset != NULL) {
2103		if (add_getset(type, type->tp_getset) < 0)
2104			goto error;
2105	}
2106
2107	/* Calculate method resolution order */
2108	if (mro_internal(type) < 0) {
2109		goto error;
2110	}
2111
2112	/* Inherit special flags from dominant base */
2113	if (type->tp_base != NULL)
2114		inherit_special(type, type->tp_base);
2115
2116	/* Initialize tp_dict properly */
2117	bases = type->tp_mro;
2118	assert(bases != NULL);
2119	assert(PyTuple_Check(bases));
2120	n = PyTuple_GET_SIZE(bases);
2121	for (i = 1; i < n; i++) {
2122		PyObject *b = PyTuple_GET_ITEM(bases, i);
2123		if (PyType_Check(b))
2124			inherit_slots(type, (PyTypeObject *)b);
2125	}
2126
2127	/* if the type dictionary doesn't contain a __doc__, set it from
2128	   the tp_doc slot.
2129	 */
2130	if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2131		if (type->tp_doc != NULL) {
2132			PyObject *doc = PyString_FromString(type->tp_doc);
2133			PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2134			Py_DECREF(doc);
2135		} else {
2136			PyDict_SetItemString(type->tp_dict,
2137					     "__doc__", Py_None);
2138		}
2139	}
2140
2141	/* Some more special stuff */
2142	base = type->tp_base;
2143	if (base != NULL) {
2144		if (type->tp_as_number == NULL)
2145			type->tp_as_number = base->tp_as_number;
2146		if (type->tp_as_sequence == NULL)
2147			type->tp_as_sequence = base->tp_as_sequence;
2148		if (type->tp_as_mapping == NULL)
2149			type->tp_as_mapping = base->tp_as_mapping;
2150	}
2151
2152	/* Link into each base class's list of subclasses */
2153	bases = type->tp_bases;
2154	n = PyTuple_GET_SIZE(bases);
2155	for (i = 0; i < n; i++) {
2156		PyObject *b = PyTuple_GET_ITEM(bases, i);
2157		if (PyType_Check(b) &&
2158		    add_subclass((PyTypeObject *)b, type) < 0)
2159			goto error;
2160	}
2161
2162	/* All done -- set the ready flag */
2163	assert(type->tp_dict != NULL);
2164	type->tp_flags =
2165		(type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
2166	return 0;
2167
2168  error:
2169	type->tp_flags &= ~Py_TPFLAGS_READYING;
2170	return -1;
2171}
2172
2173static int
2174add_subclass(PyTypeObject *base, PyTypeObject *type)
2175{
2176	int i;
2177	PyObject *list, *ref, *new;
2178
2179	list = base->tp_subclasses;
2180	if (list == NULL) {
2181		base->tp_subclasses = list = PyList_New(0);
2182		if (list == NULL)
2183			return -1;
2184	}
2185	assert(PyList_Check(list));
2186	new = PyWeakref_NewRef((PyObject *)type, NULL);
2187	i = PyList_GET_SIZE(list);
2188	while (--i >= 0) {
2189		ref = PyList_GET_ITEM(list, i);
2190		assert(PyWeakref_CheckRef(ref));
2191		if (PyWeakref_GET_OBJECT(ref) == Py_None)
2192			return PyList_SetItem(list, i, new);
2193	}
2194	i = PyList_Append(list, new);
2195	Py_DECREF(new);
2196	return i;
2197}
2198
2199
2200/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2201
2202/* There's a wrapper *function* for each distinct function typedef used
2203   for type object slots (e.g. binaryfunc, ternaryfunc, etc.).  There's a
2204   wrapper *table* for each distinct operation (e.g. __len__, __add__).
2205   Most tables have only one entry; the tables for binary operators have two
2206   entries, one regular and one with reversed arguments. */
2207
2208static PyObject *
2209wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2210{
2211	inquiry func = (inquiry)wrapped;
2212	int res;
2213
2214	if (!PyArg_ParseTuple(args, ""))
2215		return NULL;
2216	res = (*func)(self);
2217	if (res == -1 && PyErr_Occurred())
2218		return NULL;
2219	return PyInt_FromLong((long)res);
2220}
2221
2222static PyObject *
2223wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2224{
2225	binaryfunc func = (binaryfunc)wrapped;
2226	PyObject *other;
2227
2228	if (!PyArg_ParseTuple(args, "O", &other))
2229		return NULL;
2230	return (*func)(self, other);
2231}
2232
2233static PyObject *
2234wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2235{
2236	binaryfunc func = (binaryfunc)wrapped;
2237	PyObject *other;
2238
2239	if (!PyArg_ParseTuple(args, "O", &other))
2240		return NULL;
2241	if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2242	    !PyType_IsSubtype(other->ob_type, self->ob_type)) {
2243		Py_INCREF(Py_NotImplemented);
2244		return Py_NotImplemented;
2245	}
2246	return (*func)(self, other);
2247}
2248
2249static PyObject *
2250wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2251{
2252	binaryfunc func = (binaryfunc)wrapped;
2253	PyObject *other;
2254
2255	if (!PyArg_ParseTuple(args, "O", &other))
2256		return NULL;
2257	if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2258	    !PyType_IsSubtype(other->ob_type, self->ob_type)) {
2259		Py_INCREF(Py_NotImplemented);
2260		return Py_NotImplemented;
2261	}
2262	return (*func)(other, self);
2263}
2264
2265static PyObject *
2266wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2267{
2268	coercion func = (coercion)wrapped;
2269	PyObject *other, *res;
2270	int ok;
2271
2272	if (!PyArg_ParseTuple(args, "O", &other))
2273		return NULL;
2274	ok = func(&self, &other);
2275	if (ok < 0)
2276		return NULL;
2277	if (ok > 0) {
2278		Py_INCREF(Py_NotImplemented);
2279		return Py_NotImplemented;
2280	}
2281	res = PyTuple_New(2);
2282	if (res == NULL) {
2283		Py_DECREF(self);
2284		Py_DECREF(other);
2285		return NULL;
2286	}
2287	PyTuple_SET_ITEM(res, 0, self);
2288	PyTuple_SET_ITEM(res, 1, other);
2289	return res;
2290}
2291
2292static PyObject *
2293wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2294{
2295	ternaryfunc func = (ternaryfunc)wrapped;
2296	PyObject *other;
2297	PyObject *third = Py_None;
2298
2299	/* Note: This wrapper only works for __pow__() */
2300
2301	if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2302		return NULL;
2303	return (*func)(self, other, third);
2304}
2305
2306static PyObject *
2307wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2308{
2309	ternaryfunc func = (ternaryfunc)wrapped;
2310	PyObject *other;
2311	PyObject *third = Py_None;
2312
2313	/* Note: This wrapper only works for __pow__() */
2314
2315	if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2316		return NULL;
2317	return (*func)(other, self, third);
2318}
2319
2320static PyObject *
2321wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2322{
2323	unaryfunc func = (unaryfunc)wrapped;
2324
2325	if (!PyArg_ParseTuple(args, ""))
2326		return NULL;
2327	return (*func)(self);
2328}
2329
2330static PyObject *
2331wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2332{
2333	intargfunc func = (intargfunc)wrapped;
2334	int i;
2335
2336	if (!PyArg_ParseTuple(args, "i", &i))
2337		return NULL;
2338	return (*func)(self, i);
2339}
2340
2341static int
2342getindex(PyObject *self, PyObject *arg)
2343{
2344	int i;
2345
2346	i = PyInt_AsLong(arg);
2347	if (i == -1 && PyErr_Occurred())
2348		return -1;
2349	if (i < 0) {
2350		PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2351		if (sq && sq->sq_length) {
2352			int n = (*sq->sq_length)(self);
2353			if (n < 0)
2354				return -1;
2355			i += n;
2356		}
2357	}
2358	return i;
2359}
2360
2361static PyObject *
2362wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2363{
2364	intargfunc func = (intargfunc)wrapped;
2365	PyObject *arg;
2366	int i;
2367
2368	if (PyTuple_GET_SIZE(args) == 1) {
2369		arg = PyTuple_GET_ITEM(args, 0);
2370		i = getindex(self, arg);
2371		if (i == -1 && PyErr_Occurred())
2372			return NULL;
2373		return (*func)(self, i);
2374	}
2375	PyArg_ParseTuple(args, "O", &arg);
2376	assert(PyErr_Occurred());
2377	return NULL;
2378}
2379
2380static PyObject *
2381wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2382{
2383	intintargfunc func = (intintargfunc)wrapped;
2384	int i, j;
2385
2386	if (!PyArg_ParseTuple(args, "ii", &i, &j))
2387		return NULL;
2388	return (*func)(self, i, j);
2389}
2390
2391static PyObject *
2392wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
2393{
2394	intobjargproc func = (intobjargproc)wrapped;
2395	int i, res;
2396	PyObject *arg, *value;
2397
2398	if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2399		return NULL;
2400	i = getindex(self, arg);
2401	if (i == -1 && PyErr_Occurred())
2402		return NULL;
2403	res = (*func)(self, i, value);
2404	if (res == -1 && PyErr_Occurred())
2405		return NULL;
2406	Py_INCREF(Py_None);
2407	return Py_None;
2408}
2409
2410static PyObject *
2411wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
2412{
2413	intobjargproc func = (intobjargproc)wrapped;
2414	int i, res;
2415	PyObject *arg;
2416
2417	if (!PyArg_ParseTuple(args, "O", &arg))
2418		return NULL;
2419	i = getindex(self, arg);
2420	if (i == -1 && PyErr_Occurred())
2421		return NULL;
2422	res = (*func)(self, i, NULL);
2423	if (res == -1 && PyErr_Occurred())
2424		return NULL;
2425	Py_INCREF(Py_None);
2426	return Py_None;
2427}
2428
2429static PyObject *
2430wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2431{
2432	intintobjargproc func = (intintobjargproc)wrapped;
2433	int i, j, res;
2434	PyObject *value;
2435
2436	if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2437		return NULL;
2438	res = (*func)(self, i, j, value);
2439	if (res == -1 && PyErr_Occurred())
2440		return NULL;
2441	Py_INCREF(Py_None);
2442	return Py_None;
2443}
2444
2445static PyObject *
2446wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2447{
2448	intintobjargproc func = (intintobjargproc)wrapped;
2449	int i, j, res;
2450
2451	if (!PyArg_ParseTuple(args, "ii", &i, &j))
2452		return NULL;
2453	res = (*func)(self, i, j, NULL);
2454	if (res == -1 && PyErr_Occurred())
2455		return NULL;
2456	Py_INCREF(Py_None);
2457	return Py_None;
2458}
2459
2460/* XXX objobjproc is a misnomer; should be objargpred */
2461static PyObject *
2462wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2463{
2464	objobjproc func = (objobjproc)wrapped;
2465	int res;
2466	PyObject *value;
2467
2468	if (!PyArg_ParseTuple(args, "O", &value))
2469		return NULL;
2470	res = (*func)(self, value);
2471	if (res == -1 && PyErr_Occurred())
2472		return NULL;
2473	return PyInt_FromLong((long)res);
2474}
2475
2476static PyObject *
2477wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2478{
2479	objobjargproc func = (objobjargproc)wrapped;
2480	int res;
2481	PyObject *key, *value;
2482
2483	if (!PyArg_ParseTuple(args, "OO", &key, &value))
2484		return NULL;
2485	res = (*func)(self, key, value);
2486	if (res == -1 && PyErr_Occurred())
2487		return NULL;
2488	Py_INCREF(Py_None);
2489	return Py_None;
2490}
2491
2492static PyObject *
2493wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2494{
2495	objobjargproc func = (objobjargproc)wrapped;
2496	int res;
2497	PyObject *key;
2498
2499	if (!PyArg_ParseTuple(args, "O", &key))
2500		return NULL;
2501	res = (*func)(self, key, NULL);
2502	if (res == -1 && PyErr_Occurred())
2503		return NULL;
2504	Py_INCREF(Py_None);
2505	return Py_None;
2506}
2507
2508static PyObject *
2509wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2510{
2511	cmpfunc func = (cmpfunc)wrapped;
2512	int res;
2513	PyObject *other;
2514
2515	if (!PyArg_ParseTuple(args, "O", &other))
2516		return NULL;
2517	if (other->ob_type->tp_compare != func &&
2518	    !PyType_IsSubtype(other->ob_type, self->ob_type)) {
2519		PyErr_Format(
2520			PyExc_TypeError,
2521			"%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2522			self->ob_type->tp_name,
2523			self->ob_type->tp_name,
2524			other->ob_type->tp_name);
2525		return NULL;
2526	}
2527	res = (*func)(self, other);
2528	if (PyErr_Occurred())
2529		return NULL;
2530	return PyInt_FromLong((long)res);
2531}
2532
2533static PyObject *
2534wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2535{
2536	setattrofunc func = (setattrofunc)wrapped;
2537	int res;
2538	PyObject *name, *value;
2539
2540	if (!PyArg_ParseTuple(args, "OO", &name, &value))
2541		return NULL;
2542	res = (*func)(self, name, value);
2543	if (res < 0)
2544		return NULL;
2545	Py_INCREF(Py_None);
2546	return Py_None;
2547}
2548
2549static PyObject *
2550wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2551{
2552	setattrofunc func = (setattrofunc)wrapped;
2553	int res;
2554	PyObject *name;
2555
2556	if (!PyArg_ParseTuple(args, "O", &name))
2557		return NULL;
2558	res = (*func)(self, name, NULL);
2559	if (res < 0)
2560		return NULL;
2561	Py_INCREF(Py_None);
2562	return Py_None;
2563}
2564
2565static PyObject *
2566wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2567{
2568	hashfunc func = (hashfunc)wrapped;
2569	long res;
2570
2571	if (!PyArg_ParseTuple(args, ""))
2572		return NULL;
2573	res = (*func)(self);
2574	if (res == -1 && PyErr_Occurred())
2575		return NULL;
2576	return PyInt_FromLong(res);
2577}
2578
2579static PyObject *
2580wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
2581{
2582	ternaryfunc func = (ternaryfunc)wrapped;
2583
2584	return (*func)(self, args, kwds);
2585}
2586
2587static PyObject *
2588wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2589{
2590	richcmpfunc func = (richcmpfunc)wrapped;
2591	PyObject *other;
2592
2593	if (!PyArg_ParseTuple(args, "O", &other))
2594		return NULL;
2595	return (*func)(self, other, op);
2596}
2597
2598#undef RICHCMP_WRAPPER
2599#define RICHCMP_WRAPPER(NAME, OP) \
2600static PyObject * \
2601richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2602{ \
2603	return wrap_richcmpfunc(self, args, wrapped, OP); \
2604}
2605
2606RICHCMP_WRAPPER(lt, Py_LT)
2607RICHCMP_WRAPPER(le, Py_LE)
2608RICHCMP_WRAPPER(eq, Py_EQ)
2609RICHCMP_WRAPPER(ne, Py_NE)
2610RICHCMP_WRAPPER(gt, Py_GT)
2611RICHCMP_WRAPPER(ge, Py_GE)
2612
2613static PyObject *
2614wrap_next(PyObject *self, PyObject *args, void *wrapped)
2615{
2616	unaryfunc func = (unaryfunc)wrapped;
2617	PyObject *res;
2618
2619	if (!PyArg_ParseTuple(args, ""))
2620		return NULL;
2621	res = (*func)(self);
2622	if (res == NULL && !PyErr_Occurred())
2623		PyErr_SetNone(PyExc_StopIteration);
2624	return res;
2625}
2626
2627static PyObject *
2628wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2629{
2630	descrgetfunc func = (descrgetfunc)wrapped;
2631	PyObject *obj;
2632	PyObject *type = NULL;
2633
2634	if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2635		return NULL;
2636	return (*func)(self, obj, type);
2637}
2638
2639static PyObject *
2640wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
2641{
2642	descrsetfunc func = (descrsetfunc)wrapped;
2643	PyObject *obj, *value;
2644	int ret;
2645
2646	if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2647		return NULL;
2648	ret = (*func)(self, obj, value);
2649	if (ret < 0)
2650		return NULL;
2651	Py_INCREF(Py_None);
2652	return Py_None;
2653}
2654
2655static PyObject *
2656wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
2657{
2658	initproc func = (initproc)wrapped;
2659
2660	if (func(self, args, kwds) < 0)
2661		return NULL;
2662	Py_INCREF(Py_None);
2663	return Py_None;
2664}
2665
2666static PyObject *
2667tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
2668{
2669	PyTypeObject *type, *subtype, *staticbase;
2670	PyObject *arg0, *res;
2671
2672	if (self == NULL || !PyType_Check(self))
2673		Py_FatalError("__new__() called with non-type 'self'");
2674	type = (PyTypeObject *)self;
2675	if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
2676		PyErr_Format(PyExc_TypeError,
2677			     "%s.__new__(): not enough arguments",
2678			     type->tp_name);
2679		return NULL;
2680	}
2681	arg0 = PyTuple_GET_ITEM(args, 0);
2682	if (!PyType_Check(arg0)) {
2683		PyErr_Format(PyExc_TypeError,
2684			     "%s.__new__(X): X is not a type object (%s)",
2685			     type->tp_name,
2686			     arg0->ob_type->tp_name);
2687		return NULL;
2688	}
2689	subtype = (PyTypeObject *)arg0;
2690	if (!PyType_IsSubtype(subtype, type)) {
2691		PyErr_Format(PyExc_TypeError,
2692			     "%s.__new__(%s): %s is not a subtype of %s",
2693			     type->tp_name,
2694			     subtype->tp_name,
2695			     subtype->tp_name,
2696			     type->tp_name);
2697		return NULL;
2698	}
2699
2700	/* Check that the use doesn't do something silly and unsafe like
2701	   object.__new__(dict).  To do this, we check that the
2702	   most derived base that's not a heap type is this type. */
2703	staticbase = subtype;
2704	while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2705		staticbase = staticbase->tp_base;
2706	if (staticbase->tp_new != type->tp_new) {
2707		PyErr_Format(PyExc_TypeError,
2708			     "%s.__new__(%s) is not safe, use %s.__new__()",
2709			     type->tp_name,
2710			     subtype->tp_name,
2711			     staticbase == NULL ? "?" : staticbase->tp_name);
2712		return NULL;
2713	}
2714
2715	args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2716	if (args == NULL)
2717		return NULL;
2718	res = type->tp_new(subtype, args, kwds);
2719	Py_DECREF(args);
2720	return res;
2721}
2722
2723static struct PyMethodDef tp_new_methoddef[] = {
2724	{"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2725	 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
2726	{0}
2727};
2728
2729static int
2730add_tp_new_wrapper(PyTypeObject *type)
2731{
2732	PyObject *func;
2733
2734	if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
2735		return 0;
2736	func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
2737	if (func == NULL)
2738		return -1;
2739	return PyDict_SetItemString(type->tp_dict, "__new__", func);
2740}
2741
2742/* Slot wrappers that call the corresponding __foo__ slot.  See comments
2743   below at override_slots() for more explanation. */
2744
2745#define SLOT0(FUNCNAME, OPSTR) \
2746static PyObject * \
2747FUNCNAME(PyObject *self) \
2748{ \
2749	static PyObject *cache_str; \
2750	return call_method(self, OPSTR, &cache_str, "()"); \
2751}
2752
2753#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
2754static PyObject * \
2755FUNCNAME(PyObject *self, ARG1TYPE arg1) \
2756{ \
2757	static PyObject *cache_str; \
2758	return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
2759}
2760
2761
2762#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
2763static PyObject * \
2764FUNCNAME(PyObject *self, PyObject *other) \
2765{ \
2766	static PyObject *cache_str, *rcache_str; \
2767	int do_other = self->ob_type != other->ob_type && \
2768	    other->ob_type->tp_as_number != NULL && \
2769	    other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
2770	if (self->ob_type->tp_as_number != NULL && \
2771	    self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2772		PyObject *r; \
2773		if (do_other && \
2774		    PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2775			r = call_maybe( \
2776				other, ROPSTR, &rcache_str, "(O)", self); \
2777			if (r != Py_NotImplemented) \
2778				return r; \
2779			Py_DECREF(r); \
2780			do_other = 0; \
2781		} \
2782		r = call_maybe( \
2783			self, OPSTR, &cache_str, "(O)", other); \
2784		if (r != Py_NotImplemented || \
2785		    other->ob_type == self->ob_type) \
2786			return r; \
2787		Py_DECREF(r); \
2788	} \
2789	if (do_other) { \
2790		return call_maybe( \
2791			other, ROPSTR, &rcache_str, "(O)", self); \
2792	} \
2793	Py_INCREF(Py_NotImplemented); \
2794	return Py_NotImplemented; \
2795}
2796
2797#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2798	SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2799
2800#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2801static PyObject * \
2802FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2803{ \
2804	static PyObject *cache_str; \
2805	return call_method(self, OPSTR, &cache_str, \
2806			   "(" ARGCODES ")", arg1, arg2); \
2807}
2808
2809static int
2810slot_sq_length(PyObject *self)
2811{
2812	static PyObject *len_str;
2813	PyObject *res = call_method(self, "__len__", &len_str, "()");
2814	int len;
2815
2816	if (res == NULL)
2817		return -1;
2818	len = (int)PyInt_AsLong(res);
2819	Py_DECREF(res);
2820	return len;
2821}
2822
2823SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2824SLOT1(slot_sq_repeat, "__mul__", int, "i")
2825
2826/* Super-optimized version of slot_sq_item.
2827   Other slots could do the same... */
2828static PyObject *
2829slot_sq_item(PyObject *self, int i)
2830{
2831	static PyObject *getitem_str;
2832	PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2833	descrgetfunc f;
2834
2835	if (getitem_str == NULL) {
2836		getitem_str = PyString_InternFromString("__getitem__");
2837		if (getitem_str == NULL)
2838			return NULL;
2839	}
2840	func = _PyType_Lookup(self->ob_type, getitem_str);
2841	if (func != NULL) {
2842		if ((f = func->ob_type->tp_descr_get) == NULL)
2843			Py_INCREF(func);
2844		else
2845			func = f(func, self, (PyObject *)(self->ob_type));
2846		ival = PyInt_FromLong(i);
2847		if (ival != NULL) {
2848			args = PyTuple_New(1);
2849			if (args != NULL) {
2850				PyTuple_SET_ITEM(args, 0, ival);
2851				retval = PyObject_Call(func, args, NULL);
2852				Py_XDECREF(args);
2853				Py_XDECREF(func);
2854				return retval;
2855			}
2856		}
2857	}
2858	else {
2859		PyErr_SetObject(PyExc_AttributeError, getitem_str);
2860	}
2861	Py_XDECREF(args);
2862	Py_XDECREF(ival);
2863	Py_XDECREF(func);
2864	return NULL;
2865}
2866
2867SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
2868
2869static int
2870slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2871{
2872	PyObject *res;
2873	static PyObject *delitem_str, *setitem_str;
2874
2875	if (value == NULL)
2876		res = call_method(self, "__delitem__", &delitem_str,
2877				  "(i)", index);
2878	else
2879		res = call_method(self, "__setitem__", &setitem_str,
2880				  "(iO)", index, value);
2881	if (res == NULL)
2882		return -1;
2883	Py_DECREF(res);
2884	return 0;
2885}
2886
2887static int
2888slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2889{
2890	PyObject *res;
2891	static PyObject *delslice_str, *setslice_str;
2892
2893	if (value == NULL)
2894		res = call_method(self, "__delslice__", &delslice_str,
2895				  "(ii)", i, j);
2896	else
2897		res = call_method(self, "__setslice__", &setslice_str,
2898				  "(iiO)", i, j, value);
2899	if (res == NULL)
2900		return -1;
2901	Py_DECREF(res);
2902	return 0;
2903}
2904
2905static int
2906slot_sq_contains(PyObject *self, PyObject *value)
2907{
2908	PyObject *func, *res, *args;
2909	static PyObject *contains_str;
2910
2911	func = lookup_maybe(self, "__contains__", &contains_str);
2912
2913	if (func != NULL) {
2914		args = Py_BuildValue("(O)", value);
2915		if (args == NULL)
2916			res = NULL;
2917		else {
2918			res = PyObject_Call(func, args, NULL);
2919			Py_DECREF(args);
2920		}
2921		Py_DECREF(func);
2922		if (res == NULL)
2923			return -1;
2924		return PyObject_IsTrue(res);
2925	}
2926	else if (PyErr_Occurred())
2927		return -1;
2928	else {
2929		return _PySequence_IterSearch(self, value,
2930					      PY_ITERSEARCH_CONTAINS);
2931	}
2932}
2933
2934SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2935SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
2936
2937#define slot_mp_length slot_sq_length
2938
2939SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
2940
2941static int
2942slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2943{
2944	PyObject *res;
2945	static PyObject *delitem_str, *setitem_str;
2946
2947	if (value == NULL)
2948		res = call_method(self, "__delitem__", &delitem_str,
2949				  "(O)", key);
2950	else
2951		res = call_method(self, "__setitem__", &setitem_str,
2952				 "(OO)", key, value);
2953	if (res == NULL)
2954		return -1;
2955	Py_DECREF(res);
2956	return 0;
2957}
2958
2959SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2960SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2961SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2962SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2963SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2964SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2965
2966staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2967
2968SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2969	     nb_power, "__pow__", "__rpow__")
2970
2971static PyObject *
2972slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2973{
2974	static PyObject *pow_str;
2975
2976	if (modulus == Py_None)
2977		return slot_nb_power_binary(self, other);
2978	/* Three-arg power doesn't use __rpow__ */
2979	return call_method(self, "__pow__", &pow_str,
2980			   "(OO)", other, modulus);
2981}
2982
2983SLOT0(slot_nb_negative, "__neg__")
2984SLOT0(slot_nb_positive, "__pos__")
2985SLOT0(slot_nb_absolute, "__abs__")
2986
2987static int
2988slot_nb_nonzero(PyObject *self)
2989{
2990	PyObject *func, *res;
2991	static PyObject *nonzero_str, *len_str;
2992
2993	func = lookup_maybe(self, "__nonzero__", &nonzero_str);
2994	if (func == NULL) {
2995		if (PyErr_Occurred())
2996			return -1;
2997		func = lookup_maybe(self, "__len__", &len_str);
2998		if (func == NULL) {
2999			if (PyErr_Occurred())
3000				return -1;
3001			else
3002				return 1;
3003		}
3004	}
3005	res = PyObject_CallObject(func, NULL);
3006	Py_DECREF(func);
3007	if (res == NULL)
3008		return -1;
3009	return PyObject_IsTrue(res);
3010}
3011
3012SLOT0(slot_nb_invert, "__invert__")
3013SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3014SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3015SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3016SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3017SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
3018
3019static int
3020slot_nb_coerce(PyObject **a, PyObject **b)
3021{
3022	static PyObject *coerce_str;
3023	PyObject *self = *a, *other = *b;
3024
3025	if (self->ob_type->tp_as_number != NULL &&
3026	    self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3027		PyObject *r;
3028		r = call_maybe(
3029			self, "__coerce__", &coerce_str, "(O)", other);
3030		if (r == NULL)
3031			return -1;
3032		if (r == Py_NotImplemented) {
3033			Py_DECREF(r);
3034		}
3035		else {
3036			if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3037				PyErr_SetString(PyExc_TypeError,
3038					"__coerce__ didn't return a 2-tuple");
3039				Py_DECREF(r);
3040				return -1;
3041			}
3042			*a = PyTuple_GET_ITEM(r, 0);
3043			Py_INCREF(*a);
3044			*b = PyTuple_GET_ITEM(r, 1);
3045			Py_INCREF(*b);
3046			Py_DECREF(r);
3047			return 0;
3048		}
3049	}
3050	if (other->ob_type->tp_as_number != NULL &&
3051	    other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3052		PyObject *r;
3053		r = call_maybe(
3054			other, "__coerce__", &coerce_str, "(O)", self);
3055		if (r == NULL)
3056			return -1;
3057		if (r == Py_NotImplemented) {
3058			Py_DECREF(r);
3059			return 1;
3060		}
3061		if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3062			PyErr_SetString(PyExc_TypeError,
3063					"__coerce__ didn't return a 2-tuple");
3064			Py_DECREF(r);
3065			return -1;
3066		}
3067		*a = PyTuple_GET_ITEM(r, 1);
3068		Py_INCREF(*a);
3069		*b = PyTuple_GET_ITEM(r, 0);
3070		Py_INCREF(*b);
3071		Py_DECREF(r);
3072		return 0;
3073	}
3074	return 1;
3075}
3076
3077SLOT0(slot_nb_int, "__int__")
3078SLOT0(slot_nb_long, "__long__")
3079SLOT0(slot_nb_float, "__float__")
3080SLOT0(slot_nb_oct, "__oct__")
3081SLOT0(slot_nb_hex, "__hex__")
3082SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3083SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3084SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3085SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3086SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3087SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3088SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3089SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3090SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3091SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3092SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3093SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3094	 "__floordiv__", "__rfloordiv__")
3095SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3096SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3097SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
3098
3099static int
3100half_compare(PyObject *self, PyObject *other)
3101{
3102	PyObject *func, *args, *res;
3103	static PyObject *cmp_str;
3104	int c;
3105
3106	func = lookup_method(self, "__cmp__", &cmp_str);
3107	if (func == NULL) {
3108		PyErr_Clear();
3109	}
3110	else {
3111		args = Py_BuildValue("(O)", other);
3112		if (args == NULL)
3113			res = NULL;
3114		else {
3115			res = PyObject_Call(func, args, NULL);
3116			Py_DECREF(args);
3117		}
3118		if (res != Py_NotImplemented) {
3119			if (res == NULL)
3120				return -2;
3121			c = PyInt_AsLong(res);
3122			Py_DECREF(res);
3123			if (c == -1 && PyErr_Occurred())
3124				return -2;
3125			return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3126		}
3127		Py_DECREF(res);
3128	}
3129	return 2;
3130}
3131
3132/* This slot is published for the benefit of try_3way_compare in object.c */
3133int
3134_PyObject_SlotCompare(PyObject *self, PyObject *other)
3135{
3136	int c;
3137
3138	if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
3139		c = half_compare(self, other);
3140		if (c <= 1)
3141			return c;
3142	}
3143	if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
3144		c = half_compare(other, self);
3145		if (c < -1)
3146			return -2;
3147		if (c <= 1)
3148			return -c;
3149	}
3150	return (void *)self < (void *)other ? -1 :
3151		(void *)self > (void *)other ? 1 : 0;
3152}
3153
3154static PyObject *
3155slot_tp_repr(PyObject *self)
3156{
3157	PyObject *func, *res;
3158	static PyObject *repr_str;
3159
3160	func = lookup_method(self, "__repr__", &repr_str);
3161	if (func != NULL) {
3162		res = PyEval_CallObject(func, NULL);
3163		Py_DECREF(func);
3164		return res;
3165	}
3166	PyErr_Clear();
3167	return PyString_FromFormat("<%s object at %p>",
3168				   self->ob_type->tp_name, self);
3169}
3170
3171static PyObject *
3172slot_tp_str(PyObject *self)
3173{
3174	PyObject *func, *res;
3175	static PyObject *str_str;
3176
3177	func = lookup_method(self, "__str__", &str_str);
3178	if (func != NULL) {
3179		res = PyEval_CallObject(func, NULL);
3180		Py_DECREF(func);
3181		return res;
3182	}
3183	else {
3184		PyErr_Clear();
3185		return slot_tp_repr(self);
3186	}
3187}
3188
3189static long
3190slot_tp_hash(PyObject *self)
3191{
3192	PyObject *func, *res;
3193	static PyObject *hash_str, *eq_str, *cmp_str;
3194
3195	long h;
3196
3197	func = lookup_method(self, "__hash__", &hash_str);
3198
3199	if (func != NULL) {
3200		res = PyEval_CallObject(func, NULL);
3201		Py_DECREF(func);
3202		if (res == NULL)
3203			return -1;
3204		h = PyInt_AsLong(res);
3205	}
3206	else {
3207		PyErr_Clear();
3208		func = lookup_method(self, "__eq__", &eq_str);
3209		if (func == NULL) {
3210			PyErr_Clear();
3211			func = lookup_method(self, "__cmp__", &cmp_str);
3212		}
3213		if (func != NULL) {
3214			Py_DECREF(func);
3215			PyErr_SetString(PyExc_TypeError, "unhashable type");
3216			return -1;
3217		}
3218		PyErr_Clear();
3219		h = _Py_HashPointer((void *)self);
3220	}
3221	if (h == -1 && !PyErr_Occurred())
3222		h = -2;
3223	return h;
3224}
3225
3226static PyObject *
3227slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3228{
3229	static PyObject *call_str;
3230	PyObject *meth = lookup_method(self, "__call__", &call_str);
3231	PyObject *res;
3232
3233	if (meth == NULL)
3234		return NULL;
3235	res = PyObject_Call(meth, args, kwds);
3236	Py_DECREF(meth);
3237	return res;
3238}
3239
3240/* There are two slot dispatch functions for tp_getattro.
3241
3242   - slot_tp_getattro() is used when __getattribute__ is overridden
3243     but no __getattr__ hook is present;
3244
3245   - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3246
3247   The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3248   detects the absence of __getattr__ and then installs the simpler slot if
3249   necessary. */
3250
3251static PyObject *
3252slot_tp_getattro(PyObject *self, PyObject *name)
3253{
3254	static PyObject *getattribute_str = NULL;
3255	return call_method(self, "__getattribute__", &getattribute_str,
3256			   "(O)", name);
3257}
3258
3259static PyObject *
3260slot_tp_getattr_hook(PyObject *self, PyObject *name)
3261{
3262	PyTypeObject *tp = self->ob_type;
3263	PyObject *getattr, *getattribute, *res;
3264	static PyObject *getattribute_str = NULL;
3265	static PyObject *getattr_str = NULL;
3266
3267	if (getattr_str == NULL) {
3268		getattr_str = PyString_InternFromString("__getattr__");
3269		if (getattr_str == NULL)
3270			return NULL;
3271	}
3272	if (getattribute_str == NULL) {
3273		getattribute_str =
3274			PyString_InternFromString("__getattribute__");
3275		if (getattribute_str == NULL)
3276			return NULL;
3277	}
3278	getattr = _PyType_Lookup(tp, getattr_str);
3279	if (getattr == NULL) {
3280		/* No __getattr__ hook: use a simpler dispatcher */
3281		tp->tp_getattro = slot_tp_getattro;
3282		return slot_tp_getattro(self, name);
3283	}
3284	getattribute = _PyType_Lookup(tp, getattribute_str);
3285	if (getattribute == NULL ||
3286	    (getattribute->ob_type == &PyWrapperDescr_Type &&
3287	     ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3288	     (void *)PyObject_GenericGetAttr))
3289		res = PyObject_GenericGetAttr(self, name);
3290	else
3291		res = PyObject_CallFunction(getattribute, "OO", self, name);
3292	if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
3293		PyErr_Clear();
3294		res = PyObject_CallFunction(getattr, "OO", self, name);
3295	}
3296	return res;
3297}
3298
3299static int
3300slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3301{
3302	PyObject *res;
3303	static PyObject *delattr_str, *setattr_str;
3304
3305	if (value == NULL)
3306		res = call_method(self, "__delattr__", &delattr_str,
3307				  "(O)", name);
3308	else
3309		res = call_method(self, "__setattr__", &setattr_str,
3310				  "(OO)", name, value);
3311	if (res == NULL)
3312		return -1;
3313	Py_DECREF(res);
3314	return 0;
3315}
3316
3317/* Map rich comparison operators to their __xx__ namesakes */
3318static char *name_op[] = {
3319	"__lt__",
3320	"__le__",
3321	"__eq__",
3322	"__ne__",
3323	"__gt__",
3324	"__ge__",
3325};
3326
3327static PyObject *
3328half_richcompare(PyObject *self, PyObject *other, int op)
3329{
3330	PyObject *func, *args, *res;
3331	static PyObject *op_str[6];
3332
3333	func = lookup_method(self, name_op[op], &op_str[op]);
3334	if (func == NULL) {
3335		PyErr_Clear();
3336		Py_INCREF(Py_NotImplemented);
3337		return Py_NotImplemented;
3338	}
3339	args = Py_BuildValue("(O)", other);
3340	if (args == NULL)
3341		res = NULL;
3342	else {
3343		res = PyObject_Call(func, args, NULL);
3344		Py_DECREF(args);
3345	}
3346	Py_DECREF(func);
3347	return res;
3348}
3349
3350/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3351static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3352
3353static PyObject *
3354slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3355{
3356	PyObject *res;
3357
3358	if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3359		res = half_richcompare(self, other, op);
3360		if (res != Py_NotImplemented)
3361			return res;
3362		Py_DECREF(res);
3363	}
3364	if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3365		res = half_richcompare(other, self, swapped_op[op]);
3366		if (res != Py_NotImplemented) {
3367			return res;
3368		}
3369		Py_DECREF(res);
3370	}
3371	Py_INCREF(Py_NotImplemented);
3372	return Py_NotImplemented;
3373}
3374
3375static PyObject *
3376slot_tp_iter(PyObject *self)
3377{
3378	PyObject *func, *res;
3379	static PyObject *iter_str, *getitem_str;
3380
3381	func = lookup_method(self, "__iter__", &iter_str);
3382	if (func != NULL) {
3383		 res = PyObject_CallObject(func, NULL);
3384		 Py_DECREF(func);
3385		 return res;
3386	}
3387	PyErr_Clear();
3388	func = lookup_method(self, "__getitem__", &getitem_str);
3389	if (func == NULL) {
3390		PyErr_SetString(PyExc_TypeError,
3391				"iteration over non-sequence");
3392		return NULL;
3393	}
3394	Py_DECREF(func);
3395	return PySeqIter_New(self);
3396}
3397
3398static PyObject *
3399slot_tp_iternext(PyObject *self)
3400{
3401	static PyObject *next_str;
3402	return call_method(self, "next", &next_str, "()");
3403}
3404
3405static PyObject *
3406slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3407{
3408	PyTypeObject *tp = self->ob_type;
3409	PyObject *get;
3410	static PyObject *get_str = NULL;
3411
3412	if (get_str == NULL) {
3413		get_str = PyString_InternFromString("__get__");
3414		if (get_str == NULL)
3415			return NULL;
3416	}
3417	get = _PyType_Lookup(tp, get_str);
3418	if (get == NULL) {
3419		/* Avoid further slowdowns */
3420		if (tp->tp_descr_get == slot_tp_descr_get)
3421			tp->tp_descr_get = NULL;
3422		Py_INCREF(self);
3423		return self;
3424	}
3425	if (obj == NULL)
3426		obj = Py_None;
3427	if (type == NULL)
3428		type = Py_None;
3429	return PyObject_CallFunction(get, "OOO", self, obj, type);
3430}
3431
3432static int
3433slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3434{
3435	PyObject *res;
3436	static PyObject *del_str, *set_str;
3437
3438	if (value == NULL)
3439		res = call_method(self, "__delete__", &del_str,
3440				  "(O)", target);
3441	else
3442		res = call_method(self, "__set__", &set_str,
3443				  "(OO)", target, value);
3444	if (res == NULL)
3445		return -1;
3446	Py_DECREF(res);
3447	return 0;
3448}
3449
3450static int
3451slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3452{
3453	static PyObject *init_str;
3454	PyObject *meth = lookup_method(self, "__init__", &init_str);
3455	PyObject *res;
3456
3457	if (meth == NULL)
3458		return -1;
3459	res = PyObject_Call(meth, args, kwds);
3460	Py_DECREF(meth);
3461	if (res == NULL)
3462		return -1;
3463	Py_DECREF(res);
3464	return 0;
3465}
3466
3467static PyObject *
3468slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3469{
3470	PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3471	PyObject *newargs, *x;
3472	int i, n;
3473
3474	if (func == NULL)
3475		return NULL;
3476	assert(PyTuple_Check(args));
3477	n = PyTuple_GET_SIZE(args);
3478	newargs = PyTuple_New(n+1);
3479	if (newargs == NULL)
3480		return NULL;
3481	Py_INCREF(type);
3482	PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3483	for (i = 0; i < n; i++) {
3484		x = PyTuple_GET_ITEM(args, i);
3485		Py_INCREF(x);
3486		PyTuple_SET_ITEM(newargs, i+1, x);
3487	}
3488	x = PyObject_Call(func, newargs, kwds);
3489	Py_DECREF(newargs);
3490	Py_DECREF(func);
3491	return x;
3492}
3493
3494
3495/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3496   functions.  The offsets here are relative to the 'etype' structure, which
3497   incorporates the additional structures used for numbers, sequences and
3498   mappings.  Note that multiple names may map to the same slot (e.g. __eq__,
3499   __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3500   slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3501   terminated with an all-zero entry.  (This table is further initialized and
3502   sorted in init_slotdefs() below.) */
3503
3504typedef struct wrapperbase slotdef;
3505
3506#undef TPSLOT
3507#undef FLSLOT
3508#undef ETSLOT
3509#undef SQSLOT
3510#undef MPSLOT
3511#undef NBSLOT
3512#undef UNSLOT
3513#undef IBSLOT
3514#undef BINSLOT
3515#undef RBINSLOT
3516
3517#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3518	{NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3519#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3520	{NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3521	 DOC, FLAGS}
3522#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3523	{NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3524#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3525	ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3526#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3527	ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3528#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3529	ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3530#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3531	ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3532	       "x." NAME "() <==> " DOC)
3533#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3534	ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3535	       "x." NAME "(y) <==> x" DOC "y")
3536#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3537	ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3538	       "x." NAME "(y) <==> x" DOC "y")
3539#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3540	ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3541	       "x." NAME "(y) <==> y" DOC "x")
3542
3543static slotdef slotdefs[] = {
3544	SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3545	       "x.__len__() <==> len(x)"),
3546	SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3547	       "x.__add__(y) <==> x+y"),
3548	SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3549	       "x.__mul__(n) <==> x*n"),
3550	SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3551	       "x.__rmul__(n) <==> n*x"),
3552	SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3553	       "x.__getitem__(y) <==> x[y]"),
3554	SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3555	       "x.__getslice__(i, j) <==> x[i:j]"),
3556	SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3557	       "x.__setitem__(i, y) <==> x[i]=y"),
3558	SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3559	       "x.__delitem__(y) <==> del x[y]"),
3560	SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
3561	       wrap_intintobjargproc,
3562	       "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3563	SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3564	       "x.__delslice__(i, j) <==> del x[i:j]"),
3565	SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3566	       "x.__contains__(y) <==> y in x"),
3567	SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
3568	       wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
3569	SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
3570	       wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
3571
3572	MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3573	       "x.__len__() <==> len(x)"),
3574	MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
3575	       wrap_binaryfunc,
3576	       "x.__getitem__(y) <==> x[y]"),
3577	MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
3578	       wrap_objobjargproc,
3579	       "x.__setitem__(i, y) <==> x[i]=y"),
3580	MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
3581	       wrap_delitem,
3582	       "x.__delitem__(y) <==> del x[y]"),
3583
3584	BINSLOT("__add__", nb_add, slot_nb_add,
3585		"+"),
3586	RBINSLOT("__radd__", nb_add, slot_nb_add,
3587		 "+"),
3588	BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3589		"-"),
3590	RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3591		 "-"),
3592	BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3593		"*"),
3594	RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3595		 "*"),
3596	BINSLOT("__div__", nb_divide, slot_nb_divide,
3597		"/"),
3598	RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3599		 "/"),
3600	BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3601		"%"),
3602	RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3603		 "%"),
3604	BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3605		"divmod(x, y)"),
3606	RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3607		 "divmod(y, x)"),
3608	NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3609	       "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3610	NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3611	       "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3612	UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3613	UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3614	UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3615	       "abs(x)"),
3616	UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
3617	       "x != 0"),
3618	UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3619	BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3620	RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3621	BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3622	RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3623	BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3624	RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3625	BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3626	RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3627	BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3628	RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3629	NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3630	       "x.__coerce__(y) <==> coerce(x, y)"),
3631	UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3632	       "int(x)"),
3633	UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3634	       "long(x)"),
3635	UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3636	       "float(x)"),
3637	UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3638	       "oct(x)"),
3639	UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3640	       "hex(x)"),
3641	IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3642	       wrap_binaryfunc, "+"),
3643	IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3644	       wrap_binaryfunc, "-"),
3645	IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3646	       wrap_binaryfunc, "*"),
3647	IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3648	       wrap_binaryfunc, "/"),
3649	IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3650	       wrap_binaryfunc, "%"),
3651	IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3652	       wrap_ternaryfunc, "**"),
3653	IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3654	       wrap_binaryfunc, "<<"),
3655	IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3656	       wrap_binaryfunc, ">>"),
3657	IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3658	       wrap_binaryfunc, "&"),
3659	IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3660	       wrap_binaryfunc, "^"),
3661	IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3662	       wrap_binaryfunc, "|"),
3663	BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3664	RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3665	BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3666	RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3667	IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3668	       slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3669	IBSLOT("__itruediv__", nb_inplace_true_divide,
3670	       slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
3671
3672	TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3673	       "x.__str__() <==> str(x)"),
3674	TPSLOT("__str__", tp_print, NULL, NULL, ""),
3675	TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3676	       "x.__repr__() <==> repr(x)"),
3677	TPSLOT("__repr__", tp_print, NULL, NULL, ""),
3678	TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3679	       "x.__cmp__(y) <==> cmp(x,y)"),
3680	TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3681	       "x.__hash__() <==> hash(x)"),
3682	FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3683	       "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
3684	TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
3685	       wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3686	TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3687	TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3688	TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3689	TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3690	       "x.__setattr__('name', value) <==> x.name = value"),
3691	TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3692	TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3693	       "x.__delattr__('name') <==> del x.name"),
3694	TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3695	TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3696	       "x.__lt__(y) <==> x<y"),
3697	TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3698	       "x.__le__(y) <==> x<=y"),
3699	TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3700	       "x.__eq__(y) <==> x==y"),
3701	TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3702	       "x.__ne__(y) <==> x!=y"),
3703	TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3704	       "x.__gt__(y) <==> x>y"),
3705	TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3706	       "x.__ge__(y) <==> x>=y"),
3707	TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3708	       "x.__iter__() <==> iter(x)"),
3709	TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3710	       "x.next() -> the next value, or raise StopIteration"),
3711	TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3712	       "descr.__get__(obj[, type]) -> value"),
3713	TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3714	       "descr.__set__(obj, value)"),
3715	FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
3716	       "x.__init__(...) initializes x; "
3717	       "see x.__class__.__doc__ for signature",
3718	       PyWrapperFlag_KEYWORDS),
3719	TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
3720	{NULL}
3721};
3722
3723/* Given a type pointer and an offset gotten from a slotdef entry, return a
3724   pointer to the actual slot.  This is not quite the same as simply adding
3725   the offset to the type pointer, since it takes care to indirect through the
3726   proper indirection pointer (as_buffer, etc.); it returns NULL if the
3727   indirection pointer is NULL. */
3728static void **
3729slotptr(PyTypeObject *type, int offset)
3730{
3731	char *ptr;
3732
3733	assert(offset >= 0);
3734	assert(offset < offsetof(etype, as_buffer));
3735	if (offset >= offsetof(etype, as_mapping)) {
3736		ptr = (void *)type->tp_as_mapping;
3737		offset -= offsetof(etype, as_mapping);
3738	}
3739	else if (offset >= offsetof(etype, as_sequence)) {
3740		ptr = (void *)type->tp_as_sequence;
3741		offset -= offsetof(etype, as_sequence);
3742	}
3743	else if (offset >= offsetof(etype, as_number)) {
3744		ptr = (void *)type->tp_as_number;
3745		offset -= offsetof(etype, as_number);
3746	}
3747	else {
3748		ptr = (void *)type;
3749	}
3750	if (ptr != NULL)
3751		ptr += offset;
3752	return (void **)ptr;
3753}
3754
3755/* Length of array of slotdef pointers used to store slots with the
3756   same __name__.  There should be at most MAX_EQUIV-1 slotdef entries with
3757   the same __name__, for any __name__. Since that's a static property, it is
3758   appropriate to declare fixed-size arrays for this. */
3759#define MAX_EQUIV 10
3760
3761/* Return a slot pointer for a given name, but ONLY if the attribute has
3762   exactly one slot function.  The name must be an interned string. */
3763static void **
3764resolve_slotdups(PyTypeObject *type, PyObject *name)
3765{
3766	/* XXX Maybe this could be optimized more -- but is it worth it? */
3767
3768	/* pname and ptrs act as a little cache */
3769	static PyObject *pname;
3770	static slotdef *ptrs[MAX_EQUIV];
3771	slotdef *p, **pp;
3772	void **res, **ptr;
3773
3774	if (pname != name) {
3775		/* Collect all slotdefs that match name into ptrs. */
3776		pname = name;
3777		pp = ptrs;
3778		for (p = slotdefs; p->name_strobj; p++) {
3779			if (p->name_strobj == name)
3780				*pp++ = p;
3781		}
3782		*pp = NULL;
3783	}
3784
3785	/* Look in all matching slots of the type; if exactly one of these has
3786	   a filled-in slot, return its value.  Otherwise return NULL. */
3787	res = NULL;
3788	for (pp = ptrs; *pp; pp++) {
3789		ptr = slotptr(type, (*pp)->offset);
3790		if (ptr == NULL || *ptr == NULL)
3791			continue;
3792		if (res != NULL)
3793			return NULL;
3794		res = ptr;
3795	}
3796	return res;
3797}
3798
3799/* Common code for update_these_slots() and fixup_slot_dispatchers().  This
3800   does some incredibly complex thinking and then sticks something into the
3801   slot.  (It sees if the adjacent slotdefs for the same slot have conflicting
3802   interests, and then stores a generic wrapper or a specific function into
3803   the slot.)  Return a pointer to the next slotdef with a different offset,
3804   because that's convenient  for fixup_slot_dispatchers(). */
3805static slotdef *
3806update_one_slot(PyTypeObject *type, slotdef *p)
3807{
3808	PyObject *descr;
3809	PyWrapperDescrObject *d;
3810	void *generic = NULL, *specific = NULL;
3811	int use_generic = 0;
3812	int offset = p->offset;
3813	void **ptr = slotptr(type, offset);
3814
3815	if (ptr == NULL) {
3816		do {
3817			++p;
3818		} while (p->offset == offset);
3819		return p;
3820	}
3821	do {
3822		descr = _PyType_Lookup(type, p->name_strobj);
3823		if (descr == NULL)
3824			continue;
3825		if (descr->ob_type == &PyWrapperDescr_Type) {
3826			void **tptr = resolve_slotdups(type, p->name_strobj);
3827			if (tptr == NULL || tptr == ptr)
3828				generic = p->function;
3829			d = (PyWrapperDescrObject *)descr;
3830			if (d->d_base->wrapper == p->wrapper &&
3831			    PyType_IsSubtype(type, d->d_type))
3832			{
3833				if (specific == NULL ||
3834				    specific == d->d_wrapped)
3835					specific = d->d_wrapped;
3836				else
3837					use_generic = 1;
3838			}
3839		}
3840		else {
3841			use_generic = 1;
3842			generic = p->function;
3843		}
3844	} while ((++p)->offset == offset);
3845	if (specific && !use_generic)
3846		*ptr = specific;
3847	else
3848		*ptr = generic;
3849	return p;
3850}
3851
3852staticforward int recurse_down_subclasses(PyTypeObject *type,
3853					  slotdef **pp, PyObject *name);
3854
3855/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
3856   and then do the same for all this type's subtypes. */
3857static int
3858update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
3859{
3860	slotdef **pp;
3861
3862	for (pp = pp0; *pp; pp++)
3863		update_one_slot(type, *pp);
3864	return recurse_down_subclasses(type, pp0, name);
3865}
3866
3867/* Update the slots whose slotdefs are gathered in the pp array in all (direct
3868   or indirect) subclasses of type. */
3869static int
3870recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
3871{
3872	PyTypeObject *subclass;
3873	PyObject *ref, *subclasses, *dict;
3874	int i, n;
3875
3876	subclasses = type->tp_subclasses;
3877	if (subclasses == NULL)
3878		return 0;
3879	assert(PyList_Check(subclasses));
3880	n = PyList_GET_SIZE(subclasses);
3881	for (i = 0; i < n; i++) {
3882		ref = PyList_GET_ITEM(subclasses, i);
3883		assert(PyWeakref_CheckRef(ref));
3884		subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3885		if (subclass == NULL)
3886			continue;
3887		assert(PyType_Check(subclass));
3888		/* Avoid recursing down into unaffected classes */
3889		dict = subclass->tp_dict;
3890		if (dict != NULL && PyDict_Check(dict) &&
3891		    PyDict_GetItem(dict, name) != NULL)
3892			continue;
3893		if (update_these_slots(subclass, pp, name) < 0)
3894			return -1;
3895	}
3896	return 0;
3897}
3898
3899/* Comparison function for qsort() to compare slotdefs by their offset, and
3900   for equal offset by their address (to force a stable sort). */
3901static int
3902slotdef_cmp(const void *aa, const void *bb)
3903{
3904	const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3905	int c = a->offset - b->offset;
3906	if (c != 0)
3907		return c;
3908	else
3909		return a - b;
3910}
3911
3912/* Initialize the slotdefs table by adding interned string objects for the
3913   names and sorting the entries. */
3914static void
3915init_slotdefs(void)
3916{
3917	slotdef *p;
3918	static int initialized = 0;
3919
3920	if (initialized)
3921		return;
3922	for (p = slotdefs; p->name; p++) {
3923		p->name_strobj = PyString_InternFromString(p->name);
3924		if (!p->name_strobj)
3925			Py_FatalError("Out of memory interning slotdef names");
3926	}
3927	qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3928	      slotdef_cmp);
3929	initialized = 1;
3930}
3931
3932/* Update the slots after assignment to a class (type) attribute. */
3933static int
3934update_slot(PyTypeObject *type, PyObject *name)
3935{
3936	slotdef *ptrs[MAX_EQUIV];
3937	slotdef *p;
3938	slotdef **pp;
3939	int offset;
3940
3941	init_slotdefs();
3942	pp = ptrs;
3943	for (p = slotdefs; p->name; p++) {
3944		/* XXX assume name is interned! */
3945		if (p->name_strobj == name)
3946			*pp++ = p;
3947	}
3948	*pp = NULL;
3949	for (pp = ptrs; *pp; pp++) {
3950		p = *pp;
3951		offset = p->offset;
3952		while (p > slotdefs && (p-1)->offset == offset)
3953			--p;
3954		*pp = p;
3955	}
3956	if (ptrs[0] == NULL)
3957		return 0; /* Not an attribute that affects any slots */
3958	return update_these_slots(type, ptrs, name);
3959}
3960
3961/* Store the proper functions in the slot dispatches at class (type)
3962   definition time, based upon which operations the class overrides in its
3963   dict. */
3964static void
3965fixup_slot_dispatchers(PyTypeObject *type)
3966{
3967	slotdef *p;
3968
3969	init_slotdefs();
3970	for (p = slotdefs; p->name; )
3971		p = update_one_slot(type, p);
3972}
3973
3974/* This function is called by PyType_Ready() to populate the type's
3975   dictionary with method descriptors for function slots.  For each
3976   function slot (like tp_repr) that's defined in the type, one or
3977   more corresponding descriptors are added in the type's tp_dict
3978   dictionary under the appropriate name (like __repr__).  Some
3979   function slots cause more than one descriptor to be added (for
3980   example, the nb_add slot adds both __add__ and __radd__
3981   descriptors) and some function slots compete for the same
3982   descriptor (for example both sq_item and mp_subscript generate a
3983   __getitem__ descriptor).  This only adds new descriptors and
3984   doesn't overwrite entries in tp_dict that were previously
3985   defined.  The descriptors contain a reference to the C function
3986   they must call, so that it's safe if they are copied into a
3987   subtype's __dict__ and the subtype has a different C function in
3988   its slot -- calling the method defined by the descriptor will call
3989   the C function that was used to create it, rather than the C
3990   function present in the slot when it is called.  (This is important
3991   because a subtype may have a C function in the slot that calls the
3992   method from the dictionary, and we want to avoid infinite recursion
3993   here.) */
3994
3995static int
3996add_operators(PyTypeObject *type)
3997{
3998	PyObject *dict = type->tp_dict;
3999	slotdef *p;
4000	PyObject *descr;
4001	void **ptr;
4002
4003	init_slotdefs();
4004	for (p = slotdefs; p->name; p++) {
4005		if (p->wrapper == NULL)
4006			continue;
4007		ptr = slotptr(type, p->offset);
4008		if (!ptr || !*ptr)
4009			continue;
4010		if (PyDict_GetItem(dict, p->name_strobj))
4011			continue;
4012		descr = PyDescr_NewWrapper(type, p, *ptr);
4013		if (descr == NULL)
4014			return -1;
4015		if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4016			return -1;
4017		Py_DECREF(descr);
4018	}
4019	if (type->tp_new != NULL) {
4020		if (add_tp_new_wrapper(type) < 0)
4021			return -1;
4022	}
4023	return 0;
4024}
4025
4026
4027/* Cooperative 'super' */
4028
4029typedef struct {
4030	PyObject_HEAD
4031	PyTypeObject *type;
4032	PyObject *obj;
4033} superobject;
4034
4035static PyMemberDef super_members[] = {
4036	{"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4037	 "the class invoking super()"},
4038	{"__self__",  T_OBJECT, offsetof(superobject, obj), READONLY,
4039	 "the instance invoking super(); may be None"},
4040	{0}
4041};
4042
4043static void
4044super_dealloc(PyObject *self)
4045{
4046	superobject *su = (superobject *)self;
4047
4048	_PyObject_GC_UNTRACK(self);
4049	Py_XDECREF(su->obj);
4050	Py_XDECREF(su->type);
4051	self->ob_type->tp_free(self);
4052}
4053
4054static PyObject *
4055super_repr(PyObject *self)
4056{
4057	superobject *su = (superobject *)self;
4058
4059	if (su->obj)
4060		return PyString_FromFormat(
4061			"<super: <class '%s'>, <%s object>>",
4062			su->type ? su->type->tp_name : "NULL",
4063			su->obj->ob_type->tp_name);
4064	else
4065		return PyString_FromFormat(
4066			"<super: <class '%s'>, NULL>",
4067			su->type ? su->type->tp_name : "NULL");
4068}
4069
4070static PyObject *
4071super_getattro(PyObject *self, PyObject *name)
4072{
4073	superobject *su = (superobject *)self;
4074
4075	if (su->obj != NULL) {
4076		PyObject *mro, *res, *tmp, *dict;
4077		PyTypeObject *starttype;
4078		descrgetfunc f;
4079		int i, n;
4080
4081		starttype = su->obj->ob_type;
4082		mro = starttype->tp_mro;
4083
4084		if (mro == NULL)
4085			n = 0;
4086		else {
4087			assert(PyTuple_Check(mro));
4088			n = PyTuple_GET_SIZE(mro);
4089		}
4090		for (i = 0; i < n; i++) {
4091			if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
4092				break;
4093		}
4094		if (i >= n && PyType_Check(su->obj)) {
4095			starttype = (PyTypeObject *)(su->obj);
4096			mro = starttype->tp_mro;
4097			if (mro == NULL)
4098				n = 0;
4099			else {
4100				assert(PyTuple_Check(mro));
4101				n = PyTuple_GET_SIZE(mro);
4102			}
4103			for (i = 0; i < n; i++) {
4104				if ((PyObject *)(su->type) ==
4105				    PyTuple_GET_ITEM(mro, i))
4106					break;
4107			}
4108		}
4109		i++;
4110		res = NULL;
4111		for (; i < n; i++) {
4112			tmp = PyTuple_GET_ITEM(mro, i);
4113			if (PyType_Check(tmp))
4114				dict = ((PyTypeObject *)tmp)->tp_dict;
4115			else if (PyClass_Check(tmp))
4116				dict = ((PyClassObject *)tmp)->cl_dict;
4117			else
4118				continue;
4119			res = PyDict_GetItem(dict, name);
4120			if (res != NULL  && !PyDescr_IsData(res)) {
4121				Py_INCREF(res);
4122				f = res->ob_type->tp_descr_get;
4123				if (f != NULL) {
4124					tmp = f(res, su->obj,
4125						(PyObject *)starttype);
4126					Py_DECREF(res);
4127					res = tmp;
4128				}
4129				return res;
4130			}
4131		}
4132	}
4133	return PyObject_GenericGetAttr(self, name);
4134}
4135
4136static int
4137supercheck(PyTypeObject *type, PyObject *obj)
4138{
4139	if (!PyType_IsSubtype(obj->ob_type, type) &&
4140	    !(PyType_Check(obj) &&
4141	      PyType_IsSubtype((PyTypeObject *)obj, type))) {
4142		PyErr_SetString(PyExc_TypeError,
4143			"super(type, obj): "
4144			"obj must be an instance or subtype of type");
4145		return -1;
4146	}
4147	else
4148		return 0;
4149}
4150
4151static PyObject *
4152super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4153{
4154	superobject *su = (superobject *)self;
4155	superobject *new;
4156
4157	if (obj == NULL || obj == Py_None || su->obj != NULL) {
4158		/* Not binding to an object, or already bound */
4159		Py_INCREF(self);
4160		return self;
4161	}
4162	if (su->ob_type != &PySuper_Type)
4163		/* If su is an instance of a subclass of super,
4164		   call its type */
4165		return PyObject_CallFunction((PyObject *)su->ob_type,
4166					     "OO", su->type, obj);
4167	else {
4168		/* Inline the common case */
4169		if (supercheck(su->type, obj) < 0)
4170			return NULL;
4171		new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4172							 NULL, NULL);
4173		if (new == NULL)
4174			return NULL;
4175		Py_INCREF(su->type);
4176		Py_INCREF(obj);
4177		new->type = su->type;
4178		new->obj = obj;
4179		return (PyObject *)new;
4180	}
4181}
4182
4183static int
4184super_init(PyObject *self, PyObject *args, PyObject *kwds)
4185{
4186	superobject *su = (superobject *)self;
4187	PyTypeObject *type;
4188	PyObject *obj = NULL;
4189
4190	if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4191		return -1;
4192	if (obj == Py_None)
4193		obj = NULL;
4194	if (obj != NULL && supercheck(type, obj) < 0)
4195		return -1;
4196	Py_INCREF(type);
4197	Py_XINCREF(obj);
4198	su->type = type;
4199	su->obj = obj;
4200	return 0;
4201}
4202
4203static char super_doc[] =
4204"super(type) -> unbound super object\n"
4205"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
4206"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
4207"Typical use to call a cooperative superclass method:\n"
4208"class C(B):\n"
4209"    def meth(self, arg):\n"
4210"        super(C, self).meth(arg)";
4211
4212static int
4213super_traverse(PyObject *self, visitproc visit, void *arg)
4214{
4215	superobject *su = (superobject *)self;
4216	int err;
4217
4218#define VISIT(SLOT) \
4219	if (SLOT) { \
4220		err = visit((PyObject *)(SLOT), arg); \
4221		if (err) \
4222			return err; \
4223	}
4224
4225	VISIT(su->obj);
4226	VISIT(su->type);
4227
4228#undef VISIT
4229
4230	return 0;
4231}
4232
4233PyTypeObject PySuper_Type = {
4234	PyObject_HEAD_INIT(&PyType_Type)
4235	0,					/* ob_size */
4236	"super",				/* tp_name */
4237	sizeof(superobject),			/* tp_basicsize */
4238	0,					/* tp_itemsize */
4239	/* methods */
4240	super_dealloc,		 		/* tp_dealloc */
4241	0,					/* tp_print */
4242	0,					/* tp_getattr */
4243	0,					/* tp_setattr */
4244	0,					/* tp_compare */
4245	super_repr,				/* tp_repr */
4246	0,					/* tp_as_number */
4247	0,					/* tp_as_sequence */
4248	0,		       			/* tp_as_mapping */
4249	0,					/* tp_hash */
4250	0,					/* tp_call */
4251	0,					/* tp_str */
4252	super_getattro,				/* tp_getattro */
4253	0,					/* tp_setattro */
4254	0,					/* tp_as_buffer */
4255	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4256		Py_TPFLAGS_BASETYPE,		/* tp_flags */
4257 	super_doc,				/* tp_doc */
4258 	super_traverse,				/* tp_traverse */
4259 	0,					/* tp_clear */
4260	0,					/* tp_richcompare */
4261	0,					/* tp_weaklistoffset */
4262	0,					/* tp_iter */
4263	0,					/* tp_iternext */
4264	0,					/* tp_methods */
4265	super_members,				/* tp_members */
4266	0,					/* tp_getset */
4267	0,					/* tp_base */
4268	0,					/* tp_dict */
4269	super_descr_get,			/* tp_descr_get */
4270	0,					/* tp_descr_set */
4271	0,					/* tp_dictoffset */
4272	super_init,				/* tp_init */
4273	PyType_GenericAlloc,			/* tp_alloc */
4274	PyType_GenericNew,			/* tp_new */
4275	_PyObject_GC_Del,			/* tp_free */
4276};
4277