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