typeobject.c revision a6a277d8316973ca3f546e5111430a8c4ee07181
1/* Type object implementation */
2
3#include "Python.h"
4#include "structmember.h"
5
6#include <ctype.h>
7
8static PyMemberDef type_members[] = {
9	{"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10	{"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11	{"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
12	{"__weakrefoffset__", T_LONG,
13	 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14	{"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15	{"__dictoffset__", T_LONG,
16	 offsetof(PyTypeObject, tp_dictoffset), READONLY},
17	{"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18	{0}
19};
20
21static PyObject *
22type_name(PyTypeObject *type, void *context)
23{
24	char *s;
25
26	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
27		PyHeapTypeObject* et = (PyHeapTypeObject*)type;
28
29		Py_INCREF(et->name);
30		return et->name;
31	}
32	else {
33		s = strrchr(type->tp_name, '.');
34		if (s == NULL)
35			s = type->tp_name;
36		else
37			s++;
38		return PyString_FromString(s);
39	}
40}
41
42static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
45	PyHeapTypeObject* et;
46
47	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48		PyErr_Format(PyExc_TypeError,
49			     "can't set %s.__name__", type->tp_name);
50		return -1;
51	}
52	if (!value) {
53		PyErr_Format(PyExc_TypeError,
54			     "can't delete %s.__name__", type->tp_name);
55		return -1;
56	}
57	if (!PyString_Check(value)) {
58		PyErr_Format(PyExc_TypeError,
59			     "can only assign string to %s.__name__, not '%s'",
60			     type->tp_name, value->ob_type->tp_name);
61		return -1;
62	}
63	if (strlen(PyString_AS_STRING(value))
64	    != (size_t)PyString_GET_SIZE(value)) {
65		PyErr_Format(PyExc_ValueError,
66			     "__name__ must not contain null bytes");
67		return -1;
68	}
69
70	et = (PyHeapTypeObject*)type;
71
72	Py_INCREF(value);
73
74	Py_DECREF(et->name);
75	et->name = value;
76
77	type->tp_name = PyString_AS_STRING(value);
78
79	return 0;
80}
81
82static PyObject *
83type_module(PyTypeObject *type, void *context)
84{
85	PyObject *mod;
86	char *s;
87
88	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89		mod = PyDict_GetItemString(type->tp_dict, "__module__");
90		Py_XINCREF(mod);
91		return mod;
92	}
93	else {
94		s = strrchr(type->tp_name, '.');
95		if (s != NULL)
96			return PyString_FromStringAndSize(
97				type->tp_name, (int)(s - type->tp_name));
98		return PyString_FromString("__builtin__");
99	}
100}
101
102static int
103type_set_module(PyTypeObject *type, PyObject *value, void *context)
104{
105	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
106		PyErr_Format(PyExc_TypeError,
107			     "can't set %s.__module__", type->tp_name);
108		return -1;
109	}
110	if (!value) {
111		PyErr_Format(PyExc_TypeError,
112			     "can't delete %s.__module__", type->tp_name);
113		return -1;
114	}
115
116	return PyDict_SetItemString(type->tp_dict, "__module__", value);
117}
118
119static PyObject *
120type_get_bases(PyTypeObject *type, void *context)
121{
122	Py_INCREF(type->tp_bases);
123	return type->tp_bases;
124}
125
126static PyTypeObject *best_base(PyObject *);
127static int mro_internal(PyTypeObject *);
128static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
129static int add_subclass(PyTypeObject*, PyTypeObject*);
130static void remove_subclass(PyTypeObject *, PyTypeObject *);
131static void update_all_slots(PyTypeObject *);
132
133typedef int (*update_callback)(PyTypeObject *, void *);
134static int update_subclasses(PyTypeObject *type, PyObject *name,
135			     update_callback callback, void *data);
136static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
137				   update_callback callback, void *data);
138
139static int
140mro_subclasses(PyTypeObject *type, PyObject* temp)
141{
142	PyTypeObject *subclass;
143	PyObject *ref, *subclasses, *old_mro;
144	int i, n;
145
146	subclasses = type->tp_subclasses;
147	if (subclasses == NULL)
148		return 0;
149	assert(PyList_Check(subclasses));
150	n = PyList_GET_SIZE(subclasses);
151	for (i = 0; i < n; i++) {
152		ref = PyList_GET_ITEM(subclasses, i);
153		assert(PyWeakref_CheckRef(ref));
154		subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
155		assert(subclass != NULL);
156		if ((PyObject *)subclass == Py_None)
157			continue;
158		assert(PyType_Check(subclass));
159		old_mro = subclass->tp_mro;
160		if (mro_internal(subclass) < 0) {
161			subclass->tp_mro = old_mro;
162			return -1;
163		}
164		else {
165			PyObject* tuple;
166			tuple = Py_BuildValue("OO", subclass, old_mro);
167			Py_DECREF(old_mro);
168			if (!tuple)
169				return -1;
170			if (PyList_Append(temp, tuple) < 0)
171				return -1;
172			Py_DECREF(tuple);
173		}
174		if (mro_subclasses(subclass, temp) < 0)
175			return -1;
176	}
177	return 0;
178}
179
180static int
181type_set_bases(PyTypeObject *type, PyObject *value, void *context)
182{
183	int i, r = 0;
184	PyObject *ob, *temp;
185	PyTypeObject *new_base, *old_base;
186	PyObject *old_bases, *old_mro;
187
188	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
189		PyErr_Format(PyExc_TypeError,
190			     "can't set %s.__bases__", type->tp_name);
191		return -1;
192	}
193	if (!value) {
194		PyErr_Format(PyExc_TypeError,
195			     "can't delete %s.__bases__", type->tp_name);
196		return -1;
197	}
198	if (!PyTuple_Check(value)) {
199		PyErr_Format(PyExc_TypeError,
200		     "can only assign tuple to %s.__bases__, not %s",
201			     type->tp_name, value->ob_type->tp_name);
202		return -1;
203	}
204	if (PyTuple_GET_SIZE(value) == 0) {
205		PyErr_Format(PyExc_TypeError,
206		     "can only assign non-empty tuple to %s.__bases__, not ()",
207			     type->tp_name);
208		return -1;
209	}
210	for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
211		ob = PyTuple_GET_ITEM(value, i);
212		if (!PyClass_Check(ob) && !PyType_Check(ob)) {
213			PyErr_Format(
214				PyExc_TypeError,
215	"%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
216				type->tp_name, ob->ob_type->tp_name);
217			return -1;
218		}
219		if (PyType_Check(ob)) {
220			if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
221				PyErr_SetString(PyExc_TypeError,
222			"a __bases__ item causes an inheritance cycle");
223				return -1;
224			}
225		}
226	}
227
228	new_base = best_base(value);
229
230	if (!new_base) {
231		return -1;
232	}
233
234	if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
235		return -1;
236
237	Py_INCREF(new_base);
238	Py_INCREF(value);
239
240	old_bases = type->tp_bases;
241	old_base = type->tp_base;
242	old_mro = type->tp_mro;
243
244	type->tp_bases = value;
245	type->tp_base = new_base;
246
247	if (mro_internal(type) < 0) {
248		goto bail;
249	}
250
251	temp = PyList_New(0);
252	if (!temp)
253		goto bail;
254
255	r = mro_subclasses(type, temp);
256
257	if (r < 0) {
258		for (i = 0; i < PyList_Size(temp); i++) {
259			PyTypeObject* cls;
260			PyObject* mro;
261			PyArg_ParseTuple(PyList_GET_ITEM(temp, i),
262					 "OO", &cls, &mro);
263			Py_DECREF(cls->tp_mro);
264			cls->tp_mro = mro;
265			Py_INCREF(cls->tp_mro);
266		}
267		Py_DECREF(temp);
268		goto bail;
269	}
270
271	Py_DECREF(temp);
272
273	/* any base that was in __bases__ but now isn't, we
274	   need to remove |type| from its tp_subclasses.
275	   conversely, any class now in __bases__ that wasn't
276	   needs to have |type| added to its subclasses. */
277
278	/* for now, sod that: just remove from all old_bases,
279	   add to all new_bases */
280
281	for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
282		ob = PyTuple_GET_ITEM(old_bases, i);
283		if (PyType_Check(ob)) {
284			remove_subclass(
285				(PyTypeObject*)ob, type);
286		}
287	}
288
289	for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
290		ob = PyTuple_GET_ITEM(value, i);
291		if (PyType_Check(ob)) {
292			if (add_subclass((PyTypeObject*)ob, type) < 0)
293				r = -1;
294		}
295	}
296
297	update_all_slots(type);
298
299	Py_DECREF(old_bases);
300	Py_DECREF(old_base);
301	Py_DECREF(old_mro);
302
303	return r;
304
305  bail:
306	Py_DECREF(type->tp_bases);
307	Py_DECREF(type->tp_base);
308	if (type->tp_mro != old_mro) {
309		Py_DECREF(type->tp_mro);
310	}
311
312	type->tp_bases = old_bases;
313	type->tp_base = old_base;
314	type->tp_mro = old_mro;
315
316	return -1;
317}
318
319static PyObject *
320type_dict(PyTypeObject *type, void *context)
321{
322	if (type->tp_dict == NULL) {
323		Py_INCREF(Py_None);
324		return Py_None;
325	}
326	return PyDictProxy_New(type->tp_dict);
327}
328
329static PyObject *
330type_get_doc(PyTypeObject *type, void *context)
331{
332	PyObject *result;
333	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
334		return PyString_FromString(type->tp_doc);
335	result = PyDict_GetItemString(type->tp_dict, "__doc__");
336	if (result == NULL) {
337		result = Py_None;
338		Py_INCREF(result);
339	}
340	else if (result->ob_type->tp_descr_get) {
341		result = result->ob_type->tp_descr_get(result, NULL,
342						       (PyObject *)type);
343	}
344	else {
345		Py_INCREF(result);
346	}
347	return result;
348}
349
350static PyGetSetDef type_getsets[] = {
351	{"__name__", (getter)type_name, (setter)type_set_name, NULL},
352	{"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
353	{"__module__", (getter)type_module, (setter)type_set_module, NULL},
354	{"__dict__",  (getter)type_dict,  NULL, NULL},
355	{"__doc__", (getter)type_get_doc, NULL, NULL},
356	{0}
357};
358
359static int
360type_compare(PyObject *v, PyObject *w)
361{
362	/* This is called with type objects only. So we
363	   can just compare the addresses. */
364	Py_uintptr_t vv = (Py_uintptr_t)v;
365	Py_uintptr_t ww = (Py_uintptr_t)w;
366	return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
367}
368
369static PyObject *
370type_repr(PyTypeObject *type)
371{
372	PyObject *mod, *name, *rtn;
373	char *kind;
374
375	mod = type_module(type, NULL);
376	if (mod == NULL)
377		PyErr_Clear();
378	else if (!PyString_Check(mod)) {
379		Py_DECREF(mod);
380		mod = NULL;
381	}
382	name = type_name(type, NULL);
383	if (name == NULL)
384		return NULL;
385
386	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
387		kind = "class";
388	else
389		kind = "type";
390
391	if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
392		rtn = PyString_FromFormat("<%s '%s.%s'>",
393					  kind,
394					  PyString_AS_STRING(mod),
395					  PyString_AS_STRING(name));
396	}
397	else
398		rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
399
400	Py_XDECREF(mod);
401	Py_DECREF(name);
402	return rtn;
403}
404
405static PyObject *
406type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
407{
408	PyObject *obj;
409
410	if (type->tp_new == NULL) {
411		PyErr_Format(PyExc_TypeError,
412			     "cannot create '%.100s' instances",
413			     type->tp_name);
414		return NULL;
415	}
416
417	obj = type->tp_new(type, args, kwds);
418	if (obj != NULL) {
419		/* Ugly exception: when the call was type(something),
420		   don't call tp_init on the result. */
421		if (type == &PyType_Type &&
422		    PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
423		    (kwds == NULL ||
424		     (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
425			return obj;
426		/* If the returned object is not an instance of type,
427		   it won't be initialized. */
428		if (!PyType_IsSubtype(obj->ob_type, type))
429			return obj;
430		type = obj->ob_type;
431		if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
432		    type->tp_init != NULL &&
433		    type->tp_init(obj, args, kwds) < 0) {
434			Py_DECREF(obj);
435			obj = NULL;
436		}
437	}
438	return obj;
439}
440
441PyObject *
442PyType_GenericAlloc(PyTypeObject *type, int nitems)
443{
444	PyObject *obj;
445	const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
446	/* note that we need to add one, for the sentinel */
447
448	if (PyType_IS_GC(type))
449		obj = _PyObject_GC_Malloc(size);
450	else
451		obj = PyObject_MALLOC(size);
452
453	if (obj == NULL)
454		return PyErr_NoMemory();
455
456	memset(obj, '\0', size);
457
458	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
459		Py_INCREF(type);
460
461	if (type->tp_itemsize == 0)
462		PyObject_INIT(obj, type);
463	else
464		(void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
465
466	if (PyType_IS_GC(type))
467		_PyObject_GC_TRACK(obj);
468	return obj;
469}
470
471PyObject *
472PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
473{
474	return type->tp_alloc(type, 0);
475}
476
477/* Helpers for subtyping */
478
479static int
480traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
481{
482	int i, n;
483	PyMemberDef *mp;
484
485	n = type->ob_size;
486	mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
487	for (i = 0; i < n; i++, mp++) {
488		if (mp->type == T_OBJECT_EX) {
489			char *addr = (char *)self + mp->offset;
490			PyObject *obj = *(PyObject **)addr;
491			if (obj != NULL) {
492				int err = visit(obj, arg);
493				if (err)
494					return err;
495			}
496		}
497	}
498	return 0;
499}
500
501static int
502subtype_traverse(PyObject *self, visitproc visit, void *arg)
503{
504	PyTypeObject *type, *base;
505	traverseproc basetraverse;
506
507	/* Find the nearest base with a different tp_traverse,
508	   and traverse slots while we're at it */
509	type = self->ob_type;
510	base = type;
511	while ((basetraverse = base->tp_traverse) == subtype_traverse) {
512		if (base->ob_size) {
513			int err = traverse_slots(base, self, visit, arg);
514			if (err)
515				return err;
516		}
517		base = base->tp_base;
518		assert(base);
519	}
520
521	if (type->tp_dictoffset != base->tp_dictoffset) {
522		PyObject **dictptr = _PyObject_GetDictPtr(self);
523		if (dictptr && *dictptr) {
524			int err = visit(*dictptr, arg);
525			if (err)
526				return err;
527		}
528	}
529
530	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
531		/* For a heaptype, the instances count as references
532		   to the type.  Traverse the type so the collector
533		   can find cycles involving this link. */
534		int err = visit((PyObject *)type, arg);
535		if (err)
536			return err;
537	}
538
539	if (basetraverse)
540		return basetraverse(self, visit, arg);
541	return 0;
542}
543
544static void
545clear_slots(PyTypeObject *type, PyObject *self)
546{
547	int i, n;
548	PyMemberDef *mp;
549
550	n = type->ob_size;
551	mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
552	for (i = 0; i < n; i++, mp++) {
553		if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
554			char *addr = (char *)self + mp->offset;
555			PyObject *obj = *(PyObject **)addr;
556			if (obj != NULL) {
557				Py_DECREF(obj);
558				*(PyObject **)addr = NULL;
559			}
560		}
561	}
562}
563
564static int
565subtype_clear(PyObject *self)
566{
567	PyTypeObject *type, *base;
568	inquiry baseclear;
569
570	/* Find the nearest base with a different tp_clear
571	   and clear slots while we're at it */
572	type = self->ob_type;
573	base = type;
574	while ((baseclear = base->tp_clear) == subtype_clear) {
575		if (base->ob_size)
576			clear_slots(base, self);
577		base = base->tp_base;
578		assert(base);
579	}
580
581	/* There's no need to clear the instance dict (if any);
582	   the collector will call its tp_clear handler. */
583
584	if (baseclear)
585		return baseclear(self);
586	return 0;
587}
588
589static void
590subtype_dealloc(PyObject *self)
591{
592	PyTypeObject *type, *base;
593	destructor basedealloc;
594
595	/* Extract the type; we expect it to be a heap type */
596	type = self->ob_type;
597	assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
598
599	/* Test whether the type has GC exactly once */
600
601	if (!PyType_IS_GC(type)) {
602		/* It's really rare to find a dynamic type that doesn't have
603		   GC; it can only happen when deriving from 'object' and not
604		   adding any slots or instance variables.  This allows
605		   certain simplifications: there's no need to call
606		   clear_slots(), or DECREF the dict, or clear weakrefs. */
607
608		/* Maybe call finalizer; exit early if resurrected */
609		if (type->tp_del) {
610			type->tp_del(self);
611			if (self->ob_refcnt > 0)
612				return;
613		}
614
615		/* Find the nearest base with a different tp_dealloc */
616		base = type;
617		while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
618			assert(base->ob_size == 0);
619			base = base->tp_base;
620			assert(base);
621		}
622
623		/* Call the base tp_dealloc() */
624		assert(basedealloc);
625		basedealloc(self);
626
627		/* Can't reference self beyond this point */
628		Py_DECREF(type);
629
630		/* Done */
631		return;
632	}
633
634	/* We get here only if the type has GC */
635
636	/* UnTrack and re-Track around the trashcan macro, alas */
637	/* See explanation at end of function for full disclosure */
638	PyObject_GC_UnTrack(self);
639	++_PyTrash_delete_nesting;
640	Py_TRASHCAN_SAFE_BEGIN(self);
641	--_PyTrash_delete_nesting;
642	_PyObject_GC_TRACK(self); /* We'll untrack for real later */
643
644	/* Find the nearest base with a different tp_dealloc */
645	base = type;
646	while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
647		base = base->tp_base;
648		assert(base);
649	}
650
651	/* If we added a weaklist, we clear it.  Do this *before* calling
652	   the finalizer (__del__), clearing slots, or clearing the instance
653	   dict. */
654
655	if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
656		PyObject_ClearWeakRefs(self);
657
658	/* Maybe call finalizer; exit early if resurrected */
659	if (type->tp_del) {
660		type->tp_del(self);
661		if (self->ob_refcnt > 0)
662			goto endlabel;
663	}
664
665	/*  Clear slots up to the nearest base with a different tp_dealloc */
666	base = type;
667	while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
668		if (base->ob_size)
669			clear_slots(base, self);
670		base = base->tp_base;
671		assert(base);
672	}
673
674	/* If we added a dict, DECREF it */
675	if (type->tp_dictoffset && !base->tp_dictoffset) {
676		PyObject **dictptr = _PyObject_GetDictPtr(self);
677		if (dictptr != NULL) {
678			PyObject *dict = *dictptr;
679			if (dict != NULL) {
680				Py_DECREF(dict);
681				*dictptr = NULL;
682			}
683		}
684	}
685
686	/* Finalize GC if the base doesn't do GC and we do */
687	if (!PyType_IS_GC(base))
688		_PyObject_GC_UNTRACK(self);
689
690	/* Call the base tp_dealloc() */
691	assert(basedealloc);
692	basedealloc(self);
693
694	/* Can't reference self beyond this point */
695	Py_DECREF(type);
696
697  endlabel:
698	++_PyTrash_delete_nesting;
699	Py_TRASHCAN_SAFE_END(self);
700	--_PyTrash_delete_nesting;
701
702	/* Explanation of the weirdness around the trashcan macros:
703
704	   Q. What do the trashcan macros do?
705
706	   A. Read the comment titled "Trashcan mechanism" in object.h.
707	      For one, this explains why there must be a call to GC-untrack
708	      before the trashcan begin macro.  Without understanding the
709	      trashcan code, the answers to the following questions don't make
710	      sense.
711
712	   Q. Why do we GC-untrack before the trashcan and then immediately
713	      GC-track again afterward?
714
715	   A. In the case that the base class is GC-aware, the base class
716	      probably GC-untracks the object.  If it does that using the
717	      UNTRACK macro, this will crash when the object is already
718	      untracked.  Because we don't know what the base class does, the
719	      only safe thing is to make sure the object is tracked when we
720	      call the base class dealloc.  But...  The trashcan begin macro
721	      requires that the object is *untracked* before it is called.  So
722	      the dance becomes:
723
724	         GC untrack
725		 trashcan begin
726		 GC track
727
728	   Q. Why the bizarre (net-zero) manipulation of
729	      _PyTrash_delete_nesting around the trashcan macros?
730
731	   A. Some base classes (e.g. list) also use the trashcan mechanism.
732	      The following scenario used to be possible:
733
734	      - suppose the trashcan level is one below the trashcan limit
735
736	      - subtype_dealloc() is called
737
738	      - the trashcan limit is not yet reached, so the trashcan level
739	        is incremented and the code between trashcan begin and end is
740	        executed
741
742	      - this destroys much of the object's contents, including its
743	        slots and __dict__
744
745	      - basedealloc() is called; this is really list_dealloc(), or
746	        some other type which also uses the trashcan macros
747
748	      - the trashcan limit is now reached, so the object is put on the
749	        trashcan's to-be-deleted-later list
750
751	      - basedealloc() returns
752
753	      - subtype_dealloc() decrefs the object's type
754
755	      - subtype_dealloc() returns
756
757	      - later, the trashcan code starts deleting the objects from its
758	        to-be-deleted-later list
759
760	      - subtype_dealloc() is called *AGAIN* for the same object
761
762	      - at the very least (if the destroyed slots and __dict__ don't
763	        cause problems) the object's type gets decref'ed a second
764	        time, which is *BAD*!!!
765
766	      The remedy is to make sure that if the code between trashcan
767	      begin and end in subtype_dealloc() is called, the code between
768	      trashcan begin and end in basedealloc() will also be called.
769	      This is done by decrementing the level after passing into the
770	      trashcan block, and incrementing it just before leaving the
771	      block.
772
773	      But now it's possible that a chain of objects consisting solely
774	      of objects whose deallocator is subtype_dealloc() will defeat
775	      the trashcan mechanism completely: the decremented level means
776	      that the effective level never reaches the limit.  Therefore, we
777	      *increment* the level *before* entering the trashcan block, and
778	      matchingly decrement it after leaving.  This means the trashcan
779	      code will trigger a little early, but that's no big deal.
780
781	   Q. Are there any live examples of code in need of all this
782	      complexity?
783
784	   A. Yes.  See SF bug 668433 for code that crashed (when Python was
785	      compiled in debug mode) before the trashcan level manipulations
786	      were added.  For more discussion, see SF patches 581742, 575073
787	      and bug 574207.
788	*/
789}
790
791static PyTypeObject *solid_base(PyTypeObject *type);
792
793/* type test with subclassing support */
794
795int
796PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
797{
798	PyObject *mro;
799
800	if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
801		return b == a || b == &PyBaseObject_Type;
802
803	mro = a->tp_mro;
804	if (mro != NULL) {
805		/* Deal with multiple inheritance without recursion
806		   by walking the MRO tuple */
807		int i, n;
808		assert(PyTuple_Check(mro));
809		n = PyTuple_GET_SIZE(mro);
810		for (i = 0; i < n; i++) {
811			if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
812				return 1;
813		}
814		return 0;
815	}
816	else {
817		/* a is not completely initilized yet; follow tp_base */
818		do {
819			if (a == b)
820				return 1;
821			a = a->tp_base;
822		} while (a != NULL);
823		return b == &PyBaseObject_Type;
824	}
825}
826
827/* Internal routines to do a method lookup in the type
828   without looking in the instance dictionary
829   (so we can't use PyObject_GetAttr) but still binding
830   it to the instance.  The arguments are the object,
831   the method name as a C string, and the address of a
832   static variable used to cache the interned Python string.
833
834   Two variants:
835
836   - lookup_maybe() returns NULL without raising an exception
837     when the _PyType_Lookup() call fails;
838
839   - lookup_method() always raises an exception upon errors.
840*/
841
842static PyObject *
843lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
844{
845	PyObject *res;
846
847	if (*attrobj == NULL) {
848		*attrobj = PyString_InternFromString(attrstr);
849		if (*attrobj == NULL)
850			return NULL;
851	}
852	res = _PyType_Lookup(self->ob_type, *attrobj);
853	if (res != NULL) {
854		descrgetfunc f;
855		if ((f = res->ob_type->tp_descr_get) == NULL)
856			Py_INCREF(res);
857		else
858			res = f(res, self, (PyObject *)(self->ob_type));
859	}
860	return res;
861}
862
863static PyObject *
864lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
865{
866	PyObject *res = lookup_maybe(self, attrstr, attrobj);
867	if (res == NULL && !PyErr_Occurred())
868		PyErr_SetObject(PyExc_AttributeError, *attrobj);
869	return res;
870}
871
872/* A variation of PyObject_CallMethod that uses lookup_method()
873   instead of PyObject_GetAttrString().  This uses the same convention
874   as lookup_method to cache the interned name string object. */
875
876static PyObject *
877call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
878{
879	va_list va;
880	PyObject *args, *func = 0, *retval;
881	va_start(va, format);
882
883	func = lookup_maybe(o, name, nameobj);
884	if (func == NULL) {
885		va_end(va);
886		if (!PyErr_Occurred())
887			PyErr_SetObject(PyExc_AttributeError, *nameobj);
888		return NULL;
889	}
890
891	if (format && *format)
892		args = Py_VaBuildValue(format, va);
893	else
894		args = PyTuple_New(0);
895
896	va_end(va);
897
898	if (args == NULL)
899		return NULL;
900
901	assert(PyTuple_Check(args));
902	retval = PyObject_Call(func, args, NULL);
903
904	Py_DECREF(args);
905	Py_DECREF(func);
906
907	return retval;
908}
909
910/* Clone of call_method() that returns NotImplemented when the lookup fails. */
911
912static PyObject *
913call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
914{
915	va_list va;
916	PyObject *args, *func = 0, *retval;
917	va_start(va, format);
918
919	func = lookup_maybe(o, name, nameobj);
920	if (func == NULL) {
921		va_end(va);
922		if (!PyErr_Occurred()) {
923			Py_INCREF(Py_NotImplemented);
924			return Py_NotImplemented;
925		}
926		return NULL;
927	}
928
929	if (format && *format)
930		args = Py_VaBuildValue(format, va);
931	else
932		args = PyTuple_New(0);
933
934	va_end(va);
935
936	if (args == NULL)
937		return NULL;
938
939	assert(PyTuple_Check(args));
940	retval = PyObject_Call(func, args, NULL);
941
942	Py_DECREF(args);
943	Py_DECREF(func);
944
945	return retval;
946}
947
948static int
949fill_classic_mro(PyObject *mro, PyObject *cls)
950{
951	PyObject *bases, *base;
952	int i, n;
953
954	assert(PyList_Check(mro));
955	assert(PyClass_Check(cls));
956	i = PySequence_Contains(mro, cls);
957	if (i < 0)
958		return -1;
959	if (!i) {
960		if (PyList_Append(mro, cls) < 0)
961			return -1;
962	}
963	bases = ((PyClassObject *)cls)->cl_bases;
964	assert(bases && PyTuple_Check(bases));
965	n = PyTuple_GET_SIZE(bases);
966	for (i = 0; i < n; i++) {
967		base = PyTuple_GET_ITEM(bases, i);
968		if (fill_classic_mro(mro, base) < 0)
969			return -1;
970	}
971	return 0;
972}
973
974static PyObject *
975classic_mro(PyObject *cls)
976{
977	PyObject *mro;
978
979	assert(PyClass_Check(cls));
980	mro = PyList_New(0);
981	if (mro != NULL) {
982		if (fill_classic_mro(mro, cls) == 0)
983			return mro;
984		Py_DECREF(mro);
985	}
986	return NULL;
987}
988
989/*
990    Method resolution order algorithm C3 described in
991    "A Monotonic Superclass Linearization for Dylan",
992    by Kim Barrett, Bob Cassel, Paul Haahr,
993    David A. Moon, Keith Playford, and P. Tucker Withington.
994    (OOPSLA 1996)
995
996    Some notes about the rules implied by C3:
997
998    No duplicate bases.
999    It isn't legal to repeat a class in a list of base classes.
1000
1001    The next three properties are the 3 constraints in "C3".
1002
1003    Local precendece order.
1004    If A precedes B in C's MRO, then A will precede B in the MRO of all
1005    subclasses of C.
1006
1007    Monotonicity.
1008    The MRO of a class must be an extension without reordering of the
1009    MRO of each of its superclasses.
1010
1011    Extended Precedence Graph (EPG).
1012    Linearization is consistent if there is a path in the EPG from
1013    each class to all its successors in the linearization.  See
1014    the paper for definition of EPG.
1015 */
1016
1017static int
1018tail_contains(PyObject *list, int whence, PyObject *o) {
1019	int j, size;
1020	size = PyList_GET_SIZE(list);
1021
1022	for (j = whence+1; j < size; j++) {
1023		if (PyList_GET_ITEM(list, j) == o)
1024			return 1;
1025	}
1026	return 0;
1027}
1028
1029static PyObject *
1030class_name(PyObject *cls)
1031{
1032	PyObject *name = PyObject_GetAttrString(cls, "__name__");
1033	if (name == NULL) {
1034		PyErr_Clear();
1035		Py_XDECREF(name);
1036		name = PyObject_Repr(cls);
1037	}
1038	if (name == NULL)
1039		return NULL;
1040	if (!PyString_Check(name)) {
1041		Py_DECREF(name);
1042		return NULL;
1043	}
1044	return name;
1045}
1046
1047static int
1048check_duplicates(PyObject *list)
1049{
1050	int i, j, n;
1051	/* Let's use a quadratic time algorithm,
1052	   assuming that the bases lists is short.
1053	*/
1054	n = PyList_GET_SIZE(list);
1055	for (i = 0; i < n; i++) {
1056		PyObject *o = PyList_GET_ITEM(list, i);
1057		for (j = i + 1; j < n; j++) {
1058			if (PyList_GET_ITEM(list, j) == o) {
1059				o = class_name(o);
1060				PyErr_Format(PyExc_TypeError,
1061					     "duplicate base class %s",
1062					     o ? PyString_AS_STRING(o) : "?");
1063				Py_XDECREF(o);
1064				return -1;
1065			}
1066		}
1067	}
1068	return 0;
1069}
1070
1071/* Raise a TypeError for an MRO order disagreement.
1072
1073   It's hard to produce a good error message.  In the absence of better
1074   insight into error reporting, report the classes that were candidates
1075   to be put next into the MRO.  There is some conflict between the
1076   order in which they should be put in the MRO, but it's hard to
1077   diagnose what constraint can't be satisfied.
1078*/
1079
1080static void
1081set_mro_error(PyObject *to_merge, int *remain)
1082{
1083	int i, n, off, to_merge_size;
1084	char buf[1000];
1085	PyObject *k, *v;
1086	PyObject *set = PyDict_New();
1087
1088	to_merge_size = PyList_GET_SIZE(to_merge);
1089	for (i = 0; i < to_merge_size; i++) {
1090		PyObject *L = PyList_GET_ITEM(to_merge, i);
1091		if (remain[i] < PyList_GET_SIZE(L)) {
1092			PyObject *c = PyList_GET_ITEM(L, remain[i]);
1093			if (PyDict_SetItem(set, c, Py_None) < 0)
1094				return;
1095		}
1096	}
1097	n = PyDict_Size(set);
1098
1099	off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1100consistent method resolution\norder (MRO) for bases");
1101	i = 0;
1102	while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1103		PyObject *name = class_name(k);
1104		off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1105				     name ? PyString_AS_STRING(name) : "?");
1106		Py_XDECREF(name);
1107		if (--n && off+1 < sizeof(buf)) {
1108			buf[off++] = ',';
1109			buf[off] = '\0';
1110		}
1111	}
1112	PyErr_SetString(PyExc_TypeError, buf);
1113	Py_DECREF(set);
1114}
1115
1116static int
1117pmerge(PyObject *acc, PyObject* to_merge) {
1118	int i, j, to_merge_size;
1119	int *remain;
1120	int ok, empty_cnt;
1121
1122	to_merge_size = PyList_GET_SIZE(to_merge);
1123
1124	/* remain stores an index into each sublist of to_merge.
1125	   remain[i] is the index of the next base in to_merge[i]
1126	   that is not included in acc.
1127	*/
1128	remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1129	if (remain == NULL)
1130		return -1;
1131	for (i = 0; i < to_merge_size; i++)
1132		remain[i] = 0;
1133
1134  again:
1135	empty_cnt = 0;
1136	for (i = 0; i < to_merge_size; i++) {
1137		PyObject *candidate;
1138
1139		PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1140
1141		if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1142			empty_cnt++;
1143			continue;
1144                }
1145
1146		/* Choose next candidate for MRO.
1147
1148		   The input sequences alone can determine the choice.
1149		   If not, choose the class which appears in the MRO
1150		   of the earliest direct superclass of the new class.
1151		*/
1152
1153		candidate = PyList_GET_ITEM(cur_list, remain[i]);
1154		for (j = 0; j < to_merge_size; j++) {
1155			PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1156			if (tail_contains(j_lst, remain[j], candidate)) {
1157				goto skip; /* continue outer loop */
1158			}
1159		}
1160		ok = PyList_Append(acc, candidate);
1161		if (ok < 0) {
1162			PyMem_Free(remain);
1163			return -1;
1164		}
1165		for (j = 0; j < to_merge_size; j++) {
1166			PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1167			if (remain[j] < PyList_GET_SIZE(j_lst) &&
1168			    PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1169				remain[j]++;
1170			}
1171		}
1172		goto again;
1173	  skip: ;
1174	}
1175
1176	if (empty_cnt == to_merge_size) {
1177		PyMem_FREE(remain);
1178		return 0;
1179	}
1180	set_mro_error(to_merge, remain);
1181	PyMem_FREE(remain);
1182	return -1;
1183}
1184
1185static PyObject *
1186mro_implementation(PyTypeObject *type)
1187{
1188	int i, n, ok;
1189	PyObject *bases, *result;
1190	PyObject *to_merge, *bases_aslist;
1191
1192	if(type->tp_dict == NULL) {
1193		if(PyType_Ready(type) < 0)
1194			return NULL;
1195	}
1196
1197	/* Find a superclass linearization that honors the constraints
1198	   of the explicit lists of bases and the constraints implied by
1199	   each base class.
1200
1201	   to_merge is a list of lists, where each list is a superclass
1202	   linearization implied by a base class.  The last element of
1203	   to_merge is the declared list of bases.
1204	*/
1205
1206	bases = type->tp_bases;
1207	n = PyTuple_GET_SIZE(bases);
1208
1209	to_merge = PyList_New(n+1);
1210	if (to_merge == NULL)
1211		return NULL;
1212
1213	for (i = 0; i < n; i++) {
1214		PyObject *base = PyTuple_GET_ITEM(bases, i);
1215		PyObject *parentMRO;
1216		if (PyType_Check(base))
1217			parentMRO = PySequence_List(
1218				((PyTypeObject*)base)->tp_mro);
1219		else
1220			parentMRO = classic_mro(base);
1221		if (parentMRO == NULL) {
1222			Py_DECREF(to_merge);
1223			return NULL;
1224	        }
1225
1226		PyList_SET_ITEM(to_merge, i, parentMRO);
1227	}
1228
1229	bases_aslist = PySequence_List(bases);
1230	if (bases_aslist == NULL) {
1231		Py_DECREF(to_merge);
1232		return NULL;
1233	}
1234	/* This is just a basic sanity check. */
1235	if (check_duplicates(bases_aslist) < 0) {
1236		Py_DECREF(to_merge);
1237		Py_DECREF(bases_aslist);
1238		return NULL;
1239	}
1240	PyList_SET_ITEM(to_merge, n, bases_aslist);
1241
1242	result = Py_BuildValue("[O]", (PyObject *)type);
1243	if (result == NULL) {
1244		Py_DECREF(to_merge);
1245		return NULL;
1246	}
1247
1248	ok = pmerge(result, to_merge);
1249	Py_DECREF(to_merge);
1250	if (ok < 0) {
1251		Py_DECREF(result);
1252		return NULL;
1253	}
1254
1255	return result;
1256}
1257
1258static PyObject *
1259mro_external(PyObject *self)
1260{
1261	PyTypeObject *type = (PyTypeObject *)self;
1262
1263	return mro_implementation(type);
1264}
1265
1266static int
1267mro_internal(PyTypeObject *type)
1268{
1269	PyObject *mro, *result, *tuple;
1270
1271	if (type->ob_type == &PyType_Type) {
1272		result = mro_implementation(type);
1273	}
1274	else {
1275		static PyObject *mro_str;
1276		mro = lookup_method((PyObject *)type, "mro", &mro_str);
1277		if (mro == NULL)
1278			return -1;
1279		result = PyObject_CallObject(mro, NULL);
1280		Py_DECREF(mro);
1281	}
1282	if (result == NULL)
1283		return -1;
1284	tuple = PySequence_Tuple(result);
1285	Py_DECREF(result);
1286	type->tp_mro = tuple;
1287	return 0;
1288}
1289
1290
1291/* Calculate the best base amongst multiple base classes.
1292   This is the first one that's on the path to the "solid base". */
1293
1294static PyTypeObject *
1295best_base(PyObject *bases)
1296{
1297	int i, n;
1298	PyTypeObject *base, *winner, *candidate, *base_i;
1299	PyObject *base_proto;
1300
1301	assert(PyTuple_Check(bases));
1302	n = PyTuple_GET_SIZE(bases);
1303	assert(n > 0);
1304	base = NULL;
1305	winner = NULL;
1306	for (i = 0; i < n; i++) {
1307		base_proto = PyTuple_GET_ITEM(bases, i);
1308		if (PyClass_Check(base_proto))
1309			continue;
1310		if (!PyType_Check(base_proto)) {
1311			PyErr_SetString(
1312				PyExc_TypeError,
1313				"bases must be types");
1314			return NULL;
1315		}
1316		base_i = (PyTypeObject *)base_proto;
1317		if (base_i->tp_dict == NULL) {
1318			if (PyType_Ready(base_i) < 0)
1319				return NULL;
1320		}
1321		candidate = solid_base(base_i);
1322		if (winner == NULL) {
1323			winner = candidate;
1324			base = base_i;
1325		}
1326		else if (PyType_IsSubtype(winner, candidate))
1327			;
1328		else if (PyType_IsSubtype(candidate, winner)) {
1329			winner = candidate;
1330			base = base_i;
1331		}
1332		else {
1333			PyErr_SetString(
1334				PyExc_TypeError,
1335				"multiple bases have "
1336				"instance lay-out conflict");
1337			return NULL;
1338		}
1339	}
1340	if (base == NULL)
1341		PyErr_SetString(PyExc_TypeError,
1342			"a new-style class can't have only classic bases");
1343	return base;
1344}
1345
1346static int
1347extra_ivars(PyTypeObject *type, PyTypeObject *base)
1348{
1349	size_t t_size = type->tp_basicsize;
1350	size_t b_size = base->tp_basicsize;
1351
1352	assert(t_size >= b_size); /* Else type smaller than base! */
1353	if (type->tp_itemsize || base->tp_itemsize) {
1354		/* If itemsize is involved, stricter rules */
1355		return t_size != b_size ||
1356			type->tp_itemsize != base->tp_itemsize;
1357	}
1358	if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1359	    type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1360		t_size -= sizeof(PyObject *);
1361	if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1362	    type->tp_dictoffset + sizeof(PyObject *) == t_size)
1363		t_size -= sizeof(PyObject *);
1364
1365	return t_size != b_size;
1366}
1367
1368static PyTypeObject *
1369solid_base(PyTypeObject *type)
1370{
1371	PyTypeObject *base;
1372
1373	if (type->tp_base)
1374		base = solid_base(type->tp_base);
1375	else
1376		base = &PyBaseObject_Type;
1377	if (extra_ivars(type, base))
1378		return type;
1379	else
1380		return base;
1381}
1382
1383static void object_dealloc(PyObject *);
1384static int object_init(PyObject *, PyObject *, PyObject *);
1385static int update_slot(PyTypeObject *, PyObject *);
1386static void fixup_slot_dispatchers(PyTypeObject *);
1387
1388static PyObject *
1389subtype_dict(PyObject *obj, void *context)
1390{
1391	PyObject **dictptr = _PyObject_GetDictPtr(obj);
1392	PyObject *dict;
1393
1394	if (dictptr == NULL) {
1395		PyErr_SetString(PyExc_AttributeError,
1396				"This object has no __dict__");
1397		return NULL;
1398	}
1399	dict = *dictptr;
1400	if (dict == NULL)
1401		*dictptr = dict = PyDict_New();
1402	Py_XINCREF(dict);
1403	return dict;
1404}
1405
1406static int
1407subtype_setdict(PyObject *obj, PyObject *value, void *context)
1408{
1409	PyObject **dictptr = _PyObject_GetDictPtr(obj);
1410	PyObject *dict;
1411
1412	if (dictptr == NULL) {
1413		PyErr_SetString(PyExc_AttributeError,
1414				"This object has no __dict__");
1415		return -1;
1416	}
1417	if (value != NULL && !PyDict_Check(value)) {
1418		PyErr_SetString(PyExc_TypeError,
1419				"__dict__ must be set to a dictionary");
1420		return -1;
1421	}
1422	dict = *dictptr;
1423	Py_XINCREF(value);
1424	*dictptr = value;
1425	Py_XDECREF(dict);
1426	return 0;
1427}
1428
1429static PyObject *
1430subtype_getweakref(PyObject *obj, void *context)
1431{
1432	PyObject **weaklistptr;
1433	PyObject *result;
1434
1435	if (obj->ob_type->tp_weaklistoffset == 0) {
1436		PyErr_SetString(PyExc_AttributeError,
1437				"This object has no __weaklist__");
1438		return NULL;
1439	}
1440	assert(obj->ob_type->tp_weaklistoffset > 0);
1441	assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
1442	       (size_t)(obj->ob_type->tp_basicsize));
1443	weaklistptr = (PyObject **)
1444		((char *)obj + obj->ob_type->tp_weaklistoffset);
1445	if (*weaklistptr == NULL)
1446		result = Py_None;
1447	else
1448		result = *weaklistptr;
1449	Py_INCREF(result);
1450	return result;
1451}
1452
1453/* Three variants on the subtype_getsets list. */
1454
1455static PyGetSetDef subtype_getsets_full[] = {
1456	{"__dict__", subtype_dict, subtype_setdict,
1457	 PyDoc_STR("dictionary for instance variables (if defined)")},
1458	{"__weakref__", subtype_getweakref, NULL,
1459	 PyDoc_STR("list of weak references to the object (if defined)")},
1460	{0}
1461};
1462
1463static PyGetSetDef subtype_getsets_dict_only[] = {
1464	{"__dict__", subtype_dict, subtype_setdict,
1465	 PyDoc_STR("dictionary for instance variables (if defined)")},
1466	{0}
1467};
1468
1469static PyGetSetDef subtype_getsets_weakref_only[] = {
1470	{"__weakref__", subtype_getweakref, NULL,
1471	 PyDoc_STR("list of weak references to the object (if defined)")},
1472	{0}
1473};
1474
1475static int
1476valid_identifier(PyObject *s)
1477{
1478	unsigned char *p;
1479	int i, n;
1480
1481	if (!PyString_Check(s)) {
1482		PyErr_SetString(PyExc_TypeError,
1483				"__slots__ must be strings");
1484		return 0;
1485	}
1486	p = (unsigned char *) PyString_AS_STRING(s);
1487	n = PyString_GET_SIZE(s);
1488	/* We must reject an empty name.  As a hack, we bump the
1489	   length to 1 so that the loop will balk on the trailing \0. */
1490	if (n == 0)
1491		n = 1;
1492	for (i = 0; i < n; i++, p++) {
1493		if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1494			PyErr_SetString(PyExc_TypeError,
1495					"__slots__ must be identifiers");
1496			return 0;
1497		}
1498	}
1499	return 1;
1500}
1501
1502#ifdef Py_USING_UNICODE
1503/* Replace Unicode objects in slots.  */
1504
1505static PyObject *
1506_unicode_to_string(PyObject *slots, int nslots)
1507{
1508	PyObject *tmp = slots;
1509	PyObject *o, *o1;
1510	int i;
1511	intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1512	for (i = 0; i < nslots; i++) {
1513		if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1514			if (tmp == slots) {
1515				tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1516				if (tmp == NULL)
1517					return NULL;
1518			}
1519			o1 = _PyUnicode_AsDefaultEncodedString
1520					(o, NULL);
1521			if (o1 == NULL) {
1522				Py_DECREF(tmp);
1523				return 0;
1524			}
1525			Py_INCREF(o1);
1526			Py_DECREF(o);
1527			PyTuple_SET_ITEM(tmp, i, o1);
1528		}
1529	}
1530	return tmp;
1531}
1532#endif
1533
1534static PyObject *
1535type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1536{
1537	PyObject *name, *bases, *dict;
1538	static char *kwlist[] = {"name", "bases", "dict", 0};
1539	PyObject *slots, *tmp, *newslots;
1540	PyTypeObject *type, *base, *tmptype, *winner;
1541	PyHeapTypeObject *et;
1542	PyMemberDef *mp;
1543	int i, nbases, nslots, slotoffset, add_dict, add_weak;
1544	int j, may_add_dict, may_add_weak;
1545
1546	assert(args != NULL && PyTuple_Check(args));
1547	assert(kwds == NULL || PyDict_Check(kwds));
1548
1549	/* Special case: type(x) should return x->ob_type */
1550	{
1551		const int nargs = PyTuple_GET_SIZE(args);
1552		const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1553
1554		if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1555			PyObject *x = PyTuple_GET_ITEM(args, 0);
1556			Py_INCREF(x->ob_type);
1557			return (PyObject *) x->ob_type;
1558		}
1559
1560		/* SF bug 475327 -- if that didn't trigger, we need 3
1561		   arguments. but PyArg_ParseTupleAndKeywords below may give
1562		   a msg saying type() needs exactly 3. */
1563		if (nargs + nkwds != 3) {
1564			PyErr_SetString(PyExc_TypeError,
1565					"type() takes 1 or 3 arguments");
1566			return NULL;
1567		}
1568	}
1569
1570	/* Check arguments: (name, bases, dict) */
1571	if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1572					 &name,
1573					 &PyTuple_Type, &bases,
1574					 &PyDict_Type, &dict))
1575		return NULL;
1576
1577	/* Determine the proper metatype to deal with this,
1578	   and check for metatype conflicts while we're at it.
1579	   Note that if some other metatype wins to contract,
1580	   it's possible that its instances are not types. */
1581	nbases = PyTuple_GET_SIZE(bases);
1582	winner = metatype;
1583	for (i = 0; i < nbases; i++) {
1584		tmp = PyTuple_GET_ITEM(bases, i);
1585		tmptype = tmp->ob_type;
1586		if (tmptype == &PyClass_Type)
1587			continue; /* Special case classic classes */
1588		if (PyType_IsSubtype(winner, tmptype))
1589			continue;
1590		if (PyType_IsSubtype(tmptype, winner)) {
1591			winner = tmptype;
1592			continue;
1593		}
1594		PyErr_SetString(PyExc_TypeError,
1595				"metaclass conflict: "
1596				"the metaclass of a derived class "
1597				"must be a (non-strict) subclass "
1598				"of the metaclasses of all its bases");
1599		return NULL;
1600	}
1601	if (winner != metatype) {
1602		if (winner->tp_new != type_new) /* Pass it to the winner */
1603			return winner->tp_new(winner, args, kwds);
1604		metatype = winner;
1605	}
1606
1607	/* Adjust for empty tuple bases */
1608	if (nbases == 0) {
1609		bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1610		if (bases == NULL)
1611			return NULL;
1612		nbases = 1;
1613	}
1614	else
1615		Py_INCREF(bases);
1616
1617	/* XXX From here until type is allocated, "return NULL" leaks bases! */
1618
1619	/* Calculate best base, and check that all bases are type objects */
1620	base = best_base(bases);
1621	if (base == NULL) {
1622		Py_DECREF(bases);
1623		return NULL;
1624	}
1625	if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1626		PyErr_Format(PyExc_TypeError,
1627			     "type '%.100s' is not an acceptable base type",
1628			     base->tp_name);
1629		Py_DECREF(bases);
1630		return NULL;
1631	}
1632
1633	/* Check for a __slots__ sequence variable in dict, and count it */
1634	slots = PyDict_GetItemString(dict, "__slots__");
1635	nslots = 0;
1636	add_dict = 0;
1637	add_weak = 0;
1638	may_add_dict = base->tp_dictoffset == 0;
1639	may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1640	if (slots == NULL) {
1641		if (may_add_dict) {
1642			add_dict++;
1643		}
1644		if (may_add_weak) {
1645			add_weak++;
1646		}
1647	}
1648	else {
1649		/* Have slots */
1650
1651		/* Make it into a tuple */
1652		if (PyString_Check(slots))
1653			slots = Py_BuildValue("(O)", slots);
1654		else
1655			slots = PySequence_Tuple(slots);
1656		if (slots == NULL) {
1657			Py_DECREF(bases);
1658			return NULL;
1659		}
1660		assert(PyTuple_Check(slots));
1661
1662		/* Are slots allowed? */
1663		nslots = PyTuple_GET_SIZE(slots);
1664		if (nslots > 0 && base->tp_itemsize != 0) {
1665			PyErr_Format(PyExc_TypeError,
1666				     "nonempty __slots__ "
1667				     "not supported for subtype of '%s'",
1668				     base->tp_name);
1669		  bad_slots:
1670			Py_DECREF(bases);
1671			Py_DECREF(slots);
1672			return NULL;
1673		}
1674
1675#ifdef Py_USING_UNICODE
1676		tmp = _unicode_to_string(slots, nslots);
1677		if (tmp != slots) {
1678			Py_DECREF(slots);
1679			slots = tmp;
1680		}
1681		if (!tmp)
1682			return NULL;
1683#endif
1684		/* Check for valid slot names and two special cases */
1685		for (i = 0; i < nslots; i++) {
1686			PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1687			char *s;
1688			if (!valid_identifier(tmp))
1689				goto bad_slots;
1690			assert(PyString_Check(tmp));
1691			s = PyString_AS_STRING(tmp);
1692			if (strcmp(s, "__dict__") == 0) {
1693				if (!may_add_dict || add_dict) {
1694					PyErr_SetString(PyExc_TypeError,
1695						"__dict__ slot disallowed: "
1696						"we already got one");
1697					goto bad_slots;
1698				}
1699				add_dict++;
1700			}
1701			if (strcmp(s, "__weakref__") == 0) {
1702				if (!may_add_weak || add_weak) {
1703					PyErr_SetString(PyExc_TypeError,
1704						"__weakref__ slot disallowed: "
1705						"either we already got one, "
1706						"or __itemsize__ != 0");
1707					goto bad_slots;
1708				}
1709				add_weak++;
1710			}
1711		}
1712
1713		/* Copy slots into yet another tuple, demangling names */
1714		newslots = PyTuple_New(nslots - add_dict - add_weak);
1715		if (newslots == NULL)
1716			goto bad_slots;
1717		for (i = j = 0; i < nslots; i++) {
1718			char *s;
1719			char buffer[256];
1720			tmp = PyTuple_GET_ITEM(slots, i);
1721			s = PyString_AS_STRING(tmp);
1722			if ((add_dict && strcmp(s, "__dict__") == 0) ||
1723			    (add_weak && strcmp(s, "__weakref__") == 0))
1724				continue;
1725			if (_Py_Mangle(PyString_AS_STRING(name),
1726				       PyString_AS_STRING(tmp),
1727				       buffer, sizeof(buffer)))
1728			{
1729				tmp = PyString_FromString(buffer);
1730			} else {
1731				Py_INCREF(tmp);
1732			}
1733			PyTuple_SET_ITEM(newslots, j, tmp);
1734			j++;
1735		}
1736		assert(j == nslots - add_dict - add_weak);
1737		nslots = j;
1738		Py_DECREF(slots);
1739		slots = newslots;
1740
1741		/* Secondary bases may provide weakrefs or dict */
1742		if (nbases > 1 &&
1743		    ((may_add_dict && !add_dict) ||
1744		     (may_add_weak && !add_weak))) {
1745			for (i = 0; i < nbases; i++) {
1746				tmp = PyTuple_GET_ITEM(bases, i);
1747				if (tmp == (PyObject *)base)
1748					continue; /* Skip primary base */
1749				if (PyClass_Check(tmp)) {
1750					/* Classic base class provides both */
1751					if (may_add_dict && !add_dict)
1752						add_dict++;
1753					if (may_add_weak && !add_weak)
1754						add_weak++;
1755					break;
1756				}
1757				assert(PyType_Check(tmp));
1758				tmptype = (PyTypeObject *)tmp;
1759				if (may_add_dict && !add_dict &&
1760				    tmptype->tp_dictoffset != 0)
1761					add_dict++;
1762				if (may_add_weak && !add_weak &&
1763				    tmptype->tp_weaklistoffset != 0)
1764					add_weak++;
1765				if (may_add_dict && !add_dict)
1766					continue;
1767				if (may_add_weak && !add_weak)
1768					continue;
1769				/* Nothing more to check */
1770				break;
1771			}
1772		}
1773	}
1774
1775	/* XXX From here until type is safely allocated,
1776	   "return NULL" may leak slots! */
1777
1778	/* Allocate the type object */
1779	type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1780	if (type == NULL) {
1781		Py_XDECREF(slots);
1782		Py_DECREF(bases);
1783		return NULL;
1784	}
1785
1786	/* Keep name and slots alive in the extended type object */
1787	et = (PyHeapTypeObject *)type;
1788	Py_INCREF(name);
1789	et->name = name;
1790	et->slots = slots;
1791
1792	/* Initialize tp_flags */
1793	type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1794		Py_TPFLAGS_BASETYPE;
1795	if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1796		type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1797
1798	/* It's a new-style number unless it specifically inherits any
1799	   old-style numeric behavior */
1800	if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1801	    (base->tp_as_number == NULL))
1802		type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1803
1804	/* Initialize essential fields */
1805	type->tp_as_number = &et->as_number;
1806	type->tp_as_sequence = &et->as_sequence;
1807	type->tp_as_mapping = &et->as_mapping;
1808	type->tp_as_buffer = &et->as_buffer;
1809	type->tp_name = PyString_AS_STRING(name);
1810
1811	/* Set tp_base and tp_bases */
1812	type->tp_bases = bases;
1813	Py_INCREF(base);
1814	type->tp_base = base;
1815
1816	/* Initialize tp_dict from passed-in dict */
1817	type->tp_dict = dict = PyDict_Copy(dict);
1818	if (dict == NULL) {
1819		Py_DECREF(type);
1820		return NULL;
1821	}
1822
1823	/* Set __module__ in the dict */
1824	if (PyDict_GetItemString(dict, "__module__") == NULL) {
1825		tmp = PyEval_GetGlobals();
1826		if (tmp != NULL) {
1827			tmp = PyDict_GetItemString(tmp, "__name__");
1828			if (tmp != NULL) {
1829				if (PyDict_SetItemString(dict, "__module__",
1830							 tmp) < 0)
1831					return NULL;
1832			}
1833		}
1834	}
1835
1836	/* Set tp_doc to a copy of dict['__doc__'], if the latter is there
1837	   and is a string.  The __doc__ accessor will first look for tp_doc;
1838	   if that fails, it will still look into __dict__.
1839	*/
1840	{
1841		PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1842		if (doc != NULL && PyString_Check(doc)) {
1843			const size_t n = (size_t)PyString_GET_SIZE(doc);
1844			type->tp_doc = (char *)PyObject_MALLOC(n+1);
1845			if (type->tp_doc == NULL) {
1846				Py_DECREF(type);
1847				return NULL;
1848			}
1849			memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1850		}
1851	}
1852
1853	/* Special-case __new__: if it's a plain function,
1854	   make it a static function */
1855	tmp = PyDict_GetItemString(dict, "__new__");
1856	if (tmp != NULL && PyFunction_Check(tmp)) {
1857		tmp = PyStaticMethod_New(tmp);
1858		if (tmp == NULL) {
1859			Py_DECREF(type);
1860			return NULL;
1861		}
1862		PyDict_SetItemString(dict, "__new__", tmp);
1863		Py_DECREF(tmp);
1864	}
1865
1866	/* Add descriptors for custom slots from __slots__, or for __dict__ */
1867	mp = PyHeapType_GET_MEMBERS(et);
1868	slotoffset = base->tp_basicsize;
1869	if (slots != NULL) {
1870		for (i = 0; i < nslots; i++, mp++) {
1871			mp->name = PyString_AS_STRING(
1872				PyTuple_GET_ITEM(slots, i));
1873			mp->type = T_OBJECT_EX;
1874			mp->offset = slotoffset;
1875			if (base->tp_weaklistoffset == 0 &&
1876			    strcmp(mp->name, "__weakref__") == 0) {
1877				add_weak++;
1878				mp->type = T_OBJECT;
1879				mp->flags = READONLY;
1880				type->tp_weaklistoffset = slotoffset;
1881			}
1882			slotoffset += sizeof(PyObject *);
1883		}
1884	}
1885	if (add_dict) {
1886		if (base->tp_itemsize)
1887			type->tp_dictoffset = -(long)sizeof(PyObject *);
1888		else
1889			type->tp_dictoffset = slotoffset;
1890		slotoffset += sizeof(PyObject *);
1891	}
1892	if (add_weak) {
1893		assert(!base->tp_itemsize);
1894		type->tp_weaklistoffset = slotoffset;
1895		slotoffset += sizeof(PyObject *);
1896	}
1897	type->tp_basicsize = slotoffset;
1898	type->tp_itemsize = base->tp_itemsize;
1899	type->tp_members = PyHeapType_GET_MEMBERS(et);
1900
1901	if (type->tp_weaklistoffset && type->tp_dictoffset)
1902		type->tp_getset = subtype_getsets_full;
1903	else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1904		type->tp_getset = subtype_getsets_weakref_only;
1905	else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1906		type->tp_getset = subtype_getsets_dict_only;
1907	else
1908		type->tp_getset = NULL;
1909
1910	/* Special case some slots */
1911	if (type->tp_dictoffset != 0 || nslots > 0) {
1912		if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1913			type->tp_getattro = PyObject_GenericGetAttr;
1914		if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1915			type->tp_setattro = PyObject_GenericSetAttr;
1916	}
1917	type->tp_dealloc = subtype_dealloc;
1918
1919	/* Enable GC unless there are really no instance variables possible */
1920	if (!(type->tp_basicsize == sizeof(PyObject) &&
1921	      type->tp_itemsize == 0))
1922		type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1923
1924	/* Always override allocation strategy to use regular heap */
1925	type->tp_alloc = PyType_GenericAlloc;
1926	if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1927		type->tp_free = PyObject_GC_Del;
1928		type->tp_traverse = subtype_traverse;
1929		type->tp_clear = subtype_clear;
1930	}
1931	else
1932		type->tp_free = PyObject_Del;
1933
1934	/* Initialize the rest */
1935	if (PyType_Ready(type) < 0) {
1936		Py_DECREF(type);
1937		return NULL;
1938	}
1939
1940	/* Put the proper slots in place */
1941	fixup_slot_dispatchers(type);
1942
1943	return (PyObject *)type;
1944}
1945
1946/* Internal API to look for a name through the MRO.
1947   This returns a borrowed reference, and doesn't set an exception! */
1948PyObject *
1949_PyType_Lookup(PyTypeObject *type, PyObject *name)
1950{
1951	int i, n;
1952	PyObject *mro, *res, *base, *dict;
1953
1954	/* Look in tp_dict of types in MRO */
1955	mro = type->tp_mro;
1956
1957	/* If mro is NULL, the type is either not yet initialized
1958	   by PyType_Ready(), or already cleared by type_clear().
1959	   Either way the safest thing to do is to return NULL. */
1960	if (mro == NULL)
1961		return NULL;
1962
1963	assert(PyTuple_Check(mro));
1964	n = PyTuple_GET_SIZE(mro);
1965	for (i = 0; i < n; i++) {
1966		base = PyTuple_GET_ITEM(mro, i);
1967		if (PyClass_Check(base))
1968			dict = ((PyClassObject *)base)->cl_dict;
1969		else {
1970			assert(PyType_Check(base));
1971			dict = ((PyTypeObject *)base)->tp_dict;
1972		}
1973		assert(dict && PyDict_Check(dict));
1974		res = PyDict_GetItem(dict, name);
1975		if (res != NULL)
1976			return res;
1977	}
1978	return NULL;
1979}
1980
1981/* This is similar to PyObject_GenericGetAttr(),
1982   but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1983static PyObject *
1984type_getattro(PyTypeObject *type, PyObject *name)
1985{
1986	PyTypeObject *metatype = type->ob_type;
1987	PyObject *meta_attribute, *attribute;
1988	descrgetfunc meta_get;
1989
1990	/* Initialize this type (we'll assume the metatype is initialized) */
1991	if (type->tp_dict == NULL) {
1992		if (PyType_Ready(type) < 0)
1993			return NULL;
1994	}
1995
1996	/* No readable descriptor found yet */
1997	meta_get = NULL;
1998
1999	/* Look for the attribute in the metatype */
2000	meta_attribute = _PyType_Lookup(metatype, name);
2001
2002	if (meta_attribute != NULL) {
2003		meta_get = meta_attribute->ob_type->tp_descr_get;
2004
2005		if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2006			/* Data descriptors implement tp_descr_set to intercept
2007			 * writes. Assume the attribute is not overridden in
2008			 * type's tp_dict (and bases): call the descriptor now.
2009			 */
2010			return meta_get(meta_attribute, (PyObject *)type,
2011					(PyObject *)metatype);
2012		}
2013	}
2014
2015	/* No data descriptor found on metatype. Look in tp_dict of this
2016	 * type and its bases */
2017	attribute = _PyType_Lookup(type, name);
2018	if (attribute != NULL) {
2019		/* Implement descriptor functionality, if any */
2020		descrgetfunc local_get = attribute->ob_type->tp_descr_get;
2021		if (local_get != NULL) {
2022			/* NULL 2nd argument indicates the descriptor was
2023			 * found on the target object itself (or a base)  */
2024			return local_get(attribute, (PyObject *)NULL,
2025					 (PyObject *)type);
2026		}
2027
2028		Py_INCREF(attribute);
2029		return attribute;
2030	}
2031
2032	/* No attribute found in local __dict__ (or bases): use the
2033	 * descriptor from the metatype, if any */
2034	if (meta_get != NULL)
2035		return meta_get(meta_attribute, (PyObject *)type,
2036				(PyObject *)metatype);
2037
2038	/* If an ordinary attribute was found on the metatype, return it now */
2039	if (meta_attribute != NULL) {
2040		Py_INCREF(meta_attribute);
2041		return meta_attribute;
2042	}
2043
2044	/* Give up */
2045	PyErr_Format(PyExc_AttributeError,
2046			 "type object '%.50s' has no attribute '%.400s'",
2047			 type->tp_name, PyString_AS_STRING(name));
2048	return NULL;
2049}
2050
2051static int
2052type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2053{
2054	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2055		PyErr_Format(
2056			PyExc_TypeError,
2057			"can't set attributes of built-in/extension type '%s'",
2058			type->tp_name);
2059		return -1;
2060	}
2061	/* XXX Example of how I expect this to be used...
2062	if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2063		return -1;
2064	*/
2065	if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2066		return -1;
2067	return update_slot(type, name);
2068}
2069
2070static void
2071type_dealloc(PyTypeObject *type)
2072{
2073	PyHeapTypeObject *et;
2074
2075	/* Assert this is a heap-allocated type object */
2076	assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2077	_PyObject_GC_UNTRACK(type);
2078	PyObject_ClearWeakRefs((PyObject *)type);
2079	et = (PyHeapTypeObject *)type;
2080	Py_XDECREF(type->tp_base);
2081	Py_XDECREF(type->tp_dict);
2082	Py_XDECREF(type->tp_bases);
2083	Py_XDECREF(type->tp_mro);
2084	Py_XDECREF(type->tp_cache);
2085	Py_XDECREF(type->tp_subclasses);
2086	PyObject_Free(type->tp_doc);
2087	Py_XDECREF(et->name);
2088	Py_XDECREF(et->slots);
2089	type->ob_type->tp_free((PyObject *)type);
2090}
2091
2092static PyObject *
2093type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2094{
2095	PyObject *list, *raw, *ref;
2096	int i, n;
2097
2098	list = PyList_New(0);
2099	if (list == NULL)
2100		return NULL;
2101	raw = type->tp_subclasses;
2102	if (raw == NULL)
2103		return list;
2104	assert(PyList_Check(raw));
2105	n = PyList_GET_SIZE(raw);
2106	for (i = 0; i < n; i++) {
2107		ref = PyList_GET_ITEM(raw, i);
2108		assert(PyWeakref_CheckRef(ref));
2109		ref = PyWeakref_GET_OBJECT(ref);
2110		if (ref != Py_None) {
2111			if (PyList_Append(list, ref) < 0) {
2112				Py_DECREF(list);
2113				return NULL;
2114			}
2115		}
2116	}
2117	return list;
2118}
2119
2120static PyMethodDef type_methods[] = {
2121	{"mro", (PyCFunction)mro_external, METH_NOARGS,
2122	 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2123	{"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2124	 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2125	{0}
2126};
2127
2128PyDoc_STRVAR(type_doc,
2129"type(object) -> the object's type\n"
2130"type(name, bases, dict) -> a new type");
2131
2132static int
2133type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2134{
2135	int err;
2136
2137	/* Because of type_is_gc(), the collector only calls this
2138	   for heaptypes. */
2139	assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2140
2141#define VISIT(SLOT) \
2142	if (SLOT) { \
2143		err = visit((PyObject *)(SLOT), arg); \
2144		if (err) \
2145			return err; \
2146	}
2147
2148	VISIT(type->tp_dict);
2149	VISIT(type->tp_cache);
2150	VISIT(type->tp_mro);
2151	VISIT(type->tp_bases);
2152	VISIT(type->tp_base);
2153
2154	/* There's no need to visit type->tp_subclasses or
2155	   ((PyHeapTypeObject *)type)->slots, because they can't be involved
2156	   in cycles; tp_subclasses is a list of weak references,
2157	   and slots is a tuple of strings. */
2158
2159#undef VISIT
2160
2161	return 0;
2162}
2163
2164static int
2165type_clear(PyTypeObject *type)
2166{
2167	PyObject *tmp;
2168
2169	/* Because of type_is_gc(), the collector only calls this
2170	   for heaptypes. */
2171	assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2172
2173#define CLEAR(SLOT) \
2174	if (SLOT) { \
2175		tmp = (PyObject *)(SLOT); \
2176		SLOT = NULL; \
2177		Py_DECREF(tmp); \
2178	}
2179
2180	/* The only field we need to clear is tp_mro, which is part of a
2181	   hard cycle (its first element is the class itself) that won't
2182	   be broken otherwise (it's a tuple and tuples don't have a
2183	   tp_clear handler).  None of the other fields need to be
2184	   cleared, and here's why:
2185
2186	   tp_dict:
2187	       It is a dict, so the collector will call its tp_clear.
2188
2189	   tp_cache:
2190	       Not used; if it were, it would be a dict.
2191
2192	   tp_bases, tp_base:
2193	       If these are involved in a cycle, there must be at least
2194	       one other, mutable object in the cycle, e.g. a base
2195	       class's dict; the cycle will be broken that way.
2196
2197	   tp_subclasses:
2198	       A list of weak references can't be part of a cycle; and
2199	       lists have their own tp_clear.
2200
2201	   slots (in PyHeapTypeObject):
2202	       A tuple of strings can't be part of a cycle.
2203	*/
2204
2205	CLEAR(type->tp_mro);
2206
2207#undef CLEAR
2208
2209	return 0;
2210}
2211
2212static int
2213type_is_gc(PyTypeObject *type)
2214{
2215	return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2216}
2217
2218PyTypeObject PyType_Type = {
2219	PyObject_HEAD_INIT(&PyType_Type)
2220	0,					/* ob_size */
2221	"type",					/* tp_name */
2222	sizeof(PyHeapTypeObject),		/* tp_basicsize */
2223	sizeof(PyMemberDef),			/* tp_itemsize */
2224	(destructor)type_dealloc,		/* tp_dealloc */
2225	0,					/* tp_print */
2226	0,			 		/* tp_getattr */
2227	0,					/* tp_setattr */
2228	type_compare,				/* tp_compare */
2229	(reprfunc)type_repr,			/* tp_repr */
2230	0,					/* tp_as_number */
2231	0,					/* tp_as_sequence */
2232	0,					/* tp_as_mapping */
2233	(hashfunc)_Py_HashPointer,		/* tp_hash */
2234	(ternaryfunc)type_call,			/* tp_call */
2235	0,					/* tp_str */
2236	(getattrofunc)type_getattro,		/* tp_getattro */
2237	(setattrofunc)type_setattro,		/* tp_setattro */
2238	0,					/* tp_as_buffer */
2239	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2240		Py_TPFLAGS_BASETYPE,		/* tp_flags */
2241	type_doc,				/* tp_doc */
2242	(traverseproc)type_traverse,		/* tp_traverse */
2243	(inquiry)type_clear,			/* tp_clear */
2244	0,					/* tp_richcompare */
2245	offsetof(PyTypeObject, tp_weaklist),	/* tp_weaklistoffset */
2246	0,					/* tp_iter */
2247	0,					/* tp_iternext */
2248	type_methods,				/* tp_methods */
2249	type_members,				/* tp_members */
2250	type_getsets,				/* tp_getset */
2251	0,					/* tp_base */
2252	0,					/* tp_dict */
2253	0,					/* tp_descr_get */
2254	0,					/* tp_descr_set */
2255	offsetof(PyTypeObject, tp_dict),	/* tp_dictoffset */
2256	0,					/* tp_init */
2257	0,					/* tp_alloc */
2258	type_new,				/* tp_new */
2259	PyObject_GC_Del,        		/* tp_free */
2260	(inquiry)type_is_gc,			/* tp_is_gc */
2261};
2262
2263
2264/* The base type of all types (eventually)... except itself. */
2265
2266static int
2267object_init(PyObject *self, PyObject *args, PyObject *kwds)
2268{
2269	return 0;
2270}
2271
2272/* If we don't have a tp_new for a new-style class, new will use this one.
2273   Therefore this should take no arguments/keywords.  However, this new may
2274   also be inherited by objects that define a tp_init but no tp_new.  These
2275   objects WILL pass argumets to tp_new, because it gets the same args as
2276   tp_init.  So only allow arguments if we aren't using the default init, in
2277   which case we expect init to handle argument parsing. */
2278static PyObject *
2279object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2280{
2281	if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2282	     (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2283		PyErr_SetString(PyExc_TypeError,
2284				"default __new__ takes no parameters");
2285		return NULL;
2286	}
2287	return type->tp_alloc(type, 0);
2288}
2289
2290static void
2291object_dealloc(PyObject *self)
2292{
2293	self->ob_type->tp_free(self);
2294}
2295
2296static PyObject *
2297object_repr(PyObject *self)
2298{
2299	PyTypeObject *type;
2300	PyObject *mod, *name, *rtn;
2301
2302	type = self->ob_type;
2303	mod = type_module(type, NULL);
2304	if (mod == NULL)
2305		PyErr_Clear();
2306	else if (!PyString_Check(mod)) {
2307		Py_DECREF(mod);
2308		mod = NULL;
2309	}
2310	name = type_name(type, NULL);
2311	if (name == NULL)
2312		return NULL;
2313	if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
2314		rtn = PyString_FromFormat("<%s.%s object at %p>",
2315					  PyString_AS_STRING(mod),
2316					  PyString_AS_STRING(name),
2317					  self);
2318	else
2319		rtn = PyString_FromFormat("<%s object at %p>",
2320					  type->tp_name, self);
2321	Py_XDECREF(mod);
2322	Py_DECREF(name);
2323	return rtn;
2324}
2325
2326static PyObject *
2327object_str(PyObject *self)
2328{
2329	unaryfunc f;
2330
2331	f = self->ob_type->tp_repr;
2332	if (f == NULL)
2333		f = object_repr;
2334	return f(self);
2335}
2336
2337static long
2338object_hash(PyObject *self)
2339{
2340	return _Py_HashPointer(self);
2341}
2342
2343static PyObject *
2344object_get_class(PyObject *self, void *closure)
2345{
2346	Py_INCREF(self->ob_type);
2347	return (PyObject *)(self->ob_type);
2348}
2349
2350static int
2351equiv_structs(PyTypeObject *a, PyTypeObject *b)
2352{
2353	return a == b ||
2354	       (a != NULL &&
2355		b != NULL &&
2356		a->tp_basicsize == b->tp_basicsize &&
2357		a->tp_itemsize == b->tp_itemsize &&
2358		a->tp_dictoffset == b->tp_dictoffset &&
2359		a->tp_weaklistoffset == b->tp_weaklistoffset &&
2360		((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2361		 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2362}
2363
2364static int
2365same_slots_added(PyTypeObject *a, PyTypeObject *b)
2366{
2367	PyTypeObject *base = a->tp_base;
2368	int size;
2369
2370	if (base != b->tp_base)
2371		return 0;
2372	if (equiv_structs(a, base) && equiv_structs(b, base))
2373		return 1;
2374	size = base->tp_basicsize;
2375	if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2376		size += sizeof(PyObject *);
2377	if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2378		size += sizeof(PyObject *);
2379	return size == a->tp_basicsize && size == b->tp_basicsize;
2380}
2381
2382static int
2383compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2384{
2385	PyTypeObject *newbase, *oldbase;
2386
2387	if (new->tp_dealloc != old->tp_dealloc ||
2388	    new->tp_free != old->tp_free)
2389	{
2390		PyErr_Format(PyExc_TypeError,
2391			     "%s assignment: "
2392			     "'%s' deallocator differs from '%s'",
2393			     attr,
2394			     new->tp_name,
2395			     old->tp_name);
2396		return 0;
2397	}
2398	newbase = new;
2399	oldbase = old;
2400	while (equiv_structs(newbase, newbase->tp_base))
2401		newbase = newbase->tp_base;
2402	while (equiv_structs(oldbase, oldbase->tp_base))
2403		oldbase = oldbase->tp_base;
2404	if (newbase != oldbase &&
2405	    (newbase->tp_base != oldbase->tp_base ||
2406	     !same_slots_added(newbase, oldbase))) {
2407		PyErr_Format(PyExc_TypeError,
2408			     "%s assignment: "
2409			     "'%s' object layout differs from '%s'",
2410			     attr,
2411			     new->tp_name,
2412			     old->tp_name);
2413		return 0;
2414	}
2415
2416	return 1;
2417}
2418
2419static int
2420object_set_class(PyObject *self, PyObject *value, void *closure)
2421{
2422	PyTypeObject *old = self->ob_type;
2423	PyTypeObject *new;
2424
2425	if (value == NULL) {
2426		PyErr_SetString(PyExc_TypeError,
2427				"can't delete __class__ attribute");
2428		return -1;
2429	}
2430	if (!PyType_Check(value)) {
2431		PyErr_Format(PyExc_TypeError,
2432		  "__class__ must be set to new-style class, not '%s' object",
2433		  value->ob_type->tp_name);
2434		return -1;
2435	}
2436	new = (PyTypeObject *)value;
2437	if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2438	    !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2439	{
2440		PyErr_Format(PyExc_TypeError,
2441			     "__class__ assignment: only for heap types");
2442		return -1;
2443	}
2444	if (compatible_for_assignment(new, old, "__class__")) {
2445		Py_INCREF(new);
2446		self->ob_type = new;
2447		Py_DECREF(old);
2448		return 0;
2449	}
2450	else {
2451		return -1;
2452	}
2453}
2454
2455static PyGetSetDef object_getsets[] = {
2456	{"__class__", object_get_class, object_set_class,
2457	 PyDoc_STR("the object's class")},
2458	{0}
2459};
2460
2461
2462/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2463   We fall back to helpers in copy_reg for:
2464   - pickle protocols < 2
2465   - calculating the list of slot names (done only once per class)
2466   - the __newobj__ function (which is used as a token but never called)
2467*/
2468
2469static PyObject *
2470import_copy_reg(void)
2471{
2472	static PyObject *copy_reg_str;
2473
2474	if (!copy_reg_str) {
2475		copy_reg_str = PyString_InternFromString("copy_reg");
2476		if (copy_reg_str == NULL)
2477			return NULL;
2478	}
2479
2480	return PyImport_Import(copy_reg_str);
2481}
2482
2483static PyObject *
2484slotnames(PyObject *cls)
2485{
2486	PyObject *clsdict;
2487	PyObject *copy_reg;
2488	PyObject *slotnames;
2489
2490	if (!PyType_Check(cls)) {
2491		Py_INCREF(Py_None);
2492		return Py_None;
2493	}
2494
2495	clsdict = ((PyTypeObject *)cls)->tp_dict;
2496	slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2497	if (slotnames != NULL) {
2498		Py_INCREF(slotnames);
2499		return slotnames;
2500	}
2501
2502	copy_reg = import_copy_reg();
2503	if (copy_reg == NULL)
2504		return NULL;
2505
2506	slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2507	Py_DECREF(copy_reg);
2508	if (slotnames != NULL &&
2509	    slotnames != Py_None &&
2510	    !PyList_Check(slotnames))
2511	{
2512		PyErr_SetString(PyExc_TypeError,
2513			"copy_reg._slotnames didn't return a list or None");
2514		Py_DECREF(slotnames);
2515		slotnames = NULL;
2516	}
2517
2518	return slotnames;
2519}
2520
2521static PyObject *
2522reduce_2(PyObject *obj)
2523{
2524	PyObject *cls, *getnewargs;
2525	PyObject *args = NULL, *args2 = NULL;
2526	PyObject *getstate = NULL, *state = NULL, *names = NULL;
2527	PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2528	PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2529	int i, n;
2530
2531	cls = PyObject_GetAttrString(obj, "__class__");
2532	if (cls == NULL)
2533		return NULL;
2534
2535	getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2536	if (getnewargs != NULL) {
2537		args = PyObject_CallObject(getnewargs, NULL);
2538		Py_DECREF(getnewargs);
2539		if (args != NULL && !PyTuple_Check(args)) {
2540			PyErr_SetString(PyExc_TypeError,
2541				"__getnewargs__ should return a tuple");
2542			goto end;
2543		}
2544	}
2545	else {
2546		PyErr_Clear();
2547		args = PyTuple_New(0);
2548	}
2549	if (args == NULL)
2550		goto end;
2551
2552	getstate = PyObject_GetAttrString(obj, "__getstate__");
2553	if (getstate != NULL) {
2554		state = PyObject_CallObject(getstate, NULL);
2555		Py_DECREF(getstate);
2556		if (state == NULL)
2557			goto end;
2558	}
2559	else {
2560		state = PyObject_GetAttrString(obj, "__dict__");
2561		if (state == NULL) {
2562			PyErr_Clear();
2563			state = Py_None;
2564			Py_INCREF(state);
2565		}
2566		names = slotnames(cls);
2567		if (names == NULL)
2568			goto end;
2569		if (names != Py_None) {
2570			assert(PyList_Check(names));
2571			slots = PyDict_New();
2572			if (slots == NULL)
2573				goto end;
2574			n = 0;
2575			/* Can't pre-compute the list size; the list
2576			   is stored on the class so accessible to other
2577			   threads, which may be run by DECREF */
2578			for (i = 0; i < PyList_GET_SIZE(names); i++) {
2579				PyObject *name, *value;
2580				name = PyList_GET_ITEM(names, i);
2581				value = PyObject_GetAttr(obj, name);
2582				if (value == NULL)
2583					PyErr_Clear();
2584				else {
2585					int err = PyDict_SetItem(slots, name,
2586								 value);
2587					Py_DECREF(value);
2588					if (err)
2589						goto end;
2590					n++;
2591				}
2592			}
2593			if (n) {
2594				state = Py_BuildValue("(NO)", state, slots);
2595				if (state == NULL)
2596					goto end;
2597			}
2598		}
2599	}
2600
2601	if (!PyList_Check(obj)) {
2602		listitems = Py_None;
2603		Py_INCREF(listitems);
2604	}
2605	else {
2606		listitems = PyObject_GetIter(obj);
2607		if (listitems == NULL)
2608			goto end;
2609	}
2610
2611	if (!PyDict_Check(obj)) {
2612		dictitems = Py_None;
2613		Py_INCREF(dictitems);
2614	}
2615	else {
2616		dictitems = PyObject_CallMethod(obj, "iteritems", "");
2617		if (dictitems == NULL)
2618			goto end;
2619	}
2620
2621	copy_reg = import_copy_reg();
2622	if (copy_reg == NULL)
2623		goto end;
2624	newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2625	if (newobj == NULL)
2626		goto end;
2627
2628	n = PyTuple_GET_SIZE(args);
2629	args2 = PyTuple_New(n+1);
2630	if (args2 == NULL)
2631		goto end;
2632	PyTuple_SET_ITEM(args2, 0, cls);
2633	cls = NULL;
2634	for (i = 0; i < n; i++) {
2635		PyObject *v = PyTuple_GET_ITEM(args, i);
2636		Py_INCREF(v);
2637		PyTuple_SET_ITEM(args2, i+1, v);
2638	}
2639
2640	res = Py_BuildValue("(OOOOO)",
2641			    newobj, args2, state, listitems, dictitems);
2642
2643  end:
2644	Py_XDECREF(cls);
2645	Py_XDECREF(args);
2646	Py_XDECREF(args2);
2647	Py_XDECREF(slots);
2648	Py_XDECREF(state);
2649	Py_XDECREF(names);
2650	Py_XDECREF(listitems);
2651	Py_XDECREF(dictitems);
2652	Py_XDECREF(copy_reg);
2653	Py_XDECREF(newobj);
2654	return res;
2655}
2656
2657static PyObject *
2658object_reduce_ex(PyObject *self, PyObject *args)
2659{
2660	/* Call copy_reg._reduce_ex(self, proto) */
2661	PyObject *reduce, *copy_reg, *res;
2662	int proto = 0;
2663
2664	if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2665		return NULL;
2666
2667	reduce = PyObject_GetAttrString(self, "__reduce__");
2668	if (reduce == NULL)
2669		PyErr_Clear();
2670	else {
2671		PyObject *cls, *clsreduce, *objreduce;
2672		int override;
2673		cls = PyObject_GetAttrString(self, "__class__");
2674		if (cls == NULL) {
2675			Py_DECREF(reduce);
2676			return NULL;
2677		}
2678		clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2679		Py_DECREF(cls);
2680		if (clsreduce == NULL) {
2681			Py_DECREF(reduce);
2682			return NULL;
2683		}
2684		objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2685						 "__reduce__");
2686		override = (clsreduce != objreduce);
2687		Py_DECREF(clsreduce);
2688		if (override) {
2689			res = PyObject_CallObject(reduce, NULL);
2690			Py_DECREF(reduce);
2691			return res;
2692		}
2693		else
2694			Py_DECREF(reduce);
2695	}
2696
2697	if (proto >= 2)
2698		return reduce_2(self);
2699
2700	copy_reg = import_copy_reg();
2701	if (!copy_reg)
2702		return NULL;
2703
2704	res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
2705	Py_DECREF(copy_reg);
2706
2707	return res;
2708}
2709
2710static PyMethodDef object_methods[] = {
2711	{"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2712	 PyDoc_STR("helper for pickle")},
2713	{"__reduce__", object_reduce_ex, METH_VARARGS,
2714	 PyDoc_STR("helper for pickle")},
2715	{0}
2716};
2717
2718
2719PyTypeObject PyBaseObject_Type = {
2720	PyObject_HEAD_INIT(&PyType_Type)
2721 	0,					/* ob_size */
2722	"object",				/* tp_name */
2723	sizeof(PyObject),			/* tp_basicsize */
2724	0,					/* tp_itemsize */
2725	(destructor)object_dealloc,		/* tp_dealloc */
2726	0,					/* tp_print */
2727	0,			 		/* tp_getattr */
2728	0,					/* tp_setattr */
2729	0,					/* tp_compare */
2730	object_repr,				/* tp_repr */
2731	0,					/* tp_as_number */
2732	0,					/* tp_as_sequence */
2733	0,					/* tp_as_mapping */
2734	object_hash,				/* tp_hash */
2735	0,					/* tp_call */
2736	object_str,				/* tp_str */
2737	PyObject_GenericGetAttr,		/* tp_getattro */
2738	PyObject_GenericSetAttr,		/* tp_setattro */
2739	0,					/* tp_as_buffer */
2740	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2741	PyDoc_STR("The most base type"),	/* tp_doc */
2742	0,					/* tp_traverse */
2743	0,					/* tp_clear */
2744	0,					/* tp_richcompare */
2745	0,					/* tp_weaklistoffset */
2746	0,					/* tp_iter */
2747	0,					/* tp_iternext */
2748	object_methods,				/* tp_methods */
2749	0,					/* tp_members */
2750	object_getsets,				/* tp_getset */
2751	0,					/* tp_base */
2752	0,					/* tp_dict */
2753	0,					/* tp_descr_get */
2754	0,					/* tp_descr_set */
2755	0,					/* tp_dictoffset */
2756	object_init,				/* tp_init */
2757	PyType_GenericAlloc,			/* tp_alloc */
2758	object_new,				/* tp_new */
2759	PyObject_Del,           		/* tp_free */
2760};
2761
2762
2763/* Initialize the __dict__ in a type object */
2764
2765static int
2766add_methods(PyTypeObject *type, PyMethodDef *meth)
2767{
2768	PyObject *dict = type->tp_dict;
2769
2770	for (; meth->ml_name != NULL; meth++) {
2771		PyObject *descr;
2772		if (PyDict_GetItemString(dict, meth->ml_name))
2773			continue;
2774		if (meth->ml_flags & METH_CLASS) {
2775			if (meth->ml_flags & METH_STATIC) {
2776				PyErr_SetString(PyExc_ValueError,
2777				     "method cannot be both class and static");
2778				return -1;
2779			}
2780			descr = PyDescr_NewClassMethod(type, meth);
2781		}
2782		else if (meth->ml_flags & METH_STATIC) {
2783			PyObject *cfunc = PyCFunction_New(meth, NULL);
2784			if (cfunc == NULL)
2785				return -1;
2786			descr = PyStaticMethod_New(cfunc);
2787			Py_DECREF(cfunc);
2788		}
2789		else {
2790			descr = PyDescr_NewMethod(type, meth);
2791		}
2792		if (descr == NULL)
2793			return -1;
2794		if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
2795			return -1;
2796		Py_DECREF(descr);
2797	}
2798	return 0;
2799}
2800
2801static int
2802add_members(PyTypeObject *type, PyMemberDef *memb)
2803{
2804	PyObject *dict = type->tp_dict;
2805
2806	for (; memb->name != NULL; memb++) {
2807		PyObject *descr;
2808		if (PyDict_GetItemString(dict, memb->name))
2809			continue;
2810		descr = PyDescr_NewMember(type, memb);
2811		if (descr == NULL)
2812			return -1;
2813		if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2814			return -1;
2815		Py_DECREF(descr);
2816	}
2817	return 0;
2818}
2819
2820static int
2821add_getset(PyTypeObject *type, PyGetSetDef *gsp)
2822{
2823	PyObject *dict = type->tp_dict;
2824
2825	for (; gsp->name != NULL; gsp++) {
2826		PyObject *descr;
2827		if (PyDict_GetItemString(dict, gsp->name))
2828			continue;
2829		descr = PyDescr_NewGetSet(type, gsp);
2830
2831		if (descr == NULL)
2832			return -1;
2833		if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2834			return -1;
2835		Py_DECREF(descr);
2836	}
2837	return 0;
2838}
2839
2840static void
2841inherit_special(PyTypeObject *type, PyTypeObject *base)
2842{
2843	int oldsize, newsize;
2844
2845	/* Special flag magic */
2846	if (!type->tp_as_buffer && base->tp_as_buffer) {
2847		type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2848		type->tp_flags |=
2849			base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2850	}
2851	if (!type->tp_as_sequence && base->tp_as_sequence) {
2852		type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2853		type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2854	}
2855	if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2856	    (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2857		if ((!type->tp_as_number && base->tp_as_number) ||
2858		    (!type->tp_as_sequence && base->tp_as_sequence)) {
2859			type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2860			if (!type->tp_as_number && !type->tp_as_sequence) {
2861				type->tp_flags |= base->tp_flags &
2862					Py_TPFLAGS_HAVE_INPLACEOPS;
2863			}
2864		}
2865		/* Wow */
2866	}
2867	if (!type->tp_as_number && base->tp_as_number) {
2868		type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2869		type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2870	}
2871
2872	/* Copying basicsize is connected to the GC flags */
2873	oldsize = base->tp_basicsize;
2874	newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2875	if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2876	    (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2877	    (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2878	    (!type->tp_traverse && !type->tp_clear)) {
2879		type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2880		if (type->tp_traverse == NULL)
2881			type->tp_traverse = base->tp_traverse;
2882		if (type->tp_clear == NULL)
2883			type->tp_clear = base->tp_clear;
2884	}
2885	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2886		/* The condition below could use some explanation.
2887		   It appears that tp_new is not inherited for static types
2888		   whose base class is 'object'; this seems to be a precaution
2889		   so that old extension types don't suddenly become
2890		   callable (object.__new__ wouldn't insure the invariants
2891		   that the extension type's own factory function ensures).
2892		   Heap types, of course, are under our control, so they do
2893		   inherit tp_new; static extension types that specify some
2894		   other built-in type as the default are considered
2895		   new-style-aware so they also inherit object.__new__. */
2896		if (base != &PyBaseObject_Type ||
2897		    (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2898			if (type->tp_new == NULL)
2899				type->tp_new = base->tp_new;
2900		}
2901	}
2902	type->tp_basicsize = newsize;
2903
2904	/* Copy other non-function slots */
2905
2906#undef COPYVAL
2907#define COPYVAL(SLOT) \
2908	if (type->SLOT == 0) type->SLOT = base->SLOT
2909
2910	COPYVAL(tp_itemsize);
2911	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2912		COPYVAL(tp_weaklistoffset);
2913	}
2914	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2915		COPYVAL(tp_dictoffset);
2916	}
2917}
2918
2919static void
2920inherit_slots(PyTypeObject *type, PyTypeObject *base)
2921{
2922	PyTypeObject *basebase;
2923
2924#undef SLOTDEFINED
2925#undef COPYSLOT
2926#undef COPYNUM
2927#undef COPYSEQ
2928#undef COPYMAP
2929#undef COPYBUF
2930
2931#define SLOTDEFINED(SLOT) \
2932	(base->SLOT != 0 && \
2933	 (basebase == NULL || base->SLOT != basebase->SLOT))
2934
2935#define COPYSLOT(SLOT) \
2936	if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
2937
2938#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2939#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2940#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
2941#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
2942
2943	/* This won't inherit indirect slots (from tp_as_number etc.)
2944	   if type doesn't provide the space. */
2945
2946	if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2947		basebase = base->tp_base;
2948		if (basebase->tp_as_number == NULL)
2949			basebase = NULL;
2950		COPYNUM(nb_add);
2951		COPYNUM(nb_subtract);
2952		COPYNUM(nb_multiply);
2953		COPYNUM(nb_divide);
2954		COPYNUM(nb_remainder);
2955		COPYNUM(nb_divmod);
2956		COPYNUM(nb_power);
2957		COPYNUM(nb_negative);
2958		COPYNUM(nb_positive);
2959		COPYNUM(nb_absolute);
2960		COPYNUM(nb_nonzero);
2961		COPYNUM(nb_invert);
2962		COPYNUM(nb_lshift);
2963		COPYNUM(nb_rshift);
2964		COPYNUM(nb_and);
2965		COPYNUM(nb_xor);
2966		COPYNUM(nb_or);
2967		COPYNUM(nb_coerce);
2968		COPYNUM(nb_int);
2969		COPYNUM(nb_long);
2970		COPYNUM(nb_float);
2971		COPYNUM(nb_oct);
2972		COPYNUM(nb_hex);
2973		COPYNUM(nb_inplace_add);
2974		COPYNUM(nb_inplace_subtract);
2975		COPYNUM(nb_inplace_multiply);
2976		COPYNUM(nb_inplace_divide);
2977		COPYNUM(nb_inplace_remainder);
2978		COPYNUM(nb_inplace_power);
2979		COPYNUM(nb_inplace_lshift);
2980		COPYNUM(nb_inplace_rshift);
2981		COPYNUM(nb_inplace_and);
2982		COPYNUM(nb_inplace_xor);
2983		COPYNUM(nb_inplace_or);
2984		if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2985			COPYNUM(nb_true_divide);
2986			COPYNUM(nb_floor_divide);
2987			COPYNUM(nb_inplace_true_divide);
2988			COPYNUM(nb_inplace_floor_divide);
2989		}
2990	}
2991
2992	if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2993		basebase = base->tp_base;
2994		if (basebase->tp_as_sequence == NULL)
2995			basebase = NULL;
2996		COPYSEQ(sq_length);
2997		COPYSEQ(sq_concat);
2998		COPYSEQ(sq_repeat);
2999		COPYSEQ(sq_item);
3000		COPYSEQ(sq_slice);
3001		COPYSEQ(sq_ass_item);
3002		COPYSEQ(sq_ass_slice);
3003		COPYSEQ(sq_contains);
3004		COPYSEQ(sq_inplace_concat);
3005		COPYSEQ(sq_inplace_repeat);
3006	}
3007
3008	if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3009		basebase = base->tp_base;
3010		if (basebase->tp_as_mapping == NULL)
3011			basebase = NULL;
3012		COPYMAP(mp_length);
3013		COPYMAP(mp_subscript);
3014		COPYMAP(mp_ass_subscript);
3015	}
3016
3017	if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3018		basebase = base->tp_base;
3019		if (basebase->tp_as_buffer == NULL)
3020			basebase = NULL;
3021		COPYBUF(bf_getreadbuffer);
3022		COPYBUF(bf_getwritebuffer);
3023		COPYBUF(bf_getsegcount);
3024		COPYBUF(bf_getcharbuffer);
3025	}
3026
3027	basebase = base->tp_base;
3028
3029	COPYSLOT(tp_dealloc);
3030	COPYSLOT(tp_print);
3031	if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3032		type->tp_getattr = base->tp_getattr;
3033		type->tp_getattro = base->tp_getattro;
3034	}
3035	if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3036		type->tp_setattr = base->tp_setattr;
3037		type->tp_setattro = base->tp_setattro;
3038	}
3039	/* tp_compare see tp_richcompare */
3040	COPYSLOT(tp_repr);
3041	/* tp_hash see tp_richcompare */
3042	COPYSLOT(tp_call);
3043	COPYSLOT(tp_str);
3044	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
3045		if (type->tp_compare == NULL &&
3046		    type->tp_richcompare == NULL &&
3047		    type->tp_hash == NULL)
3048		{
3049			type->tp_compare = base->tp_compare;
3050			type->tp_richcompare = base->tp_richcompare;
3051			type->tp_hash = base->tp_hash;
3052		}
3053	}
3054	else {
3055		COPYSLOT(tp_compare);
3056	}
3057	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3058		COPYSLOT(tp_iter);
3059		COPYSLOT(tp_iternext);
3060	}
3061	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3062		COPYSLOT(tp_descr_get);
3063		COPYSLOT(tp_descr_set);
3064		COPYSLOT(tp_dictoffset);
3065		COPYSLOT(tp_init);
3066		COPYSLOT(tp_alloc);
3067		COPYSLOT(tp_is_gc);
3068		if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3069		    (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3070			/* They agree about gc. */
3071			COPYSLOT(tp_free);
3072		}
3073		else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3074			 type->tp_free == NULL &&
3075			 base->tp_free == _PyObject_Del) {
3076			/* A bit of magic to plug in the correct default
3077			 * tp_free function when a derived class adds gc,
3078			 * didn't define tp_free, and the base uses the
3079			 * default non-gc tp_free.
3080			 */
3081			type->tp_free = PyObject_GC_Del;
3082		}
3083		/* else they didn't agree about gc, and there isn't something
3084		 * obvious to be done -- the type is on its own.
3085		 */
3086	}
3087}
3088
3089static int add_operators(PyTypeObject *);
3090
3091int
3092PyType_Ready(PyTypeObject *type)
3093{
3094	PyObject *dict, *bases;
3095	PyTypeObject *base;
3096	int i, n;
3097
3098	if (type->tp_flags & Py_TPFLAGS_READY) {
3099		assert(type->tp_dict != NULL);
3100		return 0;
3101	}
3102	assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
3103
3104	type->tp_flags |= Py_TPFLAGS_READYING;
3105
3106#ifdef Py_TRACE_REFS
3107	/* PyType_Ready is the closest thing we have to a choke point
3108	 * for type objects, so is the best place I can think of to try
3109	 * to get type objects into the doubly-linked list of all objects.
3110	 * Still, not all type objects go thru PyType_Ready.
3111	 */
3112	_Py_AddToAllObjects((PyObject *)type, 0);
3113#endif
3114
3115	/* Initialize tp_base (defaults to BaseObject unless that's us) */
3116	base = type->tp_base;
3117	if (base == NULL && type != &PyBaseObject_Type)
3118		base = type->tp_base = &PyBaseObject_Type;
3119
3120	/* Initialize the base class */
3121	if (base && base->tp_dict == NULL) {
3122		if (PyType_Ready(base) < 0)
3123			goto error;
3124	}
3125
3126	/* Initialize ob_type if NULL.  This means extensions that want to be
3127	   compilable separately on Windows can call PyType_Ready() instead of
3128	   initializing the ob_type field of their type objects. */
3129	if (type->ob_type == NULL)
3130		type->ob_type = base->ob_type;
3131
3132	/* Initialize tp_bases */
3133	bases = type->tp_bases;
3134	if (bases == NULL) {
3135		if (base == NULL)
3136			bases = PyTuple_New(0);
3137		else
3138			bases = Py_BuildValue("(O)", base);
3139		if (bases == NULL)
3140			goto error;
3141		type->tp_bases = bases;
3142	}
3143
3144	/* Initialize tp_dict */
3145	dict = type->tp_dict;
3146	if (dict == NULL) {
3147		dict = PyDict_New();
3148		if (dict == NULL)
3149			goto error;
3150		type->tp_dict = dict;
3151	}
3152
3153	/* Add type-specific descriptors to tp_dict */
3154	if (add_operators(type) < 0)
3155		goto error;
3156	if (type->tp_methods != NULL) {
3157		if (add_methods(type, type->tp_methods) < 0)
3158			goto error;
3159	}
3160	if (type->tp_members != NULL) {
3161		if (add_members(type, type->tp_members) < 0)
3162			goto error;
3163	}
3164	if (type->tp_getset != NULL) {
3165		if (add_getset(type, type->tp_getset) < 0)
3166			goto error;
3167	}
3168
3169	/* Calculate method resolution order */
3170	if (mro_internal(type) < 0) {
3171		goto error;
3172	}
3173
3174	/* Inherit special flags from dominant base */
3175	if (type->tp_base != NULL)
3176		inherit_special(type, type->tp_base);
3177
3178	/* Initialize tp_dict properly */
3179	bases = type->tp_mro;
3180	assert(bases != NULL);
3181	assert(PyTuple_Check(bases));
3182	n = PyTuple_GET_SIZE(bases);
3183	for (i = 1; i < n; i++) {
3184		PyObject *b = PyTuple_GET_ITEM(bases, i);
3185		if (PyType_Check(b))
3186			inherit_slots(type, (PyTypeObject *)b);
3187	}
3188
3189	/* Sanity check for tp_free. */
3190	if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3191	    (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3192	    	/* This base class needs to call tp_free, but doesn't have
3193	    	 * one, or its tp_free is for non-gc'ed objects.
3194	    	 */
3195		PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3196			     "gc and is a base type but has inappropriate "
3197			     "tp_free slot",
3198			     type->tp_name);
3199		goto error;
3200	}
3201
3202	/* if the type dictionary doesn't contain a __doc__, set it from
3203	   the tp_doc slot.
3204	 */
3205	if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3206		if (type->tp_doc != NULL) {
3207			PyObject *doc = PyString_FromString(type->tp_doc);
3208			PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3209			Py_DECREF(doc);
3210		} else {
3211			PyDict_SetItemString(type->tp_dict,
3212					     "__doc__", Py_None);
3213		}
3214	}
3215
3216	/* Some more special stuff */
3217	base = type->tp_base;
3218	if (base != NULL) {
3219		if (type->tp_as_number == NULL)
3220			type->tp_as_number = base->tp_as_number;
3221		if (type->tp_as_sequence == NULL)
3222			type->tp_as_sequence = base->tp_as_sequence;
3223		if (type->tp_as_mapping == NULL)
3224			type->tp_as_mapping = base->tp_as_mapping;
3225		if (type->tp_as_buffer == NULL)
3226			type->tp_as_buffer = base->tp_as_buffer;
3227	}
3228
3229	/* Link into each base class's list of subclasses */
3230	bases = type->tp_bases;
3231	n = PyTuple_GET_SIZE(bases);
3232	for (i = 0; i < n; i++) {
3233		PyObject *b = PyTuple_GET_ITEM(bases, i);
3234		if (PyType_Check(b) &&
3235		    add_subclass((PyTypeObject *)b, type) < 0)
3236			goto error;
3237	}
3238
3239	/* All done -- set the ready flag */
3240	assert(type->tp_dict != NULL);
3241	type->tp_flags =
3242		(type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
3243	return 0;
3244
3245  error:
3246	type->tp_flags &= ~Py_TPFLAGS_READYING;
3247	return -1;
3248}
3249
3250static int
3251add_subclass(PyTypeObject *base, PyTypeObject *type)
3252{
3253	int i;
3254	PyObject *list, *ref, *new;
3255
3256	list = base->tp_subclasses;
3257	if (list == NULL) {
3258		base->tp_subclasses = list = PyList_New(0);
3259		if (list == NULL)
3260			return -1;
3261	}
3262	assert(PyList_Check(list));
3263	new = PyWeakref_NewRef((PyObject *)type, NULL);
3264	i = PyList_GET_SIZE(list);
3265	while (--i >= 0) {
3266		ref = PyList_GET_ITEM(list, i);
3267		assert(PyWeakref_CheckRef(ref));
3268		if (PyWeakref_GET_OBJECT(ref) == Py_None)
3269			return PyList_SetItem(list, i, new);
3270	}
3271	i = PyList_Append(list, new);
3272	Py_DECREF(new);
3273	return i;
3274}
3275
3276static void
3277remove_subclass(PyTypeObject *base, PyTypeObject *type)
3278{
3279	int i;
3280	PyObject *list, *ref;
3281
3282	list = base->tp_subclasses;
3283	if (list == NULL) {
3284		return;
3285	}
3286	assert(PyList_Check(list));
3287	i = PyList_GET_SIZE(list);
3288	while (--i >= 0) {
3289		ref = PyList_GET_ITEM(list, i);
3290		assert(PyWeakref_CheckRef(ref));
3291		if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3292			/* this can't fail, right? */
3293			PySequence_DelItem(list, i);
3294			return;
3295		}
3296	}
3297}
3298
3299/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3300
3301/* There's a wrapper *function* for each distinct function typedef used
3302   for type object slots (e.g. binaryfunc, ternaryfunc, etc.).  There's a
3303   wrapper *table* for each distinct operation (e.g. __len__, __add__).
3304   Most tables have only one entry; the tables for binary operators have two
3305   entries, one regular and one with reversed arguments. */
3306
3307static PyObject *
3308wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3309{
3310	inquiry func = (inquiry)wrapped;
3311	int res;
3312
3313	if (!PyArg_ParseTuple(args, ""))
3314		return NULL;
3315	res = (*func)(self);
3316	if (res == -1 && PyErr_Occurred())
3317		return NULL;
3318	return PyInt_FromLong((long)res);
3319}
3320
3321static PyObject *
3322wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3323{
3324	binaryfunc func = (binaryfunc)wrapped;
3325	PyObject *other;
3326
3327	if (!PyArg_ParseTuple(args, "O", &other))
3328		return NULL;
3329	return (*func)(self, other);
3330}
3331
3332static PyObject *
3333wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3334{
3335	binaryfunc func = (binaryfunc)wrapped;
3336	PyObject *other;
3337
3338	if (!PyArg_ParseTuple(args, "O", &other))
3339		return NULL;
3340	if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
3341	    !PyType_IsSubtype(other->ob_type, self->ob_type)) {
3342		Py_INCREF(Py_NotImplemented);
3343		return Py_NotImplemented;
3344	}
3345	return (*func)(self, other);
3346}
3347
3348static PyObject *
3349wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3350{
3351	binaryfunc func = (binaryfunc)wrapped;
3352	PyObject *other;
3353
3354	if (!PyArg_ParseTuple(args, "O", &other))
3355		return NULL;
3356	if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
3357	    !PyType_IsSubtype(other->ob_type, self->ob_type)) {
3358		Py_INCREF(Py_NotImplemented);
3359		return Py_NotImplemented;
3360	}
3361	return (*func)(other, self);
3362}
3363
3364static PyObject *
3365wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3366{
3367	coercion func = (coercion)wrapped;
3368	PyObject *other, *res;
3369	int ok;
3370
3371	if (!PyArg_ParseTuple(args, "O", &other))
3372		return NULL;
3373	ok = func(&self, &other);
3374	if (ok < 0)
3375		return NULL;
3376	if (ok > 0) {
3377		Py_INCREF(Py_NotImplemented);
3378		return Py_NotImplemented;
3379	}
3380	res = PyTuple_New(2);
3381	if (res == NULL) {
3382		Py_DECREF(self);
3383		Py_DECREF(other);
3384		return NULL;
3385	}
3386	PyTuple_SET_ITEM(res, 0, self);
3387	PyTuple_SET_ITEM(res, 1, other);
3388	return res;
3389}
3390
3391static PyObject *
3392wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3393{
3394	ternaryfunc func = (ternaryfunc)wrapped;
3395	PyObject *other;
3396	PyObject *third = Py_None;
3397
3398	/* Note: This wrapper only works for __pow__() */
3399
3400	if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3401		return NULL;
3402	return (*func)(self, other, third);
3403}
3404
3405static PyObject *
3406wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3407{
3408	ternaryfunc func = (ternaryfunc)wrapped;
3409	PyObject *other;
3410	PyObject *third = Py_None;
3411
3412	/* Note: This wrapper only works for __pow__() */
3413
3414	if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3415		return NULL;
3416	return (*func)(other, self, third);
3417}
3418
3419static PyObject *
3420wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3421{
3422	unaryfunc func = (unaryfunc)wrapped;
3423
3424	if (!PyArg_ParseTuple(args, ""))
3425		return NULL;
3426	return (*func)(self);
3427}
3428
3429static PyObject *
3430wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3431{
3432	intargfunc func = (intargfunc)wrapped;
3433	int i;
3434
3435	if (!PyArg_ParseTuple(args, "i", &i))
3436		return NULL;
3437	return (*func)(self, i);
3438}
3439
3440static int
3441getindex(PyObject *self, PyObject *arg)
3442{
3443	int i;
3444
3445	i = PyInt_AsLong(arg);
3446	if (i == -1 && PyErr_Occurred())
3447		return -1;
3448	if (i < 0) {
3449		PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3450		if (sq && sq->sq_length) {
3451			int n = (*sq->sq_length)(self);
3452			if (n < 0)
3453				return -1;
3454			i += n;
3455		}
3456	}
3457	return i;
3458}
3459
3460static PyObject *
3461wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3462{
3463	intargfunc func = (intargfunc)wrapped;
3464	PyObject *arg;
3465	int i;
3466
3467	if (PyTuple_GET_SIZE(args) == 1) {
3468		arg = PyTuple_GET_ITEM(args, 0);
3469		i = getindex(self, arg);
3470		if (i == -1 && PyErr_Occurred())
3471			return NULL;
3472		return (*func)(self, i);
3473	}
3474	PyArg_ParseTuple(args, "O", &arg);
3475	assert(PyErr_Occurred());
3476	return NULL;
3477}
3478
3479static PyObject *
3480wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3481{
3482	intintargfunc func = (intintargfunc)wrapped;
3483	int i, j;
3484
3485	if (!PyArg_ParseTuple(args, "ii", &i, &j))
3486		return NULL;
3487	return (*func)(self, i, j);
3488}
3489
3490static PyObject *
3491wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
3492{
3493	intobjargproc func = (intobjargproc)wrapped;
3494	int i, res;
3495	PyObject *arg, *value;
3496
3497	if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3498		return NULL;
3499	i = getindex(self, arg);
3500	if (i == -1 && PyErr_Occurred())
3501		return NULL;
3502	res = (*func)(self, i, value);
3503	if (res == -1 && PyErr_Occurred())
3504		return NULL;
3505	Py_INCREF(Py_None);
3506	return Py_None;
3507}
3508
3509static PyObject *
3510wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
3511{
3512	intobjargproc func = (intobjargproc)wrapped;
3513	int i, res;
3514	PyObject *arg;
3515
3516	if (!PyArg_ParseTuple(args, "O", &arg))
3517		return NULL;
3518	i = getindex(self, arg);
3519	if (i == -1 && PyErr_Occurred())
3520		return NULL;
3521	res = (*func)(self, i, NULL);
3522	if (res == -1 && PyErr_Occurred())
3523		return NULL;
3524	Py_INCREF(Py_None);
3525	return Py_None;
3526}
3527
3528static PyObject *
3529wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3530{
3531	intintobjargproc func = (intintobjargproc)wrapped;
3532	int i, j, res;
3533	PyObject *value;
3534
3535	if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3536		return NULL;
3537	res = (*func)(self, i, j, value);
3538	if (res == -1 && PyErr_Occurred())
3539		return NULL;
3540	Py_INCREF(Py_None);
3541	return Py_None;
3542}
3543
3544static PyObject *
3545wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3546{
3547	intintobjargproc func = (intintobjargproc)wrapped;
3548	int i, j, res;
3549
3550	if (!PyArg_ParseTuple(args, "ii", &i, &j))
3551		return NULL;
3552	res = (*func)(self, i, j, NULL);
3553	if (res == -1 && PyErr_Occurred())
3554		return NULL;
3555	Py_INCREF(Py_None);
3556	return Py_None;
3557}
3558
3559/* XXX objobjproc is a misnomer; should be objargpred */
3560static PyObject *
3561wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3562{
3563	objobjproc func = (objobjproc)wrapped;
3564	int res;
3565	PyObject *value;
3566
3567	if (!PyArg_ParseTuple(args, "O", &value))
3568		return NULL;
3569	res = (*func)(self, value);
3570	if (res == -1 && PyErr_Occurred())
3571		return NULL;
3572	return PyInt_FromLong((long)res);
3573}
3574
3575static PyObject *
3576wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3577{
3578	objobjargproc func = (objobjargproc)wrapped;
3579	int res;
3580	PyObject *key, *value;
3581
3582	if (!PyArg_ParseTuple(args, "OO", &key, &value))
3583		return NULL;
3584	res = (*func)(self, key, value);
3585	if (res == -1 && PyErr_Occurred())
3586		return NULL;
3587	Py_INCREF(Py_None);
3588	return Py_None;
3589}
3590
3591static PyObject *
3592wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3593{
3594	objobjargproc func = (objobjargproc)wrapped;
3595	int res;
3596	PyObject *key;
3597
3598	if (!PyArg_ParseTuple(args, "O", &key))
3599		return NULL;
3600	res = (*func)(self, key, NULL);
3601	if (res == -1 && PyErr_Occurred())
3602		return NULL;
3603	Py_INCREF(Py_None);
3604	return Py_None;
3605}
3606
3607static PyObject *
3608wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3609{
3610	cmpfunc func = (cmpfunc)wrapped;
3611	int res;
3612	PyObject *other;
3613
3614	if (!PyArg_ParseTuple(args, "O", &other))
3615		return NULL;
3616	if (other->ob_type->tp_compare != func &&
3617	    !PyType_IsSubtype(other->ob_type, self->ob_type)) {
3618		PyErr_Format(
3619			PyExc_TypeError,
3620			"%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3621			self->ob_type->tp_name,
3622			self->ob_type->tp_name,
3623			other->ob_type->tp_name);
3624		return NULL;
3625	}
3626	res = (*func)(self, other);
3627	if (PyErr_Occurred())
3628		return NULL;
3629	return PyInt_FromLong((long)res);
3630}
3631
3632/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
3633   This is called the Carlo Verre hack after its discoverer. */
3634static int
3635hackcheck(PyObject *self, setattrofunc func, char *what)
3636{
3637	PyTypeObject *type = self->ob_type;
3638	while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3639		type = type->tp_base;
3640	if (type->tp_setattro != func) {
3641		PyErr_Format(PyExc_TypeError,
3642			     "can't apply this %s to %s object",
3643			     what,
3644			     type->tp_name);
3645		return 0;
3646	}
3647	return 1;
3648}
3649
3650static PyObject *
3651wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3652{
3653	setattrofunc func = (setattrofunc)wrapped;
3654	int res;
3655	PyObject *name, *value;
3656
3657	if (!PyArg_ParseTuple(args, "OO", &name, &value))
3658		return NULL;
3659	if (!hackcheck(self, func, "__setattr__"))
3660		return NULL;
3661	res = (*func)(self, name, value);
3662	if (res < 0)
3663		return NULL;
3664	Py_INCREF(Py_None);
3665	return Py_None;
3666}
3667
3668static PyObject *
3669wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3670{
3671	setattrofunc func = (setattrofunc)wrapped;
3672	int res;
3673	PyObject *name;
3674
3675	if (!PyArg_ParseTuple(args, "O", &name))
3676		return NULL;
3677	if (!hackcheck(self, func, "__delattr__"))
3678		return NULL;
3679	res = (*func)(self, name, NULL);
3680	if (res < 0)
3681		return NULL;
3682	Py_INCREF(Py_None);
3683	return Py_None;
3684}
3685
3686static PyObject *
3687wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3688{
3689	hashfunc func = (hashfunc)wrapped;
3690	long res;
3691
3692	if (!PyArg_ParseTuple(args, ""))
3693		return NULL;
3694	res = (*func)(self);
3695	if (res == -1 && PyErr_Occurred())
3696		return NULL;
3697	return PyInt_FromLong(res);
3698}
3699
3700static PyObject *
3701wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
3702{
3703	ternaryfunc func = (ternaryfunc)wrapped;
3704
3705	return (*func)(self, args, kwds);
3706}
3707
3708static PyObject *
3709wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3710{
3711	richcmpfunc func = (richcmpfunc)wrapped;
3712	PyObject *other;
3713
3714	if (!PyArg_ParseTuple(args, "O", &other))
3715		return NULL;
3716	return (*func)(self, other, op);
3717}
3718
3719#undef RICHCMP_WRAPPER
3720#define RICHCMP_WRAPPER(NAME, OP) \
3721static PyObject * \
3722richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3723{ \
3724	return wrap_richcmpfunc(self, args, wrapped, OP); \
3725}
3726
3727RICHCMP_WRAPPER(lt, Py_LT)
3728RICHCMP_WRAPPER(le, Py_LE)
3729RICHCMP_WRAPPER(eq, Py_EQ)
3730RICHCMP_WRAPPER(ne, Py_NE)
3731RICHCMP_WRAPPER(gt, Py_GT)
3732RICHCMP_WRAPPER(ge, Py_GE)
3733
3734static PyObject *
3735wrap_next(PyObject *self, PyObject *args, void *wrapped)
3736{
3737	unaryfunc func = (unaryfunc)wrapped;
3738	PyObject *res;
3739
3740	if (!PyArg_ParseTuple(args, ""))
3741		return NULL;
3742	res = (*func)(self);
3743	if (res == NULL && !PyErr_Occurred())
3744		PyErr_SetNone(PyExc_StopIteration);
3745	return res;
3746}
3747
3748static PyObject *
3749wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3750{
3751	descrgetfunc func = (descrgetfunc)wrapped;
3752	PyObject *obj;
3753	PyObject *type = NULL;
3754
3755	if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3756		return NULL;
3757	if (obj == Py_None)
3758		obj = NULL;
3759	if (type == Py_None)
3760		type = NULL;
3761	if (type == NULL &&obj == NULL) {
3762		PyErr_SetString(PyExc_TypeError,
3763				"__get__(None, None) is invalid");
3764		return NULL;
3765	}
3766	return (*func)(self, obj, type);
3767}
3768
3769static PyObject *
3770wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
3771{
3772	descrsetfunc func = (descrsetfunc)wrapped;
3773	PyObject *obj, *value;
3774	int ret;
3775
3776	if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3777		return NULL;
3778	ret = (*func)(self, obj, value);
3779	if (ret < 0)
3780		return NULL;
3781	Py_INCREF(Py_None);
3782	return Py_None;
3783}
3784
3785static PyObject *
3786wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3787{
3788	descrsetfunc func = (descrsetfunc)wrapped;
3789	PyObject *obj;
3790	int ret;
3791
3792	if (!PyArg_ParseTuple(args, "O", &obj))
3793		return NULL;
3794	ret = (*func)(self, obj, NULL);
3795	if (ret < 0)
3796		return NULL;
3797	Py_INCREF(Py_None);
3798	return Py_None;
3799}
3800
3801static PyObject *
3802wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
3803{
3804	initproc func = (initproc)wrapped;
3805
3806	if (func(self, args, kwds) < 0)
3807		return NULL;
3808	Py_INCREF(Py_None);
3809	return Py_None;
3810}
3811
3812static PyObject *
3813tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
3814{
3815	PyTypeObject *type, *subtype, *staticbase;
3816	PyObject *arg0, *res;
3817
3818	if (self == NULL || !PyType_Check(self))
3819		Py_FatalError("__new__() called with non-type 'self'");
3820	type = (PyTypeObject *)self;
3821	if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
3822		PyErr_Format(PyExc_TypeError,
3823			     "%s.__new__(): not enough arguments",
3824			     type->tp_name);
3825		return NULL;
3826	}
3827	arg0 = PyTuple_GET_ITEM(args, 0);
3828	if (!PyType_Check(arg0)) {
3829		PyErr_Format(PyExc_TypeError,
3830			     "%s.__new__(X): X is not a type object (%s)",
3831			     type->tp_name,
3832			     arg0->ob_type->tp_name);
3833		return NULL;
3834	}
3835	subtype = (PyTypeObject *)arg0;
3836	if (!PyType_IsSubtype(subtype, type)) {
3837		PyErr_Format(PyExc_TypeError,
3838			     "%s.__new__(%s): %s is not a subtype of %s",
3839			     type->tp_name,
3840			     subtype->tp_name,
3841			     subtype->tp_name,
3842			     type->tp_name);
3843		return NULL;
3844	}
3845
3846	/* Check that the use doesn't do something silly and unsafe like
3847	   object.__new__(dict).  To do this, we check that the
3848	   most derived base that's not a heap type is this type. */
3849	staticbase = subtype;
3850	while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3851		staticbase = staticbase->tp_base;
3852	if (staticbase->tp_new != type->tp_new) {
3853		PyErr_Format(PyExc_TypeError,
3854			     "%s.__new__(%s) is not safe, use %s.__new__()",
3855			     type->tp_name,
3856			     subtype->tp_name,
3857			     staticbase == NULL ? "?" : staticbase->tp_name);
3858		return NULL;
3859	}
3860
3861	args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3862	if (args == NULL)
3863		return NULL;
3864	res = type->tp_new(subtype, args, kwds);
3865	Py_DECREF(args);
3866	return res;
3867}
3868
3869static struct PyMethodDef tp_new_methoddef[] = {
3870	{"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
3871	 PyDoc_STR("T.__new__(S, ...) -> "
3872	 	   "a new object with type S, a subtype of T")},
3873	{0}
3874};
3875
3876static int
3877add_tp_new_wrapper(PyTypeObject *type)
3878{
3879	PyObject *func;
3880
3881	if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
3882		return 0;
3883	func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
3884	if (func == NULL)
3885		return -1;
3886	return PyDict_SetItemString(type->tp_dict, "__new__", func);
3887}
3888
3889/* Slot wrappers that call the corresponding __foo__ slot.  See comments
3890   below at override_slots() for more explanation. */
3891
3892#define SLOT0(FUNCNAME, OPSTR) \
3893static PyObject * \
3894FUNCNAME(PyObject *self) \
3895{ \
3896	static PyObject *cache_str; \
3897	return call_method(self, OPSTR, &cache_str, "()"); \
3898}
3899
3900#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
3901static PyObject * \
3902FUNCNAME(PyObject *self, ARG1TYPE arg1) \
3903{ \
3904	static PyObject *cache_str; \
3905	return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
3906}
3907
3908/* Boolean helper for SLOT1BINFULL().
3909   right.__class__ is a nontrivial subclass of left.__class__. */
3910static int
3911method_is_overloaded(PyObject *left, PyObject *right, char *name)
3912{
3913	PyObject *a, *b;
3914	int ok;
3915
3916	b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3917	if (b == NULL) {
3918		PyErr_Clear();
3919		/* If right doesn't have it, it's not overloaded */
3920		return 0;
3921	}
3922
3923	a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3924	if (a == NULL) {
3925		PyErr_Clear();
3926		Py_DECREF(b);
3927		/* If right has it but left doesn't, it's overloaded */
3928		return 1;
3929	}
3930
3931	ok = PyObject_RichCompareBool(a, b, Py_NE);
3932	Py_DECREF(a);
3933	Py_DECREF(b);
3934	if (ok < 0) {
3935		PyErr_Clear();
3936		return 0;
3937	}
3938
3939	return ok;
3940}
3941
3942
3943#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
3944static PyObject * \
3945FUNCNAME(PyObject *self, PyObject *other) \
3946{ \
3947	static PyObject *cache_str, *rcache_str; \
3948	int do_other = self->ob_type != other->ob_type && \
3949	    other->ob_type->tp_as_number != NULL && \
3950	    other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
3951	if (self->ob_type->tp_as_number != NULL && \
3952	    self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3953		PyObject *r; \
3954		if (do_other && \
3955		    PyType_IsSubtype(other->ob_type, self->ob_type) && \
3956		    method_is_overloaded(self, other, ROPSTR)) { \
3957			r = call_maybe( \
3958				other, ROPSTR, &rcache_str, "(O)", self); \
3959			if (r != Py_NotImplemented) \
3960				return r; \
3961			Py_DECREF(r); \
3962			do_other = 0; \
3963		} \
3964		r = call_maybe( \
3965			self, OPSTR, &cache_str, "(O)", other); \
3966		if (r != Py_NotImplemented || \
3967		    other->ob_type == self->ob_type) \
3968			return r; \
3969		Py_DECREF(r); \
3970	} \
3971	if (do_other) { \
3972		return call_maybe( \
3973			other, ROPSTR, &rcache_str, "(O)", self); \
3974	} \
3975	Py_INCREF(Py_NotImplemented); \
3976	return Py_NotImplemented; \
3977}
3978
3979#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3980	SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3981
3982#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3983static PyObject * \
3984FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3985{ \
3986	static PyObject *cache_str; \
3987	return call_method(self, OPSTR, &cache_str, \
3988			   "(" ARGCODES ")", arg1, arg2); \
3989}
3990
3991static int
3992slot_sq_length(PyObject *self)
3993{
3994	static PyObject *len_str;
3995	PyObject *res = call_method(self, "__len__", &len_str, "()");
3996	int len;
3997
3998	if (res == NULL)
3999		return -1;
4000	len = (int)PyInt_AsLong(res);
4001	Py_DECREF(res);
4002	if (len == -1 && PyErr_Occurred())
4003		return -1;
4004	if (len < 0) {
4005		PyErr_SetString(PyExc_ValueError,
4006				"__len__() should return >= 0");
4007		return -1;
4008	}
4009	return len;
4010}
4011
4012SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
4013SLOT1(slot_sq_repeat, "__mul__", int, "i")
4014
4015/* Super-optimized version of slot_sq_item.
4016   Other slots could do the same... */
4017static PyObject *
4018slot_sq_item(PyObject *self, int i)
4019{
4020	static PyObject *getitem_str;
4021	PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4022	descrgetfunc f;
4023
4024	if (getitem_str == NULL) {
4025		getitem_str = PyString_InternFromString("__getitem__");
4026		if (getitem_str == NULL)
4027			return NULL;
4028	}
4029	func = _PyType_Lookup(self->ob_type, getitem_str);
4030	if (func != NULL) {
4031		if ((f = func->ob_type->tp_descr_get) == NULL)
4032			Py_INCREF(func);
4033		else {
4034			func = f(func, self, (PyObject *)(self->ob_type));
4035			if (func == NULL) {
4036				return NULL;
4037			}
4038		}
4039		ival = PyInt_FromLong(i);
4040		if (ival != NULL) {
4041			args = PyTuple_New(1);
4042			if (args != NULL) {
4043				PyTuple_SET_ITEM(args, 0, ival);
4044				retval = PyObject_Call(func, args, NULL);
4045				Py_XDECREF(args);
4046				Py_XDECREF(func);
4047				return retval;
4048			}
4049		}
4050	}
4051	else {
4052		PyErr_SetObject(PyExc_AttributeError, getitem_str);
4053	}
4054	Py_XDECREF(args);
4055	Py_XDECREF(ival);
4056	Py_XDECREF(func);
4057	return NULL;
4058}
4059
4060SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
4061
4062static int
4063slot_sq_ass_item(PyObject *self, int index, PyObject *value)
4064{
4065	PyObject *res;
4066	static PyObject *delitem_str, *setitem_str;
4067
4068	if (value == NULL)
4069		res = call_method(self, "__delitem__", &delitem_str,
4070				  "(i)", index);
4071	else
4072		res = call_method(self, "__setitem__", &setitem_str,
4073				  "(iO)", index, value);
4074	if (res == NULL)
4075		return -1;
4076	Py_DECREF(res);
4077	return 0;
4078}
4079
4080static int
4081slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4082{
4083	PyObject *res;
4084	static PyObject *delslice_str, *setslice_str;
4085
4086	if (value == NULL)
4087		res = call_method(self, "__delslice__", &delslice_str,
4088				  "(ii)", i, j);
4089	else
4090		res = call_method(self, "__setslice__", &setslice_str,
4091				  "(iiO)", i, j, value);
4092	if (res == NULL)
4093		return -1;
4094	Py_DECREF(res);
4095	return 0;
4096}
4097
4098static int
4099slot_sq_contains(PyObject *self, PyObject *value)
4100{
4101	PyObject *func, *res, *args;
4102	int result = -1;
4103
4104	static PyObject *contains_str;
4105
4106	func = lookup_maybe(self, "__contains__", &contains_str);
4107	if (func != NULL) {
4108		args = Py_BuildValue("(O)", value);
4109		if (args == NULL)
4110			res = NULL;
4111		else {
4112			res = PyObject_Call(func, args, NULL);
4113			Py_DECREF(args);
4114		}
4115		Py_DECREF(func);
4116		if (res != NULL) {
4117			result = PyObject_IsTrue(res);
4118			Py_DECREF(res);
4119		}
4120	}
4121	else if (! PyErr_Occurred()) {
4122		result = _PySequence_IterSearch(self, value,
4123						 PY_ITERSEARCH_CONTAINS);
4124	}
4125	return result;
4126}
4127
4128SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4129SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
4130
4131#define slot_mp_length slot_sq_length
4132
4133SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
4134
4135static int
4136slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4137{
4138	PyObject *res;
4139	static PyObject *delitem_str, *setitem_str;
4140
4141	if (value == NULL)
4142		res = call_method(self, "__delitem__", &delitem_str,
4143				  "(O)", key);
4144	else
4145		res = call_method(self, "__setitem__", &setitem_str,
4146				 "(OO)", key, value);
4147	if (res == NULL)
4148		return -1;
4149	Py_DECREF(res);
4150	return 0;
4151}
4152
4153SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4154SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4155SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4156SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4157SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4158SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4159
4160static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
4161
4162SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4163	     nb_power, "__pow__", "__rpow__")
4164
4165static PyObject *
4166slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4167{
4168	static PyObject *pow_str;
4169
4170	if (modulus == Py_None)
4171		return slot_nb_power_binary(self, other);
4172	/* Three-arg power doesn't use __rpow__.  But ternary_op
4173	   can call this when the second argument's type uses
4174	   slot_nb_power, so check before calling self.__pow__. */
4175	if (self->ob_type->tp_as_number != NULL &&
4176	    self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4177		return call_method(self, "__pow__", &pow_str,
4178				   "(OO)", other, modulus);
4179	}
4180	Py_INCREF(Py_NotImplemented);
4181	return Py_NotImplemented;
4182}
4183
4184SLOT0(slot_nb_negative, "__neg__")
4185SLOT0(slot_nb_positive, "__pos__")
4186SLOT0(slot_nb_absolute, "__abs__")
4187
4188static int
4189slot_nb_nonzero(PyObject *self)
4190{
4191	PyObject *func, *args;
4192	static PyObject *nonzero_str, *len_str;
4193	int result = -1;
4194
4195	func = lookup_maybe(self, "__nonzero__", &nonzero_str);
4196	if (func == NULL) {
4197		if (PyErr_Occurred())
4198			return -1;
4199		func = lookup_maybe(self, "__len__", &len_str);
4200		if (func == NULL)
4201			return PyErr_Occurred() ? -1 : 1;
4202 	}
4203	args = PyTuple_New(0);
4204	if (args != NULL) {
4205		PyObject *temp = PyObject_Call(func, args, NULL);
4206		Py_DECREF(args);
4207		if (temp != NULL) {
4208			if (PyInt_CheckExact(temp) || PyBool_Check(temp))
4209				result = PyObject_IsTrue(temp);
4210			else {
4211				PyErr_Format(PyExc_TypeError,
4212					     "__nonzero__ should return "
4213					     "bool or int, returned %s",
4214					     temp->ob_type->tp_name);
4215				result = -1;
4216			}
4217			Py_DECREF(temp);
4218		}
4219	}
4220	Py_DECREF(func);
4221	return result;
4222}
4223
4224SLOT0(slot_nb_invert, "__invert__")
4225SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4226SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4227SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4228SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4229SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
4230
4231static int
4232slot_nb_coerce(PyObject **a, PyObject **b)
4233{
4234	static PyObject *coerce_str;
4235	PyObject *self = *a, *other = *b;
4236
4237	if (self->ob_type->tp_as_number != NULL &&
4238	    self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4239		PyObject *r;
4240		r = call_maybe(
4241			self, "__coerce__", &coerce_str, "(O)", other);
4242		if (r == NULL)
4243			return -1;
4244		if (r == Py_NotImplemented) {
4245			Py_DECREF(r);
4246		}
4247		else {
4248			if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4249				PyErr_SetString(PyExc_TypeError,
4250					"__coerce__ didn't return a 2-tuple");
4251				Py_DECREF(r);
4252				return -1;
4253			}
4254			*a = PyTuple_GET_ITEM(r, 0);
4255			Py_INCREF(*a);
4256			*b = PyTuple_GET_ITEM(r, 1);
4257			Py_INCREF(*b);
4258			Py_DECREF(r);
4259			return 0;
4260		}
4261	}
4262	if (other->ob_type->tp_as_number != NULL &&
4263	    other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4264		PyObject *r;
4265		r = call_maybe(
4266			other, "__coerce__", &coerce_str, "(O)", self);
4267		if (r == NULL)
4268			return -1;
4269		if (r == Py_NotImplemented) {
4270			Py_DECREF(r);
4271			return 1;
4272		}
4273		if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4274			PyErr_SetString(PyExc_TypeError,
4275					"__coerce__ didn't return a 2-tuple");
4276			Py_DECREF(r);
4277			return -1;
4278		}
4279		*a = PyTuple_GET_ITEM(r, 1);
4280		Py_INCREF(*a);
4281		*b = PyTuple_GET_ITEM(r, 0);
4282		Py_INCREF(*b);
4283		Py_DECREF(r);
4284		return 0;
4285	}
4286	return 1;
4287}
4288
4289SLOT0(slot_nb_int, "__int__")
4290SLOT0(slot_nb_long, "__long__")
4291SLOT0(slot_nb_float, "__float__")
4292SLOT0(slot_nb_oct, "__oct__")
4293SLOT0(slot_nb_hex, "__hex__")
4294SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4295SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4296SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4297SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4298SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
4299SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
4300SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4301SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4302SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4303SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4304SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4305SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4306	 "__floordiv__", "__rfloordiv__")
4307SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4308SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4309SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
4310
4311static int
4312half_compare(PyObject *self, PyObject *other)
4313{
4314	PyObject *func, *args, *res;
4315	static PyObject *cmp_str;
4316	int c;
4317
4318	func = lookup_method(self, "__cmp__", &cmp_str);
4319	if (func == NULL) {
4320		PyErr_Clear();
4321	}
4322	else {
4323		args = Py_BuildValue("(O)", other);
4324		if (args == NULL)
4325			res = NULL;
4326		else {
4327			res = PyObject_Call(func, args, NULL);
4328			Py_DECREF(args);
4329		}
4330		Py_DECREF(func);
4331		if (res != Py_NotImplemented) {
4332			if (res == NULL)
4333				return -2;
4334			c = PyInt_AsLong(res);
4335			Py_DECREF(res);
4336			if (c == -1 && PyErr_Occurred())
4337				return -2;
4338			return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4339		}
4340		Py_DECREF(res);
4341	}
4342	return 2;
4343}
4344
4345/* This slot is published for the benefit of try_3way_compare in object.c */
4346int
4347_PyObject_SlotCompare(PyObject *self, PyObject *other)
4348{
4349	int c;
4350
4351	if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
4352		c = half_compare(self, other);
4353		if (c <= 1)
4354			return c;
4355	}
4356	if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
4357		c = half_compare(other, self);
4358		if (c < -1)
4359			return -2;
4360		if (c <= 1)
4361			return -c;
4362	}
4363	return (void *)self < (void *)other ? -1 :
4364		(void *)self > (void *)other ? 1 : 0;
4365}
4366
4367static PyObject *
4368slot_tp_repr(PyObject *self)
4369{
4370	PyObject *func, *res;
4371	static PyObject *repr_str;
4372
4373	func = lookup_method(self, "__repr__", &repr_str);
4374	if (func != NULL) {
4375		res = PyEval_CallObject(func, NULL);
4376		Py_DECREF(func);
4377		return res;
4378	}
4379	PyErr_Clear();
4380	return PyString_FromFormat("<%s object at %p>",
4381				   self->ob_type->tp_name, self);
4382}
4383
4384static PyObject *
4385slot_tp_str(PyObject *self)
4386{
4387	PyObject *func, *res;
4388	static PyObject *str_str;
4389
4390	func = lookup_method(self, "__str__", &str_str);
4391	if (func != NULL) {
4392		res = PyEval_CallObject(func, NULL);
4393		Py_DECREF(func);
4394		return res;
4395	}
4396	else {
4397		PyErr_Clear();
4398		return slot_tp_repr(self);
4399	}
4400}
4401
4402static long
4403slot_tp_hash(PyObject *self)
4404{
4405	PyObject *func;
4406	static PyObject *hash_str, *eq_str, *cmp_str;
4407	long h;
4408
4409	func = lookup_method(self, "__hash__", &hash_str);
4410
4411	if (func != NULL) {
4412		PyObject *res = PyEval_CallObject(func, NULL);
4413		Py_DECREF(func);
4414		if (res == NULL)
4415			return -1;
4416		h = PyInt_AsLong(res);
4417		Py_DECREF(res);
4418	}
4419	else {
4420		PyErr_Clear();
4421		func = lookup_method(self, "__eq__", &eq_str);
4422		if (func == NULL) {
4423			PyErr_Clear();
4424			func = lookup_method(self, "__cmp__", &cmp_str);
4425		}
4426		if (func != NULL) {
4427			Py_DECREF(func);
4428			PyErr_SetString(PyExc_TypeError, "unhashable type");
4429			return -1;
4430		}
4431		PyErr_Clear();
4432		h = _Py_HashPointer((void *)self);
4433	}
4434	if (h == -1 && !PyErr_Occurred())
4435		h = -2;
4436	return h;
4437}
4438
4439static PyObject *
4440slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4441{
4442	static PyObject *call_str;
4443	PyObject *meth = lookup_method(self, "__call__", &call_str);
4444	PyObject *res;
4445
4446	if (meth == NULL)
4447		return NULL;
4448	res = PyObject_Call(meth, args, kwds);
4449	Py_DECREF(meth);
4450	return res;
4451}
4452
4453/* There are two slot dispatch functions for tp_getattro.
4454
4455   - slot_tp_getattro() is used when __getattribute__ is overridden
4456     but no __getattr__ hook is present;
4457
4458   - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4459
4460   The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4461   detects the absence of __getattr__ and then installs the simpler slot if
4462   necessary. */
4463
4464static PyObject *
4465slot_tp_getattro(PyObject *self, PyObject *name)
4466{
4467	static PyObject *getattribute_str = NULL;
4468	return call_method(self, "__getattribute__", &getattribute_str,
4469			   "(O)", name);
4470}
4471
4472static PyObject *
4473slot_tp_getattr_hook(PyObject *self, PyObject *name)
4474{
4475	PyTypeObject *tp = self->ob_type;
4476	PyObject *getattr, *getattribute, *res;
4477	static PyObject *getattribute_str = NULL;
4478	static PyObject *getattr_str = NULL;
4479
4480	if (getattr_str == NULL) {
4481		getattr_str = PyString_InternFromString("__getattr__");
4482		if (getattr_str == NULL)
4483			return NULL;
4484	}
4485	if (getattribute_str == NULL) {
4486		getattribute_str =
4487			PyString_InternFromString("__getattribute__");
4488		if (getattribute_str == NULL)
4489			return NULL;
4490	}
4491	getattr = _PyType_Lookup(tp, getattr_str);
4492	if (getattr == NULL) {
4493		/* No __getattr__ hook: use a simpler dispatcher */
4494		tp->tp_getattro = slot_tp_getattro;
4495		return slot_tp_getattro(self, name);
4496	}
4497	getattribute = _PyType_Lookup(tp, getattribute_str);
4498	if (getattribute == NULL ||
4499	    (getattribute->ob_type == &PyWrapperDescr_Type &&
4500	     ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4501	     (void *)PyObject_GenericGetAttr))
4502		res = PyObject_GenericGetAttr(self, name);
4503	else
4504		res = PyObject_CallFunction(getattribute, "OO", self, name);
4505	if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
4506		PyErr_Clear();
4507		res = PyObject_CallFunction(getattr, "OO", self, name);
4508	}
4509	return res;
4510}
4511
4512static int
4513slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4514{
4515	PyObject *res;
4516	static PyObject *delattr_str, *setattr_str;
4517
4518	if (value == NULL)
4519		res = call_method(self, "__delattr__", &delattr_str,
4520				  "(O)", name);
4521	else
4522		res = call_method(self, "__setattr__", &setattr_str,
4523				  "(OO)", name, value);
4524	if (res == NULL)
4525		return -1;
4526	Py_DECREF(res);
4527	return 0;
4528}
4529
4530/* Map rich comparison operators to their __xx__ namesakes */
4531static char *name_op[] = {
4532	"__lt__",
4533	"__le__",
4534	"__eq__",
4535	"__ne__",
4536	"__gt__",
4537	"__ge__",
4538};
4539
4540static PyObject *
4541half_richcompare(PyObject *self, PyObject *other, int op)
4542{
4543	PyObject *func, *args, *res;
4544	static PyObject *op_str[6];
4545
4546	func = lookup_method(self, name_op[op], &op_str[op]);
4547	if (func == NULL) {
4548		PyErr_Clear();
4549		Py_INCREF(Py_NotImplemented);
4550		return Py_NotImplemented;
4551	}
4552	args = Py_BuildValue("(O)", other);
4553	if (args == NULL)
4554		res = NULL;
4555	else {
4556		res = PyObject_Call(func, args, NULL);
4557		Py_DECREF(args);
4558	}
4559	Py_DECREF(func);
4560	return res;
4561}
4562
4563/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4564static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4565
4566static PyObject *
4567slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4568{
4569	PyObject *res;
4570
4571	if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4572		res = half_richcompare(self, other, op);
4573		if (res != Py_NotImplemented)
4574			return res;
4575		Py_DECREF(res);
4576	}
4577	if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4578		res = half_richcompare(other, self, swapped_op[op]);
4579		if (res != Py_NotImplemented) {
4580			return res;
4581		}
4582		Py_DECREF(res);
4583	}
4584	Py_INCREF(Py_NotImplemented);
4585	return Py_NotImplemented;
4586}
4587
4588static PyObject *
4589slot_tp_iter(PyObject *self)
4590{
4591	PyObject *func, *res;
4592	static PyObject *iter_str, *getitem_str;
4593
4594	func = lookup_method(self, "__iter__", &iter_str);
4595	if (func != NULL) {
4596		PyObject *args;
4597		args = res = PyTuple_New(0);
4598		if (args != NULL) {
4599			res = PyObject_Call(func, args, NULL);
4600			Py_DECREF(args);
4601		}
4602		Py_DECREF(func);
4603		return res;
4604	}
4605	PyErr_Clear();
4606	func = lookup_method(self, "__getitem__", &getitem_str);
4607	if (func == NULL) {
4608		PyErr_SetString(PyExc_TypeError,
4609				"iteration over non-sequence");
4610		return NULL;
4611	}
4612	Py_DECREF(func);
4613	return PySeqIter_New(self);
4614}
4615
4616static PyObject *
4617slot_tp_iternext(PyObject *self)
4618{
4619	static PyObject *next_str;
4620	return call_method(self, "next", &next_str, "()");
4621}
4622
4623static PyObject *
4624slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4625{
4626	PyTypeObject *tp = self->ob_type;
4627	PyObject *get;
4628	static PyObject *get_str = NULL;
4629
4630	if (get_str == NULL) {
4631		get_str = PyString_InternFromString("__get__");
4632		if (get_str == NULL)
4633			return NULL;
4634	}
4635	get = _PyType_Lookup(tp, get_str);
4636	if (get == NULL) {
4637		/* Avoid further slowdowns */
4638		if (tp->tp_descr_get == slot_tp_descr_get)
4639			tp->tp_descr_get = NULL;
4640		Py_INCREF(self);
4641		return self;
4642	}
4643	if (obj == NULL)
4644		obj = Py_None;
4645	if (type == NULL)
4646		type = Py_None;
4647	return PyObject_CallFunction(get, "OOO", self, obj, type);
4648}
4649
4650static int
4651slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4652{
4653	PyObject *res;
4654	static PyObject *del_str, *set_str;
4655
4656	if (value == NULL)
4657		res = call_method(self, "__delete__", &del_str,
4658				  "(O)", target);
4659	else
4660		res = call_method(self, "__set__", &set_str,
4661				  "(OO)", target, value);
4662	if (res == NULL)
4663		return -1;
4664	Py_DECREF(res);
4665	return 0;
4666}
4667
4668static int
4669slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4670{
4671	static PyObject *init_str;
4672	PyObject *meth = lookup_method(self, "__init__", &init_str);
4673	PyObject *res;
4674
4675	if (meth == NULL)
4676		return -1;
4677	res = PyObject_Call(meth, args, kwds);
4678	Py_DECREF(meth);
4679	if (res == NULL)
4680		return -1;
4681	Py_DECREF(res);
4682	return 0;
4683}
4684
4685static PyObject *
4686slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4687{
4688	static PyObject *new_str;
4689	PyObject *func;
4690	PyObject *newargs, *x;
4691	int i, n;
4692
4693	if (new_str == NULL) {
4694		new_str = PyString_InternFromString("__new__");
4695		if (new_str == NULL)
4696			return NULL;
4697	}
4698	func = PyObject_GetAttr((PyObject *)type, new_str);
4699	if (func == NULL)
4700		return NULL;
4701	assert(PyTuple_Check(args));
4702	n = PyTuple_GET_SIZE(args);
4703	newargs = PyTuple_New(n+1);
4704	if (newargs == NULL)
4705		return NULL;
4706	Py_INCREF(type);
4707	PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4708	for (i = 0; i < n; i++) {
4709		x = PyTuple_GET_ITEM(args, i);
4710		Py_INCREF(x);
4711		PyTuple_SET_ITEM(newargs, i+1, x);
4712	}
4713	x = PyObject_Call(func, newargs, kwds);
4714	Py_DECREF(newargs);
4715	Py_DECREF(func);
4716	return x;
4717}
4718
4719static void
4720slot_tp_del(PyObject *self)
4721{
4722	static PyObject *del_str = NULL;
4723	PyObject *del, *res;
4724	PyObject *error_type, *error_value, *error_traceback;
4725
4726	/* Temporarily resurrect the object. */
4727	assert(self->ob_refcnt == 0);
4728	self->ob_refcnt = 1;
4729
4730	/* Save the current exception, if any. */
4731	PyErr_Fetch(&error_type, &error_value, &error_traceback);
4732
4733	/* Execute __del__ method, if any. */
4734	del = lookup_maybe(self, "__del__", &del_str);
4735	if (del != NULL) {
4736		res = PyEval_CallObject(del, NULL);
4737		if (res == NULL)
4738			PyErr_WriteUnraisable(del);
4739		else
4740			Py_DECREF(res);
4741		Py_DECREF(del);
4742	}
4743
4744	/* Restore the saved exception. */
4745	PyErr_Restore(error_type, error_value, error_traceback);
4746
4747	/* Undo the temporary resurrection; can't use DECREF here, it would
4748	 * cause a recursive call.
4749	 */
4750	assert(self->ob_refcnt > 0);
4751	if (--self->ob_refcnt == 0)
4752		return;	/* this is the normal path out */
4753
4754	/* __del__ resurrected it!  Make it look like the original Py_DECREF
4755	 * never happened.
4756	 */
4757	{
4758		int refcnt = self->ob_refcnt;
4759		_Py_NewReference(self);
4760		self->ob_refcnt = refcnt;
4761	}
4762	assert(!PyType_IS_GC(self->ob_type) ||
4763	       _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4764	/* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4765	 * _Py_NewReference bumped it again, so that's a wash.
4766	 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4767	 * chain, so no more to do there either.
4768	 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4769	 * _Py_NewReference bumped tp_allocs:  both of those need to be
4770	 * undone.
4771	 */
4772#ifdef COUNT_ALLOCS
4773	--self->ob_type->tp_frees;
4774	--self->ob_type->tp_allocs;
4775#endif
4776}
4777
4778
4779/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
4780   functions.  The offsets here are relative to the 'PyHeapTypeObject'
4781   structure, which incorporates the additional structures used for numbers,
4782   sequences and mappings.
4783   Note that multiple names may map to the same slot (e.g. __eq__,
4784   __ne__ etc. all map to tp_richcompare) and one name may map to multiple
4785   slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4786   terminated with an all-zero entry.  (This table is further initialized and
4787   sorted in init_slotdefs() below.) */
4788
4789typedef struct wrapperbase slotdef;
4790
4791#undef TPSLOT
4792#undef FLSLOT
4793#undef ETSLOT
4794#undef SQSLOT
4795#undef MPSLOT
4796#undef NBSLOT
4797#undef UNSLOT
4798#undef IBSLOT
4799#undef BINSLOT
4800#undef RBINSLOT
4801
4802#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4803	{NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4804	 PyDoc_STR(DOC)}
4805#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4806	{NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4807	 PyDoc_STR(DOC), FLAGS}
4808#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4809	{NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4810	 PyDoc_STR(DOC)}
4811#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4812	ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4813#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4814	ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4815#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4816	ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4817#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4818	ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4819	       "x." NAME "() <==> " DOC)
4820#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4821	ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4822	       "x." NAME "(y) <==> x" DOC "y")
4823#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4824	ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4825	       "x." NAME "(y) <==> x" DOC "y")
4826#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4827	ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4828	       "x." NAME "(y) <==> y" DOC "x")
4829
4830static slotdef slotdefs[] = {
4831	SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4832	       "x.__len__() <==> len(x)"),
4833	SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4834	       "x.__add__(y) <==> x+y"),
4835	SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4836	       "x.__mul__(n) <==> x*n"),
4837	SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4838	       "x.__rmul__(n) <==> n*x"),
4839	SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4840	       "x.__getitem__(y) <==> x[y]"),
4841	SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4842	       "x.__getslice__(i, j) <==> x[i:j]\n\
4843               \n\
4844               Use of negative indices is not supported."),
4845	SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4846	       "x.__setitem__(i, y) <==> x[i]=y"),
4847	SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4848	       "x.__delitem__(y) <==> del x[y]"),
4849	SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
4850	       wrap_intintobjargproc,
4851	       "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
4852               \n\
4853               Use  of negative indices is not supported."),
4854	SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4855	       "x.__delslice__(i, j) <==> del x[i:j]\n\
4856               \n\
4857               Use of negative indices is not supported."),
4858	SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4859	       "x.__contains__(y) <==> y in x"),
4860	SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
4861	       wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
4862	SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
4863	       wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
4864
4865	MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4866	       "x.__len__() <==> len(x)"),
4867	MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
4868	       wrap_binaryfunc,
4869	       "x.__getitem__(y) <==> x[y]"),
4870	MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
4871	       wrap_objobjargproc,
4872	       "x.__setitem__(i, y) <==> x[i]=y"),
4873	MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
4874	       wrap_delitem,
4875	       "x.__delitem__(y) <==> del x[y]"),
4876
4877	BINSLOT("__add__", nb_add, slot_nb_add,
4878		"+"),
4879	RBINSLOT("__radd__", nb_add, slot_nb_add,
4880		 "+"),
4881	BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4882		"-"),
4883	RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4884		 "-"),
4885	BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4886		"*"),
4887	RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4888		 "*"),
4889	BINSLOT("__div__", nb_divide, slot_nb_divide,
4890		"/"),
4891	RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4892		 "/"),
4893	BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4894		"%"),
4895	RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4896		 "%"),
4897	BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4898		"divmod(x, y)"),
4899	RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4900		 "divmod(y, x)"),
4901	NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4902	       "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4903	NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4904	       "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4905	UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4906	UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4907	UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4908	       "abs(x)"),
4909	UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
4910	       "x != 0"),
4911	UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4912	BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4913	RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4914	BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4915	RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4916	BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4917	RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4918	BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4919	RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4920	BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4921	RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4922	NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4923	       "x.__coerce__(y) <==> coerce(x, y)"),
4924	UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4925	       "int(x)"),
4926	UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4927	       "long(x)"),
4928	UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4929	       "float(x)"),
4930	UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4931	       "oct(x)"),
4932	UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4933	       "hex(x)"),
4934	IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4935	       wrap_binaryfunc, "+"),
4936	IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4937	       wrap_binaryfunc, "-"),
4938	IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4939	       wrap_binaryfunc, "*"),
4940	IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4941	       wrap_binaryfunc, "/"),
4942	IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4943	       wrap_binaryfunc, "%"),
4944	IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
4945	       wrap_binaryfunc, "**"),
4946	IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4947	       wrap_binaryfunc, "<<"),
4948	IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4949	       wrap_binaryfunc, ">>"),
4950	IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4951	       wrap_binaryfunc, "&"),
4952	IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4953	       wrap_binaryfunc, "^"),
4954	IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4955	       wrap_binaryfunc, "|"),
4956	BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4957	RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4958	BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4959	RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4960	IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4961	       slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4962	IBSLOT("__itruediv__", nb_inplace_true_divide,
4963	       slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
4964
4965	TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4966	       "x.__str__() <==> str(x)"),
4967	TPSLOT("__str__", tp_print, NULL, NULL, ""),
4968	TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4969	       "x.__repr__() <==> repr(x)"),
4970	TPSLOT("__repr__", tp_print, NULL, NULL, ""),
4971	TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4972	       "x.__cmp__(y) <==> cmp(x,y)"),
4973	TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4974	       "x.__hash__() <==> hash(x)"),
4975	FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4976	       "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
4977	TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
4978	       wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4979	TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4980	TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4981	TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4982	TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4983	       "x.__setattr__('name', value) <==> x.name = value"),
4984	TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4985	TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4986	       "x.__delattr__('name') <==> del x.name"),
4987	TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4988	TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4989	       "x.__lt__(y) <==> x<y"),
4990	TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4991	       "x.__le__(y) <==> x<=y"),
4992	TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4993	       "x.__eq__(y) <==> x==y"),
4994	TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4995	       "x.__ne__(y) <==> x!=y"),
4996	TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4997	       "x.__gt__(y) <==> x>y"),
4998	TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4999	       "x.__ge__(y) <==> x>=y"),
5000	TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5001	       "x.__iter__() <==> iter(x)"),
5002	TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5003	       "x.next() -> the next value, or raise StopIteration"),
5004	TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5005	       "descr.__get__(obj[, type]) -> value"),
5006	TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5007	       "descr.__set__(obj, value)"),
5008	TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5009	       wrap_descr_delete, "descr.__delete__(obj)"),
5010	FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5011	       "x.__init__(...) initializes x; "
5012	       "see x.__class__.__doc__ for signature",
5013	       PyWrapperFlag_KEYWORDS),
5014	TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5015	TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
5016	{NULL}
5017};
5018
5019/* Given a type pointer and an offset gotten from a slotdef entry, return a
5020   pointer to the actual slot.  This is not quite the same as simply adding
5021   the offset to the type pointer, since it takes care to indirect through the
5022   proper indirection pointer (as_buffer, etc.); it returns NULL if the
5023   indirection pointer is NULL. */
5024static void **
5025slotptr(PyTypeObject *type, int offset)
5026{
5027	char *ptr;
5028
5029	/* Note: this depends on the order of the members of PyHeapTypeObject! */
5030	assert(offset >= 0);
5031	assert(offset < offsetof(PyHeapTypeObject, as_buffer));
5032	if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5033		ptr = (void *)type->tp_as_sequence;
5034		offset -= offsetof(PyHeapTypeObject, as_sequence);
5035	}
5036	else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5037		ptr = (void *)type->tp_as_mapping;
5038		offset -= offsetof(PyHeapTypeObject, as_mapping);
5039	}
5040	else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
5041		ptr = (void *)type->tp_as_number;
5042		offset -= offsetof(PyHeapTypeObject, as_number);
5043	}
5044	else {
5045		ptr = (void *)type;
5046	}
5047	if (ptr != NULL)
5048		ptr += offset;
5049	return (void **)ptr;
5050}
5051
5052/* Length of array of slotdef pointers used to store slots with the
5053   same __name__.  There should be at most MAX_EQUIV-1 slotdef entries with
5054   the same __name__, for any __name__. Since that's a static property, it is
5055   appropriate to declare fixed-size arrays for this. */
5056#define MAX_EQUIV 10
5057
5058/* Return a slot pointer for a given name, but ONLY if the attribute has
5059   exactly one slot function.  The name must be an interned string. */
5060static void **
5061resolve_slotdups(PyTypeObject *type, PyObject *name)
5062{
5063	/* XXX Maybe this could be optimized more -- but is it worth it? */
5064
5065	/* pname and ptrs act as a little cache */
5066	static PyObject *pname;
5067	static slotdef *ptrs[MAX_EQUIV];
5068	slotdef *p, **pp;
5069	void **res, **ptr;
5070
5071	if (pname != name) {
5072		/* Collect all slotdefs that match name into ptrs. */
5073		pname = name;
5074		pp = ptrs;
5075		for (p = slotdefs; p->name_strobj; p++) {
5076			if (p->name_strobj == name)
5077				*pp++ = p;
5078		}
5079		*pp = NULL;
5080	}
5081
5082	/* Look in all matching slots of the type; if exactly one of these has
5083	   a filled-in slot, return its value.  Otherwise return NULL. */
5084	res = NULL;
5085	for (pp = ptrs; *pp; pp++) {
5086		ptr = slotptr(type, (*pp)->offset);
5087		if (ptr == NULL || *ptr == NULL)
5088			continue;
5089		if (res != NULL)
5090			return NULL;
5091		res = ptr;
5092	}
5093	return res;
5094}
5095
5096/* Common code for update_slots_callback() and fixup_slot_dispatchers().  This
5097   does some incredibly complex thinking and then sticks something into the
5098   slot.  (It sees if the adjacent slotdefs for the same slot have conflicting
5099   interests, and then stores a generic wrapper or a specific function into
5100   the slot.)  Return a pointer to the next slotdef with a different offset,
5101   because that's convenient  for fixup_slot_dispatchers(). */
5102static slotdef *
5103update_one_slot(PyTypeObject *type, slotdef *p)
5104{
5105	PyObject *descr;
5106	PyWrapperDescrObject *d;
5107	void *generic = NULL, *specific = NULL;
5108	int use_generic = 0;
5109	int offset = p->offset;
5110	void **ptr = slotptr(type, offset);
5111
5112	if (ptr == NULL) {
5113		do {
5114			++p;
5115		} while (p->offset == offset);
5116		return p;
5117	}
5118	do {
5119		descr = _PyType_Lookup(type, p->name_strobj);
5120		if (descr == NULL)
5121			continue;
5122		if (descr->ob_type == &PyWrapperDescr_Type) {
5123			void **tptr = resolve_slotdups(type, p->name_strobj);
5124			if (tptr == NULL || tptr == ptr)
5125				generic = p->function;
5126			d = (PyWrapperDescrObject *)descr;
5127			if (d->d_base->wrapper == p->wrapper &&
5128			    PyType_IsSubtype(type, d->d_type))
5129			{
5130				if (specific == NULL ||
5131				    specific == d->d_wrapped)
5132					specific = d->d_wrapped;
5133				else
5134					use_generic = 1;
5135			}
5136		}
5137		else if (descr->ob_type == &PyCFunction_Type &&
5138			 PyCFunction_GET_FUNCTION(descr) ==
5139			 (PyCFunction)tp_new_wrapper &&
5140			 strcmp(p->name, "__new__") == 0)
5141		{
5142			/* The __new__ wrapper is not a wrapper descriptor,
5143			   so must be special-cased differently.
5144			   If we don't do this, creating an instance will
5145			   always use slot_tp_new which will look up
5146			   __new__ in the MRO which will call tp_new_wrapper
5147			   which will look through the base classes looking
5148			   for a static base and call its tp_new (usually
5149			   PyType_GenericNew), after performing various
5150			   sanity checks and constructing a new argument
5151			   list.  Cut all that nonsense short -- this speeds
5152			   up instance creation tremendously. */
5153			specific = (void *)type->tp_new;
5154			/* XXX I'm not 100% sure that there isn't a hole
5155			   in this reasoning that requires additional
5156			   sanity checks.  I'll buy the first person to
5157			   point out a bug in this reasoning a beer. */
5158		}
5159		else {
5160			use_generic = 1;
5161			generic = p->function;
5162		}
5163	} while ((++p)->offset == offset);
5164	if (specific && !use_generic)
5165		*ptr = specific;
5166	else
5167		*ptr = generic;
5168	return p;
5169}
5170
5171/* In the type, update the slots whose slotdefs are gathered in the pp array.
5172   This is a callback for update_subclasses(). */
5173static int
5174update_slots_callback(PyTypeObject *type, void *data)
5175{
5176	slotdef **pp = (slotdef **)data;
5177
5178	for (; *pp; pp++)
5179		update_one_slot(type, *pp);
5180	return 0;
5181}
5182
5183/* Comparison function for qsort() to compare slotdefs by their offset, and
5184   for equal offset by their address (to force a stable sort). */
5185static int
5186slotdef_cmp(const void *aa, const void *bb)
5187{
5188	const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5189	int c = a->offset - b->offset;
5190	if (c != 0)
5191		return c;
5192	else
5193		return a - b;
5194}
5195
5196/* Initialize the slotdefs table by adding interned string objects for the
5197   names and sorting the entries. */
5198static void
5199init_slotdefs(void)
5200{
5201	slotdef *p;
5202	static int initialized = 0;
5203
5204	if (initialized)
5205		return;
5206	for (p = slotdefs; p->name; p++) {
5207		p->name_strobj = PyString_InternFromString(p->name);
5208		if (!p->name_strobj)
5209			Py_FatalError("Out of memory interning slotdef names");
5210	}
5211	qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5212	      slotdef_cmp);
5213	initialized = 1;
5214}
5215
5216/* Update the slots after assignment to a class (type) attribute. */
5217static int
5218update_slot(PyTypeObject *type, PyObject *name)
5219{
5220	slotdef *ptrs[MAX_EQUIV];
5221	slotdef *p;
5222	slotdef **pp;
5223	int offset;
5224
5225	init_slotdefs();
5226	pp = ptrs;
5227	for (p = slotdefs; p->name; p++) {
5228		/* XXX assume name is interned! */
5229		if (p->name_strobj == name)
5230			*pp++ = p;
5231	}
5232	*pp = NULL;
5233	for (pp = ptrs; *pp; pp++) {
5234		p = *pp;
5235		offset = p->offset;
5236		while (p > slotdefs && (p-1)->offset == offset)
5237			--p;
5238		*pp = p;
5239	}
5240	if (ptrs[0] == NULL)
5241		return 0; /* Not an attribute that affects any slots */
5242	return update_subclasses(type, name,
5243				 update_slots_callback, (void *)ptrs);
5244}
5245
5246/* Store the proper functions in the slot dispatches at class (type)
5247   definition time, based upon which operations the class overrides in its
5248   dict. */
5249static void
5250fixup_slot_dispatchers(PyTypeObject *type)
5251{
5252	slotdef *p;
5253
5254	init_slotdefs();
5255	for (p = slotdefs; p->name; )
5256		p = update_one_slot(type, p);
5257}
5258
5259static void
5260update_all_slots(PyTypeObject* type)
5261{
5262	slotdef *p;
5263
5264	init_slotdefs();
5265	for (p = slotdefs; p->name; p++) {
5266		/* update_slot returns int but can't actually fail */
5267		update_slot(type, p->name_strobj);
5268	}
5269}
5270
5271/* recurse_down_subclasses() and update_subclasses() are mutually
5272   recursive functions to call a callback for all subclasses,
5273   but refraining from recursing into subclasses that define 'name'. */
5274
5275static int
5276update_subclasses(PyTypeObject *type, PyObject *name,
5277		  update_callback callback, void *data)
5278{
5279	if (callback(type, data) < 0)
5280		return -1;
5281	return recurse_down_subclasses(type, name, callback, data);
5282}
5283
5284static int
5285recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5286			update_callback callback, void *data)
5287{
5288	PyTypeObject *subclass;
5289	PyObject *ref, *subclasses, *dict;
5290	int i, n;
5291
5292	subclasses = type->tp_subclasses;
5293	if (subclasses == NULL)
5294		return 0;
5295	assert(PyList_Check(subclasses));
5296	n = PyList_GET_SIZE(subclasses);
5297	for (i = 0; i < n; i++) {
5298		ref = PyList_GET_ITEM(subclasses, i);
5299		assert(PyWeakref_CheckRef(ref));
5300		subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5301		assert(subclass != NULL);
5302		if ((PyObject *)subclass == Py_None)
5303			continue;
5304		assert(PyType_Check(subclass));
5305		/* Avoid recursing down into unaffected classes */
5306		dict = subclass->tp_dict;
5307		if (dict != NULL && PyDict_Check(dict) &&
5308		    PyDict_GetItem(dict, name) != NULL)
5309			continue;
5310		if (update_subclasses(subclass, name, callback, data) < 0)
5311			return -1;
5312	}
5313	return 0;
5314}
5315
5316/* This function is called by PyType_Ready() to populate the type's
5317   dictionary with method descriptors for function slots.  For each
5318   function slot (like tp_repr) that's defined in the type, one or more
5319   corresponding descriptors are added in the type's tp_dict dictionary
5320   under the appropriate name (like __repr__).  Some function slots
5321   cause more than one descriptor to be added (for example, the nb_add
5322   slot adds both __add__ and __radd__ descriptors) and some function
5323   slots compete for the same descriptor (for example both sq_item and
5324   mp_subscript generate a __getitem__ descriptor).
5325
5326   In the latter case, the first slotdef entry encoutered wins.  Since
5327   slotdef entries are sorted by the offset of the slot in the
5328   PyHeapTypeObject, this gives us some control over disambiguating
5329   between competing slots: the members of PyHeapTypeObject are listed
5330   from most general to least general, so the most general slot is
5331   preferred.  In particular, because as_mapping comes before as_sequence,
5332   for a type that defines both mp_subscript and sq_item, mp_subscript
5333   wins.
5334
5335   This only adds new descriptors and doesn't overwrite entries in
5336   tp_dict that were previously defined.  The descriptors contain a
5337   reference to the C function they must call, so that it's safe if they
5338   are copied into a subtype's __dict__ and the subtype has a different
5339   C function in its slot -- calling the method defined by the
5340   descriptor will call the C function that was used to create it,
5341   rather than the C function present in the slot when it is called.
5342   (This is important because a subtype may have a C function in the
5343   slot that calls the method from the dictionary, and we want to avoid
5344   infinite recursion here.) */
5345
5346static int
5347add_operators(PyTypeObject *type)
5348{
5349	PyObject *dict = type->tp_dict;
5350	slotdef *p;
5351	PyObject *descr;
5352	void **ptr;
5353
5354	init_slotdefs();
5355	for (p = slotdefs; p->name; p++) {
5356		if (p->wrapper == NULL)
5357			continue;
5358		ptr = slotptr(type, p->offset);
5359		if (!ptr || !*ptr)
5360			continue;
5361		if (PyDict_GetItem(dict, p->name_strobj))
5362			continue;
5363		descr = PyDescr_NewWrapper(type, p, *ptr);
5364		if (descr == NULL)
5365			return -1;
5366		if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5367			return -1;
5368		Py_DECREF(descr);
5369	}
5370	if (type->tp_new != NULL) {
5371		if (add_tp_new_wrapper(type) < 0)
5372			return -1;
5373	}
5374	return 0;
5375}
5376
5377
5378/* Cooperative 'super' */
5379
5380typedef struct {
5381	PyObject_HEAD
5382	PyTypeObject *type;
5383	PyObject *obj;
5384	PyTypeObject *obj_type;
5385} superobject;
5386
5387static PyMemberDef super_members[] = {
5388	{"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5389	 "the class invoking super()"},
5390	{"__self__",  T_OBJECT, offsetof(superobject, obj), READONLY,
5391	 "the instance invoking super(); may be None"},
5392	{"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5393	 "the type of the the instance invoking super(); may be None"},
5394	{0}
5395};
5396
5397static void
5398super_dealloc(PyObject *self)
5399{
5400	superobject *su = (superobject *)self;
5401
5402	_PyObject_GC_UNTRACK(self);
5403	Py_XDECREF(su->obj);
5404	Py_XDECREF(su->type);
5405	Py_XDECREF(su->obj_type);
5406	self->ob_type->tp_free(self);
5407}
5408
5409static PyObject *
5410super_repr(PyObject *self)
5411{
5412	superobject *su = (superobject *)self;
5413
5414	if (su->obj_type)
5415		return PyString_FromFormat(
5416			"<super: <class '%s'>, <%s object>>",
5417			su->type ? su->type->tp_name : "NULL",
5418			su->obj_type->tp_name);
5419	else
5420		return PyString_FromFormat(
5421			"<super: <class '%s'>, NULL>",
5422			su->type ? su->type->tp_name : "NULL");
5423}
5424
5425static PyObject *
5426super_getattro(PyObject *self, PyObject *name)
5427{
5428	superobject *su = (superobject *)self;
5429	int skip = su->obj_type == NULL;
5430
5431	if (!skip) {
5432		/* We want __class__ to return the class of the super object
5433		   (i.e. super, or a subclass), not the class of su->obj. */
5434		skip = (PyString_Check(name) &&
5435			PyString_GET_SIZE(name) == 9 &&
5436			strcmp(PyString_AS_STRING(name), "__class__") == 0);
5437	}
5438
5439	if (!skip) {
5440		PyObject *mro, *res, *tmp, *dict;
5441		PyTypeObject *starttype;
5442		descrgetfunc f;
5443		int i, n;
5444
5445		starttype = su->obj_type;
5446		mro = starttype->tp_mro;
5447
5448		if (mro == NULL)
5449			n = 0;
5450		else {
5451			assert(PyTuple_Check(mro));
5452			n = PyTuple_GET_SIZE(mro);
5453		}
5454		for (i = 0; i < n; i++) {
5455			if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
5456				break;
5457		}
5458		i++;
5459		res = NULL;
5460		for (; i < n; i++) {
5461			tmp = PyTuple_GET_ITEM(mro, i);
5462			if (PyType_Check(tmp))
5463				dict = ((PyTypeObject *)tmp)->tp_dict;
5464			else if (PyClass_Check(tmp))
5465				dict = ((PyClassObject *)tmp)->cl_dict;
5466			else
5467				continue;
5468			res = PyDict_GetItem(dict, name);
5469			if (res != NULL) {
5470				Py_INCREF(res);
5471				f = res->ob_type->tp_descr_get;
5472				if (f != NULL) {
5473					tmp = f(res, su->obj,
5474						(PyObject *)starttype);
5475					Py_DECREF(res);
5476					res = tmp;
5477				}
5478				return res;
5479			}
5480		}
5481	}
5482	return PyObject_GenericGetAttr(self, name);
5483}
5484
5485static PyTypeObject *
5486supercheck(PyTypeObject *type, PyObject *obj)
5487{
5488	/* Check that a super() call makes sense.  Return a type object.
5489
5490	   obj can be a new-style class, or an instance of one:
5491
5492	   - If it is a class, it must be a subclass of 'type'.  This case is
5493	     used for class methods; the return value is obj.
5494
5495	   - If it is an instance, it must be an instance of 'type'.  This is
5496	     the normal case; the return value is obj.__class__.
5497
5498	   But... when obj is an instance, we want to allow for the case where
5499	   obj->ob_type is not a subclass of type, but obj.__class__ is!
5500	   This will allow using super() with a proxy for obj.
5501	*/
5502
5503	/* Check for first bullet above (special case) */
5504	if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5505		Py_INCREF(obj);
5506		return (PyTypeObject *)obj;
5507	}
5508
5509	/* Normal case */
5510	if (PyType_IsSubtype(obj->ob_type, type)) {
5511		Py_INCREF(obj->ob_type);
5512		return obj->ob_type;
5513	}
5514	else {
5515		/* Try the slow way */
5516		static PyObject *class_str = NULL;
5517		PyObject *class_attr;
5518
5519		if (class_str == NULL) {
5520			class_str = PyString_FromString("__class__");
5521			if (class_str == NULL)
5522				return NULL;
5523		}
5524
5525		class_attr = PyObject_GetAttr(obj, class_str);
5526
5527		if (class_attr != NULL &&
5528		    PyType_Check(class_attr) &&
5529		    (PyTypeObject *)class_attr != obj->ob_type)
5530		{
5531			int ok = PyType_IsSubtype(
5532				(PyTypeObject *)class_attr, type);
5533			if (ok)
5534				return (PyTypeObject *)class_attr;
5535		}
5536
5537		if (class_attr == NULL)
5538			PyErr_Clear();
5539		else
5540			Py_DECREF(class_attr);
5541	}
5542
5543  	PyErr_SetString(PyExc_TypeError,
5544			"super(type, obj): "
5545			"obj must be an instance or subtype of type");
5546	return NULL;
5547}
5548
5549static PyObject *
5550super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5551{
5552	superobject *su = (superobject *)self;
5553	superobject *new;
5554
5555	if (obj == NULL || obj == Py_None || su->obj != NULL) {
5556		/* Not binding to an object, or already bound */
5557		Py_INCREF(self);
5558		return self;
5559	}
5560	if (su->ob_type != &PySuper_Type)
5561		/* If su is not an instance of a subclass of super,
5562		   call its type */
5563		return PyObject_CallFunction((PyObject *)su->ob_type,
5564					     "OO", su->type, obj);
5565	else {
5566		/* Inline the common case */
5567		PyTypeObject *obj_type = supercheck(su->type, obj);
5568		if (obj_type == NULL)
5569			return NULL;
5570		new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5571							 NULL, NULL);
5572		if (new == NULL)
5573			return NULL;
5574		Py_INCREF(su->type);
5575		Py_INCREF(obj);
5576		new->type = su->type;
5577		new->obj = obj;
5578		new->obj_type = obj_type;
5579		return (PyObject *)new;
5580	}
5581}
5582
5583static int
5584super_init(PyObject *self, PyObject *args, PyObject *kwds)
5585{
5586	superobject *su = (superobject *)self;
5587	PyTypeObject *type;
5588	PyObject *obj = NULL;
5589	PyTypeObject *obj_type = NULL;
5590
5591	if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5592		return -1;
5593	if (obj == Py_None)
5594		obj = NULL;
5595	if (obj != NULL) {
5596		obj_type = supercheck(type, obj);
5597		if (obj_type == NULL)
5598			return -1;
5599		Py_INCREF(obj);
5600	}
5601	Py_INCREF(type);
5602	su->type = type;
5603	su->obj = obj;
5604	su->obj_type = obj_type;
5605	return 0;
5606}
5607
5608PyDoc_STRVAR(super_doc,
5609"super(type) -> unbound super object\n"
5610"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
5611"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
5612"Typical use to call a cooperative superclass method:\n"
5613"class C(B):\n"
5614"    def meth(self, arg):\n"
5615"        super(C, self).meth(arg)");
5616
5617static int
5618super_traverse(PyObject *self, visitproc visit, void *arg)
5619{
5620	superobject *su = (superobject *)self;
5621	int err;
5622
5623#define VISIT(SLOT) \
5624	if (SLOT) { \
5625		err = visit((PyObject *)(SLOT), arg); \
5626		if (err) \
5627			return err; \
5628	}
5629
5630	VISIT(su->obj);
5631	VISIT(su->type);
5632	VISIT(su->obj_type);
5633
5634#undef VISIT
5635
5636	return 0;
5637}
5638
5639PyTypeObject PySuper_Type = {
5640	PyObject_HEAD_INIT(&PyType_Type)
5641	0,					/* ob_size */
5642	"super",				/* tp_name */
5643	sizeof(superobject),			/* tp_basicsize */
5644	0,					/* tp_itemsize */
5645	/* methods */
5646	super_dealloc,		 		/* tp_dealloc */
5647	0,					/* tp_print */
5648	0,					/* tp_getattr */
5649	0,					/* tp_setattr */
5650	0,					/* tp_compare */
5651	super_repr,				/* tp_repr */
5652	0,					/* tp_as_number */
5653	0,					/* tp_as_sequence */
5654	0,		       			/* tp_as_mapping */
5655	0,					/* tp_hash */
5656	0,					/* tp_call */
5657	0,					/* tp_str */
5658	super_getattro,				/* tp_getattro */
5659	0,					/* tp_setattro */
5660	0,					/* tp_as_buffer */
5661	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5662		Py_TPFLAGS_BASETYPE,		/* tp_flags */
5663 	super_doc,				/* tp_doc */
5664 	super_traverse,				/* tp_traverse */
5665 	0,					/* tp_clear */
5666	0,					/* tp_richcompare */
5667	0,					/* tp_weaklistoffset */
5668	0,					/* tp_iter */
5669	0,					/* tp_iternext */
5670	0,					/* tp_methods */
5671	super_members,				/* tp_members */
5672	0,					/* tp_getset */
5673	0,					/* tp_base */
5674	0,					/* tp_dict */
5675	super_descr_get,			/* tp_descr_get */
5676	0,					/* tp_descr_set */
5677	0,					/* tp_dictoffset */
5678	super_init,				/* tp_init */
5679	PyType_GenericAlloc,			/* tp_alloc */
5680	PyType_GenericNew,			/* tp_new */
5681	PyObject_GC_Del,        		/* tp_free */
5682};
5683