blob: 518d6e8e05241d660ec8771c2e8dde6f5d56862a [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00008
9/* Support type attribute cache */
10
11/* The cache can keep references to the names alive for longer than
12 they normally would. This is why the maximum size is limited to
13 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
14 strings are used as attribute names. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000015#define MCACHE_MAX_ATTR_SIZE 100
16#define MCACHE_SIZE_EXP 10
17#define MCACHE_HASH(version, name_hash) \
18 (((unsigned int)(version) * (unsigned int)(name_hash)) \
19 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000020#define MCACHE_HASH_METHOD(type, name) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +000021 MCACHE_HASH((type)->tp_version_tag, \
22 ((PyStringObject *)(name))->ob_shash)
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000023#define MCACHE_CACHEABLE_NAME(name) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +000024 PyString_CheckExact(name) && \
25 PyString_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000026
27struct method_cache_entry {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000028 unsigned int version;
29 PyObject *name; /* reference to exactly a str or None */
30 PyObject *value; /* borrowed */
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000031};
32
33static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
34static unsigned int next_version_tag = 0;
Christian Heimes908caac2008-01-27 23:34:59 +000035
36unsigned int
37PyType_ClearCache(void)
38{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000039 Py_ssize_t i;
40 unsigned int cur_version_tag = next_version_tag - 1;
Brett Cannon8a478ce2010-05-05 20:19:26 +000041
Antoine Pitrouc83ea132010-05-09 14:46:46 +000042 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
43 method_cache[i].version = 0;
44 Py_CLEAR(method_cache[i].name);
45 method_cache[i].value = NULL;
46 }
47 next_version_tag = 0;
48 /* mark all version tags as invalid */
49 PyType_Modified(&PyBaseObject_Type);
50 return cur_version_tag;
Christian Heimes908caac2008-01-27 23:34:59 +000051}
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000052
Georg Brandl74a1dea2008-05-28 11:21:39 +000053void
54PyType_Modified(PyTypeObject *type)
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000055{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000056 /* Invalidate any cached data for the specified type and all
57 subclasses. This function is called after the base
58 classes, mro, or attributes of the type are altered.
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000059
Antoine Pitrouc83ea132010-05-09 14:46:46 +000060 Invariants:
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000061
Antoine Pitrouc83ea132010-05-09 14:46:46 +000062 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
63 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
64 objects coming from non-recompiled extension modules)
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000065
Antoine Pitrouc83ea132010-05-09 14:46:46 +000066 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
67 it must first be set on all super types.
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000068
Antoine Pitrouc83ea132010-05-09 14:46:46 +000069 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
70 type (so it must first clear it on all subclasses). The
71 tp_version_tag value is meaningless unless this flag is set.
72 We don't assign new version tags eagerly, but only as
73 needed.
74 */
75 PyObject *raw, *ref;
76 Py_ssize_t i, n;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000077
Antoine Pitrouc83ea132010-05-09 14:46:46 +000078 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
79 return;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000080
Antoine Pitrouc83ea132010-05-09 14:46:46 +000081 raw = type->tp_subclasses;
82 if (raw != NULL) {
83 n = PyList_GET_SIZE(raw);
84 for (i = 0; i < n; i++) {
85 ref = PyList_GET_ITEM(raw, i);
86 ref = PyWeakref_GET_OBJECT(ref);
87 if (ref != Py_None) {
88 PyType_Modified((PyTypeObject *)ref);
89 }
90 }
91 }
92 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000093}
94
95static void
96type_mro_modified(PyTypeObject *type, PyObject *bases) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000097 /*
98 Check that all base classes or elements of the mro of type are
99 able to be cached. This function is called after the base
100 classes or mro of the type are altered.
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000101
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000102 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
103 inherits from an old-style class, either directly or if it
104 appears in the MRO of a new-style class. No support either for
105 custom MROs that include types that are not officially super
106 types.
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000107
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000108 Called from mro_internal, which will subsequently be called on
109 each subclass when their mro is recursively updated.
110 */
111 Py_ssize_t i, n;
112 int clear = 0;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000113
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000114 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
115 return;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000116
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000117 n = PyTuple_GET_SIZE(bases);
118 for (i = 0; i < n; i++) {
119 PyObject *b = PyTuple_GET_ITEM(bases, i);
120 PyTypeObject *cls;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000121
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000122 if (!PyType_Check(b) ) {
123 clear = 1;
124 break;
125 }
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000126
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000127 cls = (PyTypeObject *)b;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000128
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000129 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
130 !PyType_IsSubtype(type, cls)) {
131 clear = 1;
132 break;
133 }
134 }
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000135
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000136 if (clear)
137 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
138 Py_TPFLAGS_VALID_VERSION_TAG);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000139}
140
141static int
142assign_version_tag(PyTypeObject *type)
143{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000144 /* Ensure that the tp_version_tag is valid and set
145 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
146 must first be done on all super classes. Return 0 if this
147 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
148 */
149 Py_ssize_t i, n;
150 PyObject *bases;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000151
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000152 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
153 return 1;
154 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
155 return 0;
156 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
157 return 0;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000158
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000159 type->tp_version_tag = next_version_tag++;
160 /* for stress-testing: next_version_tag &= 0xFF; */
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000161
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000162 if (type->tp_version_tag == 0) {
163 /* wrap-around or just starting Python - clear the whole
164 cache by filling names with references to Py_None.
165 Values are also set to NULL for added protection, as they
166 are borrowed reference */
167 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
168 method_cache[i].value = NULL;
169 Py_XDECREF(method_cache[i].name);
170 method_cache[i].name = Py_None;
171 Py_INCREF(Py_None);
172 }
173 /* mark all version tags as invalid */
174 PyType_Modified(&PyBaseObject_Type);
175 return 1;
176 }
177 bases = type->tp_bases;
178 n = PyTuple_GET_SIZE(bases);
179 for (i = 0; i < n; i++) {
180 PyObject *b = PyTuple_GET_ITEM(bases, i);
181 assert(PyType_Check(b));
182 if (!assign_version_tag((PyTypeObject *)b))
183 return 0;
184 }
185 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
186 return 1;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000187}
188
189
Guido van Rossum6f799372001-09-20 20:46:19 +0000190static PyMemberDef type_members[] = {
Benjamin Peterson6f3d6a92010-08-25 23:17:42 +0000191 {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
192 {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000193 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
194 {"__weakrefoffset__", T_LONG,
195 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
196 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
197 {"__dictoffset__", T_LONG,
198 offsetof(PyTypeObject, tp_dictoffset), READONLY},
199 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
200 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000201};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000202
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000203static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000204type_name(PyTypeObject *type, void *context)
205{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000206 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000207
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000208 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
209 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000210
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000211 Py_INCREF(et->ht_name);
212 return et->ht_name;
213 }
214 else {
215 s = strrchr(type->tp_name, '.');
216 if (s == NULL)
217 s = type->tp_name;
218 else
219 s++;
220 return PyString_FromString(s);
221 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000222}
223
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000224static int
225type_set_name(PyTypeObject *type, PyObject *value, void *context)
226{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000227 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000228
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000229 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
230 PyErr_Format(PyExc_TypeError,
231 "can't set %s.__name__", type->tp_name);
232 return -1;
233 }
234 if (!value) {
235 PyErr_Format(PyExc_TypeError,
236 "can't delete %s.__name__", type->tp_name);
237 return -1;
238 }
239 if (!PyString_Check(value)) {
240 PyErr_Format(PyExc_TypeError,
241 "can only assign string to %s.__name__, not '%s'",
242 type->tp_name, Py_TYPE(value)->tp_name);
243 return -1;
244 }
245 if (strlen(PyString_AS_STRING(value))
246 != (size_t)PyString_GET_SIZE(value)) {
247 PyErr_Format(PyExc_ValueError,
248 "__name__ must not contain null bytes");
249 return -1;
250 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000251
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000252 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000253
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000254 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000255
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000256 Py_DECREF(et->ht_name);
257 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000258
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000259 type->tp_name = PyString_AS_STRING(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000260
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000261 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000262}
263
Guido van Rossumc3542212001-08-16 09:18:56 +0000264static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000265type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000266{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000267 PyObject *mod;
268 char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000269
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000270 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
271 mod = PyDict_GetItemString(type->tp_dict, "__module__");
272 if (!mod) {
273 PyErr_Format(PyExc_AttributeError, "__module__");
274 return 0;
275 }
276 Py_XINCREF(mod);
277 return mod;
278 }
279 else {
280 s = strrchr(type->tp_name, '.');
281 if (s != NULL)
282 return PyString_FromStringAndSize(
283 type->tp_name, (Py_ssize_t)(s - type->tp_name));
284 return PyString_FromString("__builtin__");
285 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000286}
287
Guido van Rossum3926a632001-09-25 16:25:58 +0000288static int
289type_set_module(PyTypeObject *type, PyObject *value, void *context)
290{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000291 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
292 PyErr_Format(PyExc_TypeError,
293 "can't set %s.__module__", type->tp_name);
294 return -1;
295 }
296 if (!value) {
297 PyErr_Format(PyExc_TypeError,
298 "can't delete %s.__module__", type->tp_name);
299 return -1;
300 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000301
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000302 PyType_Modified(type);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000303
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000304 return PyDict_SetItemString(type->tp_dict, "__module__", value);
Guido van Rossum3926a632001-09-25 16:25:58 +0000305}
306
Tim Peters6d6c1a32001-08-02 04:15:00 +0000307static PyObject *
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +0000308type_abstractmethods(PyTypeObject *type, void *context)
309{
Benjamin Petersona5d5cc42010-10-02 00:08:58 +0000310 PyObject *mod = NULL;
Benjamin Peterson35c6be02010-10-03 02:17:04 +0000311 /* type itself has an __abstractmethods__ descriptor (this). Don't return
312 that. */
Benjamin Petersona5d5cc42010-10-02 00:08:58 +0000313 if (type != &PyType_Type)
314 mod = PyDict_GetItemString(type->tp_dict, "__abstractmethods__");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000315 if (!mod) {
Benjamin Petersonf4676b02011-01-12 19:00:37 +0000316 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000317 return NULL;
318 }
319 Py_XINCREF(mod);
320 return mod;
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +0000321}
322
323static int
324type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
325{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000326 /* __abstractmethods__ should only be set once on a type, in
327 abc.ABCMeta.__new__, so this function doesn't do anything
328 special to update subclasses.
329 */
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200330 int abstract, res;
Benjamin Peterson9b911ca2011-01-12 15:49:47 +0000331 if (value != NULL) {
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200332 abstract = PyObject_IsTrue(value);
333 if (abstract < 0)
334 return -1;
Benjamin Peterson9b911ca2011-01-12 15:49:47 +0000335 res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
336 }
337 else {
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200338 abstract = 0;
Benjamin Peterson9b911ca2011-01-12 15:49:47 +0000339 res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
340 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Benjamin Petersonf4676b02011-01-12 19:00:37 +0000341 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Benjamin Peterson9b911ca2011-01-12 15:49:47 +0000342 return -1;
343 }
344 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000345 if (res == 0) {
346 PyType_Modified(type);
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200347 if (abstract)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000348 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200349 else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000350 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000351 }
352 return res;
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +0000353}
354
355static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000356type_get_bases(PyTypeObject *type, void *context)
357{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000358 Py_INCREF(type->tp_bases);
359 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000360}
361
362static PyTypeObject *best_base(PyObject *);
363static int mro_internal(PyTypeObject *);
364static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
365static int add_subclass(PyTypeObject*, PyTypeObject*);
366static void remove_subclass(PyTypeObject *, PyTypeObject *);
367static void update_all_slots(PyTypeObject *);
368
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000369typedef int (*update_callback)(PyTypeObject *, void *);
370static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000371 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000372static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000373 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000374
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000375static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000376mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000377{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000378 PyTypeObject *subclass;
379 PyObject *ref, *subclasses, *old_mro;
380 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000381
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000382 subclasses = type->tp_subclasses;
383 if (subclasses == NULL)
384 return 0;
385 assert(PyList_Check(subclasses));
386 n = PyList_GET_SIZE(subclasses);
387 for (i = 0; i < n; i++) {
388 ref = PyList_GET_ITEM(subclasses, i);
389 assert(PyWeakref_CheckRef(ref));
390 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
391 assert(subclass != NULL);
392 if ((PyObject *)subclass == Py_None)
393 continue;
394 assert(PyType_Check(subclass));
395 old_mro = subclass->tp_mro;
396 if (mro_internal(subclass) < 0) {
397 subclass->tp_mro = old_mro;
398 return -1;
399 }
400 else {
401 PyObject* tuple;
402 tuple = PyTuple_Pack(2, subclass, old_mro);
403 Py_DECREF(old_mro);
404 if (!tuple)
405 return -1;
406 if (PyList_Append(temp, tuple) < 0)
407 return -1;
408 Py_DECREF(tuple);
409 }
410 if (mro_subclasses(subclass, temp) < 0)
411 return -1;
412 }
413 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000414}
415
416static int
417type_set_bases(PyTypeObject *type, PyObject *value, void *context)
418{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000419 Py_ssize_t i;
420 int r = 0;
421 PyObject *ob, *temp;
422 PyTypeObject *new_base, *old_base;
423 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000424
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000425 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
426 PyErr_Format(PyExc_TypeError,
427 "can't set %s.__bases__", type->tp_name);
428 return -1;
429 }
430 if (!value) {
431 PyErr_Format(PyExc_TypeError,
432 "can't delete %s.__bases__", type->tp_name);
433 return -1;
434 }
435 if (!PyTuple_Check(value)) {
436 PyErr_Format(PyExc_TypeError,
437 "can only assign tuple to %s.__bases__, not %s",
438 type->tp_name, Py_TYPE(value)->tp_name);
439 return -1;
440 }
441 if (PyTuple_GET_SIZE(value) == 0) {
442 PyErr_Format(PyExc_TypeError,
443 "can only assign non-empty tuple to %s.__bases__, not ()",
444 type->tp_name);
445 return -1;
446 }
447 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
448 ob = PyTuple_GET_ITEM(value, i);
449 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
450 PyErr_Format(
451 PyExc_TypeError,
452 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
453 type->tp_name, Py_TYPE(ob)->tp_name);
454 return -1;
455 }
456 if (PyType_Check(ob)) {
457 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
458 PyErr_SetString(PyExc_TypeError,
459 "a __bases__ item causes an inheritance cycle");
460 return -1;
461 }
462 }
463 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000464
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000465 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000466
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000467 if (!new_base) {
468 return -1;
469 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000470
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000471 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
472 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000473
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000474 Py_INCREF(new_base);
475 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000476
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000477 old_bases = type->tp_bases;
478 old_base = type->tp_base;
479 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000480
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000481 type->tp_bases = value;
482 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000483
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000484 if (mro_internal(type) < 0) {
485 goto bail;
486 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000487
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000488 temp = PyList_New(0);
489 if (!temp)
490 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000491
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000492 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000493
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000494 if (r < 0) {
495 for (i = 0; i < PyList_Size(temp); i++) {
496 PyTypeObject* cls;
497 PyObject* mro;
498 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
499 "", 2, 2, &cls, &mro);
500 Py_INCREF(mro);
501 ob = cls->tp_mro;
502 cls->tp_mro = mro;
503 Py_DECREF(ob);
504 }
505 Py_DECREF(temp);
506 goto bail;
507 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000508
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000509 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000510
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000511 /* any base that was in __bases__ but now isn't, we
512 need to remove |type| from its tp_subclasses.
513 conversely, any class now in __bases__ that wasn't
514 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000515
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000516 /* for now, sod that: just remove from all old_bases,
517 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000518
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000519 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
520 ob = PyTuple_GET_ITEM(old_bases, i);
521 if (PyType_Check(ob)) {
522 remove_subclass(
523 (PyTypeObject*)ob, type);
524 }
525 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000526
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000527 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
528 ob = PyTuple_GET_ITEM(value, i);
529 if (PyType_Check(ob)) {
530 if (add_subclass((PyTypeObject*)ob, type) < 0)
531 r = -1;
532 }
533 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000534
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000535 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000536
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000537 Py_DECREF(old_bases);
538 Py_DECREF(old_base);
539 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000540
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000541 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000542
543 bail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000544 Py_DECREF(type->tp_bases);
545 Py_DECREF(type->tp_base);
546 if (type->tp_mro != old_mro) {
547 Py_DECREF(type->tp_mro);
548 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000549
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000550 type->tp_bases = old_bases;
551 type->tp_base = old_base;
552 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000553
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000554 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000555}
556
557static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000558type_dict(PyTypeObject *type, void *context)
559{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000560 if (type->tp_dict == NULL) {
561 Py_INCREF(Py_None);
562 return Py_None;
563 }
564 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000565}
566
Tim Peters24008312002-03-17 18:56:20 +0000567static PyObject *
568type_get_doc(PyTypeObject *type, void *context)
569{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000570 PyObject *result;
571 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
572 return PyString_FromString(type->tp_doc);
573 result = PyDict_GetItemString(type->tp_dict, "__doc__");
574 if (result == NULL) {
575 result = Py_None;
576 Py_INCREF(result);
577 }
578 else if (Py_TYPE(result)->tp_descr_get) {
579 result = Py_TYPE(result)->tp_descr_get(result, NULL,
580 (PyObject *)type);
581 }
582 else {
583 Py_INCREF(result);
584 }
585 return result;
Tim Peters24008312002-03-17 18:56:20 +0000586}
587
Antoine Pitrou0668c622008-08-26 22:42:08 +0000588static PyObject *
589type___instancecheck__(PyObject *type, PyObject *inst)
590{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000591 switch (_PyObject_RealIsInstance(inst, type)) {
592 case -1:
593 return NULL;
594 case 0:
595 Py_RETURN_FALSE;
596 default:
597 Py_RETURN_TRUE;
598 }
Antoine Pitrou0668c622008-08-26 22:42:08 +0000599}
600
601
602static PyObject *
Antoine Pitrou0668c622008-08-26 22:42:08 +0000603type___subclasscheck__(PyObject *type, PyObject *inst)
604{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000605 switch (_PyObject_RealIsSubclass(inst, type)) {
606 case -1:
607 return NULL;
608 case 0:
609 Py_RETURN_FALSE;
610 default:
611 Py_RETURN_TRUE;
612 }
Antoine Pitrou0668c622008-08-26 22:42:08 +0000613}
614
Antoine Pitrou0668c622008-08-26 22:42:08 +0000615
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000616static PyGetSetDef type_getsets[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000617 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
618 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
619 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
620 {"__abstractmethods__", (getter)type_abstractmethods,
621 (setter)type_set_abstractmethods, NULL},
622 {"__dict__", (getter)type_dict, NULL, NULL},
623 {"__doc__", (getter)type_get_doc, NULL, NULL},
624 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000625};
626
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000627
Steven Bethardae42f332008-03-18 17:26:10 +0000628static PyObject*
629type_richcompare(PyObject *v, PyObject *w, int op)
630{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000631 PyObject *result;
632 Py_uintptr_t vv, ww;
633 int c;
Steven Bethardae42f332008-03-18 17:26:10 +0000634
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000635 /* Make sure both arguments are types. */
636 if (!PyType_Check(v) || !PyType_Check(w) ||
637 /* If there is a __cmp__ method defined, let it be called instead
638 of our dumb function designed merely to warn. See bug
639 #7491. */
640 Py_TYPE(v)->tp_compare || Py_TYPE(w)->tp_compare) {
641 result = Py_NotImplemented;
642 goto out;
643 }
Steven Bethardae42f332008-03-18 17:26:10 +0000644
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000645 /* Py3K warning if comparison isn't == or != */
646 if (Py_Py3kWarningFlag && op != Py_EQ && op != Py_NE &&
647 PyErr_WarnEx(PyExc_DeprecationWarning,
648 "type inequality comparisons not supported "
649 "in 3.x", 1) < 0) {
650 return NULL;
651 }
Steven Bethardae42f332008-03-18 17:26:10 +0000652
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000653 /* Compare addresses */
654 vv = (Py_uintptr_t)v;
655 ww = (Py_uintptr_t)w;
656 switch (op) {
657 case Py_LT: c = vv < ww; break;
658 case Py_LE: c = vv <= ww; break;
659 case Py_EQ: c = vv == ww; break;
660 case Py_NE: c = vv != ww; break;
661 case Py_GT: c = vv > ww; break;
662 case Py_GE: c = vv >= ww; break;
663 default:
664 result = Py_NotImplemented;
665 goto out;
666 }
667 result = c ? Py_True : Py_False;
Steven Bethardae42f332008-03-18 17:26:10 +0000668
669 /* incref and return */
670 out:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000671 Py_INCREF(result);
672 return result;
Steven Bethardae42f332008-03-18 17:26:10 +0000673}
674
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000675static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000676type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000677{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000678 PyObject *mod, *name, *rtn;
679 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000680
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000681 mod = type_module(type, NULL);
682 if (mod == NULL)
683 PyErr_Clear();
684 else if (!PyString_Check(mod)) {
685 Py_DECREF(mod);
686 mod = NULL;
687 }
688 name = type_name(type, NULL);
Christian Heimes4e80eea2012-09-10 03:00:14 +0200689 if (name == NULL) {
690 Py_XDECREF(mod);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000691 return NULL;
Christian Heimes4e80eea2012-09-10 03:00:14 +0200692 }
Barry Warsaw7ce36942001-08-24 18:34:26 +0000693
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000694 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
695 kind = "class";
696 else
697 kind = "type";
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000698
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000699 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
700 rtn = PyString_FromFormat("<%s '%s.%s'>",
701 kind,
702 PyString_AS_STRING(mod),
703 PyString_AS_STRING(name));
704 }
705 else
706 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000707
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000708 Py_XDECREF(mod);
709 Py_DECREF(name);
710 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000711}
712
Tim Peters6d6c1a32001-08-02 04:15:00 +0000713static PyObject *
714type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
715{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000716 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000717
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000718 if (type->tp_new == NULL) {
719 PyErr_Format(PyExc_TypeError,
720 "cannot create '%.100s' instances",
721 type->tp_name);
722 return NULL;
723 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000724
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000725 obj = type->tp_new(type, args, kwds);
726 if (obj != NULL) {
727 /* Ugly exception: when the call was type(something),
728 don't call tp_init on the result. */
729 if (type == &PyType_Type &&
730 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
731 (kwds == NULL ||
732 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
733 return obj;
734 /* If the returned object is not an instance of type,
735 it won't be initialized. */
736 if (!PyType_IsSubtype(obj->ob_type, type))
737 return obj;
738 type = obj->ob_type;
739 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
740 type->tp_init != NULL &&
741 type->tp_init(obj, args, kwds) < 0) {
742 Py_DECREF(obj);
743 obj = NULL;
744 }
745 }
746 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000747}
748
749PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000750PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000751{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000752 PyObject *obj;
753 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
754 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000755
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000756 if (PyType_IS_GC(type))
757 obj = _PyObject_GC_Malloc(size);
758 else
759 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000760
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000761 if (obj == NULL)
762 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000763
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000764 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000765
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000766 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
767 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000768
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000769 if (type->tp_itemsize == 0)
770 PyObject_INIT(obj, type);
771 else
772 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000773
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000774 if (PyType_IS_GC(type))
775 _PyObject_GC_TRACK(obj);
776 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000777}
778
779PyObject *
780PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
781{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000782 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000783}
784
Guido van Rossum9475a232001-10-05 20:51:39 +0000785/* Helpers for subtyping */
786
787static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000788traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
789{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000790 Py_ssize_t i, n;
791 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000792
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000793 n = Py_SIZE(type);
794 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
795 for (i = 0; i < n; i++, mp++) {
796 if (mp->type == T_OBJECT_EX) {
797 char *addr = (char *)self + mp->offset;
798 PyObject *obj = *(PyObject **)addr;
799 if (obj != NULL) {
800 int err = visit(obj, arg);
801 if (err)
802 return err;
803 }
804 }
805 }
806 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000807}
808
809static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000810subtype_traverse(PyObject *self, visitproc visit, void *arg)
811{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000812 PyTypeObject *type, *base;
813 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000814
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000815 /* Find the nearest base with a different tp_traverse,
816 and traverse slots while we're at it */
817 type = Py_TYPE(self);
818 base = type;
819 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
820 if (Py_SIZE(base)) {
821 int err = traverse_slots(base, self, visit, arg);
822 if (err)
823 return err;
824 }
825 base = base->tp_base;
826 assert(base);
827 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000828
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000829 if (type->tp_dictoffset != base->tp_dictoffset) {
830 PyObject **dictptr = _PyObject_GetDictPtr(self);
831 if (dictptr && *dictptr)
832 Py_VISIT(*dictptr);
833 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000834
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000835 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
836 /* For a heaptype, the instances count as references
837 to the type. Traverse the type so the collector
838 can find cycles involving this link. */
839 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000840
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000841 if (basetraverse)
842 return basetraverse(self, visit, arg);
843 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000844}
845
846static void
847clear_slots(PyTypeObject *type, PyObject *self)
848{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000849 Py_ssize_t i, n;
850 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000851
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000852 n = Py_SIZE(type);
853 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
854 for (i = 0; i < n; i++, mp++) {
855 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
856 char *addr = (char *)self + mp->offset;
857 PyObject *obj = *(PyObject **)addr;
858 if (obj != NULL) {
859 *(PyObject **)addr = NULL;
860 Py_DECREF(obj);
861 }
862 }
863 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000864}
865
866static int
867subtype_clear(PyObject *self)
868{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000869 PyTypeObject *type, *base;
870 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000871
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000872 /* Find the nearest base with a different tp_clear
873 and clear slots while we're at it */
874 type = Py_TYPE(self);
875 base = type;
876 while ((baseclear = base->tp_clear) == subtype_clear) {
877 if (Py_SIZE(base))
878 clear_slots(base, self);
879 base = base->tp_base;
880 assert(base);
881 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000882
Benjamin Petersona8d45852012-03-07 18:41:11 -0600883 /* Clear the instance dict (if any), to break cycles involving only
884 __dict__ slots (as in the case 'self.__dict__ is self'). */
885 if (type->tp_dictoffset != base->tp_dictoffset) {
886 PyObject **dictptr = _PyObject_GetDictPtr(self);
887 if (dictptr && *dictptr)
888 Py_CLEAR(*dictptr);
889 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000890
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000891 if (baseclear)
892 return baseclear(self);
893 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000894}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000895
896static void
897subtype_dealloc(PyObject *self)
898{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000899 PyTypeObject *type, *base;
900 destructor basedealloc;
Antoine Pitrou58098a72012-09-06 00:59:49 +0200901 PyThreadState *tstate = PyThreadState_GET();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000902
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000903 /* Extract the type; we expect it to be a heap type */
904 type = Py_TYPE(self);
905 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000906
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000907 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000908
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000909 if (!PyType_IS_GC(type)) {
910 /* It's really rare to find a dynamic type that doesn't have
911 GC; it can only happen when deriving from 'object' and not
912 adding any slots or instance variables. This allows
913 certain simplifications: there's no need to call
914 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000915
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000916 /* Maybe call finalizer; exit early if resurrected */
917 if (type->tp_del) {
918 type->tp_del(self);
919 if (self->ob_refcnt > 0)
920 return;
921 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000922
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000923 /* Find the nearest base with a different tp_dealloc */
924 base = type;
925 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
926 assert(Py_SIZE(base) == 0);
927 base = base->tp_base;
928 assert(base);
929 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000930
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000931 /* Extract the type again; tp_del may have changed it */
932 type = Py_TYPE(self);
Benjamin Peterson5083dc52009-04-25 00:41:22 +0000933
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000934 /* Call the base tp_dealloc() */
935 assert(basedealloc);
936 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000937
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000938 /* Can't reference self beyond this point */
939 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000940
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000941 /* Done */
942 return;
943 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000944
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000945 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000946
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000947 /* UnTrack and re-Track around the trashcan macro, alas */
948 /* See explanation at end of function for full disclosure */
949 PyObject_GC_UnTrack(self);
950 ++_PyTrash_delete_nesting;
Antoine Pitrou58098a72012-09-06 00:59:49 +0200951 ++ tstate->trash_delete_nesting;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000952 Py_TRASHCAN_SAFE_BEGIN(self);
953 --_PyTrash_delete_nesting;
Antoine Pitrou58098a72012-09-06 00:59:49 +0200954 -- tstate->trash_delete_nesting;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000955 /* DO NOT restore GC tracking at this point. weakref callbacks
956 * (if any, and whether directly here or indirectly in something we
957 * call) may trigger GC, and if self is tracked at that point, it
958 * will look like trash to GC and GC will try to delete self again.
959 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000960
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000961 /* Find the nearest base with a different tp_dealloc */
962 base = type;
963 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
964 base = base->tp_base;
965 assert(base);
966 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000967
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000968 /* If we added a weaklist, we clear it. Do this *before* calling
969 the finalizer (__del__), clearing slots, or clearing the instance
970 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000971
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000972 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
973 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000974
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000975 /* Maybe call finalizer; exit early if resurrected */
976 if (type->tp_del) {
977 _PyObject_GC_TRACK(self);
978 type->tp_del(self);
979 if (self->ob_refcnt > 0)
980 goto endlabel; /* resurrected */
981 else
982 _PyObject_GC_UNTRACK(self);
983 /* New weakrefs could be created during the finalizer call.
984 If this occurs, clear them out without calling their
985 finalizers since they might rely on part of the object
986 being finalized that has already been destroyed. */
987 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
988 /* Modeled after GET_WEAKREFS_LISTPTR() */
989 PyWeakReference **list = (PyWeakReference **) \
990 PyObject_GET_WEAKREFS_LISTPTR(self);
991 while (*list)
992 _PyWeakref_ClearRef(*list);
993 }
994 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000995
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000996 /* Clear slots up to the nearest base with a different tp_dealloc */
997 base = type;
998 while (base->tp_dealloc == subtype_dealloc) {
999 if (Py_SIZE(base))
1000 clear_slots(base, self);
1001 base = base->tp_base;
1002 assert(base);
1003 }
Guido van Rossum59195fd2003-06-13 20:54:40 +00001004
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001005 /* If we added a dict, DECREF it */
1006 if (type->tp_dictoffset && !base->tp_dictoffset) {
1007 PyObject **dictptr = _PyObject_GetDictPtr(self);
1008 if (dictptr != NULL) {
1009 PyObject *dict = *dictptr;
1010 if (dict != NULL) {
1011 Py_DECREF(dict);
1012 *dictptr = NULL;
1013 }
1014 }
1015 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001016
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001017 /* Extract the type again; tp_del may have changed it */
1018 type = Py_TYPE(self);
Benjamin Peterson5083dc52009-04-25 00:41:22 +00001019
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001020 /* Call the base tp_dealloc(); first retrack self if
1021 * basedealloc knows about gc.
1022 */
1023 if (PyType_IS_GC(base))
1024 _PyObject_GC_TRACK(self);
1025 assert(basedealloc);
1026 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001027
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001028 /* Can't reference self beyond this point */
1029 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001030
Guido van Rossum0906e072002-08-07 20:42:09 +00001031 endlabel:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001032 ++_PyTrash_delete_nesting;
Antoine Pitrou58098a72012-09-06 00:59:49 +02001033 ++ tstate->trash_delete_nesting;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001034 Py_TRASHCAN_SAFE_END(self);
1035 --_PyTrash_delete_nesting;
Antoine Pitrou58098a72012-09-06 00:59:49 +02001036 -- tstate->trash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001037
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001038 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001039
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001040 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001041
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001042 A. Read the comment titled "Trashcan mechanism" in object.h.
1043 For one, this explains why there must be a call to GC-untrack
1044 before the trashcan begin macro. Without understanding the
1045 trashcan code, the answers to the following questions don't make
1046 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001047
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001048 Q. Why do we GC-untrack before the trashcan and then immediately
1049 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001050
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001051 A. In the case that the base class is GC-aware, the base class
1052 probably GC-untracks the object. If it does that using the
1053 UNTRACK macro, this will crash when the object is already
1054 untracked. Because we don't know what the base class does, the
1055 only safe thing is to make sure the object is tracked when we
1056 call the base class dealloc. But... The trashcan begin macro
1057 requires that the object is *untracked* before it is called. So
1058 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001059
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001060 GC untrack
1061 trashcan begin
1062 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001063
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001064 Q. Why did the last question say "immediately GC-track again"?
1065 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001066
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001067 A. Because the code *used* to re-track immediately. Bad Idea.
1068 self has a refcount of 0, and if gc ever gets its hands on it
1069 (which can happen if any weakref callback gets invoked), it
1070 looks like trash to gc too, and gc also tries to delete self
Ezio Melottic2077b02011-03-16 12:34:31 +02001071 then. But we're already deleting self. Double deallocation is
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001072 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001073
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001074 Q. Why the bizarre (net-zero) manipulation of
1075 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001076
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001077 A. Some base classes (e.g. list) also use the trashcan mechanism.
1078 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001079
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001080 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001081
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001082 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001083
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001084 - the trashcan limit is not yet reached, so the trashcan level
1085 is incremented and the code between trashcan begin and end is
1086 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001087
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001088 - this destroys much of the object's contents, including its
1089 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001090
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001091 - basedealloc() is called; this is really list_dealloc(), or
1092 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001093
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001094 - the trashcan limit is now reached, so the object is put on the
1095 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001096
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001097 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001098
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001099 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001100
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001101 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001102
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001103 - later, the trashcan code starts deleting the objects from its
1104 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001105
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001106 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001107
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001108 - at the very least (if the destroyed slots and __dict__ don't
1109 cause problems) the object's type gets decref'ed a second
1110 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001111
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001112 The remedy is to make sure that if the code between trashcan
1113 begin and end in subtype_dealloc() is called, the code between
1114 trashcan begin and end in basedealloc() will also be called.
1115 This is done by decrementing the level after passing into the
1116 trashcan block, and incrementing it just before leaving the
1117 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001118
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001119 But now it's possible that a chain of objects consisting solely
1120 of objects whose deallocator is subtype_dealloc() will defeat
1121 the trashcan mechanism completely: the decremented level means
1122 that the effective level never reaches the limit. Therefore, we
1123 *increment* the level *before* entering the trashcan block, and
1124 matchingly decrement it after leaving. This means the trashcan
1125 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001126
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001127 Q. Are there any live examples of code in need of all this
1128 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001129
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001130 A. Yes. See SF bug 668433 for code that crashed (when Python was
1131 compiled in debug mode) before the trashcan level manipulations
1132 were added. For more discussion, see SF patches 581742, 575073
1133 and bug 574207.
1134 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001135}
1136
Jeremy Hylton938ace62002-07-17 16:30:39 +00001137static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001138
Tim Peters6d6c1a32001-08-02 04:15:00 +00001139/* type test with subclassing support */
1140
1141int
1142PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1143{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001144 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001145
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001146 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1147 return b == a || b == &PyBaseObject_Type;
Guido van Rossum9478d072001-09-07 18:52:13 +00001148
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001149 mro = a->tp_mro;
1150 if (mro != NULL) {
1151 /* Deal with multiple inheritance without recursion
1152 by walking the MRO tuple */
1153 Py_ssize_t i, n;
1154 assert(PyTuple_Check(mro));
1155 n = PyTuple_GET_SIZE(mro);
1156 for (i = 0; i < n; i++) {
1157 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1158 return 1;
1159 }
1160 return 0;
1161 }
1162 else {
1163 /* a is not completely initilized yet; follow tp_base */
1164 do {
1165 if (a == b)
1166 return 1;
1167 a = a->tp_base;
1168 } while (a != NULL);
1169 return b == &PyBaseObject_Type;
1170 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001171}
1172
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001173/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001174 without looking in the instance dictionary
1175 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001176 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001177 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001178 static variable used to cache the interned Python string.
1179
1180 Two variants:
1181
1182 - lookup_maybe() returns NULL without raising an exception
1183 when the _PyType_Lookup() call fails;
1184
1185 - lookup_method() always raises an exception upon errors.
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001186
1187 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001188*/
Guido van Rossum60718732001-08-28 17:47:51 +00001189
1190static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001191lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001192{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001193 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001194
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001195 if (*attrobj == NULL) {
1196 *attrobj = PyString_InternFromString(attrstr);
1197 if (*attrobj == NULL)
1198 return NULL;
1199 }
1200 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
1201 if (res != NULL) {
1202 descrgetfunc f;
1203 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1204 Py_INCREF(res);
1205 else
1206 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1207 }
1208 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001209}
1210
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001211static PyObject *
1212lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1213{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001214 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1215 if (res == NULL && !PyErr_Occurred())
1216 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1217 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001218}
1219
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001220PyObject *
1221_PyObject_LookupSpecial(PyObject *self, char *attrstr, PyObject **attrobj)
1222{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001223 assert(!PyInstance_Check(self));
1224 return lookup_maybe(self, attrstr, attrobj);
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001225}
1226
Guido van Rossum2730b132001-08-28 18:22:14 +00001227/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001228 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001229 as lookup_method to cache the interned name string object. */
1230
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001231static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001232call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1233{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001234 va_list va;
1235 PyObject *args, *func = 0, *retval;
1236 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001237
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001238 func = lookup_maybe(o, name, nameobj);
1239 if (func == NULL) {
1240 va_end(va);
1241 if (!PyErr_Occurred())
1242 PyErr_SetObject(PyExc_AttributeError, *nameobj);
1243 return NULL;
1244 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001245
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001246 if (format && *format)
1247 args = Py_VaBuildValue(format, va);
1248 else
1249 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001250
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001251 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001252
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001253 if (args == NULL)
1254 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001255
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001256 assert(PyTuple_Check(args));
1257 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001258
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001259 Py_DECREF(args);
1260 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001261
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001262 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001263}
1264
1265/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1266
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001267static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001268call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1269{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001270 va_list va;
1271 PyObject *args, *func = 0, *retval;
1272 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001273
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001274 func = lookup_maybe(o, name, nameobj);
1275 if (func == NULL) {
1276 va_end(va);
1277 if (!PyErr_Occurred()) {
1278 Py_INCREF(Py_NotImplemented);
1279 return Py_NotImplemented;
1280 }
1281 return NULL;
1282 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001283
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001284 if (format && *format)
1285 args = Py_VaBuildValue(format, va);
1286 else
1287 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001288
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001289 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001290
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001291 if (args == NULL)
1292 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001293
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001294 assert(PyTuple_Check(args));
1295 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001296
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001297 Py_DECREF(args);
1298 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001299
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001300 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001301}
1302
Tim Petersa91e9642001-11-14 23:32:33 +00001303static int
1304fill_classic_mro(PyObject *mro, PyObject *cls)
1305{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001306 PyObject *bases, *base;
1307 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001308
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001309 assert(PyList_Check(mro));
1310 assert(PyClass_Check(cls));
1311 i = PySequence_Contains(mro, cls);
1312 if (i < 0)
1313 return -1;
1314 if (!i) {
1315 if (PyList_Append(mro, cls) < 0)
1316 return -1;
1317 }
1318 bases = ((PyClassObject *)cls)->cl_bases;
1319 assert(bases && PyTuple_Check(bases));
1320 n = PyTuple_GET_SIZE(bases);
1321 for (i = 0; i < n; i++) {
1322 base = PyTuple_GET_ITEM(bases, i);
1323 if (fill_classic_mro(mro, base) < 0)
1324 return -1;
1325 }
1326 return 0;
Tim Petersa91e9642001-11-14 23:32:33 +00001327}
1328
1329static PyObject *
1330classic_mro(PyObject *cls)
1331{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001332 PyObject *mro;
Tim Petersa91e9642001-11-14 23:32:33 +00001333
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001334 assert(PyClass_Check(cls));
1335 mro = PyList_New(0);
1336 if (mro != NULL) {
1337 if (fill_classic_mro(mro, cls) == 0)
1338 return mro;
1339 Py_DECREF(mro);
1340 }
1341 return NULL;
Tim Petersa91e9642001-11-14 23:32:33 +00001342}
1343
Tim Petersea7f75d2002-12-07 21:39:16 +00001344/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001345 Method resolution order algorithm C3 described in
1346 "A Monotonic Superclass Linearization for Dylan",
1347 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001348 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001349 (OOPSLA 1996)
1350
Guido van Rossum98f33732002-11-25 21:36:54 +00001351 Some notes about the rules implied by C3:
1352
Tim Petersea7f75d2002-12-07 21:39:16 +00001353 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001354 It isn't legal to repeat a class in a list of base classes.
1355
1356 The next three properties are the 3 constraints in "C3".
1357
Tim Petersea7f75d2002-12-07 21:39:16 +00001358 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001359 If A precedes B in C's MRO, then A will precede B in the MRO of all
1360 subclasses of C.
1361
1362 Monotonicity.
1363 The MRO of a class must be an extension without reordering of the
1364 MRO of each of its superclasses.
1365
1366 Extended Precedence Graph (EPG).
1367 Linearization is consistent if there is a path in the EPG from
1368 each class to all its successors in the linearization. See
1369 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001370 */
1371
Tim Petersea7f75d2002-12-07 21:39:16 +00001372static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001373tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001374 Py_ssize_t j, size;
1375 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001376
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001377 for (j = whence+1; j < size; j++) {
1378 if (PyList_GET_ITEM(list, j) == o)
1379 return 1;
1380 }
1381 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001382}
1383
Guido van Rossum98f33732002-11-25 21:36:54 +00001384static PyObject *
1385class_name(PyObject *cls)
1386{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001387 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1388 if (name == NULL) {
1389 PyErr_Clear();
1390 Py_XDECREF(name);
1391 name = PyObject_Repr(cls);
1392 }
1393 if (name == NULL)
1394 return NULL;
1395 if (!PyString_Check(name)) {
1396 Py_DECREF(name);
1397 return NULL;
1398 }
1399 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001400}
1401
1402static int
1403check_duplicates(PyObject *list)
1404{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001405 Py_ssize_t i, j, n;
1406 /* Let's use a quadratic time algorithm,
1407 assuming that the bases lists is short.
1408 */
1409 n = PyList_GET_SIZE(list);
1410 for (i = 0; i < n; i++) {
1411 PyObject *o = PyList_GET_ITEM(list, i);
1412 for (j = i + 1; j < n; j++) {
1413 if (PyList_GET_ITEM(list, j) == o) {
1414 o = class_name(o);
1415 PyErr_Format(PyExc_TypeError,
1416 "duplicate base class %s",
1417 o ? PyString_AS_STRING(o) : "?");
1418 Py_XDECREF(o);
1419 return -1;
1420 }
1421 }
1422 }
1423 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001424}
1425
1426/* Raise a TypeError for an MRO order disagreement.
1427
1428 It's hard to produce a good error message. In the absence of better
1429 insight into error reporting, report the classes that were candidates
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001430 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001431 order in which they should be put in the MRO, but it's hard to
1432 diagnose what constraint can't be satisfied.
1433*/
1434
1435static void
1436set_mro_error(PyObject *to_merge, int *remain)
1437{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001438 Py_ssize_t i, n, off, to_merge_size;
1439 char buf[1000];
1440 PyObject *k, *v;
1441 PyObject *set = PyDict_New();
1442 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001443
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001444 to_merge_size = PyList_GET_SIZE(to_merge);
1445 for (i = 0; i < to_merge_size; i++) {
1446 PyObject *L = PyList_GET_ITEM(to_merge, i);
1447 if (remain[i] < PyList_GET_SIZE(L)) {
1448 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1449 if (PyDict_SetItem(set, c, Py_None) < 0) {
1450 Py_DECREF(set);
1451 return;
1452 }
1453 }
1454 }
1455 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001456
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001457 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001458consistent method resolution\norder (MRO) for bases");
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001459 i = 0;
1460 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1461 PyObject *name = class_name(k);
1462 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1463 name ? PyString_AS_STRING(name) : "?");
1464 Py_XDECREF(name);
1465 if (--n && (size_t)(off+1) < sizeof(buf)) {
1466 buf[off++] = ',';
1467 buf[off] = '\0';
1468 }
1469 }
1470 PyErr_SetString(PyExc_TypeError, buf);
1471 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001472}
1473
Tim Petersea7f75d2002-12-07 21:39:16 +00001474static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001475pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001476 Py_ssize_t i, j, to_merge_size, empty_cnt;
1477 int *remain;
1478 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001479
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001480 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001481
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001482 /* remain stores an index into each sublist of to_merge.
1483 remain[i] is the index of the next base in to_merge[i]
1484 that is not included in acc.
1485 */
1486 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1487 if (remain == NULL)
1488 return -1;
1489 for (i = 0; i < to_merge_size; i++)
1490 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001491
1492 again:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001493 empty_cnt = 0;
1494 for (i = 0; i < to_merge_size; i++) {
1495 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001496
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001497 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001498
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001499 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1500 empty_cnt++;
1501 continue;
1502 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001503
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001504 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001505
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001506 The input sequences alone can determine the choice.
1507 If not, choose the class which appears in the MRO
1508 of the earliest direct superclass of the new class.
1509 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001510
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001511 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1512 for (j = 0; j < to_merge_size; j++) {
1513 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1514 if (tail_contains(j_lst, remain[j], candidate)) {
1515 goto skip; /* continue outer loop */
1516 }
1517 }
1518 ok = PyList_Append(acc, candidate);
1519 if (ok < 0) {
1520 PyMem_Free(remain);
1521 return -1;
1522 }
1523 for (j = 0; j < to_merge_size; j++) {
1524 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1525 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1526 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1527 remain[j]++;
1528 }
1529 }
1530 goto again;
1531 skip: ;
1532 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001533
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001534 if (empty_cnt == to_merge_size) {
1535 PyMem_FREE(remain);
1536 return 0;
1537 }
1538 set_mro_error(to_merge, remain);
1539 PyMem_FREE(remain);
1540 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001541}
1542
Tim Peters6d6c1a32001-08-02 04:15:00 +00001543static PyObject *
1544mro_implementation(PyTypeObject *type)
1545{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001546 Py_ssize_t i, n;
1547 int ok;
1548 PyObject *bases, *result;
1549 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001551 if (type->tp_dict == NULL) {
1552 if (PyType_Ready(type) < 0)
1553 return NULL;
1554 }
Guido van Rossum63517572002-06-18 16:44:57 +00001555
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001556 /* Find a superclass linearization that honors the constraints
1557 of the explicit lists of bases and the constraints implied by
1558 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001559
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001560 to_merge is a list of lists, where each list is a superclass
1561 linearization implied by a base class. The last element of
1562 to_merge is the declared list of bases.
1563 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001564
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001565 bases = type->tp_bases;
1566 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001567
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001568 to_merge = PyList_New(n+1);
1569 if (to_merge == NULL)
1570 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001571
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001572 for (i = 0; i < n; i++) {
1573 PyObject *base = PyTuple_GET_ITEM(bases, i);
1574 PyObject *parentMRO;
1575 if (PyType_Check(base))
1576 parentMRO = PySequence_List(
1577 ((PyTypeObject*)base)->tp_mro);
1578 else
1579 parentMRO = classic_mro(base);
1580 if (parentMRO == NULL) {
1581 Py_DECREF(to_merge);
1582 return NULL;
1583 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001584
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001585 PyList_SET_ITEM(to_merge, i, parentMRO);
1586 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001587
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001588 bases_aslist = PySequence_List(bases);
1589 if (bases_aslist == NULL) {
1590 Py_DECREF(to_merge);
1591 return NULL;
1592 }
1593 /* This is just a basic sanity check. */
1594 if (check_duplicates(bases_aslist) < 0) {
1595 Py_DECREF(to_merge);
1596 Py_DECREF(bases_aslist);
1597 return NULL;
1598 }
1599 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001600
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001601 result = Py_BuildValue("[O]", (PyObject *)type);
1602 if (result == NULL) {
1603 Py_DECREF(to_merge);
1604 return NULL;
1605 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001606
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001607 ok = pmerge(result, to_merge);
1608 Py_DECREF(to_merge);
1609 if (ok < 0) {
1610 Py_DECREF(result);
1611 return NULL;
1612 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001613
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001614 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001615}
1616
1617static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001618mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001619{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001620 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001621
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001622 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001623}
1624
1625static int
1626mro_internal(PyTypeObject *type)
1627{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001628 PyObject *mro, *result, *tuple;
1629 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001630
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001631 if (Py_TYPE(type) == &PyType_Type) {
1632 result = mro_implementation(type);
1633 }
1634 else {
1635 static PyObject *mro_str;
1636 checkit = 1;
1637 mro = lookup_method((PyObject *)type, "mro", &mro_str);
1638 if (mro == NULL)
1639 return -1;
1640 result = PyObject_CallObject(mro, NULL);
1641 Py_DECREF(mro);
1642 }
1643 if (result == NULL)
1644 return -1;
1645 tuple = PySequence_Tuple(result);
1646 Py_DECREF(result);
1647 if (tuple == NULL)
1648 return -1;
1649 if (checkit) {
1650 Py_ssize_t i, len;
1651 PyObject *cls;
1652 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001653
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001654 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001655
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001656 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001657
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001658 for (i = 0; i < len; i++) {
1659 PyTypeObject *t;
1660 cls = PyTuple_GET_ITEM(tuple, i);
1661 if (PyClass_Check(cls))
1662 continue;
1663 else if (!PyType_Check(cls)) {
1664 PyErr_Format(PyExc_TypeError,
1665 "mro() returned a non-class ('%.500s')",
1666 Py_TYPE(cls)->tp_name);
1667 Py_DECREF(tuple);
1668 return -1;
1669 }
1670 t = (PyTypeObject*)cls;
1671 if (!PyType_IsSubtype(solid, solid_base(t))) {
1672 PyErr_Format(PyExc_TypeError,
1673 "mro() returned base with unsuitable layout ('%.500s')",
1674 t->tp_name);
1675 Py_DECREF(tuple);
1676 return -1;
1677 }
1678 }
1679 }
1680 type->tp_mro = tuple;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001681
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001682 type_mro_modified(type, type->tp_mro);
1683 /* corner case: the old-style super class might have been hidden
1684 from the custom MRO */
1685 type_mro_modified(type, type->tp_bases);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001686
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001687 PyType_Modified(type);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001688
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001689 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690}
1691
1692
1693/* Calculate the best base amongst multiple base classes.
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001694 This is the first one that's on the path to the "solid base". */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001695
1696static PyTypeObject *
1697best_base(PyObject *bases)
1698{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001699 Py_ssize_t i, n;
1700 PyTypeObject *base, *winner, *candidate, *base_i;
1701 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001702
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001703 assert(PyTuple_Check(bases));
1704 n = PyTuple_GET_SIZE(bases);
1705 assert(n > 0);
1706 base = NULL;
1707 winner = NULL;
1708 for (i = 0; i < n; i++) {
1709 base_proto = PyTuple_GET_ITEM(bases, i);
1710 if (PyClass_Check(base_proto))
1711 continue;
1712 if (!PyType_Check(base_proto)) {
1713 PyErr_SetString(
1714 PyExc_TypeError,
1715 "bases must be types");
1716 return NULL;
1717 }
1718 base_i = (PyTypeObject *)base_proto;
1719 if (base_i->tp_dict == NULL) {
1720 if (PyType_Ready(base_i) < 0)
1721 return NULL;
1722 }
1723 candidate = solid_base(base_i);
1724 if (winner == NULL) {
1725 winner = candidate;
1726 base = base_i;
1727 }
1728 else if (PyType_IsSubtype(winner, candidate))
1729 ;
1730 else if (PyType_IsSubtype(candidate, winner)) {
1731 winner = candidate;
1732 base = base_i;
1733 }
1734 else {
1735 PyErr_SetString(
1736 PyExc_TypeError,
1737 "multiple bases have "
1738 "instance lay-out conflict");
1739 return NULL;
1740 }
1741 }
1742 if (base == NULL)
1743 PyErr_SetString(PyExc_TypeError,
1744 "a new-style class can't have only classic bases");
1745 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001746}
1747
1748static int
1749extra_ivars(PyTypeObject *type, PyTypeObject *base)
1750{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001751 size_t t_size = type->tp_basicsize;
1752 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001753
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001754 assert(t_size >= b_size); /* Else type smaller than base! */
1755 if (type->tp_itemsize || base->tp_itemsize) {
1756 /* If itemsize is involved, stricter rules */
1757 return t_size != b_size ||
1758 type->tp_itemsize != base->tp_itemsize;
1759 }
1760 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1761 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1762 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1763 t_size -= sizeof(PyObject *);
1764 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1765 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1766 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1767 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001768
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001769 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001770}
1771
1772static PyTypeObject *
1773solid_base(PyTypeObject *type)
1774{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001775 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001776
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001777 if (type->tp_base)
1778 base = solid_base(type->tp_base);
1779 else
1780 base = &PyBaseObject_Type;
1781 if (extra_ivars(type, base))
1782 return type;
1783 else
1784 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001785}
1786
Jeremy Hylton938ace62002-07-17 16:30:39 +00001787static void object_dealloc(PyObject *);
1788static int object_init(PyObject *, PyObject *, PyObject *);
1789static int update_slot(PyTypeObject *, PyObject *);
1790static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001791
Armin Rigo9790a272007-05-02 19:23:31 +00001792/*
1793 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1794 * inherited from various builtin types. The builtin base usually provides
1795 * its own __dict__ descriptor, so we use that when we can.
1796 */
1797static PyTypeObject *
1798get_builtin_base_with_dict(PyTypeObject *type)
1799{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001800 while (type->tp_base != NULL) {
1801 if (type->tp_dictoffset != 0 &&
1802 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1803 return type;
1804 type = type->tp_base;
1805 }
1806 return NULL;
Armin Rigo9790a272007-05-02 19:23:31 +00001807}
1808
1809static PyObject *
1810get_dict_descriptor(PyTypeObject *type)
1811{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001812 static PyObject *dict_str;
1813 PyObject *descr;
Armin Rigo9790a272007-05-02 19:23:31 +00001814
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001815 if (dict_str == NULL) {
1816 dict_str = PyString_InternFromString("__dict__");
1817 if (dict_str == NULL)
1818 return NULL;
1819 }
1820 descr = _PyType_Lookup(type, dict_str);
1821 if (descr == NULL || !PyDescr_IsData(descr))
1822 return NULL;
Armin Rigo9790a272007-05-02 19:23:31 +00001823
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001824 return descr;
Armin Rigo9790a272007-05-02 19:23:31 +00001825}
1826
1827static void
1828raise_dict_descr_error(PyObject *obj)
1829{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001830 PyErr_Format(PyExc_TypeError,
1831 "this __dict__ descriptor does not support "
1832 "'%.200s' objects", obj->ob_type->tp_name);
Armin Rigo9790a272007-05-02 19:23:31 +00001833}
1834
Tim Peters6d6c1a32001-08-02 04:15:00 +00001835static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001836subtype_dict(PyObject *obj, void *context)
1837{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001838 PyObject **dictptr;
1839 PyObject *dict;
1840 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001841
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001842 base = get_builtin_base_with_dict(obj->ob_type);
1843 if (base != NULL) {
1844 descrgetfunc func;
1845 PyObject *descr = get_dict_descriptor(base);
1846 if (descr == NULL) {
1847 raise_dict_descr_error(obj);
1848 return NULL;
1849 }
1850 func = descr->ob_type->tp_descr_get;
1851 if (func == NULL) {
1852 raise_dict_descr_error(obj);
1853 return NULL;
1854 }
1855 return func(descr, obj, (PyObject *)(obj->ob_type));
1856 }
Armin Rigo9790a272007-05-02 19:23:31 +00001857
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001858 dictptr = _PyObject_GetDictPtr(obj);
1859 if (dictptr == NULL) {
1860 PyErr_SetString(PyExc_AttributeError,
1861 "This object has no __dict__");
1862 return NULL;
1863 }
1864 dict = *dictptr;
1865 if (dict == NULL)
1866 *dictptr = dict = PyDict_New();
1867 Py_XINCREF(dict);
1868 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001869}
1870
Guido van Rossum6661be32001-10-26 04:26:12 +00001871static int
1872subtype_setdict(PyObject *obj, PyObject *value, void *context)
1873{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001874 PyObject **dictptr;
1875 PyObject *dict;
1876 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001877
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001878 base = get_builtin_base_with_dict(obj->ob_type);
1879 if (base != NULL) {
1880 descrsetfunc func;
1881 PyObject *descr = get_dict_descriptor(base);
1882 if (descr == NULL) {
1883 raise_dict_descr_error(obj);
1884 return -1;
1885 }
1886 func = descr->ob_type->tp_descr_set;
1887 if (func == NULL) {
1888 raise_dict_descr_error(obj);
1889 return -1;
1890 }
1891 return func(descr, obj, value);
1892 }
Armin Rigo9790a272007-05-02 19:23:31 +00001893
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001894 dictptr = _PyObject_GetDictPtr(obj);
1895 if (dictptr == NULL) {
1896 PyErr_SetString(PyExc_AttributeError,
1897 "This object has no __dict__");
1898 return -1;
1899 }
1900 if (value != NULL && !PyDict_Check(value)) {
1901 PyErr_Format(PyExc_TypeError,
1902 "__dict__ must be set to a dictionary, "
1903 "not a '%.200s'", Py_TYPE(value)->tp_name);
1904 return -1;
1905 }
1906 dict = *dictptr;
1907 Py_XINCREF(value);
1908 *dictptr = value;
1909 Py_XDECREF(dict);
1910 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001911}
1912
Guido van Rossumad47da02002-08-12 19:05:44 +00001913static PyObject *
1914subtype_getweakref(PyObject *obj, void *context)
1915{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001916 PyObject **weaklistptr;
1917 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001918
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001919 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1920 PyErr_SetString(PyExc_AttributeError,
1921 "This object has no __weakref__");
1922 return NULL;
1923 }
1924 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1925 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1926 (size_t)(Py_TYPE(obj)->tp_basicsize));
1927 weaklistptr = (PyObject **)
1928 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1929 if (*weaklistptr == NULL)
1930 result = Py_None;
1931 else
1932 result = *weaklistptr;
1933 Py_INCREF(result);
1934 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001935}
1936
Guido van Rossum373c7412003-01-07 13:41:37 +00001937/* Three variants on the subtype_getsets list. */
1938
1939static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001940 {"__dict__", subtype_dict, subtype_setdict,
1941 PyDoc_STR("dictionary for instance variables (if defined)")},
1942 {"__weakref__", subtype_getweakref, NULL,
1943 PyDoc_STR("list of weak references to the object (if defined)")},
1944 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001945};
1946
Guido van Rossum373c7412003-01-07 13:41:37 +00001947static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001948 {"__dict__", subtype_dict, subtype_setdict,
1949 PyDoc_STR("dictionary for instance variables (if defined)")},
1950 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001951};
1952
1953static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001954 {"__weakref__", subtype_getweakref, NULL,
1955 PyDoc_STR("list of weak references to the object (if defined)")},
1956 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001957};
1958
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001959static int
1960valid_identifier(PyObject *s)
1961{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001962 unsigned char *p;
1963 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001964
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001965 if (!PyString_Check(s)) {
1966 PyErr_Format(PyExc_TypeError,
1967 "__slots__ items must be strings, not '%.200s'",
1968 Py_TYPE(s)->tp_name);
1969 return 0;
1970 }
1971 p = (unsigned char *) PyString_AS_STRING(s);
1972 n = PyString_GET_SIZE(s);
1973 /* We must reject an empty name. As a hack, we bump the
1974 length to 1 so that the loop will balk on the trailing \0. */
1975 if (n == 0)
1976 n = 1;
1977 for (i = 0; i < n; i++, p++) {
1978 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1979 PyErr_SetString(PyExc_TypeError,
1980 "__slots__ must be identifiers");
1981 return 0;
1982 }
1983 }
1984 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001985}
1986
Martin v. Löwisd919a592002-10-14 21:07:28 +00001987#ifdef Py_USING_UNICODE
1988/* Replace Unicode objects in slots. */
1989
1990static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001991_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001992{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001993 PyObject *tmp = NULL;
1994 PyObject *slot_name, *new_name;
1995 Py_ssize_t i;
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001996
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001997 for (i = 0; i < nslots; i++) {
1998 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1999 if (tmp == NULL) {
2000 tmp = PySequence_List(slots);
2001 if (tmp == NULL)
2002 return NULL;
2003 }
2004 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
2005 NULL);
2006 if (new_name == NULL) {
2007 Py_DECREF(tmp);
2008 return NULL;
2009 }
2010 Py_INCREF(new_name);
2011 PyList_SET_ITEM(tmp, i, new_name);
2012 Py_DECREF(slot_name);
2013 }
2014 }
2015 if (tmp != NULL) {
2016 slots = PyList_AsTuple(tmp);
2017 Py_DECREF(tmp);
2018 }
2019 return slots;
Martin v. Löwisd919a592002-10-14 21:07:28 +00002020}
2021#endif
2022
Guido van Rossumf102e242007-03-23 18:53:03 +00002023/* Forward */
2024static int
2025object_init(PyObject *self, PyObject *args, PyObject *kwds);
2026
2027static int
2028type_init(PyObject *cls, PyObject *args, PyObject *kwds)
2029{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002030 int res;
Guido van Rossumf102e242007-03-23 18:53:03 +00002031
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002032 assert(args != NULL && PyTuple_Check(args));
2033 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumf102e242007-03-23 18:53:03 +00002034
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002035 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
2036 PyErr_SetString(PyExc_TypeError,
2037 "type.__init__() takes no keyword arguments");
2038 return -1;
2039 }
Guido van Rossumf102e242007-03-23 18:53:03 +00002040
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002041 if (args != NULL && PyTuple_Check(args) &&
2042 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
2043 PyErr_SetString(PyExc_TypeError,
2044 "type.__init__() takes 1 or 3 arguments");
2045 return -1;
2046 }
Guido van Rossumf102e242007-03-23 18:53:03 +00002047
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002048 /* Call object.__init__(self) now. */
2049 /* XXX Could call super(type, cls).__init__() but what's the point? */
2050 args = PyTuple_GetSlice(args, 0, 0);
2051 res = object_init(cls, args, NULL);
2052 Py_DECREF(args);
2053 return res;
Guido van Rossumf102e242007-03-23 18:53:03 +00002054}
2055
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002056static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002057type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2058{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002059 PyObject *name, *bases, *dict;
2060 static char *kwlist[] = {"name", "bases", "dict", 0};
2061 PyObject *slots, *tmp, *newslots;
2062 PyTypeObject *type, *base, *tmptype, *winner;
2063 PyHeapTypeObject *et;
2064 PyMemberDef *mp;
2065 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
2066 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002068 assert(args != NULL && PyTuple_Check(args));
2069 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00002070
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002071 /* Special case: type(x) should return x->ob_type */
2072 {
2073 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2074 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002075
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002076 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2077 PyObject *x = PyTuple_GET_ITEM(args, 0);
2078 Py_INCREF(Py_TYPE(x));
2079 return (PyObject *) Py_TYPE(x);
2080 }
Tim Peters3abca122001-10-27 19:37:48 +00002081
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002082 /* SF bug 475327 -- if that didn't trigger, we need 3
2083 arguments. but PyArg_ParseTupleAndKeywords below may give
2084 a msg saying type() needs exactly 3. */
2085 if (nargs + nkwds != 3) {
2086 PyErr_SetString(PyExc_TypeError,
2087 "type() takes 1 or 3 arguments");
2088 return NULL;
2089 }
2090 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002091
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002092 /* Check arguments: (name, bases, dict) */
2093 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
2094 &name,
2095 &PyTuple_Type, &bases,
2096 &PyDict_Type, &dict))
2097 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002098
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002099 /* Determine the proper metatype to deal with this,
2100 and check for metatype conflicts while we're at it.
2101 Note that if some other metatype wins to contract,
2102 it's possible that its instances are not types. */
2103 nbases = PyTuple_GET_SIZE(bases);
2104 winner = metatype;
2105 for (i = 0; i < nbases; i++) {
2106 tmp = PyTuple_GET_ITEM(bases, i);
2107 tmptype = tmp->ob_type;
2108 if (tmptype == &PyClass_Type)
2109 continue; /* Special case classic classes */
2110 if (PyType_IsSubtype(winner, tmptype))
2111 continue;
2112 if (PyType_IsSubtype(tmptype, winner)) {
2113 winner = tmptype;
2114 continue;
2115 }
2116 PyErr_SetString(PyExc_TypeError,
2117 "metaclass conflict: "
2118 "the metaclass of a derived class "
2119 "must be a (non-strict) subclass "
2120 "of the metaclasses of all its bases");
2121 return NULL;
2122 }
2123 if (winner != metatype) {
2124 if (winner->tp_new != type_new) /* Pass it to the winner */
2125 return winner->tp_new(winner, args, kwds);
2126 metatype = winner;
2127 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002128
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002129 /* Adjust for empty tuple bases */
2130 if (nbases == 0) {
2131 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2132 if (bases == NULL)
2133 return NULL;
2134 nbases = 1;
2135 }
2136 else
2137 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002138
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002139 /* XXX From here until type is allocated, "return NULL" leaks bases! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002140
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002141 /* Calculate best base, and check that all bases are type objects */
2142 base = best_base(bases);
2143 if (base == NULL) {
2144 Py_DECREF(bases);
2145 return NULL;
2146 }
2147 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2148 PyErr_Format(PyExc_TypeError,
2149 "type '%.100s' is not an acceptable base type",
2150 base->tp_name);
2151 Py_DECREF(bases);
2152 return NULL;
2153 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002154
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002155 /* Check for a __slots__ sequence variable in dict, and count it */
2156 slots = PyDict_GetItemString(dict, "__slots__");
2157 nslots = 0;
2158 add_dict = 0;
2159 add_weak = 0;
2160 may_add_dict = base->tp_dictoffset == 0;
2161 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2162 if (slots == NULL) {
2163 if (may_add_dict) {
2164 add_dict++;
2165 }
2166 if (may_add_weak) {
2167 add_weak++;
2168 }
2169 }
2170 else {
2171 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002172
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002173 /* Make it into a tuple */
2174 if (PyString_Check(slots) || PyUnicode_Check(slots))
2175 slots = PyTuple_Pack(1, slots);
2176 else
2177 slots = PySequence_Tuple(slots);
2178 if (slots == NULL) {
2179 Py_DECREF(bases);
2180 return NULL;
2181 }
2182 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002183
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002184 /* Are slots allowed? */
2185 nslots = PyTuple_GET_SIZE(slots);
2186 if (nslots > 0 && base->tp_itemsize != 0) {
2187 PyErr_Format(PyExc_TypeError,
2188 "nonempty __slots__ "
2189 "not supported for subtype of '%s'",
2190 base->tp_name);
2191 bad_slots:
2192 Py_DECREF(bases);
2193 Py_DECREF(slots);
2194 return NULL;
2195 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002196
Martin v. Löwisd919a592002-10-14 21:07:28 +00002197#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002198 tmp = _unicode_to_string(slots, nslots);
2199 if (tmp == NULL)
2200 goto bad_slots;
2201 if (tmp != slots) {
2202 Py_DECREF(slots);
2203 slots = tmp;
2204 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00002205#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002206 /* Check for valid slot names and two special cases */
2207 for (i = 0; i < nslots; i++) {
2208 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2209 char *s;
2210 if (!valid_identifier(tmp))
2211 goto bad_slots;
2212 assert(PyString_Check(tmp));
2213 s = PyString_AS_STRING(tmp);
2214 if (strcmp(s, "__dict__") == 0) {
2215 if (!may_add_dict || add_dict) {
2216 PyErr_SetString(PyExc_TypeError,
2217 "__dict__ slot disallowed: "
2218 "we already got one");
2219 goto bad_slots;
2220 }
2221 add_dict++;
2222 }
2223 if (strcmp(s, "__weakref__") == 0) {
2224 if (!may_add_weak || add_weak) {
2225 PyErr_SetString(PyExc_TypeError,
2226 "__weakref__ slot disallowed: "
2227 "either we already got one, "
2228 "or __itemsize__ != 0");
2229 goto bad_slots;
2230 }
2231 add_weak++;
2232 }
2233 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002234
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002235 /* Copy slots into a list, mangle names and sort them.
2236 Sorted names are needed for __class__ assignment.
2237 Convert them back to tuple at the end.
2238 */
2239 newslots = PyList_New(nslots - add_dict - add_weak);
2240 if (newslots == NULL)
2241 goto bad_slots;
2242 for (i = j = 0; i < nslots; i++) {
2243 char *s;
2244 tmp = PyTuple_GET_ITEM(slots, i);
2245 s = PyString_AS_STRING(tmp);
2246 if ((add_dict && strcmp(s, "__dict__") == 0) ||
2247 (add_weak && strcmp(s, "__weakref__") == 0))
2248 continue;
2249 tmp =_Py_Mangle(name, tmp);
Benjamin Petersonde66ecc2011-08-16 22:26:48 -05002250 if (!tmp) {
2251 Py_DECREF(newslots);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002252 goto bad_slots;
Benjamin Petersonde66ecc2011-08-16 22:26:48 -05002253 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002254 PyList_SET_ITEM(newslots, j, tmp);
2255 j++;
2256 }
2257 assert(j == nslots - add_dict - add_weak);
2258 nslots = j;
2259 Py_DECREF(slots);
2260 if (PyList_Sort(newslots) == -1) {
2261 Py_DECREF(bases);
2262 Py_DECREF(newslots);
2263 return NULL;
2264 }
2265 slots = PyList_AsTuple(newslots);
2266 Py_DECREF(newslots);
2267 if (slots == NULL) {
2268 Py_DECREF(bases);
2269 return NULL;
2270 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002271
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002272 /* Secondary bases may provide weakrefs or dict */
2273 if (nbases > 1 &&
2274 ((may_add_dict && !add_dict) ||
2275 (may_add_weak && !add_weak))) {
2276 for (i = 0; i < nbases; i++) {
2277 tmp = PyTuple_GET_ITEM(bases, i);
2278 if (tmp == (PyObject *)base)
2279 continue; /* Skip primary base */
2280 if (PyClass_Check(tmp)) {
2281 /* Classic base class provides both */
2282 if (may_add_dict && !add_dict)
2283 add_dict++;
2284 if (may_add_weak && !add_weak)
2285 add_weak++;
2286 break;
2287 }
2288 assert(PyType_Check(tmp));
2289 tmptype = (PyTypeObject *)tmp;
2290 if (may_add_dict && !add_dict &&
2291 tmptype->tp_dictoffset != 0)
2292 add_dict++;
2293 if (may_add_weak && !add_weak &&
2294 tmptype->tp_weaklistoffset != 0)
2295 add_weak++;
2296 if (may_add_dict && !add_dict)
2297 continue;
2298 if (may_add_weak && !add_weak)
2299 continue;
2300 /* Nothing more to check */
2301 break;
2302 }
2303 }
2304 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002305
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002306 /* XXX From here until type is safely allocated,
2307 "return NULL" may leak slots! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002308
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002309 /* Allocate the type object */
2310 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
2311 if (type == NULL) {
2312 Py_XDECREF(slots);
2313 Py_DECREF(bases);
2314 return NULL;
2315 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002316
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002317 /* Keep name and slots alive in the extended type object */
2318 et = (PyHeapTypeObject *)type;
2319 Py_INCREF(name);
2320 et->ht_name = name;
2321 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002322
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002323 /* Initialize tp_flags */
2324 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2325 Py_TPFLAGS_BASETYPE;
2326 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2327 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2328 if (base->tp_flags & Py_TPFLAGS_HAVE_NEWBUFFER)
2329 type->tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002330
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002331 /* It's a new-style number unless it specifically inherits any
2332 old-style numeric behavior */
2333 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
2334 (base->tp_as_number == NULL))
2335 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002336
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002337 /* Initialize essential fields */
2338 type->tp_as_number = &et->as_number;
2339 type->tp_as_sequence = &et->as_sequence;
2340 type->tp_as_mapping = &et->as_mapping;
2341 type->tp_as_buffer = &et->as_buffer;
2342 type->tp_name = PyString_AS_STRING(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002343
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002344 /* Set tp_base and tp_bases */
2345 type->tp_bases = bases;
2346 Py_INCREF(base);
2347 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002348
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002349 /* Initialize tp_dict from passed-in dict */
2350 type->tp_dict = dict = PyDict_Copy(dict);
2351 if (dict == NULL) {
2352 Py_DECREF(type);
2353 return NULL;
2354 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002355
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002356 /* Set __module__ in the dict */
2357 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2358 tmp = PyEval_GetGlobals();
2359 if (tmp != NULL) {
2360 tmp = PyDict_GetItemString(tmp, "__name__");
2361 if (tmp != NULL) {
2362 if (PyDict_SetItemString(dict, "__module__",
2363 tmp) < 0)
2364 return NULL;
2365 }
2366 }
2367 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002368
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002369 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2370 and is a string. The __doc__ accessor will first look for tp_doc;
2371 if that fails, it will still look into __dict__.
2372 */
2373 {
2374 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2375 if (doc != NULL && PyString_Check(doc)) {
2376 const size_t n = (size_t)PyString_GET_SIZE(doc);
2377 char *tp_doc = (char *)PyObject_MALLOC(n+1);
2378 if (tp_doc == NULL) {
2379 Py_DECREF(type);
2380 return NULL;
2381 }
2382 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
2383 type->tp_doc = tp_doc;
2384 }
2385 }
Tim Peters2f93e282001-10-04 05:27:00 +00002386
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002387 /* Special-case __new__: if it's a plain function,
2388 make it a static function */
2389 tmp = PyDict_GetItemString(dict, "__new__");
2390 if (tmp != NULL && PyFunction_Check(tmp)) {
2391 tmp = PyStaticMethod_New(tmp);
2392 if (tmp == NULL) {
2393 Py_DECREF(type);
2394 return NULL;
2395 }
2396 PyDict_SetItemString(dict, "__new__", tmp);
2397 Py_DECREF(tmp);
2398 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002399
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002400 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2401 mp = PyHeapType_GET_MEMBERS(et);
2402 slotoffset = base->tp_basicsize;
2403 if (slots != NULL) {
2404 for (i = 0; i < nslots; i++, mp++) {
2405 mp->name = PyString_AS_STRING(
2406 PyTuple_GET_ITEM(slots, i));
2407 mp->type = T_OBJECT_EX;
2408 mp->offset = slotoffset;
Žiga Seilnacht89032082007-03-11 15:54:54 +00002409
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002410 /* __dict__ and __weakref__ are already filtered out */
2411 assert(strcmp(mp->name, "__dict__") != 0);
2412 assert(strcmp(mp->name, "__weakref__") != 0);
Žiga Seilnacht89032082007-03-11 15:54:54 +00002413
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002414 slotoffset += sizeof(PyObject *);
2415 }
2416 }
2417 if (add_dict) {
2418 if (base->tp_itemsize)
2419 type->tp_dictoffset = -(long)sizeof(PyObject *);
2420 else
2421 type->tp_dictoffset = slotoffset;
2422 slotoffset += sizeof(PyObject *);
2423 }
2424 if (add_weak) {
2425 assert(!base->tp_itemsize);
2426 type->tp_weaklistoffset = slotoffset;
2427 slotoffset += sizeof(PyObject *);
2428 }
2429 type->tp_basicsize = slotoffset;
2430 type->tp_itemsize = base->tp_itemsize;
2431 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002432
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002433 if (type->tp_weaklistoffset && type->tp_dictoffset)
2434 type->tp_getset = subtype_getsets_full;
2435 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2436 type->tp_getset = subtype_getsets_weakref_only;
2437 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2438 type->tp_getset = subtype_getsets_dict_only;
2439 else
2440 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002441
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002442 /* Special case some slots */
2443 if (type->tp_dictoffset != 0 || nslots > 0) {
2444 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2445 type->tp_getattro = PyObject_GenericGetAttr;
2446 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2447 type->tp_setattro = PyObject_GenericSetAttr;
2448 }
2449 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002450
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002451 /* Enable GC unless there are really no instance variables possible */
2452 if (!(type->tp_basicsize == sizeof(PyObject) &&
2453 type->tp_itemsize == 0))
2454 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002455
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002456 /* Always override allocation strategy to use regular heap */
2457 type->tp_alloc = PyType_GenericAlloc;
2458 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2459 type->tp_free = PyObject_GC_Del;
2460 type->tp_traverse = subtype_traverse;
2461 type->tp_clear = subtype_clear;
2462 }
2463 else
2464 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002465
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002466 /* Initialize the rest */
2467 if (PyType_Ready(type) < 0) {
2468 Py_DECREF(type);
2469 return NULL;
2470 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002471
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002472 /* Put the proper slots in place */
2473 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002474
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002475 return (PyObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002476}
2477
2478/* Internal API to look for a name through the MRO.
2479 This returns a borrowed reference, and doesn't set an exception! */
2480PyObject *
2481_PyType_Lookup(PyTypeObject *type, PyObject *name)
2482{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002483 Py_ssize_t i, n;
2484 PyObject *mro, *res, *base, *dict;
2485 unsigned int h;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002486
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002487 if (MCACHE_CACHEABLE_NAME(name) &&
2488 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2489 /* fast path */
2490 h = MCACHE_HASH_METHOD(type, name);
2491 if (method_cache[h].version == type->tp_version_tag &&
2492 method_cache[h].name == name)
2493 return method_cache[h].value;
2494 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002495
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002496 /* Look in tp_dict of types in MRO */
2497 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002498
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002499 /* If mro is NULL, the type is either not yet initialized
2500 by PyType_Ready(), or already cleared by type_clear().
2501 Either way the safest thing to do is to return NULL. */
2502 if (mro == NULL)
2503 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002504
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002505 res = NULL;
2506 assert(PyTuple_Check(mro));
2507 n = PyTuple_GET_SIZE(mro);
2508 for (i = 0; i < n; i++) {
2509 base = PyTuple_GET_ITEM(mro, i);
2510 if (PyClass_Check(base))
2511 dict = ((PyClassObject *)base)->cl_dict;
2512 else {
2513 assert(PyType_Check(base));
2514 dict = ((PyTypeObject *)base)->tp_dict;
2515 }
2516 assert(dict && PyDict_Check(dict));
2517 res = PyDict_GetItem(dict, name);
2518 if (res != NULL)
2519 break;
2520 }
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002521
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002522 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2523 h = MCACHE_HASH_METHOD(type, name);
2524 method_cache[h].version = type->tp_version_tag;
2525 method_cache[h].value = res; /* borrowed */
2526 Py_INCREF(name);
2527 Py_DECREF(method_cache[h].name);
2528 method_cache[h].name = name;
2529 }
2530 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002531}
2532
2533/* This is similar to PyObject_GenericGetAttr(),
2534 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2535static PyObject *
2536type_getattro(PyTypeObject *type, PyObject *name)
2537{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002538 PyTypeObject *metatype = Py_TYPE(type);
2539 PyObject *meta_attribute, *attribute;
2540 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002541
Benjamin Peterson6e7832b2012-03-16 09:32:59 -05002542 if (!PyString_Check(name)) {
2543 PyErr_Format(PyExc_TypeError,
2544 "attribute name must be string, not '%.200s'",
2545 name->ob_type->tp_name);
2546 return NULL;
2547 }
2548
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002549 /* Initialize this type (we'll assume the metatype is initialized) */
2550 if (type->tp_dict == NULL) {
2551 if (PyType_Ready(type) < 0)
2552 return NULL;
2553 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002554
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002555 /* No readable descriptor found yet */
2556 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002557
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002558 /* Look for the attribute in the metatype */
2559 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002560
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002561 if (meta_attribute != NULL) {
2562 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002563
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002564 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2565 /* Data descriptors implement tp_descr_set to intercept
2566 * writes. Assume the attribute is not overridden in
2567 * type's tp_dict (and bases): call the descriptor now.
2568 */
2569 return meta_get(meta_attribute, (PyObject *)type,
2570 (PyObject *)metatype);
2571 }
2572 Py_INCREF(meta_attribute);
2573 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002574
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002575 /* No data descriptor found on metatype. Look in tp_dict of this
2576 * type and its bases */
2577 attribute = _PyType_Lookup(type, name);
2578 if (attribute != NULL) {
2579 /* Implement descriptor functionality, if any */
2580 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002581
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002582 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002583
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002584 if (local_get != NULL) {
2585 /* NULL 2nd argument indicates the descriptor was
2586 * found on the target object itself (or a base) */
2587 return local_get(attribute, (PyObject *)NULL,
2588 (PyObject *)type);
2589 }
Tim Peters34592512002-07-11 06:23:50 +00002590
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002591 Py_INCREF(attribute);
2592 return attribute;
2593 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002594
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002595 /* No attribute found in local __dict__ (or bases): use the
2596 * descriptor from the metatype, if any */
2597 if (meta_get != NULL) {
2598 PyObject *res;
2599 res = meta_get(meta_attribute, (PyObject *)type,
2600 (PyObject *)metatype);
2601 Py_DECREF(meta_attribute);
2602 return res;
2603 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002604
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002605 /* If an ordinary attribute was found on the metatype, return it now */
2606 if (meta_attribute != NULL) {
2607 return meta_attribute;
2608 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002609
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002610 /* Give up */
2611 PyErr_Format(PyExc_AttributeError,
2612 "type object '%.50s' has no attribute '%.400s'",
2613 type->tp_name, PyString_AS_STRING(name));
2614 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002615}
2616
2617static int
2618type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2619{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002620 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2621 PyErr_Format(
2622 PyExc_TypeError,
2623 "can't set attributes of built-in/extension type '%s'",
2624 type->tp_name);
2625 return -1;
2626 }
2627 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2628 return -1;
2629 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002630}
2631
2632static void
2633type_dealloc(PyTypeObject *type)
2634{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002635 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002636
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002637 /* Assert this is a heap-allocated type object */
2638 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2639 _PyObject_GC_UNTRACK(type);
2640 PyObject_ClearWeakRefs((PyObject *)type);
2641 et = (PyHeapTypeObject *)type;
2642 Py_XDECREF(type->tp_base);
2643 Py_XDECREF(type->tp_dict);
2644 Py_XDECREF(type->tp_bases);
2645 Py_XDECREF(type->tp_mro);
2646 Py_XDECREF(type->tp_cache);
2647 Py_XDECREF(type->tp_subclasses);
2648 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2649 * of most other objects. It's okay to cast it to char *.
2650 */
2651 PyObject_Free((char *)type->tp_doc);
2652 Py_XDECREF(et->ht_name);
2653 Py_XDECREF(et->ht_slots);
2654 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002655}
2656
Guido van Rossum1c450732001-10-08 15:18:27 +00002657static PyObject *
2658type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2659{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002660 PyObject *list, *raw, *ref;
2661 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002662
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002663 list = PyList_New(0);
2664 if (list == NULL)
2665 return NULL;
2666 raw = type->tp_subclasses;
2667 if (raw == NULL)
2668 return list;
2669 assert(PyList_Check(raw));
2670 n = PyList_GET_SIZE(raw);
2671 for (i = 0; i < n; i++) {
2672 ref = PyList_GET_ITEM(raw, i);
2673 assert(PyWeakref_CheckRef(ref));
2674 ref = PyWeakref_GET_OBJECT(ref);
2675 if (ref != Py_None) {
2676 if (PyList_Append(list, ref) < 0) {
2677 Py_DECREF(list);
2678 return NULL;
2679 }
2680 }
2681 }
2682 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002683}
2684
Tim Peters6d6c1a32001-08-02 04:15:00 +00002685static PyMethodDef type_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002686 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2687 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2688 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2689 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2690 {"__instancecheck__", type___instancecheck__, METH_O,
Benjamin Peterson80a09c72011-05-24 12:42:51 -05002691 PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002692 {"__subclasscheck__", type___subclasscheck__, METH_O,
Benjamin Peterson80a09c72011-05-24 12:42:51 -05002693 PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002694 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002695};
2696
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002697PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002698"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002699"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002700
Guido van Rossum048eb752001-10-02 21:24:57 +00002701static int
2702type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2703{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002704 /* Because of type_is_gc(), the collector only calls this
2705 for heaptypes. */
2706 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002707
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002708 Py_VISIT(type->tp_dict);
2709 Py_VISIT(type->tp_cache);
2710 Py_VISIT(type->tp_mro);
2711 Py_VISIT(type->tp_bases);
2712 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002713
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002714 /* There's no need to visit type->tp_subclasses or
2715 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2716 in cycles; tp_subclasses is a list of weak references,
2717 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002718
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002719 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002720}
2721
2722static int
2723type_clear(PyTypeObject *type)
2724{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002725 /* Because of type_is_gc(), the collector only calls this
2726 for heaptypes. */
2727 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002728
Antoine Pitrou5b4b2da2011-12-15 14:15:31 +01002729 /* We need to invalidate the method cache carefully before clearing
2730 the dict, so that other objects caught in a reference cycle
2731 don't start calling destroyed methods.
2732
2733 Otherwise, the only field we need to clear is tp_mro, which is
2734 part of a hard cycle (its first element is the class itself) that
2735 won't be broken otherwise (it's a tuple and tuples don't have a
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002736 tp_clear handler). None of the other fields need to be
2737 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002738
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002739 tp_cache:
2740 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002741
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002742 tp_bases, tp_base:
2743 If these are involved in a cycle, there must be at least
2744 one other, mutable object in the cycle, e.g. a base
2745 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002746
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002747 tp_subclasses:
2748 A list of weak references can't be part of a cycle; and
2749 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002750
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002751 slots (in PyHeapTypeObject):
2752 A tuple of strings can't be part of a cycle.
2753 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002754
Antoine Pitrou5b4b2da2011-12-15 14:15:31 +01002755 PyType_Modified(type);
2756 if (type->tp_dict)
2757 PyDict_Clear(type->tp_dict);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002758 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002759
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002760 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002761}
2762
2763static int
2764type_is_gc(PyTypeObject *type)
2765{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002766 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002767}
2768
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002769PyTypeObject PyType_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002770 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2771 "type", /* tp_name */
2772 sizeof(PyHeapTypeObject), /* tp_basicsize */
2773 sizeof(PyMemberDef), /* tp_itemsize */
2774 (destructor)type_dealloc, /* tp_dealloc */
2775 0, /* tp_print */
2776 0, /* tp_getattr */
2777 0, /* tp_setattr */
2778 0, /* tp_compare */
2779 (reprfunc)type_repr, /* tp_repr */
2780 0, /* tp_as_number */
2781 0, /* tp_as_sequence */
2782 0, /* tp_as_mapping */
2783 (hashfunc)_Py_HashPointer, /* tp_hash */
2784 (ternaryfunc)type_call, /* tp_call */
2785 0, /* tp_str */
2786 (getattrofunc)type_getattro, /* tp_getattro */
2787 (setattrofunc)type_setattro, /* tp_setattro */
2788 0, /* tp_as_buffer */
2789 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2790 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2791 type_doc, /* tp_doc */
2792 (traverseproc)type_traverse, /* tp_traverse */
2793 (inquiry)type_clear, /* tp_clear */
2794 type_richcompare, /* tp_richcompare */
2795 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2796 0, /* tp_iter */
2797 0, /* tp_iternext */
2798 type_methods, /* tp_methods */
2799 type_members, /* tp_members */
2800 type_getsets, /* tp_getset */
2801 0, /* tp_base */
2802 0, /* tp_dict */
2803 0, /* tp_descr_get */
2804 0, /* tp_descr_set */
2805 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2806 type_init, /* tp_init */
2807 0, /* tp_alloc */
2808 type_new, /* tp_new */
2809 PyObject_GC_Del, /* tp_free */
2810 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002811};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002812
2813
2814/* The base type of all types (eventually)... except itself. */
2815
Guido van Rossum143b5642007-03-23 04:58:42 +00002816/* You may wonder why object.__new__() only complains about arguments
2817 when object.__init__() is not overridden, and vice versa.
2818
2819 Consider the use cases:
2820
2821 1. When neither is overridden, we want to hear complaints about
2822 excess (i.e., any) arguments, since their presence could
2823 indicate there's a bug.
2824
2825 2. When defining an Immutable type, we are likely to override only
2826 __new__(), since __init__() is called too late to initialize an
2827 Immutable object. Since __new__() defines the signature for the
2828 type, it would be a pain to have to override __init__() just to
2829 stop it from complaining about excess arguments.
2830
2831 3. When defining a Mutable type, we are likely to override only
2832 __init__(). So here the converse reasoning applies: we don't
2833 want to have to override __new__() just to stop it from
2834 complaining.
2835
2836 4. When __init__() is overridden, and the subclass __init__() calls
2837 object.__init__(), the latter should complain about excess
2838 arguments; ditto for __new__().
2839
2840 Use cases 2 and 3 make it unattractive to unconditionally check for
2841 excess arguments. The best solution that addresses all four use
2842 cases is as follows: __init__() complains about excess arguments
2843 unless __new__() is overridden and __init__() is not overridden
2844 (IOW, if __init__() is overridden or __new__() is not overridden);
2845 symmetrically, __new__() complains about excess arguments unless
2846 __init__() is overridden and __new__() is not overridden
2847 (IOW, if __new__() is overridden or __init__() is not overridden).
2848
2849 However, for backwards compatibility, this breaks too much code.
2850 Therefore, in 2.6, we'll *warn* about excess arguments when both
2851 methods are overridden; for all other cases we'll use the above
2852 rules.
2853
2854*/
2855
2856/* Forward */
2857static PyObject *
2858object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2859
2860static int
2861excess_args(PyObject *args, PyObject *kwds)
2862{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002863 return PyTuple_GET_SIZE(args) ||
2864 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossum143b5642007-03-23 04:58:42 +00002865}
2866
Tim Peters6d6c1a32001-08-02 04:15:00 +00002867static int
2868object_init(PyObject *self, PyObject *args, PyObject *kwds)
2869{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002870 int err = 0;
2871 if (excess_args(args, kwds)) {
2872 PyTypeObject *type = Py_TYPE(self);
2873 if (type->tp_init != object_init &&
2874 type->tp_new != object_new)
2875 {
2876 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2877 "object.__init__() takes no parameters",
2878 1);
2879 }
2880 else if (type->tp_init != object_init ||
2881 type->tp_new == object_new)
2882 {
2883 PyErr_SetString(PyExc_TypeError,
2884 "object.__init__() takes no parameters");
2885 err = -1;
2886 }
2887 }
2888 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002889}
2890
Guido van Rossum298e4212003-02-13 16:30:16 +00002891static PyObject *
2892object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2893{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002894 int err = 0;
2895 if (excess_args(args, kwds)) {
2896 if (type->tp_new != object_new &&
2897 type->tp_init != object_init)
2898 {
2899 err = PyErr_WarnEx(PyExc_DeprecationWarning,
R David Murray5aff27a2013-02-18 22:04:59 -05002900 "object() takes no parameters",
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002901 1);
2902 }
2903 else if (type->tp_new != object_new ||
2904 type->tp_init == object_init)
2905 {
2906 PyErr_SetString(PyExc_TypeError,
R David Murray5aff27a2013-02-18 22:04:59 -05002907 "object() takes no parameters");
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002908 err = -1;
2909 }
2910 }
2911 if (err < 0)
2912 return NULL;
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00002913
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002914 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2915 static PyObject *comma = NULL;
2916 PyObject *abstract_methods = NULL;
2917 PyObject *builtins;
2918 PyObject *sorted;
2919 PyObject *sorted_methods = NULL;
2920 PyObject *joined = NULL;
2921 const char *joined_str;
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00002922
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002923 /* Compute ", ".join(sorted(type.__abstractmethods__))
2924 into joined. */
2925 abstract_methods = type_abstractmethods(type, NULL);
2926 if (abstract_methods == NULL)
2927 goto error;
2928 builtins = PyEval_GetBuiltins();
2929 if (builtins == NULL)
2930 goto error;
2931 sorted = PyDict_GetItemString(builtins, "sorted");
2932 if (sorted == NULL)
2933 goto error;
2934 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2935 abstract_methods,
2936 NULL);
2937 if (sorted_methods == NULL)
2938 goto error;
2939 if (comma == NULL) {
2940 comma = PyString_InternFromString(", ");
2941 if (comma == NULL)
2942 goto error;
2943 }
2944 joined = PyObject_CallMethod(comma, "join",
2945 "O", sorted_methods);
2946 if (joined == NULL)
2947 goto error;
2948 joined_str = PyString_AsString(joined);
2949 if (joined_str == NULL)
2950 goto error;
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00002951
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002952 PyErr_Format(PyExc_TypeError,
2953 "Can't instantiate abstract class %s "
2954 "with abstract methods %s",
2955 type->tp_name,
2956 joined_str);
2957 error:
2958 Py_XDECREF(joined);
2959 Py_XDECREF(sorted_methods);
2960 Py_XDECREF(abstract_methods);
2961 return NULL;
2962 }
2963 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00002964}
2965
Tim Peters6d6c1a32001-08-02 04:15:00 +00002966static void
2967object_dealloc(PyObject *self)
2968{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002969 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002970}
2971
Guido van Rossum8e248182001-08-12 05:17:56 +00002972static PyObject *
2973object_repr(PyObject *self)
2974{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002975 PyTypeObject *type;
2976 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002977
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002978 type = Py_TYPE(self);
2979 mod = type_module(type, NULL);
2980 if (mod == NULL)
2981 PyErr_Clear();
2982 else if (!PyString_Check(mod)) {
2983 Py_DECREF(mod);
2984 mod = NULL;
2985 }
2986 name = type_name(type, NULL);
Christian Heimes47770ed2012-09-10 16:57:36 +02002987 if (name == NULL) {
2988 Py_XDECREF(mod);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002989 return NULL;
Christian Heimes47770ed2012-09-10 16:57:36 +02002990 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002991 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
2992 rtn = PyString_FromFormat("<%s.%s object at %p>",
2993 PyString_AS_STRING(mod),
2994 PyString_AS_STRING(name),
2995 self);
2996 else
2997 rtn = PyString_FromFormat("<%s object at %p>",
2998 type->tp_name, self);
2999 Py_XDECREF(mod);
3000 Py_DECREF(name);
3001 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00003002}
3003
Guido van Rossumb8f63662001-08-15 23:57:02 +00003004static PyObject *
3005object_str(PyObject *self)
3006{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003007 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003008
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003009 f = Py_TYPE(self)->tp_repr;
Benjamin Petersond157a4c2012-04-24 11:06:25 -04003010 if (f == NULL)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003011 f = object_repr;
3012 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003013}
3014
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003015static PyObject *
3016object_get_class(PyObject *self, void *closure)
3017{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003018 Py_INCREF(Py_TYPE(self));
3019 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003020}
3021
3022static int
3023equiv_structs(PyTypeObject *a, PyTypeObject *b)
3024{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003025 return a == b ||
3026 (a != NULL &&
3027 b != NULL &&
3028 a->tp_basicsize == b->tp_basicsize &&
3029 a->tp_itemsize == b->tp_itemsize &&
3030 a->tp_dictoffset == b->tp_dictoffset &&
3031 a->tp_weaklistoffset == b->tp_weaklistoffset &&
3032 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3033 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003034}
3035
3036static int
3037same_slots_added(PyTypeObject *a, PyTypeObject *b)
3038{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003039 PyTypeObject *base = a->tp_base;
3040 Py_ssize_t size;
3041 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003042
Benjamin Petersoncf94b8b2011-01-17 19:30:29 +00003043 assert(base == b->tp_base);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003044 size = base->tp_basicsize;
3045 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3046 size += sizeof(PyObject *);
3047 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3048 size += sizeof(PyObject *);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00003049
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003050 /* Check slots compliance */
3051 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3052 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3053 if (slots_a && slots_b) {
3054 if (PyObject_Compare(slots_a, slots_b) != 0)
3055 return 0;
3056 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3057 }
3058 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003059}
3060
3061static int
Anthony Baxtera6286212006-04-11 07:42:36 +00003062compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003063{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003064 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003065
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003066 if (newto->tp_dealloc != oldto->tp_dealloc ||
3067 newto->tp_free != oldto->tp_free)
3068 {
3069 PyErr_Format(PyExc_TypeError,
3070 "%s assignment: "
3071 "'%s' deallocator differs from '%s'",
3072 attr,
3073 newto->tp_name,
3074 oldto->tp_name);
3075 return 0;
3076 }
3077 newbase = newto;
3078 oldbase = oldto;
3079 while (equiv_structs(newbase, newbase->tp_base))
3080 newbase = newbase->tp_base;
3081 while (equiv_structs(oldbase, oldbase->tp_base))
3082 oldbase = oldbase->tp_base;
3083 if (newbase != oldbase &&
3084 (newbase->tp_base != oldbase->tp_base ||
3085 !same_slots_added(newbase, oldbase))) {
3086 PyErr_Format(PyExc_TypeError,
3087 "%s assignment: "
3088 "'%s' object layout differs from '%s'",
3089 attr,
3090 newto->tp_name,
3091 oldto->tp_name);
3092 return 0;
3093 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003094
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003095 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003096}
3097
3098static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003099object_set_class(PyObject *self, PyObject *value, void *closure)
3100{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003101 PyTypeObject *oldto = Py_TYPE(self);
3102 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003103
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003104 if (value == NULL) {
3105 PyErr_SetString(PyExc_TypeError,
3106 "can't delete __class__ attribute");
3107 return -1;
3108 }
3109 if (!PyType_Check(value)) {
3110 PyErr_Format(PyExc_TypeError,
3111 "__class__ must be set to new-style class, not '%s' object",
3112 Py_TYPE(value)->tp_name);
3113 return -1;
3114 }
3115 newto = (PyTypeObject *)value;
3116 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3117 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3118 {
3119 PyErr_Format(PyExc_TypeError,
3120 "__class__ assignment: only for heap types");
3121 return -1;
3122 }
3123 if (compatible_for_assignment(newto, oldto, "__class__")) {
3124 Py_INCREF(newto);
3125 Py_TYPE(self) = newto;
3126 Py_DECREF(oldto);
3127 return 0;
3128 }
3129 else {
3130 return -1;
3131 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003132}
3133
3134static PyGetSetDef object_getsets[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003135 {"__class__", object_get_class, object_set_class,
3136 PyDoc_STR("the object's class")},
3137 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003138};
3139
Guido van Rossumc53f0092003-02-18 22:05:12 +00003140
Guido van Rossum036f9992003-02-21 22:02:54 +00003141/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Georg Brandldffbf5f2008-05-20 07:49:57 +00003142 We fall back to helpers in copy_reg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003143 - pickle protocols < 2
3144 - calculating the list of slot names (done only once per class)
3145 - the __newobj__ function (which is used as a token but never called)
3146*/
3147
3148static PyObject *
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003149import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003150{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003151 static PyObject *copyreg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00003152
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003153 if (!copyreg_str) {
3154 copyreg_str = PyString_InternFromString("copy_reg");
3155 if (copyreg_str == NULL)
3156 return NULL;
3157 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003158
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003159 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003160}
3161
3162static PyObject *
3163slotnames(PyObject *cls)
3164{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003165 PyObject *clsdict;
3166 PyObject *copyreg;
3167 PyObject *slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003168
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003169 if (!PyType_Check(cls)) {
3170 Py_INCREF(Py_None);
3171 return Py_None;
3172 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003173
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003174 clsdict = ((PyTypeObject *)cls)->tp_dict;
3175 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
3176 if (slotnames != NULL && PyList_Check(slotnames)) {
3177 Py_INCREF(slotnames);
3178 return slotnames;
3179 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003180
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003181 copyreg = import_copyreg();
3182 if (copyreg == NULL)
3183 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003184
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003185 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
3186 Py_DECREF(copyreg);
3187 if (slotnames != NULL &&
3188 slotnames != Py_None &&
3189 !PyList_Check(slotnames))
3190 {
3191 PyErr_SetString(PyExc_TypeError,
3192 "copy_reg._slotnames didn't return a list or None");
3193 Py_DECREF(slotnames);
3194 slotnames = NULL;
3195 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003196
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003197 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003198}
3199
3200static PyObject *
3201reduce_2(PyObject *obj)
3202{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003203 PyObject *cls, *getnewargs;
3204 PyObject *args = NULL, *args2 = NULL;
3205 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3206 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3207 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3208 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00003209
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003210 cls = PyObject_GetAttrString(obj, "__class__");
3211 if (cls == NULL)
3212 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003213
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003214 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
3215 if (getnewargs != NULL) {
3216 args = PyObject_CallObject(getnewargs, NULL);
3217 Py_DECREF(getnewargs);
3218 if (args != NULL && !PyTuple_Check(args)) {
3219 PyErr_Format(PyExc_TypeError,
3220 "__getnewargs__ should return a tuple, "
3221 "not '%.200s'", Py_TYPE(args)->tp_name);
3222 goto end;
3223 }
3224 }
3225 else {
3226 PyErr_Clear();
3227 args = PyTuple_New(0);
3228 }
3229 if (args == NULL)
3230 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003231
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003232 getstate = PyObject_GetAttrString(obj, "__getstate__");
3233 if (getstate != NULL) {
3234 state = PyObject_CallObject(getstate, NULL);
3235 Py_DECREF(getstate);
3236 if (state == NULL)
3237 goto end;
3238 }
3239 else {
3240 PyErr_Clear();
3241 state = PyObject_GetAttrString(obj, "__dict__");
3242 if (state == NULL) {
3243 PyErr_Clear();
3244 state = Py_None;
3245 Py_INCREF(state);
3246 }
3247 names = slotnames(cls);
3248 if (names == NULL)
3249 goto end;
3250 if (names != Py_None) {
3251 assert(PyList_Check(names));
3252 slots = PyDict_New();
3253 if (slots == NULL)
3254 goto end;
3255 n = 0;
3256 /* Can't pre-compute the list size; the list
3257 is stored on the class so accessible to other
3258 threads, which may be run by DECREF */
3259 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3260 PyObject *name, *value;
3261 name = PyList_GET_ITEM(names, i);
3262 value = PyObject_GetAttr(obj, name);
3263 if (value == NULL)
3264 PyErr_Clear();
3265 else {
3266 int err = PyDict_SetItem(slots, name,
3267 value);
3268 Py_DECREF(value);
3269 if (err)
3270 goto end;
3271 n++;
3272 }
3273 }
3274 if (n) {
3275 state = Py_BuildValue("(NO)", state, slots);
3276 if (state == NULL)
3277 goto end;
3278 }
3279 }
3280 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003281
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003282 if (!PyList_Check(obj)) {
3283 listitems = Py_None;
3284 Py_INCREF(listitems);
3285 }
3286 else {
3287 listitems = PyObject_GetIter(obj);
3288 if (listitems == NULL)
3289 goto end;
3290 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003291
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003292 if (!PyDict_Check(obj)) {
3293 dictitems = Py_None;
3294 Py_INCREF(dictitems);
3295 }
3296 else {
3297 dictitems = PyObject_CallMethod(obj, "iteritems", "");
3298 if (dictitems == NULL)
3299 goto end;
3300 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003301
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003302 copyreg = import_copyreg();
3303 if (copyreg == NULL)
3304 goto end;
3305 newobj = PyObject_GetAttrString(copyreg, "__newobj__");
3306 if (newobj == NULL)
3307 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003308
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003309 n = PyTuple_GET_SIZE(args);
3310 args2 = PyTuple_New(n+1);
3311 if (args2 == NULL)
3312 goto end;
3313 PyTuple_SET_ITEM(args2, 0, cls);
3314 cls = NULL;
3315 for (i = 0; i < n; i++) {
3316 PyObject *v = PyTuple_GET_ITEM(args, i);
3317 Py_INCREF(v);
3318 PyTuple_SET_ITEM(args2, i+1, v);
3319 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003320
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003321 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003322
3323 end:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003324 Py_XDECREF(cls);
3325 Py_XDECREF(args);
3326 Py_XDECREF(args2);
3327 Py_XDECREF(slots);
3328 Py_XDECREF(state);
3329 Py_XDECREF(names);
3330 Py_XDECREF(listitems);
3331 Py_XDECREF(dictitems);
3332 Py_XDECREF(copyreg);
3333 Py_XDECREF(newobj);
3334 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003335}
3336
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003337/*
3338 * There were two problems when object.__reduce__ and object.__reduce_ex__
3339 * were implemented in the same function:
3340 * - trying to pickle an object with a custom __reduce__ method that
3341 * fell back to object.__reduce__ in certain circumstances led to
3342 * infinite recursion at Python level and eventual RuntimeError.
3343 * - Pickling objects that lied about their type by overwriting the
3344 * __class__ descriptor could lead to infinite recursion at C level
3345 * and eventual segfault.
3346 *
3347 * Because of backwards compatibility, the two methods still have to
3348 * behave in the same way, even if this is not required by the pickle
3349 * protocol. This common functionality was moved to the _common_reduce
3350 * function.
3351 */
3352static PyObject *
3353_common_reduce(PyObject *self, int proto)
3354{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003355 PyObject *copyreg, *res;
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003356
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003357 if (proto >= 2)
3358 return reduce_2(self);
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003359
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003360 copyreg = import_copyreg();
3361 if (!copyreg)
3362 return NULL;
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003363
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003364 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3365 Py_DECREF(copyreg);
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003366
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003367 return res;
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003368}
3369
3370static PyObject *
3371object_reduce(PyObject *self, PyObject *args)
3372{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003373 int proto = 0;
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003374
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003375 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3376 return NULL;
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003377
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003378 return _common_reduce(self, proto);
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003379}
3380
Guido van Rossum036f9992003-02-21 22:02:54 +00003381static PyObject *
3382object_reduce_ex(PyObject *self, PyObject *args)
3383{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003384 PyObject *reduce, *res;
3385 int proto = 0;
Guido van Rossum036f9992003-02-21 22:02:54 +00003386
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003387 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3388 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003389
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003390 reduce = PyObject_GetAttrString(self, "__reduce__");
3391 if (reduce == NULL)
3392 PyErr_Clear();
3393 else {
3394 PyObject *cls, *clsreduce, *objreduce;
3395 int override;
3396 cls = PyObject_GetAttrString(self, "__class__");
3397 if (cls == NULL) {
3398 Py_DECREF(reduce);
3399 return NULL;
3400 }
3401 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3402 Py_DECREF(cls);
3403 if (clsreduce == NULL) {
3404 Py_DECREF(reduce);
3405 return NULL;
3406 }
3407 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3408 "__reduce__");
3409 override = (clsreduce != objreduce);
3410 Py_DECREF(clsreduce);
3411 if (override) {
3412 res = PyObject_CallObject(reduce, NULL);
3413 Py_DECREF(reduce);
3414 return res;
3415 }
3416 else
3417 Py_DECREF(reduce);
3418 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003419
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003420 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003421}
3422
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00003423static PyObject *
3424object_subclasshook(PyObject *cls, PyObject *args)
3425{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003426 Py_INCREF(Py_NotImplemented);
3427 return Py_NotImplemented;
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00003428}
3429
3430PyDoc_STRVAR(object_subclasshook_doc,
3431"Abstract classes can override this to customize issubclass().\n"
3432"\n"
3433"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3434"It should return True, False or NotImplemented. If it returns\n"
3435"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3436"overrides the normal algorithm (and the outcome is cached).\n");
3437
Eric Smitha9f7d622008-02-17 19:46:49 +00003438/*
3439 from PEP 3101, this code implements:
3440
3441 class object:
3442 def __format__(self, format_spec):
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003443 if isinstance(format_spec, str):
3444 return format(str(self), format_spec)
3445 elif isinstance(format_spec, unicode):
3446 return format(unicode(self), format_spec)
Eric Smitha9f7d622008-02-17 19:46:49 +00003447*/
3448static PyObject *
3449object_format(PyObject *self, PyObject *args)
3450{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003451 PyObject *format_spec;
3452 PyObject *self_as_str = NULL;
3453 PyObject *result = NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003454 Py_ssize_t format_len;
Eric Smitha9f7d622008-02-17 19:46:49 +00003455
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003456 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3457 return NULL;
Benjamin Peterson78821dd2009-01-25 17:15:10 +00003458#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003459 if (PyUnicode_Check(format_spec)) {
3460 format_len = PyUnicode_GET_SIZE(format_spec);
3461 self_as_str = PyObject_Unicode(self);
3462 } else if (PyString_Check(format_spec)) {
Benjamin Peterson78821dd2009-01-25 17:15:10 +00003463#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003464 if (PyString_Check(format_spec)) {
Benjamin Peterson78821dd2009-01-25 17:15:10 +00003465#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003466 format_len = PyString_GET_SIZE(format_spec);
3467 self_as_str = PyObject_Str(self);
3468 } else {
3469 PyErr_SetString(PyExc_TypeError,
3470 "argument to __format__ must be unicode or str");
3471 return NULL;
3472 }
Eric Smitha9f7d622008-02-17 19:46:49 +00003473
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003474 if (self_as_str != NULL) {
3475 /* Issue 7994: If we're converting to a string, we
3476 should reject format specifications */
3477 if (format_len > 0) {
3478 if (PyErr_WarnEx(PyExc_PendingDeprecationWarning,
3479 "object.__format__ with a non-empty format "
3480 "string is deprecated", 1) < 0) {
3481 goto done;
3482 }
3483 /* Eventually this will become an error:
3484 PyErr_Format(PyExc_TypeError,
3485 "non-empty format string passed to object.__format__");
3486 goto done;
3487 */
Eric Smitha9f7d622008-02-17 19:46:49 +00003488 }
Benjamin Peterson67783b12010-06-05 01:00:10 +00003489 result = PyObject_Format(self_as_str, format_spec);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003490 }
Eric Smitha9f7d622008-02-17 19:46:49 +00003491
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003492done:
3493 Py_XDECREF(self_as_str);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003494
3495 return result;
Eric Smitha9f7d622008-02-17 19:46:49 +00003496}
3497
Robert Schuppenies51df0642008-06-01 16:16:17 +00003498static PyObject *
3499object_sizeof(PyObject *self, PyObject *args)
3500{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003501 Py_ssize_t res, isize;
Robert Schuppenies51df0642008-06-01 16:16:17 +00003502
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003503 res = 0;
3504 isize = self->ob_type->tp_itemsize;
3505 if (isize > 0)
3506 res = self->ob_type->ob_size * isize;
3507 res += self->ob_type->tp_basicsize;
Robert Schuppenies51df0642008-06-01 16:16:17 +00003508
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003509 return PyInt_FromSsize_t(res);
Robert Schuppenies51df0642008-06-01 16:16:17 +00003510}
3511
Guido van Rossum3926a632001-09-25 16:25:58 +00003512static PyMethodDef object_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003513 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3514 PyDoc_STR("helper for pickle")},
3515 {"__reduce__", object_reduce, METH_VARARGS,
3516 PyDoc_STR("helper for pickle")},
3517 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3518 object_subclasshook_doc},
3519 {"__format__", object_format, METH_VARARGS,
3520 PyDoc_STR("default object formatter")},
3521 {"__sizeof__", object_sizeof, METH_NOARGS,
Benjamin Peterson80a09c72011-05-24 12:42:51 -05003522 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003523 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003524};
3525
Guido van Rossum036f9992003-02-21 22:02:54 +00003526
Tim Peters6d6c1a32001-08-02 04:15:00 +00003527PyTypeObject PyBaseObject_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003528 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3529 "object", /* tp_name */
3530 sizeof(PyObject), /* tp_basicsize */
3531 0, /* tp_itemsize */
3532 object_dealloc, /* tp_dealloc */
3533 0, /* tp_print */
3534 0, /* tp_getattr */
3535 0, /* tp_setattr */
3536 0, /* tp_compare */
3537 object_repr, /* tp_repr */
3538 0, /* tp_as_number */
3539 0, /* tp_as_sequence */
3540 0, /* tp_as_mapping */
3541 (hashfunc)_Py_HashPointer, /* tp_hash */
3542 0, /* tp_call */
3543 object_str, /* tp_str */
3544 PyObject_GenericGetAttr, /* tp_getattro */
3545 PyObject_GenericSetAttr, /* tp_setattro */
3546 0, /* tp_as_buffer */
3547 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3548 PyDoc_STR("The most base type"), /* tp_doc */
3549 0, /* tp_traverse */
3550 0, /* tp_clear */
3551 0, /* tp_richcompare */
3552 0, /* tp_weaklistoffset */
3553 0, /* tp_iter */
3554 0, /* tp_iternext */
3555 object_methods, /* tp_methods */
3556 0, /* tp_members */
3557 object_getsets, /* tp_getset */
3558 0, /* tp_base */
3559 0, /* tp_dict */
3560 0, /* tp_descr_get */
3561 0, /* tp_descr_set */
3562 0, /* tp_dictoffset */
3563 object_init, /* tp_init */
3564 PyType_GenericAlloc, /* tp_alloc */
3565 object_new, /* tp_new */
3566 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003567};
3568
3569
3570/* Initialize the __dict__ in a type object */
3571
3572static int
3573add_methods(PyTypeObject *type, PyMethodDef *meth)
3574{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003575 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003576
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003577 for (; meth->ml_name != NULL; meth++) {
3578 PyObject *descr;
Benjamin Petersonf1ae5cf2012-05-08 09:22:24 -04003579 int err;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003580 if (PyDict_GetItemString(dict, meth->ml_name) &&
3581 !(meth->ml_flags & METH_COEXIST))
3582 continue;
3583 if (meth->ml_flags & METH_CLASS) {
3584 if (meth->ml_flags & METH_STATIC) {
3585 PyErr_SetString(PyExc_ValueError,
3586 "method cannot be both class and static");
3587 return -1;
3588 }
3589 descr = PyDescr_NewClassMethod(type, meth);
3590 }
3591 else if (meth->ml_flags & METH_STATIC) {
3592 PyObject *cfunc = PyCFunction_New(meth, NULL);
3593 if (cfunc == NULL)
3594 return -1;
3595 descr = PyStaticMethod_New(cfunc);
3596 Py_DECREF(cfunc);
3597 }
3598 else {
3599 descr = PyDescr_NewMethod(type, meth);
3600 }
3601 if (descr == NULL)
3602 return -1;
Benjamin Petersonf1ae5cf2012-05-08 09:22:24 -04003603 err = PyDict_SetItemString(dict, meth->ml_name, descr);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003604 Py_DECREF(descr);
Benjamin Petersonf1ae5cf2012-05-08 09:22:24 -04003605 if (err < 0)
3606 return -1;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003607 }
3608 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003609}
3610
3611static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003612add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003613{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003614 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003615
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003616 for (; memb->name != NULL; memb++) {
3617 PyObject *descr;
3618 if (PyDict_GetItemString(dict, memb->name))
3619 continue;
3620 descr = PyDescr_NewMember(type, memb);
3621 if (descr == NULL)
3622 return -1;
3623 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3624 return -1;
3625 Py_DECREF(descr);
3626 }
3627 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003628}
3629
3630static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003631add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003632{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003633 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003634
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003635 for (; gsp->name != NULL; gsp++) {
3636 PyObject *descr;
3637 if (PyDict_GetItemString(dict, gsp->name))
3638 continue;
3639 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003640
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003641 if (descr == NULL)
3642 return -1;
3643 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3644 return -1;
3645 Py_DECREF(descr);
3646 }
3647 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003648}
3649
Antoine Pitrou789be0c2009-04-02 21:18:34 +00003650#define BUFFER_FLAGS (Py_TPFLAGS_HAVE_GETCHARBUFFER | Py_TPFLAGS_HAVE_NEWBUFFER)
3651
Guido van Rossum13d52f02001-08-10 21:24:08 +00003652static void
3653inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003654{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003655 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003656
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003657 /* Special flag magic */
3658 if (!type->tp_as_buffer && base->tp_as_buffer) {
3659 type->tp_flags &= ~BUFFER_FLAGS;
3660 type->tp_flags |=
3661 base->tp_flags & BUFFER_FLAGS;
3662 }
3663 if (!type->tp_as_sequence && base->tp_as_sequence) {
3664 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3665 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3666 }
3667 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3668 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3669 if ((!type->tp_as_number && base->tp_as_number) ||
3670 (!type->tp_as_sequence && base->tp_as_sequence)) {
3671 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3672 if (!type->tp_as_number && !type->tp_as_sequence) {
3673 type->tp_flags |= base->tp_flags &
3674 Py_TPFLAGS_HAVE_INPLACEOPS;
3675 }
3676 }
3677 /* Wow */
3678 }
3679 if (!type->tp_as_number && base->tp_as_number) {
3680 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3681 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3682 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00003683
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003684 /* Copying basicsize is connected to the GC flags */
3685 oldsize = base->tp_basicsize;
3686 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3687 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3688 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3689 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3690 (!type->tp_traverse && !type->tp_clear)) {
3691 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3692 if (type->tp_traverse == NULL)
3693 type->tp_traverse = base->tp_traverse;
3694 if (type->tp_clear == NULL)
3695 type->tp_clear = base->tp_clear;
3696 }
3697 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3698 /* The condition below could use some explanation.
3699 It appears that tp_new is not inherited for static types
3700 whose base class is 'object'; this seems to be a precaution
3701 so that old extension types don't suddenly become
3702 callable (object.__new__ wouldn't insure the invariants
3703 that the extension type's own factory function ensures).
3704 Heap types, of course, are under our control, so they do
3705 inherit tp_new; static extension types that specify some
3706 other built-in type as the default are considered
3707 new-style-aware so they also inherit object.__new__. */
3708 if (base != &PyBaseObject_Type ||
3709 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3710 if (type->tp_new == NULL)
3711 type->tp_new = base->tp_new;
3712 }
3713 }
3714 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003715
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003716 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003717
3718#undef COPYVAL
3719#define COPYVAL(SLOT) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003720 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003721
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003722 COPYVAL(tp_itemsize);
3723 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3724 COPYVAL(tp_weaklistoffset);
3725 }
3726 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3727 COPYVAL(tp_dictoffset);
3728 }
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003729
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003730 /* Setup fast subclass flags */
3731 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3732 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3733 else if (PyType_IsSubtype(base, &PyType_Type))
3734 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3735 else if (PyType_IsSubtype(base, &PyInt_Type))
3736 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3737 else if (PyType_IsSubtype(base, &PyLong_Type))
3738 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3739 else if (PyType_IsSubtype(base, &PyString_Type))
3740 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003741#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003742 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3743 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003744#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003745 else if (PyType_IsSubtype(base, &PyTuple_Type))
3746 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3747 else if (PyType_IsSubtype(base, &PyList_Type))
3748 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3749 else if (PyType_IsSubtype(base, &PyDict_Type))
3750 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003751}
3752
Nick Coghlan48361f52008-08-11 15:45:58 +00003753static int
3754overrides_name(PyTypeObject *type, char *name)
3755{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003756 PyObject *dict = type->tp_dict;
Nick Coghlan48361f52008-08-11 15:45:58 +00003757
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003758 assert(dict != NULL);
3759 if (PyDict_GetItemString(dict, name) != NULL) {
3760 return 1;
3761 }
3762 return 0;
Nick Coghlan48361f52008-08-11 15:45:58 +00003763}
3764
3765#define OVERRIDES_HASH(x) overrides_name(x, "__hash__")
Nick Coghlan48361f52008-08-11 15:45:58 +00003766#define OVERRIDES_EQ(x) overrides_name(x, "__eq__")
3767
Guido van Rossum13d52f02001-08-10 21:24:08 +00003768static void
3769inherit_slots(PyTypeObject *type, PyTypeObject *base)
3770{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003771 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003772
3773#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003774#undef COPYSLOT
3775#undef COPYNUM
3776#undef COPYSEQ
3777#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003778#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003779
3780#define SLOTDEFINED(SLOT) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003781 (base->SLOT != 0 && \
3782 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003783
Tim Peters6d6c1a32001-08-02 04:15:00 +00003784#define COPYSLOT(SLOT) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003785 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003786
3787#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3788#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3789#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003790#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003791
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003792 /* This won't inherit indirect slots (from tp_as_number etc.)
3793 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003794
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003795 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3796 basebase = base->tp_base;
3797 if (basebase->tp_as_number == NULL)
3798 basebase = NULL;
3799 COPYNUM(nb_add);
3800 COPYNUM(nb_subtract);
3801 COPYNUM(nb_multiply);
3802 COPYNUM(nb_divide);
3803 COPYNUM(nb_remainder);
3804 COPYNUM(nb_divmod);
3805 COPYNUM(nb_power);
3806 COPYNUM(nb_negative);
3807 COPYNUM(nb_positive);
3808 COPYNUM(nb_absolute);
3809 COPYNUM(nb_nonzero);
3810 COPYNUM(nb_invert);
3811 COPYNUM(nb_lshift);
3812 COPYNUM(nb_rshift);
3813 COPYNUM(nb_and);
3814 COPYNUM(nb_xor);
3815 COPYNUM(nb_or);
3816 COPYNUM(nb_coerce);
3817 COPYNUM(nb_int);
3818 COPYNUM(nb_long);
3819 COPYNUM(nb_float);
3820 COPYNUM(nb_oct);
3821 COPYNUM(nb_hex);
3822 COPYNUM(nb_inplace_add);
3823 COPYNUM(nb_inplace_subtract);
3824 COPYNUM(nb_inplace_multiply);
3825 COPYNUM(nb_inplace_divide);
3826 COPYNUM(nb_inplace_remainder);
3827 COPYNUM(nb_inplace_power);
3828 COPYNUM(nb_inplace_lshift);
3829 COPYNUM(nb_inplace_rshift);
3830 COPYNUM(nb_inplace_and);
3831 COPYNUM(nb_inplace_xor);
3832 COPYNUM(nb_inplace_or);
3833 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3834 COPYNUM(nb_true_divide);
3835 COPYNUM(nb_floor_divide);
3836 COPYNUM(nb_inplace_true_divide);
3837 COPYNUM(nb_inplace_floor_divide);
3838 }
3839 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3840 COPYNUM(nb_index);
3841 }
3842 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003843
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003844 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3845 basebase = base->tp_base;
3846 if (basebase->tp_as_sequence == NULL)
3847 basebase = NULL;
3848 COPYSEQ(sq_length);
3849 COPYSEQ(sq_concat);
3850 COPYSEQ(sq_repeat);
3851 COPYSEQ(sq_item);
3852 COPYSEQ(sq_slice);
3853 COPYSEQ(sq_ass_item);
3854 COPYSEQ(sq_ass_slice);
3855 COPYSEQ(sq_contains);
3856 COPYSEQ(sq_inplace_concat);
3857 COPYSEQ(sq_inplace_repeat);
3858 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003859
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003860 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3861 basebase = base->tp_base;
3862 if (basebase->tp_as_mapping == NULL)
3863 basebase = NULL;
3864 COPYMAP(mp_length);
3865 COPYMAP(mp_subscript);
3866 COPYMAP(mp_ass_subscript);
3867 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003868
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003869 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3870 basebase = base->tp_base;
3871 if (basebase->tp_as_buffer == NULL)
3872 basebase = NULL;
3873 COPYBUF(bf_getreadbuffer);
3874 COPYBUF(bf_getwritebuffer);
3875 COPYBUF(bf_getsegcount);
3876 COPYBUF(bf_getcharbuffer);
3877 COPYBUF(bf_getbuffer);
3878 COPYBUF(bf_releasebuffer);
3879 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00003880
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003881 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003882
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003883 COPYSLOT(tp_dealloc);
3884 COPYSLOT(tp_print);
3885 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3886 type->tp_getattr = base->tp_getattr;
3887 type->tp_getattro = base->tp_getattro;
3888 }
3889 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3890 type->tp_setattr = base->tp_setattr;
3891 type->tp_setattro = base->tp_setattro;
3892 }
3893 /* tp_compare see tp_richcompare */
3894 COPYSLOT(tp_repr);
3895 /* tp_hash see tp_richcompare */
3896 COPYSLOT(tp_call);
3897 COPYSLOT(tp_str);
3898 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
3899 if (type->tp_compare == NULL &&
3900 type->tp_richcompare == NULL &&
3901 type->tp_hash == NULL)
3902 {
3903 type->tp_compare = base->tp_compare;
3904 type->tp_richcompare = base->tp_richcompare;
3905 type->tp_hash = base->tp_hash;
3906 /* Check for changes to inherited methods in Py3k*/
3907 if (Py_Py3kWarningFlag) {
3908 if (base->tp_hash &&
3909 (base->tp_hash != PyObject_HashNotImplemented) &&
3910 !OVERRIDES_HASH(type)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003911 if (OVERRIDES_EQ(type)) {
Mark Dickinsone4b83e02010-06-05 12:14:43 +00003912 if (PyErr_WarnPy3k("Overriding "
3913 "__eq__ blocks inheritance "
3914 "of __hash__ in 3.x",
3915 1) < 0)
3916 /* XXX This isn't right. If the warning is turned
3917 into an exception, we should be communicating
3918 the error back to the caller, but figuring out
Mark Dickinson77acee92010-06-05 12:51:21 +00003919 how to clean up in that case is tricky. See
Mark Dickinsone4b83e02010-06-05 12:14:43 +00003920 issue 8627 for more. */
3921 PyErr_Clear();
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003922 }
3923 }
3924 }
3925 }
3926 }
3927 else {
3928 COPYSLOT(tp_compare);
3929 }
3930 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3931 COPYSLOT(tp_iter);
3932 COPYSLOT(tp_iternext);
3933 }
3934 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3935 COPYSLOT(tp_descr_get);
3936 COPYSLOT(tp_descr_set);
3937 COPYSLOT(tp_dictoffset);
3938 COPYSLOT(tp_init);
3939 COPYSLOT(tp_alloc);
3940 COPYSLOT(tp_is_gc);
3941 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3942 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3943 /* They agree about gc. */
3944 COPYSLOT(tp_free);
3945 }
3946 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3947 type->tp_free == NULL &&
3948 base->tp_free == _PyObject_Del) {
3949 /* A bit of magic to plug in the correct default
3950 * tp_free function when a derived class adds gc,
3951 * didn't define tp_free, and the base uses the
3952 * default non-gc tp_free.
3953 */
3954 type->tp_free = PyObject_GC_Del;
3955 }
3956 /* else they didn't agree about gc, and there isn't something
3957 * obvious to be done -- the type is on its own.
3958 */
3959 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003960}
3961
Jeremy Hylton938ace62002-07-17 16:30:39 +00003962static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003963
Tim Peters6d6c1a32001-08-02 04:15:00 +00003964int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003965PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003966{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003967 PyObject *dict, *bases;
3968 PyTypeObject *base;
3969 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003970
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003971 if (type->tp_flags & Py_TPFLAGS_READY) {
3972 assert(type->tp_dict != NULL);
3973 return 0;
3974 }
3975 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003976
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003977 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003978
Tim Peters36eb4df2003-03-23 03:33:13 +00003979#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003980 /* PyType_Ready is the closest thing we have to a choke point
3981 * for type objects, so is the best place I can think of to try
3982 * to get type objects into the doubly-linked list of all objects.
3983 * Still, not all type objects go thru PyType_Ready.
3984 */
3985 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003986#endif
3987
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003988 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3989 base = type->tp_base;
3990 if (base == NULL && type != &PyBaseObject_Type) {
3991 base = type->tp_base = &PyBaseObject_Type;
3992 Py_INCREF(base);
3993 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003994
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003995 /* Now the only way base can still be NULL is if type is
3996 * &PyBaseObject_Type.
3997 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003998
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003999 /* Initialize the base class */
4000 if (base && base->tp_dict == NULL) {
4001 if (PyType_Ready(base) < 0)
4002 goto error;
4003 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00004004
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004005 /* Initialize ob_type if NULL. This means extensions that want to be
4006 compilable separately on Windows can call PyType_Ready() instead of
4007 initializing the ob_type field of their type objects. */
4008 /* The test for base != NULL is really unnecessary, since base is only
4009 NULL when type is &PyBaseObject_Type, and we know its ob_type is
4010 not NULL (it's initialized to &PyType_Type). But coverity doesn't
4011 know that. */
4012 if (Py_TYPE(type) == NULL && base != NULL)
4013 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00004014
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004015 /* Initialize tp_bases */
4016 bases = type->tp_bases;
4017 if (bases == NULL) {
4018 if (base == NULL)
4019 bases = PyTuple_New(0);
4020 else
4021 bases = PyTuple_Pack(1, base);
4022 if (bases == NULL)
4023 goto error;
4024 type->tp_bases = bases;
4025 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004026
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004027 /* Initialize tp_dict */
4028 dict = type->tp_dict;
4029 if (dict == NULL) {
4030 dict = PyDict_New();
4031 if (dict == NULL)
4032 goto error;
4033 type->tp_dict = dict;
4034 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004035
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004036 /* Add type-specific descriptors to tp_dict */
4037 if (add_operators(type) < 0)
4038 goto error;
4039 if (type->tp_methods != NULL) {
4040 if (add_methods(type, type->tp_methods) < 0)
4041 goto error;
4042 }
4043 if (type->tp_members != NULL) {
4044 if (add_members(type, type->tp_members) < 0)
4045 goto error;
4046 }
4047 if (type->tp_getset != NULL) {
4048 if (add_getset(type, type->tp_getset) < 0)
4049 goto error;
4050 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004051
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004052 /* Calculate method resolution order */
4053 if (mro_internal(type) < 0) {
4054 goto error;
4055 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004056
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004057 /* Inherit special flags from dominant base */
4058 if (type->tp_base != NULL)
4059 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004060
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004061 /* Initialize tp_dict properly */
4062 bases = type->tp_mro;
4063 assert(bases != NULL);
4064 assert(PyTuple_Check(bases));
4065 n = PyTuple_GET_SIZE(bases);
4066 for (i = 1; i < n; i++) {
4067 PyObject *b = PyTuple_GET_ITEM(bases, i);
4068 if (PyType_Check(b))
4069 inherit_slots(type, (PyTypeObject *)b);
4070 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004071
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004072 /* Sanity check for tp_free. */
4073 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4074 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4075 /* This base class needs to call tp_free, but doesn't have
4076 * one, or its tp_free is for non-gc'ed objects.
4077 */
4078 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4079 "gc and is a base type but has inappropriate "
4080 "tp_free slot",
4081 type->tp_name);
4082 goto error;
4083 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004084
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004085 /* if the type dictionary doesn't contain a __doc__, set it from
4086 the tp_doc slot.
4087 */
4088 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
4089 if (type->tp_doc != NULL) {
4090 PyObject *doc = PyString_FromString(type->tp_doc);
4091 if (doc == NULL)
4092 goto error;
4093 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
4094 Py_DECREF(doc);
4095 } else {
4096 PyDict_SetItemString(type->tp_dict,
4097 "__doc__", Py_None);
4098 }
4099 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004100
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004101 /* Some more special stuff */
4102 base = type->tp_base;
4103 if (base != NULL) {
4104 if (type->tp_as_number == NULL)
4105 type->tp_as_number = base->tp_as_number;
4106 if (type->tp_as_sequence == NULL)
4107 type->tp_as_sequence = base->tp_as_sequence;
4108 if (type->tp_as_mapping == NULL)
4109 type->tp_as_mapping = base->tp_as_mapping;
4110 if (type->tp_as_buffer == NULL)
4111 type->tp_as_buffer = base->tp_as_buffer;
4112 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004113
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004114 /* Link into each base class's list of subclasses */
4115 bases = type->tp_bases;
4116 n = PyTuple_GET_SIZE(bases);
4117 for (i = 0; i < n; i++) {
4118 PyObject *b = PyTuple_GET_ITEM(bases, i);
4119 if (PyType_Check(b) &&
4120 add_subclass((PyTypeObject *)b, type) < 0)
4121 goto error;
4122 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004123
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004124 /* All done -- set the ready flag */
4125 assert(type->tp_dict != NULL);
4126 type->tp_flags =
4127 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4128 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004129
4130 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004131 type->tp_flags &= ~Py_TPFLAGS_READYING;
4132 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004133}
4134
Guido van Rossum1c450732001-10-08 15:18:27 +00004135static int
4136add_subclass(PyTypeObject *base, PyTypeObject *type)
4137{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004138 Py_ssize_t i;
4139 int result;
4140 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004141
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004142 list = base->tp_subclasses;
4143 if (list == NULL) {
4144 base->tp_subclasses = list = PyList_New(0);
4145 if (list == NULL)
4146 return -1;
4147 }
4148 assert(PyList_Check(list));
4149 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4150 i = PyList_GET_SIZE(list);
4151 while (--i >= 0) {
4152 ref = PyList_GET_ITEM(list, i);
4153 assert(PyWeakref_CheckRef(ref));
4154 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4155 return PyList_SetItem(list, i, newobj);
4156 }
4157 result = PyList_Append(list, newobj);
4158 Py_DECREF(newobj);
4159 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004160}
4161
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004162static void
4163remove_subclass(PyTypeObject *base, PyTypeObject *type)
4164{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004165 Py_ssize_t i;
4166 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004167
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004168 list = base->tp_subclasses;
4169 if (list == NULL) {
4170 return;
4171 }
4172 assert(PyList_Check(list));
4173 i = PyList_GET_SIZE(list);
4174 while (--i >= 0) {
4175 ref = PyList_GET_ITEM(list, i);
4176 assert(PyWeakref_CheckRef(ref));
4177 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4178 /* this can't fail, right? */
4179 PySequence_DelItem(list, i);
4180 return;
4181 }
4182 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004183}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004184
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004185static int
4186check_num_args(PyObject *ob, int n)
4187{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004188 if (!PyTuple_CheckExact(ob)) {
4189 PyErr_SetString(PyExc_SystemError,
4190 "PyArg_UnpackTuple() argument list is not a tuple");
4191 return 0;
4192 }
4193 if (n == PyTuple_GET_SIZE(ob))
4194 return 1;
4195 PyErr_Format(
4196 PyExc_TypeError,
4197 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4198 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004199}
4200
Tim Peters6d6c1a32001-08-02 04:15:00 +00004201/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4202
4203/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004204 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004205 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4206 Most tables have only one entry; the tables for binary operators have two
4207 entries, one regular and one with reversed arguments. */
4208
4209static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004210wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004211{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004212 lenfunc func = (lenfunc)wrapped;
4213 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004214
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004215 if (!check_num_args(args, 0))
4216 return NULL;
4217 res = (*func)(self);
4218 if (res == -1 && PyErr_Occurred())
4219 return NULL;
4220 return PyInt_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004221}
4222
Tim Peters6d6c1a32001-08-02 04:15:00 +00004223static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004224wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4225{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004226 inquiry func = (inquiry)wrapped;
4227 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004228
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004229 if (!check_num_args(args, 0))
4230 return NULL;
4231 res = (*func)(self);
4232 if (res == -1 && PyErr_Occurred())
4233 return NULL;
4234 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004235}
4236
4237static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004238wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4239{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004240 binaryfunc func = (binaryfunc)wrapped;
4241 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004242
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004243 if (!check_num_args(args, 1))
4244 return NULL;
4245 other = PyTuple_GET_ITEM(args, 0);
4246 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004247}
4248
4249static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004250wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4251{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004252 binaryfunc func = (binaryfunc)wrapped;
4253 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004254
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004255 if (!check_num_args(args, 1))
4256 return NULL;
4257 other = PyTuple_GET_ITEM(args, 0);
4258 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
4259 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
4260 Py_INCREF(Py_NotImplemented);
4261 return Py_NotImplemented;
4262 }
4263 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004264}
4265
4266static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004267wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4268{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004269 binaryfunc func = (binaryfunc)wrapped;
4270 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004271
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004272 if (!check_num_args(args, 1))
4273 return NULL;
4274 other = PyTuple_GET_ITEM(args, 0);
4275 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
4276 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
4277 Py_INCREF(Py_NotImplemented);
4278 return Py_NotImplemented;
4279 }
4280 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004281}
4282
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004283static PyObject *
4284wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
4285{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004286 coercion func = (coercion)wrapped;
4287 PyObject *other, *res;
4288 int ok;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004289
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004290 if (!check_num_args(args, 1))
4291 return NULL;
4292 other = PyTuple_GET_ITEM(args, 0);
4293 ok = func(&self, &other);
4294 if (ok < 0)
4295 return NULL;
4296 if (ok > 0) {
4297 Py_INCREF(Py_NotImplemented);
4298 return Py_NotImplemented;
4299 }
4300 res = PyTuple_New(2);
4301 if (res == NULL) {
4302 Py_DECREF(self);
4303 Py_DECREF(other);
4304 return NULL;
4305 }
4306 PyTuple_SET_ITEM(res, 0, self);
4307 PyTuple_SET_ITEM(res, 1, other);
4308 return res;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004309}
4310
Tim Peters6d6c1a32001-08-02 04:15:00 +00004311static PyObject *
4312wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4313{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004314 ternaryfunc func = (ternaryfunc)wrapped;
4315 PyObject *other;
4316 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004317
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004318 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004319
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004320 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4321 return NULL;
4322 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004323}
4324
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004325static PyObject *
4326wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4327{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004328 ternaryfunc func = (ternaryfunc)wrapped;
4329 PyObject *other;
4330 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004331
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004332 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004333
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004334 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4335 return NULL;
4336 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004337}
4338
Tim Peters6d6c1a32001-08-02 04:15:00 +00004339static PyObject *
4340wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4341{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004342 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004343
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004344 if (!check_num_args(args, 0))
4345 return NULL;
4346 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004347}
4348
Tim Peters6d6c1a32001-08-02 04:15:00 +00004349static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00004350wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004351{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004352 ssizeargfunc func = (ssizeargfunc)wrapped;
4353 PyObject* o;
4354 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004355
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004356 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4357 return NULL;
4358 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4359 if (i == -1 && PyErr_Occurred())
4360 return NULL;
4361 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004362}
4363
Martin v. Löwis18e16552006-02-15 17:27:45 +00004364static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004365getindex(PyObject *self, PyObject *arg)
4366{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004367 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004368
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004369 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4370 if (i == -1 && PyErr_Occurred())
4371 return -1;
4372 if (i < 0) {
4373 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4374 if (sq && sq->sq_length) {
4375 Py_ssize_t n = (*sq->sq_length)(self);
4376 if (n < 0)
4377 return -1;
4378 i += n;
4379 }
4380 }
4381 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004382}
4383
4384static PyObject *
4385wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4386{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004387 ssizeargfunc func = (ssizeargfunc)wrapped;
4388 PyObject *arg;
4389 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004390
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004391 if (PyTuple_GET_SIZE(args) == 1) {
4392 arg = PyTuple_GET_ITEM(args, 0);
4393 i = getindex(self, arg);
4394 if (i == -1 && PyErr_Occurred())
4395 return NULL;
4396 return (*func)(self, i);
4397 }
4398 check_num_args(args, 1);
4399 assert(PyErr_Occurred());
4400 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004401}
4402
Tim Peters6d6c1a32001-08-02 04:15:00 +00004403static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004404wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004405{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004406 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
4407 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004408
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004409 if (!PyArg_ParseTuple(args, "nn", &i, &j))
4410 return NULL;
4411 return (*func)(self, i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004412}
4413
Tim Peters6d6c1a32001-08-02 04:15:00 +00004414static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004415wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004416{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004417 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4418 Py_ssize_t i;
4419 int res;
4420 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004421
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004422 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4423 return NULL;
4424 i = getindex(self, arg);
4425 if (i == -1 && PyErr_Occurred())
4426 return NULL;
4427 res = (*func)(self, i, value);
4428 if (res == -1 && PyErr_Occurred())
4429 return NULL;
4430 Py_INCREF(Py_None);
4431 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004432}
4433
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004434static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004435wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004436{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004437 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4438 Py_ssize_t i;
4439 int res;
4440 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004441
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004442 if (!check_num_args(args, 1))
4443 return NULL;
4444 arg = PyTuple_GET_ITEM(args, 0);
4445 i = getindex(self, arg);
4446 if (i == -1 && PyErr_Occurred())
4447 return NULL;
4448 res = (*func)(self, i, NULL);
4449 if (res == -1 && PyErr_Occurred())
4450 return NULL;
4451 Py_INCREF(Py_None);
4452 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004453}
4454
Tim Peters6d6c1a32001-08-02 04:15:00 +00004455static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004456wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004457{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004458 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4459 Py_ssize_t i, j;
4460 int res;
4461 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004462
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004463 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
4464 return NULL;
4465 res = (*func)(self, i, j, value);
4466 if (res == -1 && PyErr_Occurred())
4467 return NULL;
4468 Py_INCREF(Py_None);
4469 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004470}
4471
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004472static PyObject *
4473wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
4474{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004475 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4476 Py_ssize_t i, j;
4477 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004478
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004479 if (!PyArg_ParseTuple(args, "nn", &i, &j))
4480 return NULL;
4481 res = (*func)(self, i, j, NULL);
4482 if (res == -1 && PyErr_Occurred())
4483 return NULL;
4484 Py_INCREF(Py_None);
4485 return Py_None;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004486}
4487
Tim Peters6d6c1a32001-08-02 04:15:00 +00004488/* XXX objobjproc is a misnomer; should be objargpred */
4489static PyObject *
4490wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4491{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004492 objobjproc func = (objobjproc)wrapped;
4493 int res;
4494 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004495
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004496 if (!check_num_args(args, 1))
4497 return NULL;
4498 value = PyTuple_GET_ITEM(args, 0);
4499 res = (*func)(self, value);
4500 if (res == -1 && PyErr_Occurred())
4501 return NULL;
4502 else
4503 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004504}
4505
Tim Peters6d6c1a32001-08-02 04:15:00 +00004506static PyObject *
4507wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4508{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004509 objobjargproc func = (objobjargproc)wrapped;
4510 int res;
4511 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004512
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004513 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4514 return NULL;
4515 res = (*func)(self, key, value);
4516 if (res == -1 && PyErr_Occurred())
4517 return NULL;
4518 Py_INCREF(Py_None);
4519 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004520}
4521
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004522static PyObject *
4523wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4524{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004525 objobjargproc func = (objobjargproc)wrapped;
4526 int res;
4527 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004528
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004529 if (!check_num_args(args, 1))
4530 return NULL;
4531 key = PyTuple_GET_ITEM(args, 0);
4532 res = (*func)(self, key, NULL);
4533 if (res == -1 && PyErr_Occurred())
4534 return NULL;
4535 Py_INCREF(Py_None);
4536 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004537}
4538
Tim Peters6d6c1a32001-08-02 04:15:00 +00004539static PyObject *
4540wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
4541{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004542 cmpfunc func = (cmpfunc)wrapped;
4543 int res;
4544 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004545
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004546 if (!check_num_args(args, 1))
4547 return NULL;
4548 other = PyTuple_GET_ITEM(args, 0);
4549 if (Py_TYPE(other)->tp_compare != func &&
4550 !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
4551 PyErr_Format(
4552 PyExc_TypeError,
4553 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
4554 Py_TYPE(self)->tp_name,
4555 Py_TYPE(self)->tp_name,
4556 Py_TYPE(other)->tp_name);
4557 return NULL;
4558 }
4559 res = (*func)(self, other);
4560 if (PyErr_Occurred())
4561 return NULL;
4562 return PyInt_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004563}
4564
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004565/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004566 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004567static int
4568hackcheck(PyObject *self, setattrofunc func, char *what)
4569{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004570 PyTypeObject *type = Py_TYPE(self);
4571 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4572 type = type->tp_base;
4573 /* If type is NULL now, this is a really weird type.
4574 In the spirit of backwards compatibility (?), just shut up. */
4575 if (type && type->tp_setattro != func) {
4576 PyErr_Format(PyExc_TypeError,
4577 "can't apply this %s to %s object",
4578 what,
4579 type->tp_name);
4580 return 0;
4581 }
4582 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004583}
4584
Tim Peters6d6c1a32001-08-02 04:15:00 +00004585static PyObject *
4586wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4587{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004588 setattrofunc func = (setattrofunc)wrapped;
4589 int res;
4590 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004591
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004592 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4593 return NULL;
4594 if (!hackcheck(self, func, "__setattr__"))
4595 return NULL;
4596 res = (*func)(self, name, value);
4597 if (res < 0)
4598 return NULL;
4599 Py_INCREF(Py_None);
4600 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004601}
4602
4603static PyObject *
4604wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4605{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004606 setattrofunc func = (setattrofunc)wrapped;
4607 int res;
4608 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004609
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004610 if (!check_num_args(args, 1))
4611 return NULL;
4612 name = PyTuple_GET_ITEM(args, 0);
4613 if (!hackcheck(self, func, "__delattr__"))
4614 return NULL;
4615 res = (*func)(self, name, NULL);
4616 if (res < 0)
4617 return NULL;
4618 Py_INCREF(Py_None);
4619 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004620}
4621
Tim Peters6d6c1a32001-08-02 04:15:00 +00004622static PyObject *
4623wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4624{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004625 hashfunc func = (hashfunc)wrapped;
4626 long res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004627
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004628 if (!check_num_args(args, 0))
4629 return NULL;
4630 res = (*func)(self);
4631 if (res == -1 && PyErr_Occurred())
4632 return NULL;
4633 return PyInt_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004634}
4635
Tim Peters6d6c1a32001-08-02 04:15:00 +00004636static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004637wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004638{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004639 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004640
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004641 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004642}
4643
Tim Peters6d6c1a32001-08-02 04:15:00 +00004644static PyObject *
4645wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4646{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004647 richcmpfunc func = (richcmpfunc)wrapped;
4648 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004649
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004650 if (!check_num_args(args, 1))
4651 return NULL;
4652 other = PyTuple_GET_ITEM(args, 0);
4653 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004654}
4655
4656#undef RICHCMP_WRAPPER
4657#define RICHCMP_WRAPPER(NAME, OP) \
4658static PyObject * \
4659richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4660{ \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004661 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004662}
4663
Jack Jansen8e938b42001-08-08 15:29:49 +00004664RICHCMP_WRAPPER(lt, Py_LT)
4665RICHCMP_WRAPPER(le, Py_LE)
4666RICHCMP_WRAPPER(eq, Py_EQ)
4667RICHCMP_WRAPPER(ne, Py_NE)
4668RICHCMP_WRAPPER(gt, Py_GT)
4669RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004670
Tim Peters6d6c1a32001-08-02 04:15:00 +00004671static PyObject *
4672wrap_next(PyObject *self, PyObject *args, void *wrapped)
4673{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004674 unaryfunc func = (unaryfunc)wrapped;
4675 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004676
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004677 if (!check_num_args(args, 0))
4678 return NULL;
4679 res = (*func)(self);
4680 if (res == NULL && !PyErr_Occurred())
4681 PyErr_SetNone(PyExc_StopIteration);
4682 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004683}
4684
Tim Peters6d6c1a32001-08-02 04:15:00 +00004685static PyObject *
4686wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4687{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004688 descrgetfunc func = (descrgetfunc)wrapped;
4689 PyObject *obj;
4690 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004691
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004692 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4693 return NULL;
4694 if (obj == Py_None)
4695 obj = NULL;
4696 if (type == Py_None)
4697 type = NULL;
4698 if (type == NULL &&obj == NULL) {
4699 PyErr_SetString(PyExc_TypeError,
4700 "__get__(None, None) is invalid");
4701 return NULL;
4702 }
4703 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004704}
4705
Tim Peters6d6c1a32001-08-02 04:15:00 +00004706static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004707wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004708{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004709 descrsetfunc func = (descrsetfunc)wrapped;
4710 PyObject *obj, *value;
4711 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004712
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004713 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4714 return NULL;
4715 ret = (*func)(self, obj, value);
4716 if (ret < 0)
4717 return NULL;
4718 Py_INCREF(Py_None);
4719 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004720}
Guido van Rossum22b13872002-08-06 21:41:44 +00004721
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004722static PyObject *
4723wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4724{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004725 descrsetfunc func = (descrsetfunc)wrapped;
4726 PyObject *obj;
4727 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004728
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004729 if (!check_num_args(args, 1))
4730 return NULL;
4731 obj = PyTuple_GET_ITEM(args, 0);
4732 ret = (*func)(self, obj, NULL);
4733 if (ret < 0)
4734 return NULL;
4735 Py_INCREF(Py_None);
4736 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004737}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004738
Tim Peters6d6c1a32001-08-02 04:15:00 +00004739static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004740wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004741{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004742 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004743
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004744 if (func(self, args, kwds) < 0)
4745 return NULL;
4746 Py_INCREF(Py_None);
4747 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004748}
4749
Tim Peters6d6c1a32001-08-02 04:15:00 +00004750static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004751tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004752{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004753 PyTypeObject *type, *subtype, *staticbase;
4754 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004755
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004756 if (self == NULL || !PyType_Check(self))
4757 Py_FatalError("__new__() called with non-type 'self'");
4758 type = (PyTypeObject *)self;
4759 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4760 PyErr_Format(PyExc_TypeError,
4761 "%s.__new__(): not enough arguments",
4762 type->tp_name);
4763 return NULL;
4764 }
4765 arg0 = PyTuple_GET_ITEM(args, 0);
4766 if (!PyType_Check(arg0)) {
4767 PyErr_Format(PyExc_TypeError,
4768 "%s.__new__(X): X is not a type object (%s)",
4769 type->tp_name,
4770 Py_TYPE(arg0)->tp_name);
4771 return NULL;
4772 }
4773 subtype = (PyTypeObject *)arg0;
4774 if (!PyType_IsSubtype(subtype, type)) {
4775 PyErr_Format(PyExc_TypeError,
4776 "%s.__new__(%s): %s is not a subtype of %s",
4777 type->tp_name,
4778 subtype->tp_name,
4779 subtype->tp_name,
4780 type->tp_name);
4781 return NULL;
4782 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004783
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004784 /* Check that the use doesn't do something silly and unsafe like
4785 object.__new__(dict). To do this, we check that the
4786 most derived base that's not a heap type is this type. */
4787 staticbase = subtype;
4788 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4789 staticbase = staticbase->tp_base;
4790 /* If staticbase is NULL now, it is a really weird type.
4791 In the spirit of backwards compatibility (?), just shut up. */
4792 if (staticbase && staticbase->tp_new != type->tp_new) {
4793 PyErr_Format(PyExc_TypeError,
4794 "%s.__new__(%s) is not safe, use %s.__new__()",
4795 type->tp_name,
4796 subtype->tp_name,
4797 staticbase == NULL ? "?" : staticbase->tp_name);
4798 return NULL;
4799 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004800
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004801 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4802 if (args == NULL)
4803 return NULL;
4804 res = type->tp_new(subtype, args, kwds);
4805 Py_DECREF(args);
4806 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004807}
4808
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004809static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004810 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4811 PyDoc_STR("T.__new__(S, ...) -> "
4812 "a new object with type S, a subtype of T")},
4813 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004814};
4815
4816static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004817add_tp_new_wrapper(PyTypeObject *type)
4818{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004819 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004820
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004821 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
4822 return 0;
4823 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4824 if (func == NULL)
4825 return -1;
4826 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
4827 Py_DECREF(func);
4828 return -1;
4829 }
4830 Py_DECREF(func);
4831 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004832}
4833
Guido van Rossumf040ede2001-08-07 16:40:56 +00004834/* Slot wrappers that call the corresponding __foo__ slot. See comments
4835 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004836
Guido van Rossumdc91b992001-08-08 22:26:22 +00004837#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004838static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004839FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004840{ \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004841 static PyObject *cache_str; \
4842 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004843}
4844
Guido van Rossumdc91b992001-08-08 22:26:22 +00004845#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004846static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004847FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004848{ \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004849 static PyObject *cache_str; \
4850 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004851}
4852
Guido van Rossumcd118802003-01-06 22:57:47 +00004853/* Boolean helper for SLOT1BINFULL().
4854 right.__class__ is a nontrivial subclass of left.__class__. */
4855static int
4856method_is_overloaded(PyObject *left, PyObject *right, char *name)
4857{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004858 PyObject *a, *b;
4859 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004860
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004861 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
4862 if (b == NULL) {
4863 PyErr_Clear();
4864 /* If right doesn't have it, it's not overloaded */
4865 return 0;
4866 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004867
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004868 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
4869 if (a == NULL) {
4870 PyErr_Clear();
4871 Py_DECREF(b);
4872 /* If right has it but left doesn't, it's overloaded */
4873 return 1;
4874 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004875
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004876 ok = PyObject_RichCompareBool(a, b, Py_NE);
4877 Py_DECREF(a);
4878 Py_DECREF(b);
4879 if (ok < 0) {
4880 PyErr_Clear();
4881 return 0;
4882 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004883
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004884 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004885}
4886
Guido van Rossumdc91b992001-08-08 22:26:22 +00004887
4888#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004889static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004890FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004891{ \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004892 static PyObject *cache_str, *rcache_str; \
4893 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4894 Py_TYPE(other)->tp_as_number != NULL && \
4895 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4896 if (Py_TYPE(self)->tp_as_number != NULL && \
4897 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4898 PyObject *r; \
4899 if (do_other && \
4900 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4901 method_is_overloaded(self, other, ROPSTR)) { \
4902 r = call_maybe( \
4903 other, ROPSTR, &rcache_str, "(O)", self); \
4904 if (r != Py_NotImplemented) \
4905 return r; \
4906 Py_DECREF(r); \
4907 do_other = 0; \
4908 } \
4909 r = call_maybe( \
4910 self, OPSTR, &cache_str, "(O)", other); \
4911 if (r != Py_NotImplemented || \
4912 Py_TYPE(other) == Py_TYPE(self)) \
4913 return r; \
4914 Py_DECREF(r); \
4915 } \
4916 if (do_other) { \
4917 return call_maybe( \
4918 other, ROPSTR, &rcache_str, "(O)", self); \
4919 } \
4920 Py_INCREF(Py_NotImplemented); \
4921 return Py_NotImplemented; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004922}
4923
4924#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004925 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004926
4927#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4928static PyObject * \
4929FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4930{ \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004931 static PyObject *cache_str; \
4932 return call_method(self, OPSTR, &cache_str, \
4933 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004934}
4935
Martin v. Löwis18e16552006-02-15 17:27:45 +00004936static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004937slot_sq_length(PyObject *self)
4938{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004939 static PyObject *len_str;
4940 PyObject *res = call_method(self, "__len__", &len_str, "()");
4941 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004942
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004943 if (res == NULL)
4944 return -1;
4945 len = PyInt_AsSsize_t(res);
4946 Py_DECREF(res);
4947 if (len < 0) {
4948 if (!PyErr_Occurred())
4949 PyErr_SetString(PyExc_ValueError,
4950 "__len__() should return >= 0");
4951 return -1;
4952 }
4953 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004954}
4955
Guido van Rossumf4593e02001-10-03 12:09:30 +00004956/* Super-optimized version of slot_sq_item.
4957 Other slots could do the same... */
4958static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004959slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004960{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004961 static PyObject *getitem_str;
4962 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4963 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004964
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004965 if (getitem_str == NULL) {
4966 getitem_str = PyString_InternFromString("__getitem__");
4967 if (getitem_str == NULL)
4968 return NULL;
4969 }
4970 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
4971 if (func != NULL) {
4972 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
4973 Py_INCREF(func);
4974 else {
4975 func = f(func, self, (PyObject *)(Py_TYPE(self)));
4976 if (func == NULL) {
4977 return NULL;
4978 }
4979 }
4980 ival = PyInt_FromSsize_t(i);
4981 if (ival != NULL) {
4982 args = PyTuple_New(1);
4983 if (args != NULL) {
4984 PyTuple_SET_ITEM(args, 0, ival);
4985 retval = PyObject_Call(func, args, NULL);
4986 Py_XDECREF(args);
4987 Py_XDECREF(func);
4988 return retval;
4989 }
4990 }
4991 }
4992 else {
4993 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4994 }
4995 Py_XDECREF(args);
4996 Py_XDECREF(ival);
4997 Py_XDECREF(func);
4998 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004999}
5000
Benjamin Peterson712ee922008-08-24 18:10:20 +00005001static PyObject*
5002slot_sq_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j)
5003{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005004 static PyObject *getslice_str;
5005
5006 if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
5007 "use __getitem__", 1) < 0)
5008 return NULL;
5009 return call_method(self, "__getslice__", &getslice_str,
5010 "nn", i, j);
Benjamin Peterson712ee922008-08-24 18:10:20 +00005011}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005012
5013static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005014slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005015{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005016 PyObject *res;
5017 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005018
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005019 if (value == NULL)
5020 res = call_method(self, "__delitem__", &delitem_str,
5021 "(n)", index);
5022 else
5023 res = call_method(self, "__setitem__", &setitem_str,
5024 "(nO)", index, value);
5025 if (res == NULL)
5026 return -1;
5027 Py_DECREF(res);
5028 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005029}
5030
5031static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005032slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005033{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005034 PyObject *res;
5035 static PyObject *delslice_str, *setslice_str;
5036
5037 if (value == NULL) {
5038 if (PyErr_WarnPy3k("in 3.x, __delslice__ has been removed; "
5039 "use __delitem__", 1) < 0)
5040 return -1;
5041 res = call_method(self, "__delslice__", &delslice_str,
5042 "(nn)", i, j);
5043 }
5044 else {
5045 if (PyErr_WarnPy3k("in 3.x, __setslice__ has been removed; "
5046 "use __setitem__", 1) < 0)
5047 return -1;
5048 res = call_method(self, "__setslice__", &setslice_str,
5049 "(nnO)", i, j, value);
5050 }
5051 if (res == NULL)
5052 return -1;
5053 Py_DECREF(res);
5054 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005055}
5056
5057static int
5058slot_sq_contains(PyObject *self, PyObject *value)
5059{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005060 PyObject *func, *res, *args;
5061 int result = -1;
Tim Petersbf9b2442003-03-23 05:35:36 +00005062
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005063 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005064
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005065 func = lookup_maybe(self, "__contains__", &contains_str);
5066 if (func != NULL) {
5067 args = PyTuple_Pack(1, value);
5068 if (args == NULL)
5069 res = NULL;
5070 else {
5071 res = PyObject_Call(func, args, NULL);
5072 Py_DECREF(args);
5073 }
5074 Py_DECREF(func);
5075 if (res != NULL) {
5076 result = PyObject_IsTrue(res);
5077 Py_DECREF(res);
5078 }
5079 }
5080 else if (! PyErr_Occurred()) {
5081 /* Possible results: -1 and 1 */
5082 result = (int)_PySequence_IterSearch(self, value,
5083 PY_ITERSEARCH_CONTAINS);
5084 }
5085 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005086}
5087
Tim Peters6d6c1a32001-08-02 04:15:00 +00005088#define slot_mp_length slot_sq_length
5089
Guido van Rossumdc91b992001-08-08 22:26:22 +00005090SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005091
5092static int
5093slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5094{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005095 PyObject *res;
5096 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005097
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005098 if (value == NULL)
5099 res = call_method(self, "__delitem__", &delitem_str,
5100 "(O)", key);
5101 else
5102 res = call_method(self, "__setitem__", &setitem_str,
5103 "(OO)", key, value);
5104 if (res == NULL)
5105 return -1;
5106 Py_DECREF(res);
5107 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005108}
5109
Guido van Rossumdc91b992001-08-08 22:26:22 +00005110SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5111SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5112SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
5113SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
5114SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5115SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5116
Jeremy Hylton938ace62002-07-17 16:30:39 +00005117static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005118
5119SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005120 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005121
5122static PyObject *
5123slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5124{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005125 static PyObject *pow_str;
Guido van Rossum2730b132001-08-28 18:22:14 +00005126
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005127 if (modulus == Py_None)
5128 return slot_nb_power_binary(self, other);
5129 /* Three-arg power doesn't use __rpow__. But ternary_op
5130 can call this when the second argument's type uses
5131 slot_nb_power, so check before calling self.__pow__. */
5132 if (Py_TYPE(self)->tp_as_number != NULL &&
5133 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
5134 return call_method(self, "__pow__", &pow_str,
5135 "(OO)", other, modulus);
5136 }
5137 Py_INCREF(Py_NotImplemented);
5138 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005139}
5140
5141SLOT0(slot_nb_negative, "__neg__")
5142SLOT0(slot_nb_positive, "__pos__")
5143SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005144
5145static int
5146slot_nb_nonzero(PyObject *self)
5147{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005148 PyObject *func, *args;
5149 static PyObject *nonzero_str, *len_str;
5150 int result = -1;
5151 int using_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005152
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005153 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
5154 if (func == NULL) {
5155 if (PyErr_Occurred())
5156 return -1;
5157 func = lookup_maybe(self, "__len__", &len_str);
5158 if (func == NULL)
5159 return PyErr_Occurred() ? -1 : 1;
5160 using_len = 1;
5161 }
5162 args = PyTuple_New(0);
5163 if (args != NULL) {
5164 PyObject *temp = PyObject_Call(func, args, NULL);
5165 Py_DECREF(args);
5166 if (temp != NULL) {
5167 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
5168 result = PyObject_IsTrue(temp);
5169 else {
5170 PyErr_Format(PyExc_TypeError,
5171 "%s should return "
5172 "bool or int, returned %s",
5173 (using_len ? "__len__"
5174 : "__nonzero__"),
5175 temp->ob_type->tp_name);
5176 result = -1;
5177 }
5178 Py_DECREF(temp);
5179 }
5180 }
5181 Py_DECREF(func);
5182 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005183}
5184
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005185
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005186static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005187slot_nb_index(PyObject *self)
5188{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005189 static PyObject *index_str;
5190 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005191}
5192
5193
Guido van Rossumdc91b992001-08-08 22:26:22 +00005194SLOT0(slot_nb_invert, "__invert__")
5195SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5196SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5197SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5198SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5199SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005200
5201static int
5202slot_nb_coerce(PyObject **a, PyObject **b)
5203{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005204 static PyObject *coerce_str;
5205 PyObject *self = *a, *other = *b;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005206
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005207 if (self->ob_type->tp_as_number != NULL &&
5208 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5209 PyObject *r;
5210 r = call_maybe(
5211 self, "__coerce__", &coerce_str, "(O)", other);
5212 if (r == NULL)
5213 return -1;
5214 if (r == Py_NotImplemented) {
5215 Py_DECREF(r);
5216 }
5217 else {
5218 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5219 PyErr_SetString(PyExc_TypeError,
5220 "__coerce__ didn't return a 2-tuple");
5221 Py_DECREF(r);
5222 return -1;
5223 }
5224 *a = PyTuple_GET_ITEM(r, 0);
5225 Py_INCREF(*a);
5226 *b = PyTuple_GET_ITEM(r, 1);
5227 Py_INCREF(*b);
5228 Py_DECREF(r);
5229 return 0;
5230 }
5231 }
5232 if (other->ob_type->tp_as_number != NULL &&
5233 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5234 PyObject *r;
5235 r = call_maybe(
5236 other, "__coerce__", &coerce_str, "(O)", self);
5237 if (r == NULL)
5238 return -1;
5239 if (r == Py_NotImplemented) {
5240 Py_DECREF(r);
5241 return 1;
5242 }
5243 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5244 PyErr_SetString(PyExc_TypeError,
5245 "__coerce__ didn't return a 2-tuple");
5246 Py_DECREF(r);
5247 return -1;
5248 }
5249 *a = PyTuple_GET_ITEM(r, 1);
5250 Py_INCREF(*a);
5251 *b = PyTuple_GET_ITEM(r, 0);
5252 Py_INCREF(*b);
5253 Py_DECREF(r);
5254 return 0;
5255 }
5256 return 1;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005257}
5258
Guido van Rossumdc91b992001-08-08 22:26:22 +00005259SLOT0(slot_nb_int, "__int__")
5260SLOT0(slot_nb_long, "__long__")
5261SLOT0(slot_nb_float, "__float__")
5262SLOT0(slot_nb_oct, "__oct__")
5263SLOT0(slot_nb_hex, "__hex__")
5264SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5265SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5266SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
5267SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
5268SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Martin v. Löwisfd963262007-02-09 12:19:32 +00005269/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005270static PyObject *
5271slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5272{
5273 static PyObject *cache_str;
5274 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
Martin v. Löwisfd963262007-02-09 12:19:32 +00005275}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005276SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5277SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5278SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5279SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5280SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5281SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005282 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005283SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5284SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5285SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005286
5287static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00005288half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005289{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005290 PyObject *func, *args, *res;
5291 static PyObject *cmp_str;
5292 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005293
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005294 func = lookup_method(self, "__cmp__", &cmp_str);
5295 if (func == NULL) {
5296 PyErr_Clear();
5297 }
5298 else {
5299 args = PyTuple_Pack(1, other);
5300 if (args == NULL)
5301 res = NULL;
5302 else {
5303 res = PyObject_Call(func, args, NULL);
5304 Py_DECREF(args);
5305 }
5306 Py_DECREF(func);
5307 if (res != Py_NotImplemented) {
5308 if (res == NULL)
5309 return -2;
5310 c = PyInt_AsLong(res);
5311 Py_DECREF(res);
5312 if (c == -1 && PyErr_Occurred())
5313 return -2;
5314 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
5315 }
5316 Py_DECREF(res);
5317 }
5318 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005319}
5320
Guido van Rossumab3b0342001-09-18 20:38:53 +00005321/* This slot is published for the benefit of try_3way_compare in object.c */
5322int
5323_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00005324{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005325 int c;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005326
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005327 if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
5328 c = half_compare(self, other);
5329 if (c <= 1)
5330 return c;
5331 }
5332 if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
5333 c = half_compare(other, self);
5334 if (c < -1)
5335 return -2;
5336 if (c <= 1)
5337 return -c;
5338 }
5339 return (void *)self < (void *)other ? -1 :
5340 (void *)self > (void *)other ? 1 : 0;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005341}
5342
5343static PyObject *
5344slot_tp_repr(PyObject *self)
5345{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005346 PyObject *func, *res;
5347 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005348
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005349 func = lookup_method(self, "__repr__", &repr_str);
5350 if (func != NULL) {
5351 res = PyEval_CallObject(func, NULL);
5352 Py_DECREF(func);
5353 return res;
5354 }
5355 PyErr_Clear();
5356 return PyString_FromFormat("<%s object at %p>",
5357 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005358}
5359
5360static PyObject *
5361slot_tp_str(PyObject *self)
5362{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005363 PyObject *func, *res;
5364 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005365
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005366 func = lookup_method(self, "__str__", &str_str);
5367 if (func != NULL) {
5368 res = PyEval_CallObject(func, NULL);
5369 Py_DECREF(func);
5370 return res;
5371 }
5372 else {
5373 PyErr_Clear();
5374 return slot_tp_repr(self);
5375 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005376}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005377
5378static long
5379slot_tp_hash(PyObject *self)
5380{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005381 PyObject *func;
5382 static PyObject *hash_str, *eq_str, *cmp_str;
5383 long h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005384
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005385 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005386
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005387 if (func != NULL && func != Py_None) {
5388 PyObject *res = PyEval_CallObject(func, NULL);
5389 Py_DECREF(func);
5390 if (res == NULL)
5391 return -1;
5392 if (PyLong_Check(res))
5393 h = PyLong_Type.tp_hash(res);
5394 else
5395 h = PyInt_AsLong(res);
5396 Py_DECREF(res);
5397 }
5398 else {
5399 Py_XDECREF(func); /* may be None */
5400 PyErr_Clear();
5401 func = lookup_method(self, "__eq__", &eq_str);
5402 if (func == NULL) {
5403 PyErr_Clear();
5404 func = lookup_method(self, "__cmp__", &cmp_str);
5405 }
5406 if (func != NULL) {
5407 Py_DECREF(func);
5408 return PyObject_HashNotImplemented(self);
5409 }
5410 PyErr_Clear();
5411 h = _Py_HashPointer((void *)self);
5412 }
5413 if (h == -1 && !PyErr_Occurred())
5414 h = -2;
5415 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005416}
5417
5418static PyObject *
5419slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5420{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005421 static PyObject *call_str;
5422 PyObject *meth = lookup_method(self, "__call__", &call_str);
5423 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005424
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005425 if (meth == NULL)
5426 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00005427
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005428 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00005429
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005430 Py_DECREF(meth);
5431 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005432}
5433
Guido van Rossum14a6f832001-10-17 13:59:09 +00005434/* There are two slot dispatch functions for tp_getattro.
5435
5436 - slot_tp_getattro() is used when __getattribute__ is overridden
5437 but no __getattr__ hook is present;
5438
5439 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5440
Guido van Rossumc334df52002-04-04 23:44:47 +00005441 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5442 detects the absence of __getattr__ and then installs the simpler slot if
5443 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005444
Tim Peters6d6c1a32001-08-02 04:15:00 +00005445static PyObject *
5446slot_tp_getattro(PyObject *self, PyObject *name)
5447{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005448 static PyObject *getattribute_str = NULL;
5449 return call_method(self, "__getattribute__", &getattribute_str,
5450 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005451}
5452
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005453static PyObject *
Benjamin Peterson273c2332008-11-17 22:39:09 +00005454call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5455{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005456 PyObject *res, *descr = NULL;
5457 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson273c2332008-11-17 22:39:09 +00005458
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005459 if (f != NULL) {
5460 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5461 if (descr == NULL)
5462 return NULL;
5463 else
5464 attr = descr;
5465 }
5466 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5467 Py_XDECREF(descr);
5468 return res;
Benjamin Peterson273c2332008-11-17 22:39:09 +00005469}
5470
5471static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005472slot_tp_getattr_hook(PyObject *self, PyObject *name)
5473{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005474 PyTypeObject *tp = Py_TYPE(self);
5475 PyObject *getattr, *getattribute, *res;
5476 static PyObject *getattribute_str = NULL;
5477 static PyObject *getattr_str = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005478
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005479 if (getattr_str == NULL) {
5480 getattr_str = PyString_InternFromString("__getattr__");
5481 if (getattr_str == NULL)
5482 return NULL;
5483 }
5484 if (getattribute_str == NULL) {
5485 getattribute_str =
5486 PyString_InternFromString("__getattribute__");
5487 if (getattribute_str == NULL)
5488 return NULL;
5489 }
5490 /* speed hack: we could use lookup_maybe, but that would resolve the
5491 method fully for each attribute lookup for classes with
5492 __getattr__, even when the attribute is present. So we use
5493 _PyType_Lookup and create the method only when needed, with
5494 call_attribute. */
5495 getattr = _PyType_Lookup(tp, getattr_str);
5496 if (getattr == NULL) {
5497 /* No __getattr__ hook: use a simpler dispatcher */
5498 tp->tp_getattro = slot_tp_getattro;
5499 return slot_tp_getattro(self, name);
5500 }
5501 Py_INCREF(getattr);
5502 /* speed hack: we could use lookup_maybe, but that would resolve the
5503 method fully for each attribute lookup for classes with
5504 __getattr__, even when self has the default __getattribute__
5505 method. So we use _PyType_Lookup and create the method only when
5506 needed, with call_attribute. */
5507 getattribute = _PyType_Lookup(tp, getattribute_str);
5508 if (getattribute == NULL ||
5509 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5510 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5511 (void *)PyObject_GenericGetAttr))
5512 res = PyObject_GenericGetAttr(self, name);
5513 else {
5514 Py_INCREF(getattribute);
5515 res = call_attribute(self, getattribute, name);
5516 Py_DECREF(getattribute);
5517 }
5518 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5519 PyErr_Clear();
5520 res = call_attribute(self, getattr, name);
5521 }
5522 Py_DECREF(getattr);
5523 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005524}
5525
Tim Peters6d6c1a32001-08-02 04:15:00 +00005526static int
5527slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5528{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005529 PyObject *res;
5530 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005531
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005532 if (value == NULL)
5533 res = call_method(self, "__delattr__", &delattr_str,
5534 "(O)", name);
5535 else
5536 res = call_method(self, "__setattr__", &setattr_str,
5537 "(OO)", name, value);
5538 if (res == NULL)
5539 return -1;
5540 Py_DECREF(res);
5541 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005542}
5543
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005544static char *name_op[] = {
5545 "__lt__",
5546 "__le__",
5547 "__eq__",
5548 "__ne__",
5549 "__gt__",
5550 "__ge__",
5551};
5552
Tim Peters6d6c1a32001-08-02 04:15:00 +00005553static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005554half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005555{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005556 PyObject *func, *args, *res;
5557 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005558
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005559 func = lookup_method(self, name_op[op], &op_str[op]);
5560 if (func == NULL) {
5561 PyErr_Clear();
5562 Py_INCREF(Py_NotImplemented);
5563 return Py_NotImplemented;
5564 }
5565 args = PyTuple_Pack(1, other);
5566 if (args == NULL)
5567 res = NULL;
5568 else {
5569 res = PyObject_Call(func, args, NULL);
5570 Py_DECREF(args);
5571 }
5572 Py_DECREF(func);
5573 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005574}
5575
Guido van Rossumb8f63662001-08-15 23:57:02 +00005576static PyObject *
5577slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5578{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005579 PyObject *res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005580
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005581 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
5582 res = half_richcompare(self, other, op);
5583 if (res != Py_NotImplemented)
5584 return res;
5585 Py_DECREF(res);
5586 }
5587 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
5588 res = half_richcompare(other, self, _Py_SwappedOp[op]);
5589 if (res != Py_NotImplemented) {
5590 return res;
5591 }
5592 Py_DECREF(res);
5593 }
5594 Py_INCREF(Py_NotImplemented);
5595 return Py_NotImplemented;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005596}
5597
5598static PyObject *
5599slot_tp_iter(PyObject *self)
5600{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005601 PyObject *func, *res;
5602 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005603
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005604 func = lookup_method(self, "__iter__", &iter_str);
5605 if (func != NULL) {
5606 PyObject *args;
5607 args = res = PyTuple_New(0);
5608 if (args != NULL) {
5609 res = PyObject_Call(func, args, NULL);
5610 Py_DECREF(args);
5611 }
5612 Py_DECREF(func);
5613 return res;
5614 }
5615 PyErr_Clear();
5616 func = lookup_method(self, "__getitem__", &getitem_str);
5617 if (func == NULL) {
5618 PyErr_Format(PyExc_TypeError,
5619 "'%.200s' object is not iterable",
5620 Py_TYPE(self)->tp_name);
5621 return NULL;
5622 }
5623 Py_DECREF(func);
5624 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005625}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005626
5627static PyObject *
5628slot_tp_iternext(PyObject *self)
5629{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005630 static PyObject *next_str;
5631 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005632}
5633
Guido van Rossum1a493502001-08-17 16:47:50 +00005634static PyObject *
5635slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5636{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005637 PyTypeObject *tp = Py_TYPE(self);
5638 PyObject *get;
5639 static PyObject *get_str = NULL;
Guido van Rossum1a493502001-08-17 16:47:50 +00005640
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005641 if (get_str == NULL) {
5642 get_str = PyString_InternFromString("__get__");
5643 if (get_str == NULL)
5644 return NULL;
5645 }
5646 get = _PyType_Lookup(tp, get_str);
5647 if (get == NULL) {
5648 /* Avoid further slowdowns */
5649 if (tp->tp_descr_get == slot_tp_descr_get)
5650 tp->tp_descr_get = NULL;
5651 Py_INCREF(self);
5652 return self;
5653 }
5654 if (obj == NULL)
5655 obj = Py_None;
5656 if (type == NULL)
5657 type = Py_None;
5658 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005659}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005660
5661static int
5662slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5663{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005664 PyObject *res;
5665 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005666
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005667 if (value == NULL)
5668 res = call_method(self, "__delete__", &del_str,
5669 "(O)", target);
5670 else
5671 res = call_method(self, "__set__", &set_str,
5672 "(OO)", target, value);
5673 if (res == NULL)
5674 return -1;
5675 Py_DECREF(res);
5676 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005677}
5678
5679static int
5680slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5681{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005682 static PyObject *init_str;
5683 PyObject *meth = lookup_method(self, "__init__", &init_str);
5684 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005685
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005686 if (meth == NULL)
5687 return -1;
5688 res = PyObject_Call(meth, args, kwds);
5689 Py_DECREF(meth);
5690 if (res == NULL)
5691 return -1;
5692 if (res != Py_None) {
5693 PyErr_Format(PyExc_TypeError,
5694 "__init__() should return None, not '%.200s'",
5695 Py_TYPE(res)->tp_name);
5696 Py_DECREF(res);
5697 return -1;
5698 }
5699 Py_DECREF(res);
5700 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005701}
5702
5703static PyObject *
5704slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5705{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005706 static PyObject *new_str;
5707 PyObject *func;
5708 PyObject *newargs, *x;
5709 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005710
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005711 if (new_str == NULL) {
5712 new_str = PyString_InternFromString("__new__");
5713 if (new_str == NULL)
5714 return NULL;
5715 }
5716 func = PyObject_GetAttr((PyObject *)type, new_str);
5717 if (func == NULL)
5718 return NULL;
5719 assert(PyTuple_Check(args));
5720 n = PyTuple_GET_SIZE(args);
5721 newargs = PyTuple_New(n+1);
5722 if (newargs == NULL)
5723 return NULL;
5724 Py_INCREF(type);
5725 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5726 for (i = 0; i < n; i++) {
5727 x = PyTuple_GET_ITEM(args, i);
5728 Py_INCREF(x);
5729 PyTuple_SET_ITEM(newargs, i+1, x);
5730 }
5731 x = PyObject_Call(func, newargs, kwds);
5732 Py_DECREF(newargs);
5733 Py_DECREF(func);
5734 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005735}
5736
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005737static void
5738slot_tp_del(PyObject *self)
5739{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005740 static PyObject *del_str = NULL;
5741 PyObject *del, *res;
5742 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005743
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005744 /* Temporarily resurrect the object. */
5745 assert(self->ob_refcnt == 0);
5746 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005747
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005748 /* Save the current exception, if any. */
5749 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005750
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005751 /* Execute __del__ method, if any. */
5752 del = lookup_maybe(self, "__del__", &del_str);
5753 if (del != NULL) {
5754 res = PyEval_CallObject(del, NULL);
5755 if (res == NULL)
5756 PyErr_WriteUnraisable(del);
5757 else
5758 Py_DECREF(res);
5759 Py_DECREF(del);
5760 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005761
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005762 /* Restore the saved exception. */
5763 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005764
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005765 /* Undo the temporary resurrection; can't use DECREF here, it would
5766 * cause a recursive call.
5767 */
5768 assert(self->ob_refcnt > 0);
5769 if (--self->ob_refcnt == 0)
5770 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005771
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005772 /* __del__ resurrected it! Make it look like the original Py_DECREF
5773 * never happened.
5774 */
5775 {
5776 Py_ssize_t refcnt = self->ob_refcnt;
5777 _Py_NewReference(self);
5778 self->ob_refcnt = refcnt;
5779 }
5780 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5781 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5782 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5783 * we need to undo that. */
5784 _Py_DEC_REFTOTAL;
5785 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5786 * chain, so no more to do there.
5787 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5788 * _Py_NewReference bumped tp_allocs: both of those need to be
5789 * undone.
5790 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005791#ifdef COUNT_ALLOCS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005792 --Py_TYPE(self)->tp_frees;
5793 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005794#endif
5795}
5796
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005797
5798/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005799 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005800 structure, which incorporates the additional structures used for numbers,
5801 sequences and mappings.
5802 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005803 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005804 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5805 terminated with an all-zero entry. (This table is further initialized and
5806 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005807
Guido van Rossum6d204072001-10-21 00:44:31 +00005808typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005809
5810#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005811#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005812#undef ETSLOT
5813#undef SQSLOT
5814#undef MPSLOT
5815#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005816#undef UNSLOT
5817#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005818#undef BINSLOT
5819#undef RBINSLOT
5820
Guido van Rossum6d204072001-10-21 00:44:31 +00005821#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005822 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5823 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005824#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005825 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5826 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005827#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005828 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5829 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005830#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005831 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005832#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005833 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005834#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005835 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005836#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005837 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5838 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005839#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005840 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5841 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005842#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005843 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5844 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005845#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005846 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5847 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005848#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005849 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5850 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005851#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005852 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5853 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005854
5855static slotdef slotdefs[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005856 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5857 "x.__len__() <==> len(x)"),
5858 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5859 The logic in abstract.c always falls back to nb_add/nb_multiply in
5860 this case. Defining both the nb_* and the sq_* slots to call the
5861 user-defined methods has unexpected side-effects, as shown by
5862 test_descr.notimplemented() */
5863 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5864 "x.__add__(y) <==> x+y"),
5865 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5866 "x.__mul__(n) <==> x*n"),
5867 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5868 "x.__rmul__(n) <==> n*x"),
5869 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5870 "x.__getitem__(y) <==> x[y]"),
5871 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
5872 "x.__getslice__(i, j) <==> x[i:j]\n\
5873 \n\
5874 Use of negative indices is not supported."),
5875 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5876 "x.__setitem__(i, y) <==> x[i]=y"),
5877 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5878 "x.__delitem__(y) <==> del x[y]"),
5879 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
5880 wrap_ssizessizeobjargproc,
5881 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
5882 \n\
5883 Use of negative indices is not supported."),
5884 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
5885 "x.__delslice__(i, j) <==> del x[i:j]\n\
5886 \n\
5887 Use of negative indices is not supported."),
5888 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5889 "x.__contains__(y) <==> y in x"),
5890 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5891 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5892 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5893 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005894
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005895 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5896 "x.__len__() <==> len(x)"),
5897 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5898 wrap_binaryfunc,
5899 "x.__getitem__(y) <==> x[y]"),
5900 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5901 wrap_objobjargproc,
5902 "x.__setitem__(i, y) <==> x[i]=y"),
5903 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5904 wrap_delitem,
5905 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005906
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005907 BINSLOT("__add__", nb_add, slot_nb_add,
5908 "+"),
5909 RBINSLOT("__radd__", nb_add, slot_nb_add,
5910 "+"),
5911 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5912 "-"),
5913 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5914 "-"),
5915 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5916 "*"),
5917 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5918 "*"),
5919 BINSLOT("__div__", nb_divide, slot_nb_divide,
5920 "/"),
5921 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5922 "/"),
5923 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5924 "%"),
5925 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5926 "%"),
5927 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5928 "divmod(x, y)"),
5929 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5930 "divmod(y, x)"),
5931 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5932 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5933 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5934 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5935 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5936 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5937 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5938 "abs(x)"),
5939 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
5940 "x != 0"),
5941 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5942 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5943 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5944 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5945 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5946 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5947 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5948 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5949 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5950 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5951 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5952 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5953 "x.__coerce__(y) <==> coerce(x, y)"),
5954 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5955 "int(x)"),
5956 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5957 "long(x)"),
5958 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5959 "float(x)"),
5960 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5961 "oct(x)"),
5962 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5963 "hex(x)"),
5964 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5965 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5966 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
Eli Benderskyd7841852011-11-11 16:52:16 +02005967 wrap_binaryfunc, "+="),
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005968 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
Eli Benderskyd7841852011-11-11 16:52:16 +02005969 wrap_binaryfunc, "-="),
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005970 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
Eli Benderskyd7841852011-11-11 16:52:16 +02005971 wrap_binaryfunc, "*="),
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005972 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
Eli Benderskyd7841852011-11-11 16:52:16 +02005973 wrap_binaryfunc, "/="),
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005974 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
Eli Benderskyd7841852011-11-11 16:52:16 +02005975 wrap_binaryfunc, "%="),
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005976 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Eli Benderskyd7841852011-11-11 16:52:16 +02005977 wrap_binaryfunc, "**="),
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005978 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
Eli Benderskyd7841852011-11-11 16:52:16 +02005979 wrap_binaryfunc, "<<="),
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005980 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
Eli Benderskyd7841852011-11-11 16:52:16 +02005981 wrap_binaryfunc, ">>="),
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005982 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
Eli Benderskyd7841852011-11-11 16:52:16 +02005983 wrap_binaryfunc, "&="),
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005984 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
Eli Benderskyd7841852011-11-11 16:52:16 +02005985 wrap_binaryfunc, "^="),
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005986 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
Eli Benderskyd7841852011-11-11 16:52:16 +02005987 wrap_binaryfunc, "|="),
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005988 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5989 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5990 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5991 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5992 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5993 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5994 IBSLOT("__itruediv__", nb_inplace_true_divide,
5995 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005996
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005997 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5998 "x.__str__() <==> str(x)"),
5999 TPSLOT("__str__", tp_print, NULL, NULL, ""),
6000 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
6001 "x.__repr__() <==> repr(x)"),
6002 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
6003 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
6004 "x.__cmp__(y) <==> cmp(x,y)"),
6005 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
6006 "x.__hash__() <==> hash(x)"),
6007 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
6008 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
6009 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
6010 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
6011 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
6012 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
6013 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
6014 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
6015 "x.__setattr__('name', value) <==> x.name = value"),
6016 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
6017 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
6018 "x.__delattr__('name') <==> del x.name"),
6019 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
6020 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
6021 "x.__lt__(y) <==> x<y"),
6022 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
6023 "x.__le__(y) <==> x<=y"),
6024 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
6025 "x.__eq__(y) <==> x==y"),
6026 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
6027 "x.__ne__(y) <==> x!=y"),
6028 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
6029 "x.__gt__(y) <==> x>y"),
6030 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
6031 "x.__ge__(y) <==> x>=y"),
6032 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
6033 "x.__iter__() <==> iter(x)"),
6034 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
6035 "x.next() -> the next value, or raise StopIteration"),
6036 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
6037 "descr.__get__(obj[, type]) -> value"),
6038 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
6039 "descr.__set__(obj, value)"),
6040 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
6041 wrap_descr_delete, "descr.__delete__(obj)"),
6042 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
6043 "x.__init__(...) initializes x; "
Alexander Belopolskyb8de9fa2010-08-16 20:30:26 +00006044 "see help(type(x)) for signature",
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006045 PyWrapperFlag_KEYWORDS),
6046 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
6047 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
6048 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006049};
6050
Guido van Rossumc334df52002-04-04 23:44:47 +00006051/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006052 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00006053 the offset to the type pointer, since it takes care to indirect through the
6054 proper indirection pointer (as_buffer, etc.); it returns NULL if the
6055 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006056static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00006057slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006058{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006059 char *ptr;
6060 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006061
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006062 /* Note: this depends on the order of the members of PyHeapTypeObject! */
6063 assert(offset >= 0);
6064 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
6065 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
6066 ptr = (char *)type->tp_as_sequence;
6067 offset -= offsetof(PyHeapTypeObject, as_sequence);
6068 }
6069 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
6070 ptr = (char *)type->tp_as_mapping;
6071 offset -= offsetof(PyHeapTypeObject, as_mapping);
6072 }
6073 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
6074 ptr = (char *)type->tp_as_number;
6075 offset -= offsetof(PyHeapTypeObject, as_number);
6076 }
6077 else {
6078 ptr = (char *)type;
6079 }
6080 if (ptr != NULL)
6081 ptr += offset;
6082 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006083}
Guido van Rossumf040ede2001-08-07 16:40:56 +00006084
Guido van Rossumc334df52002-04-04 23:44:47 +00006085/* Length of array of slotdef pointers used to store slots with the
6086 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
6087 the same __name__, for any __name__. Since that's a static property, it is
6088 appropriate to declare fixed-size arrays for this. */
6089#define MAX_EQUIV 10
6090
6091/* Return a slot pointer for a given name, but ONLY if the attribute has
6092 exactly one slot function. The name must be an interned string. */
6093static void **
6094resolve_slotdups(PyTypeObject *type, PyObject *name)
6095{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006096 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00006097
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006098 /* pname and ptrs act as a little cache */
6099 static PyObject *pname;
6100 static slotdef *ptrs[MAX_EQUIV];
6101 slotdef *p, **pp;
6102 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00006103
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006104 if (pname != name) {
6105 /* Collect all slotdefs that match name into ptrs. */
6106 pname = name;
6107 pp = ptrs;
6108 for (p = slotdefs; p->name_strobj; p++) {
6109 if (p->name_strobj == name)
6110 *pp++ = p;
6111 }
6112 *pp = NULL;
6113 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006114
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006115 /* Look in all matching slots of the type; if exactly one of these has
6116 a filled-in slot, return its value. Otherwise return NULL. */
6117 res = NULL;
6118 for (pp = ptrs; *pp; pp++) {
6119 ptr = slotptr(type, (*pp)->offset);
6120 if (ptr == NULL || *ptr == NULL)
6121 continue;
6122 if (res != NULL)
6123 return NULL;
6124 res = ptr;
6125 }
6126 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00006127}
6128
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006129/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00006130 does some incredibly complex thinking and then sticks something into the
6131 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
6132 interests, and then stores a generic wrapper or a specific function into
6133 the slot.) Return a pointer to the next slotdef with a different offset,
6134 because that's convenient for fixup_slot_dispatchers(). */
6135static slotdef *
6136update_one_slot(PyTypeObject *type, slotdef *p)
6137{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006138 PyObject *descr;
6139 PyWrapperDescrObject *d;
6140 void *generic = NULL, *specific = NULL;
6141 int use_generic = 0;
6142 int offset = p->offset;
6143 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00006144
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006145 if (ptr == NULL) {
6146 do {
6147 ++p;
6148 } while (p->offset == offset);
6149 return p;
6150 }
6151 do {
6152 descr = _PyType_Lookup(type, p->name_strobj);
6153 if (descr == NULL) {
6154 if (ptr == (void**)&type->tp_iternext) {
6155 specific = _PyObject_NextNotImplemented;
6156 }
6157 continue;
6158 }
Benjamin Petersond157a4c2012-04-24 11:06:25 -04006159 if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
6160 ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006161 void **tptr = resolve_slotdups(type, p->name_strobj);
6162 if (tptr == NULL || tptr == ptr)
6163 generic = p->function;
6164 d = (PyWrapperDescrObject *)descr;
6165 if (d->d_base->wrapper == p->wrapper &&
6166 PyType_IsSubtype(type, d->d_type))
6167 {
6168 if (specific == NULL ||
6169 specific == d->d_wrapped)
6170 specific = d->d_wrapped;
6171 else
6172 use_generic = 1;
6173 }
6174 }
6175 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6176 PyCFunction_GET_FUNCTION(descr) ==
6177 (PyCFunction)tp_new_wrapper &&
6178 ptr == (void**)&type->tp_new)
6179 {
6180 /* The __new__ wrapper is not a wrapper descriptor,
6181 so must be special-cased differently.
6182 If we don't do this, creating an instance will
6183 always use slot_tp_new which will look up
6184 __new__ in the MRO which will call tp_new_wrapper
6185 which will look through the base classes looking
6186 for a static base and call its tp_new (usually
6187 PyType_GenericNew), after performing various
6188 sanity checks and constructing a new argument
6189 list. Cut all that nonsense short -- this speeds
6190 up instance creation tremendously. */
6191 specific = (void *)type->tp_new;
6192 /* XXX I'm not 100% sure that there isn't a hole
6193 in this reasoning that requires additional
6194 sanity checks. I'll buy the first person to
6195 point out a bug in this reasoning a beer. */
6196 }
6197 else if (descr == Py_None &&
6198 ptr == (void**)&type->tp_hash) {
6199 /* We specifically allow __hash__ to be set to None
6200 to prevent inheritance of the default
6201 implementation from object.__hash__ */
6202 specific = PyObject_HashNotImplemented;
6203 }
6204 else {
6205 use_generic = 1;
6206 generic = p->function;
6207 }
6208 } while ((++p)->offset == offset);
6209 if (specific && !use_generic)
6210 *ptr = specific;
6211 else
6212 *ptr = generic;
6213 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00006214}
6215
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006216/* In the type, update the slots whose slotdefs are gathered in the pp array.
6217 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006218static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006219update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006220{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006221 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006222
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006223 for (; *pp; pp++)
6224 update_one_slot(type, *pp);
6225 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006226}
6227
Guido van Rossumc334df52002-04-04 23:44:47 +00006228/* Comparison function for qsort() to compare slotdefs by their offset, and
6229 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006230static int
6231slotdef_cmp(const void *aa, const void *bb)
6232{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006233 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
6234 int c = a->offset - b->offset;
6235 if (c != 0)
6236 return c;
6237 else
6238 /* Cannot use a-b, as this gives off_t,
6239 which may lose precision when converted to int. */
6240 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006241}
6242
Guido van Rossumc334df52002-04-04 23:44:47 +00006243/* Initialize the slotdefs table by adding interned string objects for the
6244 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006245static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006246init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006247{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006248 slotdef *p;
6249 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006250
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006251 if (initialized)
6252 return;
6253 for (p = slotdefs; p->name; p++) {
6254 p->name_strobj = PyString_InternFromString(p->name);
6255 if (!p->name_strobj)
6256 Py_FatalError("Out of memory interning slotdef names");
6257 }
6258 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
6259 slotdef_cmp);
6260 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006261}
6262
Guido van Rossumc334df52002-04-04 23:44:47 +00006263/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006264static int
6265update_slot(PyTypeObject *type, PyObject *name)
6266{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006267 slotdef *ptrs[MAX_EQUIV];
6268 slotdef *p;
6269 slotdef **pp;
6270 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006271
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006272 /* Clear the VALID_VERSION flag of 'type' and all its
6273 subclasses. This could possibly be unified with the
6274 update_subclasses() recursion below, but carefully:
6275 they each have their own conditions on which to stop
6276 recursing into subclasses. */
6277 PyType_Modified(type);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00006278
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006279 init_slotdefs();
6280 pp = ptrs;
6281 for (p = slotdefs; p->name; p++) {
6282 /* XXX assume name is interned! */
6283 if (p->name_strobj == name)
6284 *pp++ = p;
6285 }
6286 *pp = NULL;
6287 for (pp = ptrs; *pp; pp++) {
6288 p = *pp;
6289 offset = p->offset;
6290 while (p > slotdefs && (p-1)->offset == offset)
6291 --p;
6292 *pp = p;
6293 }
6294 if (ptrs[0] == NULL)
6295 return 0; /* Not an attribute that affects any slots */
6296 return update_subclasses(type, name,
6297 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006298}
6299
Guido van Rossumc334df52002-04-04 23:44:47 +00006300/* Store the proper functions in the slot dispatches at class (type)
6301 definition time, based upon which operations the class overrides in its
6302 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006303static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006304fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006305{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006306 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006307
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006308 init_slotdefs();
6309 for (p = slotdefs; p->name; )
6310 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006311}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006312
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006313static void
6314update_all_slots(PyTypeObject* type)
6315{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006316 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006317
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006318 init_slotdefs();
6319 for (p = slotdefs; p->name; p++) {
6320 /* update_slot returns int but can't actually fail */
6321 update_slot(type, p->name_strobj);
6322 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006323}
6324
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006325/* recurse_down_subclasses() and update_subclasses() are mutually
6326 recursive functions to call a callback for all subclasses,
6327 but refraining from recursing into subclasses that define 'name'. */
6328
6329static int
6330update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006331 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006332{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006333 if (callback(type, data) < 0)
6334 return -1;
6335 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006336}
6337
6338static int
6339recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006340 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006341{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006342 PyTypeObject *subclass;
6343 PyObject *ref, *subclasses, *dict;
6344 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006345
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006346 subclasses = type->tp_subclasses;
6347 if (subclasses == NULL)
6348 return 0;
6349 assert(PyList_Check(subclasses));
6350 n = PyList_GET_SIZE(subclasses);
6351 for (i = 0; i < n; i++) {
6352 ref = PyList_GET_ITEM(subclasses, i);
6353 assert(PyWeakref_CheckRef(ref));
6354 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6355 assert(subclass != NULL);
6356 if ((PyObject *)subclass == Py_None)
6357 continue;
6358 assert(PyType_Check(subclass));
6359 /* Avoid recursing down into unaffected classes */
6360 dict = subclass->tp_dict;
6361 if (dict != NULL && PyDict_Check(dict) &&
6362 PyDict_GetItem(dict, name) != NULL)
6363 continue;
6364 if (update_subclasses(subclass, name, callback, data) < 0)
6365 return -1;
6366 }
6367 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006368}
6369
Guido van Rossum6d204072001-10-21 00:44:31 +00006370/* This function is called by PyType_Ready() to populate the type's
6371 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006372 function slot (like tp_repr) that's defined in the type, one or more
6373 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006374 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006375 cause more than one descriptor to be added (for example, the nb_add
6376 slot adds both __add__ and __radd__ descriptors) and some function
6377 slots compete for the same descriptor (for example both sq_item and
6378 mp_subscript generate a __getitem__ descriptor).
6379
Ezio Melottic2077b02011-03-16 12:34:31 +02006380 In the latter case, the first slotdef entry encountered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006381 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006382 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006383 between competing slots: the members of PyHeapTypeObject are listed
6384 from most general to least general, so the most general slot is
6385 preferred. In particular, because as_mapping comes before as_sequence,
6386 for a type that defines both mp_subscript and sq_item, mp_subscript
6387 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006388
6389 This only adds new descriptors and doesn't overwrite entries in
6390 tp_dict that were previously defined. The descriptors contain a
6391 reference to the C function they must call, so that it's safe if they
6392 are copied into a subtype's __dict__ and the subtype has a different
6393 C function in its slot -- calling the method defined by the
6394 descriptor will call the C function that was used to create it,
6395 rather than the C function present in the slot when it is called.
6396 (This is important because a subtype may have a C function in the
6397 slot that calls the method from the dictionary, and we want to avoid
6398 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006399
6400static int
6401add_operators(PyTypeObject *type)
6402{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006403 PyObject *dict = type->tp_dict;
6404 slotdef *p;
6405 PyObject *descr;
6406 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006407
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006408 init_slotdefs();
6409 for (p = slotdefs; p->name; p++) {
6410 if (p->wrapper == NULL)
6411 continue;
6412 ptr = slotptr(type, p->offset);
6413 if (!ptr || !*ptr)
6414 continue;
6415 if (PyDict_GetItem(dict, p->name_strobj))
6416 continue;
6417 if (*ptr == PyObject_HashNotImplemented) {
6418 /* Classes may prevent the inheritance of the tp_hash
6419 slot by storing PyObject_HashNotImplemented in it. Make it
6420 visible as a None value for the __hash__ attribute. */
6421 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6422 return -1;
6423 }
6424 else {
6425 descr = PyDescr_NewWrapper(type, p, *ptr);
6426 if (descr == NULL)
6427 return -1;
6428 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6429 return -1;
6430 Py_DECREF(descr);
6431 }
6432 }
6433 if (type->tp_new != NULL) {
6434 if (add_tp_new_wrapper(type) < 0)
6435 return -1;
6436 }
6437 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006438}
6439
Guido van Rossum705f0f52001-08-24 16:47:00 +00006440
6441/* Cooperative 'super' */
6442
6443typedef struct {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006444 PyObject_HEAD
6445 PyTypeObject *type;
6446 PyObject *obj;
6447 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006448} superobject;
6449
Guido van Rossum6f799372001-09-20 20:46:19 +00006450static PyMemberDef super_members[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006451 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6452 "the class invoking super()"},
6453 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6454 "the instance invoking super(); may be None"},
6455 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6456 "the type of the instance invoking super(); may be None"},
6457 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006458};
6459
Guido van Rossum705f0f52001-08-24 16:47:00 +00006460static void
6461super_dealloc(PyObject *self)
6462{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006463 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006464
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006465 _PyObject_GC_UNTRACK(self);
6466 Py_XDECREF(su->obj);
6467 Py_XDECREF(su->type);
6468 Py_XDECREF(su->obj_type);
6469 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006470}
6471
6472static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006473super_repr(PyObject *self)
6474{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006475 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006476
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006477 if (su->obj_type)
6478 return PyString_FromFormat(
6479 "<super: <class '%s'>, <%s object>>",
6480 su->type ? su->type->tp_name : "NULL",
6481 su->obj_type->tp_name);
6482 else
6483 return PyString_FromFormat(
6484 "<super: <class '%s'>, NULL>",
6485 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006486}
6487
6488static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006489super_getattro(PyObject *self, PyObject *name)
6490{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006491 superobject *su = (superobject *)self;
6492 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006493
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006494 if (!skip) {
6495 /* We want __class__ to return the class of the super object
6496 (i.e. super, or a subclass), not the class of su->obj. */
6497 skip = (PyString_Check(name) &&
6498 PyString_GET_SIZE(name) == 9 &&
6499 strcmp(PyString_AS_STRING(name), "__class__") == 0);
6500 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006501
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006502 if (!skip) {
6503 PyObject *mro, *res, *tmp, *dict;
6504 PyTypeObject *starttype;
6505 descrgetfunc f;
6506 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006507
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006508 starttype = su->obj_type;
6509 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006510
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006511 if (mro == NULL)
6512 n = 0;
6513 else {
6514 assert(PyTuple_Check(mro));
6515 n = PyTuple_GET_SIZE(mro);
6516 }
6517 for (i = 0; i < n; i++) {
6518 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6519 break;
6520 }
6521 i++;
6522 res = NULL;
6523 for (; i < n; i++) {
6524 tmp = PyTuple_GET_ITEM(mro, i);
6525 if (PyType_Check(tmp))
6526 dict = ((PyTypeObject *)tmp)->tp_dict;
6527 else if (PyClass_Check(tmp))
6528 dict = ((PyClassObject *)tmp)->cl_dict;
6529 else
6530 continue;
6531 res = PyDict_GetItem(dict, name);
6532 if (res != NULL) {
6533 Py_INCREF(res);
6534 f = Py_TYPE(res)->tp_descr_get;
6535 if (f != NULL) {
6536 tmp = f(res,
6537 /* Only pass 'obj' param if
6538 this is instance-mode super
6539 (See SF ID #743627)
6540 */
6541 (su->obj == (PyObject *)
6542 su->obj_type
6543 ? (PyObject *)NULL
6544 : su->obj),
6545 (PyObject *)starttype);
6546 Py_DECREF(res);
6547 res = tmp;
6548 }
6549 return res;
6550 }
6551 }
6552 }
6553 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006554}
6555
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006556static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006557supercheck(PyTypeObject *type, PyObject *obj)
6558{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006559 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006560
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006561 obj can be a new-style class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006562
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006563 - If it is a class, it must be a subclass of 'type'. This case is
6564 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006565
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006566 - If it is an instance, it must be an instance of 'type'. This is
6567 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006568
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006569 But... when obj is an instance, we want to allow for the case where
6570 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6571 This will allow using super() with a proxy for obj.
6572 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006573
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006574 /* Check for first bullet above (special case) */
6575 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6576 Py_INCREF(obj);
6577 return (PyTypeObject *)obj;
6578 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006579
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006580 /* Normal case */
6581 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6582 Py_INCREF(Py_TYPE(obj));
6583 return Py_TYPE(obj);
6584 }
6585 else {
6586 /* Try the slow way */
6587 static PyObject *class_str = NULL;
6588 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006589
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006590 if (class_str == NULL) {
6591 class_str = PyString_FromString("__class__");
6592 if (class_str == NULL)
6593 return NULL;
6594 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006595
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006596 class_attr = PyObject_GetAttr(obj, class_str);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006597
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006598 if (class_attr != NULL &&
6599 PyType_Check(class_attr) &&
6600 (PyTypeObject *)class_attr != Py_TYPE(obj))
6601 {
6602 int ok = PyType_IsSubtype(
6603 (PyTypeObject *)class_attr, type);
6604 if (ok)
6605 return (PyTypeObject *)class_attr;
6606 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006607
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006608 if (class_attr == NULL)
6609 PyErr_Clear();
6610 else
6611 Py_DECREF(class_attr);
6612 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006613
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006614 PyErr_SetString(PyExc_TypeError,
6615 "super(type, obj): "
6616 "obj must be an instance or subtype of type");
6617 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006618}
6619
Guido van Rossum705f0f52001-08-24 16:47:00 +00006620static PyObject *
6621super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6622{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006623 superobject *su = (superobject *)self;
6624 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006625
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006626 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6627 /* Not binding to an object, or already bound */
6628 Py_INCREF(self);
6629 return self;
6630 }
6631 if (Py_TYPE(su) != &PySuper_Type)
6632 /* If su is an instance of a (strict) subclass of super,
6633 call its type */
6634 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6635 su->type, obj, NULL);
6636 else {
6637 /* Inline the common case */
6638 PyTypeObject *obj_type = supercheck(su->type, obj);
6639 if (obj_type == NULL)
6640 return NULL;
6641 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6642 NULL, NULL);
6643 if (newobj == NULL)
6644 return NULL;
6645 Py_INCREF(su->type);
6646 Py_INCREF(obj);
6647 newobj->type = su->type;
6648 newobj->obj = obj;
6649 newobj->obj_type = obj_type;
6650 return (PyObject *)newobj;
6651 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006652}
6653
6654static int
6655super_init(PyObject *self, PyObject *args, PyObject *kwds)
6656{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006657 superobject *su = (superobject *)self;
6658 PyTypeObject *type;
6659 PyObject *obj = NULL;
6660 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006661
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006662 if (!_PyArg_NoKeywords("super", kwds))
6663 return -1;
6664 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
6665 return -1;
6666 if (obj == Py_None)
6667 obj = NULL;
6668 if (obj != NULL) {
6669 obj_type = supercheck(type, obj);
6670 if (obj_type == NULL)
6671 return -1;
6672 Py_INCREF(obj);
6673 }
6674 Py_INCREF(type);
6675 su->type = type;
6676 su->obj = obj;
6677 su->obj_type = obj_type;
6678 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006679}
6680
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006681PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00006682"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Raymond Hettingerac7b49f2013-01-18 23:23:11 -08006683"super(type) -> unbound super object\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006684"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006685"Typical use to call a cooperative superclass method:\n"
6686"class C(B):\n"
6687" def meth(self, arg):\n"
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006688" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006689
Guido van Rossum048eb752001-10-02 21:24:57 +00006690static int
6691super_traverse(PyObject *self, visitproc visit, void *arg)
6692{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006693 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006694
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006695 Py_VISIT(su->obj);
6696 Py_VISIT(su->type);
6697 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006698
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006699 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006700}
6701
Guido van Rossum705f0f52001-08-24 16:47:00 +00006702PyTypeObject PySuper_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006703 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6704 "super", /* tp_name */
6705 sizeof(superobject), /* tp_basicsize */
6706 0, /* tp_itemsize */
6707 /* methods */
6708 super_dealloc, /* tp_dealloc */
6709 0, /* tp_print */
6710 0, /* tp_getattr */
6711 0, /* tp_setattr */
6712 0, /* tp_compare */
6713 super_repr, /* tp_repr */
6714 0, /* tp_as_number */
6715 0, /* tp_as_sequence */
6716 0, /* tp_as_mapping */
6717 0, /* tp_hash */
6718 0, /* tp_call */
6719 0, /* tp_str */
6720 super_getattro, /* tp_getattro */
6721 0, /* tp_setattro */
6722 0, /* tp_as_buffer */
6723 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6724 Py_TPFLAGS_BASETYPE, /* tp_flags */
6725 super_doc, /* tp_doc */
6726 super_traverse, /* tp_traverse */
6727 0, /* tp_clear */
6728 0, /* tp_richcompare */
6729 0, /* tp_weaklistoffset */
6730 0, /* tp_iter */
6731 0, /* tp_iternext */
6732 0, /* tp_methods */
6733 super_members, /* tp_members */
6734 0, /* tp_getset */
6735 0, /* tp_base */
6736 0, /* tp_dict */
6737 super_descr_get, /* tp_descr_get */
6738 0, /* tp_descr_set */
6739 0, /* tp_dictoffset */
6740 super_init, /* tp_init */
6741 PyType_GenericAlloc, /* tp_alloc */
6742 PyType_GenericNew, /* tp_new */
6743 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006744};