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