blob: baf62ab52781f071c6a703cf69a6ecad81786c6f [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 */
Benjamin Peterson9b911ca2011-01-12 15:49:47 +0000330 int res;
331 if (value != NULL) {
332 res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
333 }
334 else {
335 res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
336 if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
Benjamin Petersonf4676b02011-01-12 19:00:37 +0000337 PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
Benjamin Peterson9b911ca2011-01-12 15:49:47 +0000338 return -1;
339 }
340 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000341 if (res == 0) {
342 PyType_Modified(type);
343 if (value && PyObject_IsTrue(value)) {
344 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
345 }
346 else {
347 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
348 }
349 }
350 return res;
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +0000351}
352
353static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000354type_get_bases(PyTypeObject *type, void *context)
355{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000356 Py_INCREF(type->tp_bases);
357 return type->tp_bases;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000358}
359
360static PyTypeObject *best_base(PyObject *);
361static int mro_internal(PyTypeObject *);
362static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
363static int add_subclass(PyTypeObject*, PyTypeObject*);
364static void remove_subclass(PyTypeObject *, PyTypeObject *);
365static void update_all_slots(PyTypeObject *);
366
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000367typedef int (*update_callback)(PyTypeObject *, void *);
368static int update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000369 update_callback callback, void *data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000370static int recurse_down_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 +0000372
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000373static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000374mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000375{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000376 PyTypeObject *subclass;
377 PyObject *ref, *subclasses, *old_mro;
378 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000379
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000380 subclasses = type->tp_subclasses;
381 if (subclasses == NULL)
382 return 0;
383 assert(PyList_Check(subclasses));
384 n = PyList_GET_SIZE(subclasses);
385 for (i = 0; i < n; i++) {
386 ref = PyList_GET_ITEM(subclasses, i);
387 assert(PyWeakref_CheckRef(ref));
388 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
389 assert(subclass != NULL);
390 if ((PyObject *)subclass == Py_None)
391 continue;
392 assert(PyType_Check(subclass));
393 old_mro = subclass->tp_mro;
394 if (mro_internal(subclass) < 0) {
395 subclass->tp_mro = old_mro;
396 return -1;
397 }
398 else {
399 PyObject* tuple;
400 tuple = PyTuple_Pack(2, subclass, old_mro);
401 Py_DECREF(old_mro);
402 if (!tuple)
403 return -1;
404 if (PyList_Append(temp, tuple) < 0)
405 return -1;
406 Py_DECREF(tuple);
407 }
408 if (mro_subclasses(subclass, temp) < 0)
409 return -1;
410 }
411 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000412}
413
414static int
415type_set_bases(PyTypeObject *type, PyObject *value, void *context)
416{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000417 Py_ssize_t i;
418 int r = 0;
419 PyObject *ob, *temp;
420 PyTypeObject *new_base, *old_base;
421 PyObject *old_bases, *old_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000422
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000423 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
424 PyErr_Format(PyExc_TypeError,
425 "can't set %s.__bases__", type->tp_name);
426 return -1;
427 }
428 if (!value) {
429 PyErr_Format(PyExc_TypeError,
430 "can't delete %s.__bases__", type->tp_name);
431 return -1;
432 }
433 if (!PyTuple_Check(value)) {
434 PyErr_Format(PyExc_TypeError,
435 "can only assign tuple to %s.__bases__, not %s",
436 type->tp_name, Py_TYPE(value)->tp_name);
437 return -1;
438 }
439 if (PyTuple_GET_SIZE(value) == 0) {
440 PyErr_Format(PyExc_TypeError,
441 "can only assign non-empty tuple to %s.__bases__, not ()",
442 type->tp_name);
443 return -1;
444 }
445 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
446 ob = PyTuple_GET_ITEM(value, i);
447 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
448 PyErr_Format(
449 PyExc_TypeError,
450 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
451 type->tp_name, Py_TYPE(ob)->tp_name);
452 return -1;
453 }
454 if (PyType_Check(ob)) {
455 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
456 PyErr_SetString(PyExc_TypeError,
457 "a __bases__ item causes an inheritance cycle");
458 return -1;
459 }
460 }
461 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000462
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000463 new_base = best_base(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000464
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000465 if (!new_base) {
466 return -1;
467 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000468
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000469 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
470 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000471
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000472 Py_INCREF(new_base);
473 Py_INCREF(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000474
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000475 old_bases = type->tp_bases;
476 old_base = type->tp_base;
477 old_mro = type->tp_mro;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000478
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000479 type->tp_bases = value;
480 type->tp_base = new_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000481
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000482 if (mro_internal(type) < 0) {
483 goto bail;
484 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000485
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000486 temp = PyList_New(0);
487 if (!temp)
488 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000489
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000490 r = mro_subclasses(type, temp);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000491
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000492 if (r < 0) {
493 for (i = 0; i < PyList_Size(temp); i++) {
494 PyTypeObject* cls;
495 PyObject* mro;
496 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
497 "", 2, 2, &cls, &mro);
498 Py_INCREF(mro);
499 ob = cls->tp_mro;
500 cls->tp_mro = mro;
501 Py_DECREF(ob);
502 }
503 Py_DECREF(temp);
504 goto bail;
505 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000506
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000507 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000508
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000509 /* any base that was in __bases__ but now isn't, we
510 need to remove |type| from its tp_subclasses.
511 conversely, any class now in __bases__ that wasn't
512 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000513
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000514 /* for now, sod that: just remove from all old_bases,
515 add to all new_bases */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000516
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000517 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
518 ob = PyTuple_GET_ITEM(old_bases, i);
519 if (PyType_Check(ob)) {
520 remove_subclass(
521 (PyTypeObject*)ob, type);
522 }
523 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000524
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000525 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
526 ob = PyTuple_GET_ITEM(value, i);
527 if (PyType_Check(ob)) {
528 if (add_subclass((PyTypeObject*)ob, type) < 0)
529 r = -1;
530 }
531 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000532
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000533 update_all_slots(type);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000534
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000535 Py_DECREF(old_bases);
536 Py_DECREF(old_base);
537 Py_DECREF(old_mro);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000538
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000539 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000540
541 bail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000542 Py_DECREF(type->tp_bases);
543 Py_DECREF(type->tp_base);
544 if (type->tp_mro != old_mro) {
545 Py_DECREF(type->tp_mro);
546 }
Michael W. Hudsone723e452003-08-07 14:58:10 +0000547
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000548 type->tp_bases = old_bases;
549 type->tp_base = old_base;
550 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000551
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000552 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000553}
554
555static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000556type_dict(PyTypeObject *type, void *context)
557{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000558 if (type->tp_dict == NULL) {
559 Py_INCREF(Py_None);
560 return Py_None;
561 }
562 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000563}
564
Tim Peters24008312002-03-17 18:56:20 +0000565static PyObject *
566type_get_doc(PyTypeObject *type, void *context)
567{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000568 PyObject *result;
569 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
570 return PyString_FromString(type->tp_doc);
571 result = PyDict_GetItemString(type->tp_dict, "__doc__");
572 if (result == NULL) {
573 result = Py_None;
574 Py_INCREF(result);
575 }
576 else if (Py_TYPE(result)->tp_descr_get) {
577 result = Py_TYPE(result)->tp_descr_get(result, NULL,
578 (PyObject *)type);
579 }
580 else {
581 Py_INCREF(result);
582 }
583 return result;
Tim Peters24008312002-03-17 18:56:20 +0000584}
585
Antoine Pitrou0668c622008-08-26 22:42:08 +0000586static PyObject *
587type___instancecheck__(PyObject *type, PyObject *inst)
588{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000589 switch (_PyObject_RealIsInstance(inst, type)) {
590 case -1:
591 return NULL;
592 case 0:
593 Py_RETURN_FALSE;
594 default:
595 Py_RETURN_TRUE;
596 }
Antoine Pitrou0668c622008-08-26 22:42:08 +0000597}
598
599
600static PyObject *
Antoine Pitrou0668c622008-08-26 22:42:08 +0000601type___subclasscheck__(PyObject *type, PyObject *inst)
602{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000603 switch (_PyObject_RealIsSubclass(inst, type)) {
604 case -1:
605 return NULL;
606 case 0:
607 Py_RETURN_FALSE;
608 default:
609 Py_RETURN_TRUE;
610 }
Antoine Pitrou0668c622008-08-26 22:42:08 +0000611}
612
Antoine Pitrou0668c622008-08-26 22:42:08 +0000613
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000614static PyGetSetDef type_getsets[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000615 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
616 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
617 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
618 {"__abstractmethods__", (getter)type_abstractmethods,
619 (setter)type_set_abstractmethods, NULL},
620 {"__dict__", (getter)type_dict, NULL, NULL},
621 {"__doc__", (getter)type_get_doc, NULL, NULL},
622 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000623};
624
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000625
Steven Bethardae42f332008-03-18 17:26:10 +0000626static PyObject*
627type_richcompare(PyObject *v, PyObject *w, int op)
628{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000629 PyObject *result;
630 Py_uintptr_t vv, ww;
631 int c;
Steven Bethardae42f332008-03-18 17:26:10 +0000632
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000633 /* Make sure both arguments are types. */
634 if (!PyType_Check(v) || !PyType_Check(w) ||
635 /* If there is a __cmp__ method defined, let it be called instead
636 of our dumb function designed merely to warn. See bug
637 #7491. */
638 Py_TYPE(v)->tp_compare || Py_TYPE(w)->tp_compare) {
639 result = Py_NotImplemented;
640 goto out;
641 }
Steven Bethardae42f332008-03-18 17:26:10 +0000642
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000643 /* Py3K warning if comparison isn't == or != */
644 if (Py_Py3kWarningFlag && op != Py_EQ && op != Py_NE &&
645 PyErr_WarnEx(PyExc_DeprecationWarning,
646 "type inequality comparisons not supported "
647 "in 3.x", 1) < 0) {
648 return NULL;
649 }
Steven Bethardae42f332008-03-18 17:26:10 +0000650
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000651 /* Compare addresses */
652 vv = (Py_uintptr_t)v;
653 ww = (Py_uintptr_t)w;
654 switch (op) {
655 case Py_LT: c = vv < ww; break;
656 case Py_LE: c = vv <= ww; break;
657 case Py_EQ: c = vv == ww; break;
658 case Py_NE: c = vv != ww; break;
659 case Py_GT: c = vv > ww; break;
660 case Py_GE: c = vv >= ww; break;
661 default:
662 result = Py_NotImplemented;
663 goto out;
664 }
665 result = c ? Py_True : Py_False;
Steven Bethardae42f332008-03-18 17:26:10 +0000666
667 /* incref and return */
668 out:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000669 Py_INCREF(result);
670 return result;
Steven Bethardae42f332008-03-18 17:26:10 +0000671}
672
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000673static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000674type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000675{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000676 PyObject *mod, *name, *rtn;
677 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000678
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000679 mod = type_module(type, NULL);
680 if (mod == NULL)
681 PyErr_Clear();
682 else if (!PyString_Check(mod)) {
683 Py_DECREF(mod);
684 mod = NULL;
685 }
686 name = type_name(type, NULL);
687 if (name == NULL)
688 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000689
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000690 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
691 kind = "class";
692 else
693 kind = "type";
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000694
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000695 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
696 rtn = PyString_FromFormat("<%s '%s.%s'>",
697 kind,
698 PyString_AS_STRING(mod),
699 PyString_AS_STRING(name));
700 }
701 else
702 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000703
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000704 Py_XDECREF(mod);
705 Py_DECREF(name);
706 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000707}
708
Tim Peters6d6c1a32001-08-02 04:15:00 +0000709static PyObject *
710type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
711{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000712 PyObject *obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000713
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000714 if (type->tp_new == NULL) {
715 PyErr_Format(PyExc_TypeError,
716 "cannot create '%.100s' instances",
717 type->tp_name);
718 return NULL;
719 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000720
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000721 obj = type->tp_new(type, args, kwds);
722 if (obj != NULL) {
723 /* Ugly exception: when the call was type(something),
724 don't call tp_init on the result. */
725 if (type == &PyType_Type &&
726 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
727 (kwds == NULL ||
728 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
729 return obj;
730 /* If the returned object is not an instance of type,
731 it won't be initialized. */
732 if (!PyType_IsSubtype(obj->ob_type, type))
733 return obj;
734 type = obj->ob_type;
735 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
736 type->tp_init != NULL &&
737 type->tp_init(obj, args, kwds) < 0) {
738 Py_DECREF(obj);
739 obj = NULL;
740 }
741 }
742 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000743}
744
745PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000746PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000747{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000748 PyObject *obj;
749 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
750 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000751
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000752 if (PyType_IS_GC(type))
753 obj = _PyObject_GC_Malloc(size);
754 else
755 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000756
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000757 if (obj == NULL)
758 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000759
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000760 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000761
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000762 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
763 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000764
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000765 if (type->tp_itemsize == 0)
766 PyObject_INIT(obj, type);
767 else
768 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000769
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000770 if (PyType_IS_GC(type))
771 _PyObject_GC_TRACK(obj);
772 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000773}
774
775PyObject *
776PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
777{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000778 return type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000779}
780
Guido van Rossum9475a232001-10-05 20:51:39 +0000781/* Helpers for subtyping */
782
783static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000784traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
785{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000786 Py_ssize_t i, n;
787 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000788
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000789 n = Py_SIZE(type);
790 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
791 for (i = 0; i < n; i++, mp++) {
792 if (mp->type == T_OBJECT_EX) {
793 char *addr = (char *)self + mp->offset;
794 PyObject *obj = *(PyObject **)addr;
795 if (obj != NULL) {
796 int err = visit(obj, arg);
797 if (err)
798 return err;
799 }
800 }
801 }
802 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000803}
804
805static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000806subtype_traverse(PyObject *self, visitproc visit, void *arg)
807{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000808 PyTypeObject *type, *base;
809 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000810
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000811 /* Find the nearest base with a different tp_traverse,
812 and traverse slots while we're at it */
813 type = Py_TYPE(self);
814 base = type;
815 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
816 if (Py_SIZE(base)) {
817 int err = traverse_slots(base, self, visit, arg);
818 if (err)
819 return err;
820 }
821 base = base->tp_base;
822 assert(base);
823 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000824
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000825 if (type->tp_dictoffset != base->tp_dictoffset) {
826 PyObject **dictptr = _PyObject_GetDictPtr(self);
827 if (dictptr && *dictptr)
828 Py_VISIT(*dictptr);
829 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000830
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000831 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
832 /* For a heaptype, the instances count as references
833 to the type. Traverse the type so the collector
834 can find cycles involving this link. */
835 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000836
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000837 if (basetraverse)
838 return basetraverse(self, visit, arg);
839 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000840}
841
842static void
843clear_slots(PyTypeObject *type, PyObject *self)
844{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000845 Py_ssize_t i, n;
846 PyMemberDef *mp;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000847
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000848 n = Py_SIZE(type);
849 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
850 for (i = 0; i < n; i++, mp++) {
851 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
852 char *addr = (char *)self + mp->offset;
853 PyObject *obj = *(PyObject **)addr;
854 if (obj != NULL) {
855 *(PyObject **)addr = NULL;
856 Py_DECREF(obj);
857 }
858 }
859 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000860}
861
862static int
863subtype_clear(PyObject *self)
864{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000865 PyTypeObject *type, *base;
866 inquiry baseclear;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000867
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000868 /* Find the nearest base with a different tp_clear
869 and clear slots while we're at it */
870 type = Py_TYPE(self);
871 base = type;
872 while ((baseclear = base->tp_clear) == subtype_clear) {
873 if (Py_SIZE(base))
874 clear_slots(base, self);
875 base = base->tp_base;
876 assert(base);
877 }
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000878
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000879 /* There's no need to clear the instance dict (if any);
880 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000881
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000882 if (baseclear)
883 return baseclear(self);
884 return 0;
Guido van Rossum9475a232001-10-05 20:51:39 +0000885}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000886
887static void
888subtype_dealloc(PyObject *self)
889{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000890 PyTypeObject *type, *base;
891 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000892
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000893 /* Extract the type; we expect it to be a heap type */
894 type = Py_TYPE(self);
895 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000896
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000897 /* Test whether the type has GC exactly once */
Guido van Rossum22b13872002-08-06 21:41:44 +0000898
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000899 if (!PyType_IS_GC(type)) {
900 /* It's really rare to find a dynamic type that doesn't have
901 GC; it can only happen when deriving from 'object' and not
902 adding any slots or instance variables. This allows
903 certain simplifications: there's no need to call
904 clear_slots(), or DECREF the dict, or clear weakrefs. */
Guido van Rossum22b13872002-08-06 21:41:44 +0000905
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000906 /* Maybe call finalizer; exit early if resurrected */
907 if (type->tp_del) {
908 type->tp_del(self);
909 if (self->ob_refcnt > 0)
910 return;
911 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000912
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000913 /* Find the nearest base with a different tp_dealloc */
914 base = type;
915 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
916 assert(Py_SIZE(base) == 0);
917 base = base->tp_base;
918 assert(base);
919 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000920
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000921 /* Extract the type again; tp_del may have changed it */
922 type = Py_TYPE(self);
Benjamin Peterson5083dc52009-04-25 00:41:22 +0000923
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000924 /* Call the base tp_dealloc() */
925 assert(basedealloc);
926 basedealloc(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000927
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000928 /* Can't reference self beyond this point */
929 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +0000930
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000931 /* Done */
932 return;
933 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000934
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000935 /* We get here only if the type has GC */
Guido van Rossum22b13872002-08-06 21:41:44 +0000936
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000937 /* UnTrack and re-Track around the trashcan macro, alas */
938 /* See explanation at end of function for full disclosure */
939 PyObject_GC_UnTrack(self);
940 ++_PyTrash_delete_nesting;
941 Py_TRASHCAN_SAFE_BEGIN(self);
942 --_PyTrash_delete_nesting;
943 /* DO NOT restore GC tracking at this point. weakref callbacks
944 * (if any, and whether directly here or indirectly in something we
945 * call) may trigger GC, and if self is tracked at that point, it
946 * will look like trash to GC and GC will try to delete self again.
947 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000948
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000949 /* Find the nearest base with a different tp_dealloc */
950 base = type;
951 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
952 base = base->tp_base;
953 assert(base);
954 }
Guido van Rossum14227b42001-12-06 02:35:58 +0000955
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000956 /* If we added a weaklist, we clear it. Do this *before* calling
957 the finalizer (__del__), clearing slots, or clearing the instance
958 dict. */
Guido van Rossum59195fd2003-06-13 20:54:40 +0000959
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000960 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
961 PyObject_ClearWeakRefs(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000962
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000963 /* Maybe call finalizer; exit early if resurrected */
964 if (type->tp_del) {
965 _PyObject_GC_TRACK(self);
966 type->tp_del(self);
967 if (self->ob_refcnt > 0)
968 goto endlabel; /* resurrected */
969 else
970 _PyObject_GC_UNTRACK(self);
971 /* New weakrefs could be created during the finalizer call.
972 If this occurs, clear them out without calling their
973 finalizers since they might rely on part of the object
974 being finalized that has already been destroyed. */
975 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
976 /* Modeled after GET_WEAKREFS_LISTPTR() */
977 PyWeakReference **list = (PyWeakReference **) \
978 PyObject_GET_WEAKREFS_LISTPTR(self);
979 while (*list)
980 _PyWeakref_ClearRef(*list);
981 }
982 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000983
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000984 /* Clear slots up to the nearest base with a different tp_dealloc */
985 base = type;
986 while (base->tp_dealloc == subtype_dealloc) {
987 if (Py_SIZE(base))
988 clear_slots(base, self);
989 base = base->tp_base;
990 assert(base);
991 }
Guido van Rossum59195fd2003-06-13 20:54:40 +0000992
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000993 /* If we added a dict, DECREF it */
994 if (type->tp_dictoffset && !base->tp_dictoffset) {
995 PyObject **dictptr = _PyObject_GetDictPtr(self);
996 if (dictptr != NULL) {
997 PyObject *dict = *dictptr;
998 if (dict != NULL) {
999 Py_DECREF(dict);
1000 *dictptr = NULL;
1001 }
1002 }
1003 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001004
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001005 /* Extract the type again; tp_del may have changed it */
1006 type = Py_TYPE(self);
Benjamin Peterson5083dc52009-04-25 00:41:22 +00001007
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001008 /* Call the base tp_dealloc(); first retrack self if
1009 * basedealloc knows about gc.
1010 */
1011 if (PyType_IS_GC(base))
1012 _PyObject_GC_TRACK(self);
1013 assert(basedealloc);
1014 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001015
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001016 /* Can't reference self beyond this point */
1017 Py_DECREF(type);
Guido van Rossum22b13872002-08-06 21:41:44 +00001018
Guido van Rossum0906e072002-08-07 20:42:09 +00001019 endlabel:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001020 ++_PyTrash_delete_nesting;
1021 Py_TRASHCAN_SAFE_END(self);
1022 --_PyTrash_delete_nesting;
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001023
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001024 /* Explanation of the weirdness around the trashcan macros:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001025
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001026 Q. What do the trashcan macros do?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001027
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001028 A. Read the comment titled "Trashcan mechanism" in object.h.
1029 For one, this explains why there must be a call to GC-untrack
1030 before the trashcan begin macro. Without understanding the
1031 trashcan code, the answers to the following questions don't make
1032 sense.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001033
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001034 Q. Why do we GC-untrack before the trashcan and then immediately
1035 GC-track again afterward?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001036
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001037 A. In the case that the base class is GC-aware, the base class
1038 probably GC-untracks the object. If it does that using the
1039 UNTRACK macro, this will crash when the object is already
1040 untracked. Because we don't know what the base class does, the
1041 only safe thing is to make sure the object is tracked when we
1042 call the base class dealloc. But... The trashcan begin macro
1043 requires that the object is *untracked* before it is called. So
1044 the dance becomes:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001045
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001046 GC untrack
1047 trashcan begin
1048 GC track
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001049
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001050 Q. Why did the last question say "immediately GC-track again"?
1051 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001052
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001053 A. Because the code *used* to re-track immediately. Bad Idea.
1054 self has a refcount of 0, and if gc ever gets its hands on it
1055 (which can happen if any weakref callback gets invoked), it
1056 looks like trash to gc too, and gc also tries to delete self
1057 then. But we're already deleting self. Double dealloction is
1058 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001059
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001060 Q. Why the bizarre (net-zero) manipulation of
1061 _PyTrash_delete_nesting around the trashcan macros?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001062
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001063 A. Some base classes (e.g. list) also use the trashcan mechanism.
1064 The following scenario used to be possible:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001065
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001066 - suppose the trashcan level is one below the trashcan limit
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001067
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001068 - subtype_dealloc() is called
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001069
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001070 - the trashcan limit is not yet reached, so the trashcan level
1071 is incremented and the code between trashcan begin and end is
1072 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001073
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001074 - this destroys much of the object's contents, including its
1075 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001076
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001077 - basedealloc() is called; this is really list_dealloc(), or
1078 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001079
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001080 - the trashcan limit is now reached, so the object is put on the
1081 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001082
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001083 - basedealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001084
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001085 - subtype_dealloc() decrefs the object's type
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001086
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001087 - subtype_dealloc() returns
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001088
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001089 - later, the trashcan code starts deleting the objects from its
1090 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001091
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001092 - subtype_dealloc() is called *AGAIN* for the same object
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001093
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001094 - at the very least (if the destroyed slots and __dict__ don't
1095 cause problems) the object's type gets decref'ed a second
1096 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001097
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001098 The remedy is to make sure that if the code between trashcan
1099 begin and end in subtype_dealloc() is called, the code between
1100 trashcan begin and end in basedealloc() will also be called.
1101 This is done by decrementing the level after passing into the
1102 trashcan block, and incrementing it just before leaving the
1103 block.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001104
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001105 But now it's possible that a chain of objects consisting solely
1106 of objects whose deallocator is subtype_dealloc() will defeat
1107 the trashcan mechanism completely: the decremented level means
1108 that the effective level never reaches the limit. Therefore, we
1109 *increment* the level *before* entering the trashcan block, and
1110 matchingly decrement it after leaving. This means the trashcan
1111 code will trigger a little early, but that's no big deal.
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001112
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001113 Q. Are there any live examples of code in need of all this
1114 complexity?
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001115
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001116 A. Yes. See SF bug 668433 for code that crashed (when Python was
1117 compiled in debug mode) before the trashcan level manipulations
1118 were added. For more discussion, see SF patches 581742, 575073
1119 and bug 574207.
1120 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001121}
1122
Jeremy Hylton938ace62002-07-17 16:30:39 +00001123static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001124
Tim Peters6d6c1a32001-08-02 04:15:00 +00001125/* type test with subclassing support */
1126
1127int
1128PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1129{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001130 PyObject *mro;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001131
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001132 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1133 return b == a || b == &PyBaseObject_Type;
Guido van Rossum9478d072001-09-07 18:52:13 +00001134
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001135 mro = a->tp_mro;
1136 if (mro != NULL) {
1137 /* Deal with multiple inheritance without recursion
1138 by walking the MRO tuple */
1139 Py_ssize_t i, n;
1140 assert(PyTuple_Check(mro));
1141 n = PyTuple_GET_SIZE(mro);
1142 for (i = 0; i < n; i++) {
1143 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1144 return 1;
1145 }
1146 return 0;
1147 }
1148 else {
1149 /* a is not completely initilized yet; follow tp_base */
1150 do {
1151 if (a == b)
1152 return 1;
1153 a = a->tp_base;
1154 } while (a != NULL);
1155 return b == &PyBaseObject_Type;
1156 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001157}
1158
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001159/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001160 without looking in the instance dictionary
1161 (so we can't use PyObject_GetAttr) but still binding
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001162 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001163 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001164 static variable used to cache the interned Python string.
1165
1166 Two variants:
1167
1168 - lookup_maybe() returns NULL without raising an exception
1169 when the _PyType_Lookup() call fails;
1170
1171 - lookup_method() always raises an exception upon errors.
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001172
1173 - _PyObject_LookupSpecial() exported for the benefit of other places.
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001174*/
Guido van Rossum60718732001-08-28 17:47:51 +00001175
1176static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001177lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001178{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001179 PyObject *res;
Guido van Rossum60718732001-08-28 17:47:51 +00001180
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001181 if (*attrobj == NULL) {
1182 *attrobj = PyString_InternFromString(attrstr);
1183 if (*attrobj == NULL)
1184 return NULL;
1185 }
1186 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
1187 if (res != NULL) {
1188 descrgetfunc f;
1189 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1190 Py_INCREF(res);
1191 else
1192 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1193 }
1194 return res;
Guido van Rossum60718732001-08-28 17:47:51 +00001195}
1196
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001197static PyObject *
1198lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1199{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001200 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1201 if (res == NULL && !PyErr_Occurred())
1202 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1203 return res;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001204}
1205
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001206PyObject *
1207_PyObject_LookupSpecial(PyObject *self, char *attrstr, PyObject **attrobj)
1208{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001209 assert(!PyInstance_Check(self));
1210 return lookup_maybe(self, attrstr, attrobj);
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001211}
1212
Guido van Rossum2730b132001-08-28 18:22:14 +00001213/* A variation of PyObject_CallMethod that uses lookup_method()
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001214 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001215 as lookup_method to cache the interned name string object. */
1216
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001217static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001218call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1219{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001220 va_list va;
1221 PyObject *args, *func = 0, *retval;
1222 va_start(va, format);
Guido van Rossum2730b132001-08-28 18:22:14 +00001223
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001224 func = lookup_maybe(o, name, nameobj);
1225 if (func == NULL) {
1226 va_end(va);
1227 if (!PyErr_Occurred())
1228 PyErr_SetObject(PyExc_AttributeError, *nameobj);
1229 return NULL;
1230 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001231
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001232 if (format && *format)
1233 args = Py_VaBuildValue(format, va);
1234 else
1235 args = PyTuple_New(0);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001236
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001237 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001238
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001239 if (args == NULL)
1240 return NULL;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001241
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001242 assert(PyTuple_Check(args));
1243 retval = PyObject_Call(func, args, NULL);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001244
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001245 Py_DECREF(args);
1246 Py_DECREF(func);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001247
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001248 return retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001249}
1250
1251/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1252
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001253static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001254call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1255{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001256 va_list va;
1257 PyObject *args, *func = 0, *retval;
1258 va_start(va, format);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001259
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001260 func = lookup_maybe(o, name, nameobj);
1261 if (func == NULL) {
1262 va_end(va);
1263 if (!PyErr_Occurred()) {
1264 Py_INCREF(Py_NotImplemented);
1265 return Py_NotImplemented;
1266 }
1267 return NULL;
1268 }
Guido van Rossum2730b132001-08-28 18:22:14 +00001269
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001270 if (format && *format)
1271 args = Py_VaBuildValue(format, va);
1272 else
1273 args = PyTuple_New(0);
Guido van Rossum2730b132001-08-28 18:22:14 +00001274
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001275 va_end(va);
Guido van Rossum2730b132001-08-28 18:22:14 +00001276
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001277 if (args == NULL)
1278 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001279
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001280 assert(PyTuple_Check(args));
1281 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001282
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001283 Py_DECREF(args);
1284 Py_DECREF(func);
Guido van Rossum2730b132001-08-28 18:22:14 +00001285
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001286 return retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001287}
1288
Tim Petersa91e9642001-11-14 23:32:33 +00001289static int
1290fill_classic_mro(PyObject *mro, PyObject *cls)
1291{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001292 PyObject *bases, *base;
1293 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001294
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001295 assert(PyList_Check(mro));
1296 assert(PyClass_Check(cls));
1297 i = PySequence_Contains(mro, cls);
1298 if (i < 0)
1299 return -1;
1300 if (!i) {
1301 if (PyList_Append(mro, cls) < 0)
1302 return -1;
1303 }
1304 bases = ((PyClassObject *)cls)->cl_bases;
1305 assert(bases && PyTuple_Check(bases));
1306 n = PyTuple_GET_SIZE(bases);
1307 for (i = 0; i < n; i++) {
1308 base = PyTuple_GET_ITEM(bases, i);
1309 if (fill_classic_mro(mro, base) < 0)
1310 return -1;
1311 }
1312 return 0;
Tim Petersa91e9642001-11-14 23:32:33 +00001313}
1314
1315static PyObject *
1316classic_mro(PyObject *cls)
1317{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001318 PyObject *mro;
Tim Petersa91e9642001-11-14 23:32:33 +00001319
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001320 assert(PyClass_Check(cls));
1321 mro = PyList_New(0);
1322 if (mro != NULL) {
1323 if (fill_classic_mro(mro, cls) == 0)
1324 return mro;
1325 Py_DECREF(mro);
1326 }
1327 return NULL;
Tim Petersa91e9642001-11-14 23:32:33 +00001328}
1329
Tim Petersea7f75d2002-12-07 21:39:16 +00001330/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001331 Method resolution order algorithm C3 described in
1332 "A Monotonic Superclass Linearization for Dylan",
1333 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001334 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001335 (OOPSLA 1996)
1336
Guido van Rossum98f33732002-11-25 21:36:54 +00001337 Some notes about the rules implied by C3:
1338
Tim Petersea7f75d2002-12-07 21:39:16 +00001339 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001340 It isn't legal to repeat a class in a list of base classes.
1341
1342 The next three properties are the 3 constraints in "C3".
1343
Tim Petersea7f75d2002-12-07 21:39:16 +00001344 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001345 If A precedes B in C's MRO, then A will precede B in the MRO of all
1346 subclasses of C.
1347
1348 Monotonicity.
1349 The MRO of a class must be an extension without reordering of the
1350 MRO of each of its superclasses.
1351
1352 Extended Precedence Graph (EPG).
1353 Linearization is consistent if there is a path in the EPG from
1354 each class to all its successors in the linearization. See
1355 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001356 */
1357
Tim Petersea7f75d2002-12-07 21:39:16 +00001358static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001359tail_contains(PyObject *list, int whence, PyObject *o) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001360 Py_ssize_t j, size;
1361 size = PyList_GET_SIZE(list);
Guido van Rossum1f121312002-11-14 19:49:16 +00001362
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001363 for (j = whence+1; j < size; j++) {
1364 if (PyList_GET_ITEM(list, j) == o)
1365 return 1;
1366 }
1367 return 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001368}
1369
Guido van Rossum98f33732002-11-25 21:36:54 +00001370static PyObject *
1371class_name(PyObject *cls)
1372{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001373 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1374 if (name == NULL) {
1375 PyErr_Clear();
1376 Py_XDECREF(name);
1377 name = PyObject_Repr(cls);
1378 }
1379 if (name == NULL)
1380 return NULL;
1381 if (!PyString_Check(name)) {
1382 Py_DECREF(name);
1383 return NULL;
1384 }
1385 return name;
Guido van Rossum98f33732002-11-25 21:36:54 +00001386}
1387
1388static int
1389check_duplicates(PyObject *list)
1390{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001391 Py_ssize_t i, j, n;
1392 /* Let's use a quadratic time algorithm,
1393 assuming that the bases lists is short.
1394 */
1395 n = PyList_GET_SIZE(list);
1396 for (i = 0; i < n; i++) {
1397 PyObject *o = PyList_GET_ITEM(list, i);
1398 for (j = i + 1; j < n; j++) {
1399 if (PyList_GET_ITEM(list, j) == o) {
1400 o = class_name(o);
1401 PyErr_Format(PyExc_TypeError,
1402 "duplicate base class %s",
1403 o ? PyString_AS_STRING(o) : "?");
1404 Py_XDECREF(o);
1405 return -1;
1406 }
1407 }
1408 }
1409 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001410}
1411
1412/* Raise a TypeError for an MRO order disagreement.
1413
1414 It's hard to produce a good error message. In the absence of better
1415 insight into error reporting, report the classes that were candidates
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001416 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001417 order in which they should be put in the MRO, but it's hard to
1418 diagnose what constraint can't be satisfied.
1419*/
1420
1421static void
1422set_mro_error(PyObject *to_merge, int *remain)
1423{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001424 Py_ssize_t i, n, off, to_merge_size;
1425 char buf[1000];
1426 PyObject *k, *v;
1427 PyObject *set = PyDict_New();
1428 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001429
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001430 to_merge_size = PyList_GET_SIZE(to_merge);
1431 for (i = 0; i < to_merge_size; i++) {
1432 PyObject *L = PyList_GET_ITEM(to_merge, i);
1433 if (remain[i] < PyList_GET_SIZE(L)) {
1434 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1435 if (PyDict_SetItem(set, c, Py_None) < 0) {
1436 Py_DECREF(set);
1437 return;
1438 }
1439 }
1440 }
1441 n = PyDict_Size(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001442
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001443 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
Raymond Hettingerf394df42003-04-06 19:13:41 +00001444consistent method resolution\norder (MRO) for bases");
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001445 i = 0;
1446 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1447 PyObject *name = class_name(k);
1448 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1449 name ? PyString_AS_STRING(name) : "?");
1450 Py_XDECREF(name);
1451 if (--n && (size_t)(off+1) < sizeof(buf)) {
1452 buf[off++] = ',';
1453 buf[off] = '\0';
1454 }
1455 }
1456 PyErr_SetString(PyExc_TypeError, buf);
1457 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001458}
1459
Tim Petersea7f75d2002-12-07 21:39:16 +00001460static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001461pmerge(PyObject *acc, PyObject* to_merge) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001462 Py_ssize_t i, j, to_merge_size, empty_cnt;
1463 int *remain;
1464 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001465
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001466 to_merge_size = PyList_GET_SIZE(to_merge);
Guido van Rossum1f121312002-11-14 19:49:16 +00001467
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001468 /* remain stores an index into each sublist of to_merge.
1469 remain[i] is the index of the next base in to_merge[i]
1470 that is not included in acc.
1471 */
1472 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1473 if (remain == NULL)
1474 return -1;
1475 for (i = 0; i < to_merge_size; i++)
1476 remain[i] = 0;
Guido van Rossum1f121312002-11-14 19:49:16 +00001477
1478 again:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001479 empty_cnt = 0;
1480 for (i = 0; i < to_merge_size; i++) {
1481 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001482
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001483 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
Guido van Rossum1f121312002-11-14 19:49:16 +00001484
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001485 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1486 empty_cnt++;
1487 continue;
1488 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001489
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001490 /* Choose next candidate for MRO.
Guido van Rossum98f33732002-11-25 21:36:54 +00001491
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001492 The input sequences alone can determine the choice.
1493 If not, choose the class which appears in the MRO
1494 of the earliest direct superclass of the new class.
1495 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001496
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001497 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1498 for (j = 0; j < to_merge_size; j++) {
1499 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1500 if (tail_contains(j_lst, remain[j], candidate)) {
1501 goto skip; /* continue outer loop */
1502 }
1503 }
1504 ok = PyList_Append(acc, candidate);
1505 if (ok < 0) {
1506 PyMem_Free(remain);
1507 return -1;
1508 }
1509 for (j = 0; j < to_merge_size; j++) {
1510 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1511 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1512 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1513 remain[j]++;
1514 }
1515 }
1516 goto again;
1517 skip: ;
1518 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001519
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001520 if (empty_cnt == to_merge_size) {
1521 PyMem_FREE(remain);
1522 return 0;
1523 }
1524 set_mro_error(to_merge, remain);
1525 PyMem_FREE(remain);
1526 return -1;
Guido van Rossum1f121312002-11-14 19:49:16 +00001527}
1528
Tim Peters6d6c1a32001-08-02 04:15:00 +00001529static PyObject *
1530mro_implementation(PyTypeObject *type)
1531{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001532 Py_ssize_t i, n;
1533 int ok;
1534 PyObject *bases, *result;
1535 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001536
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001537 if (type->tp_dict == NULL) {
1538 if (PyType_Ready(type) < 0)
1539 return NULL;
1540 }
Guido van Rossum63517572002-06-18 16:44:57 +00001541
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001542 /* Find a superclass linearization that honors the constraints
1543 of the explicit lists of bases and the constraints implied by
1544 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001545
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001546 to_merge is a list of lists, where each list is a superclass
1547 linearization implied by a base class. The last element of
1548 to_merge is the declared list of bases.
1549 */
Guido van Rossum98f33732002-11-25 21:36:54 +00001550
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001551 bases = type->tp_bases;
1552 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001553
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001554 to_merge = PyList_New(n+1);
1555 if (to_merge == NULL)
1556 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001557
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001558 for (i = 0; i < n; i++) {
1559 PyObject *base = PyTuple_GET_ITEM(bases, i);
1560 PyObject *parentMRO;
1561 if (PyType_Check(base))
1562 parentMRO = PySequence_List(
1563 ((PyTypeObject*)base)->tp_mro);
1564 else
1565 parentMRO = classic_mro(base);
1566 if (parentMRO == NULL) {
1567 Py_DECREF(to_merge);
1568 return NULL;
1569 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001570
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001571 PyList_SET_ITEM(to_merge, i, parentMRO);
1572 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001573
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001574 bases_aslist = PySequence_List(bases);
1575 if (bases_aslist == NULL) {
1576 Py_DECREF(to_merge);
1577 return NULL;
1578 }
1579 /* This is just a basic sanity check. */
1580 if (check_duplicates(bases_aslist) < 0) {
1581 Py_DECREF(to_merge);
1582 Py_DECREF(bases_aslist);
1583 return NULL;
1584 }
1585 PyList_SET_ITEM(to_merge, n, bases_aslist);
Guido van Rossum1f121312002-11-14 19:49:16 +00001586
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001587 result = Py_BuildValue("[O]", (PyObject *)type);
1588 if (result == NULL) {
1589 Py_DECREF(to_merge);
1590 return NULL;
1591 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001592
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001593 ok = pmerge(result, to_merge);
1594 Py_DECREF(to_merge);
1595 if (ok < 0) {
1596 Py_DECREF(result);
1597 return NULL;
1598 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001599
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001600 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001601}
1602
1603static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001604mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001605{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001606 PyTypeObject *type = (PyTypeObject *)self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001607
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001608 return mro_implementation(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001609}
1610
1611static int
1612mro_internal(PyTypeObject *type)
1613{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001614 PyObject *mro, *result, *tuple;
1615 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001616
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001617 if (Py_TYPE(type) == &PyType_Type) {
1618 result = mro_implementation(type);
1619 }
1620 else {
1621 static PyObject *mro_str;
1622 checkit = 1;
1623 mro = lookup_method((PyObject *)type, "mro", &mro_str);
1624 if (mro == NULL)
1625 return -1;
1626 result = PyObject_CallObject(mro, NULL);
1627 Py_DECREF(mro);
1628 }
1629 if (result == NULL)
1630 return -1;
1631 tuple = PySequence_Tuple(result);
1632 Py_DECREF(result);
1633 if (tuple == NULL)
1634 return -1;
1635 if (checkit) {
1636 Py_ssize_t i, len;
1637 PyObject *cls;
1638 PyTypeObject *solid;
Armin Rigo037d1e02005-12-29 17:07:39 +00001639
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001640 solid = solid_base(type);
Armin Rigo037d1e02005-12-29 17:07:39 +00001641
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001642 len = PyTuple_GET_SIZE(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001643
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001644 for (i = 0; i < len; i++) {
1645 PyTypeObject *t;
1646 cls = PyTuple_GET_ITEM(tuple, i);
1647 if (PyClass_Check(cls))
1648 continue;
1649 else if (!PyType_Check(cls)) {
1650 PyErr_Format(PyExc_TypeError,
1651 "mro() returned a non-class ('%.500s')",
1652 Py_TYPE(cls)->tp_name);
1653 Py_DECREF(tuple);
1654 return -1;
1655 }
1656 t = (PyTypeObject*)cls;
1657 if (!PyType_IsSubtype(solid, solid_base(t))) {
1658 PyErr_Format(PyExc_TypeError,
1659 "mro() returned base with unsuitable layout ('%.500s')",
1660 t->tp_name);
1661 Py_DECREF(tuple);
1662 return -1;
1663 }
1664 }
1665 }
1666 type->tp_mro = tuple;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001667
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001668 type_mro_modified(type, type->tp_mro);
1669 /* corner case: the old-style super class might have been hidden
1670 from the custom MRO */
1671 type_mro_modified(type, type->tp_bases);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001672
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001673 PyType_Modified(type);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001674
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001675 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001676}
1677
1678
1679/* Calculate the best base amongst multiple base classes.
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001680 This is the first one that's on the path to the "solid base". */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681
1682static PyTypeObject *
1683best_base(PyObject *bases)
1684{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001685 Py_ssize_t i, n;
1686 PyTypeObject *base, *winner, *candidate, *base_i;
1687 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001688
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001689 assert(PyTuple_Check(bases));
1690 n = PyTuple_GET_SIZE(bases);
1691 assert(n > 0);
1692 base = NULL;
1693 winner = NULL;
1694 for (i = 0; i < n; i++) {
1695 base_proto = PyTuple_GET_ITEM(bases, i);
1696 if (PyClass_Check(base_proto))
1697 continue;
1698 if (!PyType_Check(base_proto)) {
1699 PyErr_SetString(
1700 PyExc_TypeError,
1701 "bases must be types");
1702 return NULL;
1703 }
1704 base_i = (PyTypeObject *)base_proto;
1705 if (base_i->tp_dict == NULL) {
1706 if (PyType_Ready(base_i) < 0)
1707 return NULL;
1708 }
1709 candidate = solid_base(base_i);
1710 if (winner == NULL) {
1711 winner = candidate;
1712 base = base_i;
1713 }
1714 else if (PyType_IsSubtype(winner, candidate))
1715 ;
1716 else if (PyType_IsSubtype(candidate, winner)) {
1717 winner = candidate;
1718 base = base_i;
1719 }
1720 else {
1721 PyErr_SetString(
1722 PyExc_TypeError,
1723 "multiple bases have "
1724 "instance lay-out conflict");
1725 return NULL;
1726 }
1727 }
1728 if (base == NULL)
1729 PyErr_SetString(PyExc_TypeError,
1730 "a new-style class can't have only classic bases");
1731 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001732}
1733
1734static int
1735extra_ivars(PyTypeObject *type, PyTypeObject *base)
1736{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001737 size_t t_size = type->tp_basicsize;
1738 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001739
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001740 assert(t_size >= b_size); /* Else type smaller than base! */
1741 if (type->tp_itemsize || base->tp_itemsize) {
1742 /* If itemsize is involved, stricter rules */
1743 return t_size != b_size ||
1744 type->tp_itemsize != base->tp_itemsize;
1745 }
1746 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1747 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1748 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1749 t_size -= sizeof(PyObject *);
1750 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1751 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1752 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1753 t_size -= sizeof(PyObject *);
Guido van Rossum9676b222001-08-17 20:32:36 +00001754
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001755 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001756}
1757
1758static PyTypeObject *
1759solid_base(PyTypeObject *type)
1760{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001761 PyTypeObject *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001762
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001763 if (type->tp_base)
1764 base = solid_base(type->tp_base);
1765 else
1766 base = &PyBaseObject_Type;
1767 if (extra_ivars(type, base))
1768 return type;
1769 else
1770 return base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001771}
1772
Jeremy Hylton938ace62002-07-17 16:30:39 +00001773static void object_dealloc(PyObject *);
1774static int object_init(PyObject *, PyObject *, PyObject *);
1775static int update_slot(PyTypeObject *, PyObject *);
1776static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001777
Armin Rigo9790a272007-05-02 19:23:31 +00001778/*
1779 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1780 * inherited from various builtin types. The builtin base usually provides
1781 * its own __dict__ descriptor, so we use that when we can.
1782 */
1783static PyTypeObject *
1784get_builtin_base_with_dict(PyTypeObject *type)
1785{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001786 while (type->tp_base != NULL) {
1787 if (type->tp_dictoffset != 0 &&
1788 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1789 return type;
1790 type = type->tp_base;
1791 }
1792 return NULL;
Armin Rigo9790a272007-05-02 19:23:31 +00001793}
1794
1795static PyObject *
1796get_dict_descriptor(PyTypeObject *type)
1797{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001798 static PyObject *dict_str;
1799 PyObject *descr;
Armin Rigo9790a272007-05-02 19:23:31 +00001800
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001801 if (dict_str == NULL) {
1802 dict_str = PyString_InternFromString("__dict__");
1803 if (dict_str == NULL)
1804 return NULL;
1805 }
1806 descr = _PyType_Lookup(type, dict_str);
1807 if (descr == NULL || !PyDescr_IsData(descr))
1808 return NULL;
Armin Rigo9790a272007-05-02 19:23:31 +00001809
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001810 return descr;
Armin Rigo9790a272007-05-02 19:23:31 +00001811}
1812
1813static void
1814raise_dict_descr_error(PyObject *obj)
1815{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001816 PyErr_Format(PyExc_TypeError,
1817 "this __dict__ descriptor does not support "
1818 "'%.200s' objects", obj->ob_type->tp_name);
Armin Rigo9790a272007-05-02 19:23:31 +00001819}
1820
Tim Peters6d6c1a32001-08-02 04:15:00 +00001821static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001822subtype_dict(PyObject *obj, void *context)
1823{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001824 PyObject **dictptr;
1825 PyObject *dict;
1826 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001827
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001828 base = get_builtin_base_with_dict(obj->ob_type);
1829 if (base != NULL) {
1830 descrgetfunc func;
1831 PyObject *descr = get_dict_descriptor(base);
1832 if (descr == NULL) {
1833 raise_dict_descr_error(obj);
1834 return NULL;
1835 }
1836 func = descr->ob_type->tp_descr_get;
1837 if (func == NULL) {
1838 raise_dict_descr_error(obj);
1839 return NULL;
1840 }
1841 return func(descr, obj, (PyObject *)(obj->ob_type));
1842 }
Armin Rigo9790a272007-05-02 19:23:31 +00001843
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001844 dictptr = _PyObject_GetDictPtr(obj);
1845 if (dictptr == NULL) {
1846 PyErr_SetString(PyExc_AttributeError,
1847 "This object has no __dict__");
1848 return NULL;
1849 }
1850 dict = *dictptr;
1851 if (dict == NULL)
1852 *dictptr = dict = PyDict_New();
1853 Py_XINCREF(dict);
1854 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001855}
1856
Guido van Rossum6661be32001-10-26 04:26:12 +00001857static int
1858subtype_setdict(PyObject *obj, PyObject *value, void *context)
1859{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001860 PyObject **dictptr;
1861 PyObject *dict;
1862 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001863
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001864 base = get_builtin_base_with_dict(obj->ob_type);
1865 if (base != NULL) {
1866 descrsetfunc func;
1867 PyObject *descr = get_dict_descriptor(base);
1868 if (descr == NULL) {
1869 raise_dict_descr_error(obj);
1870 return -1;
1871 }
1872 func = descr->ob_type->tp_descr_set;
1873 if (func == NULL) {
1874 raise_dict_descr_error(obj);
1875 return -1;
1876 }
1877 return func(descr, obj, value);
1878 }
Armin Rigo9790a272007-05-02 19:23:31 +00001879
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001880 dictptr = _PyObject_GetDictPtr(obj);
1881 if (dictptr == NULL) {
1882 PyErr_SetString(PyExc_AttributeError,
1883 "This object has no __dict__");
1884 return -1;
1885 }
1886 if (value != NULL && !PyDict_Check(value)) {
1887 PyErr_Format(PyExc_TypeError,
1888 "__dict__ must be set to a dictionary, "
1889 "not a '%.200s'", Py_TYPE(value)->tp_name);
1890 return -1;
1891 }
1892 dict = *dictptr;
1893 Py_XINCREF(value);
1894 *dictptr = value;
1895 Py_XDECREF(dict);
1896 return 0;
Guido van Rossum6661be32001-10-26 04:26:12 +00001897}
1898
Guido van Rossumad47da02002-08-12 19:05:44 +00001899static PyObject *
1900subtype_getweakref(PyObject *obj, void *context)
1901{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001902 PyObject **weaklistptr;
1903 PyObject *result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001904
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001905 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1906 PyErr_SetString(PyExc_AttributeError,
1907 "This object has no __weakref__");
1908 return NULL;
1909 }
1910 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1911 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1912 (size_t)(Py_TYPE(obj)->tp_basicsize));
1913 weaklistptr = (PyObject **)
1914 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1915 if (*weaklistptr == NULL)
1916 result = Py_None;
1917 else
1918 result = *weaklistptr;
1919 Py_INCREF(result);
1920 return result;
Guido van Rossumad47da02002-08-12 19:05:44 +00001921}
1922
Guido van Rossum373c7412003-01-07 13:41:37 +00001923/* Three variants on the subtype_getsets list. */
1924
1925static PyGetSetDef subtype_getsets_full[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001926 {"__dict__", subtype_dict, subtype_setdict,
1927 PyDoc_STR("dictionary for instance variables (if defined)")},
1928 {"__weakref__", subtype_getweakref, NULL,
1929 PyDoc_STR("list of weak references to the object (if defined)")},
1930 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001931};
1932
Guido van Rossum373c7412003-01-07 13:41:37 +00001933static PyGetSetDef subtype_getsets_dict_only[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001934 {"__dict__", subtype_dict, subtype_setdict,
1935 PyDoc_STR("dictionary for instance variables (if defined)")},
1936 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001937};
1938
1939static PyGetSetDef subtype_getsets_weakref_only[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001940 {"__weakref__", subtype_getweakref, NULL,
1941 PyDoc_STR("list of weak references to the object (if defined)")},
1942 {0}
Guido van Rossum373c7412003-01-07 13:41:37 +00001943};
1944
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001945static int
1946valid_identifier(PyObject *s)
1947{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001948 unsigned char *p;
1949 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001950
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001951 if (!PyString_Check(s)) {
1952 PyErr_Format(PyExc_TypeError,
1953 "__slots__ items must be strings, not '%.200s'",
1954 Py_TYPE(s)->tp_name);
1955 return 0;
1956 }
1957 p = (unsigned char *) PyString_AS_STRING(s);
1958 n = PyString_GET_SIZE(s);
1959 /* We must reject an empty name. As a hack, we bump the
1960 length to 1 so that the loop will balk on the trailing \0. */
1961 if (n == 0)
1962 n = 1;
1963 for (i = 0; i < n; i++, p++) {
1964 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1965 PyErr_SetString(PyExc_TypeError,
1966 "__slots__ must be identifiers");
1967 return 0;
1968 }
1969 }
1970 return 1;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001971}
1972
Martin v. Löwisd919a592002-10-14 21:07:28 +00001973#ifdef Py_USING_UNICODE
1974/* Replace Unicode objects in slots. */
1975
1976static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001977_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001978{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001979 PyObject *tmp = NULL;
1980 PyObject *slot_name, *new_name;
1981 Py_ssize_t i;
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001982
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001983 for (i = 0; i < nslots; i++) {
1984 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1985 if (tmp == NULL) {
1986 tmp = PySequence_List(slots);
1987 if (tmp == NULL)
1988 return NULL;
1989 }
1990 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1991 NULL);
1992 if (new_name == NULL) {
1993 Py_DECREF(tmp);
1994 return NULL;
1995 }
1996 Py_INCREF(new_name);
1997 PyList_SET_ITEM(tmp, i, new_name);
1998 Py_DECREF(slot_name);
1999 }
2000 }
2001 if (tmp != NULL) {
2002 slots = PyList_AsTuple(tmp);
2003 Py_DECREF(tmp);
2004 }
2005 return slots;
Martin v. Löwisd919a592002-10-14 21:07:28 +00002006}
2007#endif
2008
Guido van Rossumf102e242007-03-23 18:53:03 +00002009/* Forward */
2010static int
2011object_init(PyObject *self, PyObject *args, PyObject *kwds);
2012
2013static int
2014type_init(PyObject *cls, PyObject *args, PyObject *kwds)
2015{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002016 int res;
Guido van Rossumf102e242007-03-23 18:53:03 +00002017
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002018 assert(args != NULL && PyTuple_Check(args));
2019 assert(kwds == NULL || PyDict_Check(kwds));
Guido van Rossumf102e242007-03-23 18:53:03 +00002020
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002021 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
2022 PyErr_SetString(PyExc_TypeError,
2023 "type.__init__() takes no keyword arguments");
2024 return -1;
2025 }
Guido van Rossumf102e242007-03-23 18:53:03 +00002026
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002027 if (args != NULL && PyTuple_Check(args) &&
2028 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
2029 PyErr_SetString(PyExc_TypeError,
2030 "type.__init__() takes 1 or 3 arguments");
2031 return -1;
2032 }
Guido van Rossumf102e242007-03-23 18:53:03 +00002033
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002034 /* Call object.__init__(self) now. */
2035 /* XXX Could call super(type, cls).__init__() but what's the point? */
2036 args = PyTuple_GetSlice(args, 0, 0);
2037 res = object_init(cls, args, NULL);
2038 Py_DECREF(args);
2039 return res;
Guido van Rossumf102e242007-03-23 18:53:03 +00002040}
2041
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002042static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2044{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002045 PyObject *name, *bases, *dict;
2046 static char *kwlist[] = {"name", "bases", "dict", 0};
2047 PyObject *slots, *tmp, *newslots;
2048 PyTypeObject *type, *base, *tmptype, *winner;
2049 PyHeapTypeObject *et;
2050 PyMemberDef *mp;
2051 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
2052 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002053
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002054 assert(args != NULL && PyTuple_Check(args));
2055 assert(kwds == NULL || PyDict_Check(kwds));
Tim Peters3abca122001-10-27 19:37:48 +00002056
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002057 /* Special case: type(x) should return x->ob_type */
2058 {
2059 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2060 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002061
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002062 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2063 PyObject *x = PyTuple_GET_ITEM(args, 0);
2064 Py_INCREF(Py_TYPE(x));
2065 return (PyObject *) Py_TYPE(x);
2066 }
Tim Peters3abca122001-10-27 19:37:48 +00002067
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002068 /* SF bug 475327 -- if that didn't trigger, we need 3
2069 arguments. but PyArg_ParseTupleAndKeywords below may give
2070 a msg saying type() needs exactly 3. */
2071 if (nargs + nkwds != 3) {
2072 PyErr_SetString(PyExc_TypeError,
2073 "type() takes 1 or 3 arguments");
2074 return NULL;
2075 }
2076 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002077
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002078 /* Check arguments: (name, bases, dict) */
2079 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
2080 &name,
2081 &PyTuple_Type, &bases,
2082 &PyDict_Type, &dict))
2083 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002084
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002085 /* Determine the proper metatype to deal with this,
2086 and check for metatype conflicts while we're at it.
2087 Note that if some other metatype wins to contract,
2088 it's possible that its instances are not types. */
2089 nbases = PyTuple_GET_SIZE(bases);
2090 winner = metatype;
2091 for (i = 0; i < nbases; i++) {
2092 tmp = PyTuple_GET_ITEM(bases, i);
2093 tmptype = tmp->ob_type;
2094 if (tmptype == &PyClass_Type)
2095 continue; /* Special case classic classes */
2096 if (PyType_IsSubtype(winner, tmptype))
2097 continue;
2098 if (PyType_IsSubtype(tmptype, winner)) {
2099 winner = tmptype;
2100 continue;
2101 }
2102 PyErr_SetString(PyExc_TypeError,
2103 "metaclass conflict: "
2104 "the metaclass of a derived class "
2105 "must be a (non-strict) subclass "
2106 "of the metaclasses of all its bases");
2107 return NULL;
2108 }
2109 if (winner != metatype) {
2110 if (winner->tp_new != type_new) /* Pass it to the winner */
2111 return winner->tp_new(winner, args, kwds);
2112 metatype = winner;
2113 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002114
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002115 /* Adjust for empty tuple bases */
2116 if (nbases == 0) {
2117 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2118 if (bases == NULL)
2119 return NULL;
2120 nbases = 1;
2121 }
2122 else
2123 Py_INCREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002124
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002125 /* XXX From here until type is allocated, "return NULL" leaks bases! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002126
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002127 /* Calculate best base, and check that all bases are type objects */
2128 base = best_base(bases);
2129 if (base == NULL) {
2130 Py_DECREF(bases);
2131 return NULL;
2132 }
2133 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2134 PyErr_Format(PyExc_TypeError,
2135 "type '%.100s' is not an acceptable base type",
2136 base->tp_name);
2137 Py_DECREF(bases);
2138 return NULL;
2139 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002140
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002141 /* Check for a __slots__ sequence variable in dict, and count it */
2142 slots = PyDict_GetItemString(dict, "__slots__");
2143 nslots = 0;
2144 add_dict = 0;
2145 add_weak = 0;
2146 may_add_dict = base->tp_dictoffset == 0;
2147 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2148 if (slots == NULL) {
2149 if (may_add_dict) {
2150 add_dict++;
2151 }
2152 if (may_add_weak) {
2153 add_weak++;
2154 }
2155 }
2156 else {
2157 /* Have slots */
Guido van Rossumad47da02002-08-12 19:05:44 +00002158
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002159 /* Make it into a tuple */
2160 if (PyString_Check(slots) || PyUnicode_Check(slots))
2161 slots = PyTuple_Pack(1, slots);
2162 else
2163 slots = PySequence_Tuple(slots);
2164 if (slots == NULL) {
2165 Py_DECREF(bases);
2166 return NULL;
2167 }
2168 assert(PyTuple_Check(slots));
Guido van Rossumad47da02002-08-12 19:05:44 +00002169
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002170 /* Are slots allowed? */
2171 nslots = PyTuple_GET_SIZE(slots);
2172 if (nslots > 0 && base->tp_itemsize != 0) {
2173 PyErr_Format(PyExc_TypeError,
2174 "nonempty __slots__ "
2175 "not supported for subtype of '%s'",
2176 base->tp_name);
2177 bad_slots:
2178 Py_DECREF(bases);
2179 Py_DECREF(slots);
2180 return NULL;
2181 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002182
Martin v. Löwisd919a592002-10-14 21:07:28 +00002183#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002184 tmp = _unicode_to_string(slots, nslots);
2185 if (tmp == NULL)
2186 goto bad_slots;
2187 if (tmp != slots) {
2188 Py_DECREF(slots);
2189 slots = tmp;
2190 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00002191#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002192 /* Check for valid slot names and two special cases */
2193 for (i = 0; i < nslots; i++) {
2194 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2195 char *s;
2196 if (!valid_identifier(tmp))
2197 goto bad_slots;
2198 assert(PyString_Check(tmp));
2199 s = PyString_AS_STRING(tmp);
2200 if (strcmp(s, "__dict__") == 0) {
2201 if (!may_add_dict || add_dict) {
2202 PyErr_SetString(PyExc_TypeError,
2203 "__dict__ slot disallowed: "
2204 "we already got one");
2205 goto bad_slots;
2206 }
2207 add_dict++;
2208 }
2209 if (strcmp(s, "__weakref__") == 0) {
2210 if (!may_add_weak || add_weak) {
2211 PyErr_SetString(PyExc_TypeError,
2212 "__weakref__ slot disallowed: "
2213 "either we already got one, "
2214 "or __itemsize__ != 0");
2215 goto bad_slots;
2216 }
2217 add_weak++;
2218 }
2219 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002220
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002221 /* Copy slots into a list, mangle names and sort them.
2222 Sorted names are needed for __class__ assignment.
2223 Convert them back to tuple at the end.
2224 */
2225 newslots = PyList_New(nslots - add_dict - add_weak);
2226 if (newslots == NULL)
2227 goto bad_slots;
2228 for (i = j = 0; i < nslots; i++) {
2229 char *s;
2230 tmp = PyTuple_GET_ITEM(slots, i);
2231 s = PyString_AS_STRING(tmp);
2232 if ((add_dict && strcmp(s, "__dict__") == 0) ||
2233 (add_weak && strcmp(s, "__weakref__") == 0))
2234 continue;
2235 tmp =_Py_Mangle(name, tmp);
2236 if (!tmp)
2237 goto bad_slots;
2238 PyList_SET_ITEM(newslots, j, tmp);
2239 j++;
2240 }
2241 assert(j == nslots - add_dict - add_weak);
2242 nslots = j;
2243 Py_DECREF(slots);
2244 if (PyList_Sort(newslots) == -1) {
2245 Py_DECREF(bases);
2246 Py_DECREF(newslots);
2247 return NULL;
2248 }
2249 slots = PyList_AsTuple(newslots);
2250 Py_DECREF(newslots);
2251 if (slots == NULL) {
2252 Py_DECREF(bases);
2253 return NULL;
2254 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002255
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002256 /* Secondary bases may provide weakrefs or dict */
2257 if (nbases > 1 &&
2258 ((may_add_dict && !add_dict) ||
2259 (may_add_weak && !add_weak))) {
2260 for (i = 0; i < nbases; i++) {
2261 tmp = PyTuple_GET_ITEM(bases, i);
2262 if (tmp == (PyObject *)base)
2263 continue; /* Skip primary base */
2264 if (PyClass_Check(tmp)) {
2265 /* Classic base class provides both */
2266 if (may_add_dict && !add_dict)
2267 add_dict++;
2268 if (may_add_weak && !add_weak)
2269 add_weak++;
2270 break;
2271 }
2272 assert(PyType_Check(tmp));
2273 tmptype = (PyTypeObject *)tmp;
2274 if (may_add_dict && !add_dict &&
2275 tmptype->tp_dictoffset != 0)
2276 add_dict++;
2277 if (may_add_weak && !add_weak &&
2278 tmptype->tp_weaklistoffset != 0)
2279 add_weak++;
2280 if (may_add_dict && !add_dict)
2281 continue;
2282 if (may_add_weak && !add_weak)
2283 continue;
2284 /* Nothing more to check */
2285 break;
2286 }
2287 }
2288 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002289
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002290 /* XXX From here until type is safely allocated,
2291 "return NULL" may leak slots! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002292
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002293 /* Allocate the type object */
2294 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
2295 if (type == NULL) {
2296 Py_XDECREF(slots);
2297 Py_DECREF(bases);
2298 return NULL;
2299 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002300
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002301 /* Keep name and slots alive in the extended type object */
2302 et = (PyHeapTypeObject *)type;
2303 Py_INCREF(name);
2304 et->ht_name = name;
2305 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002306
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002307 /* Initialize tp_flags */
2308 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2309 Py_TPFLAGS_BASETYPE;
2310 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2311 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2312 if (base->tp_flags & Py_TPFLAGS_HAVE_NEWBUFFER)
2313 type->tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002314
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002315 /* It's a new-style number unless it specifically inherits any
2316 old-style numeric behavior */
2317 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
2318 (base->tp_as_number == NULL))
2319 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002320
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002321 /* Initialize essential fields */
2322 type->tp_as_number = &et->as_number;
2323 type->tp_as_sequence = &et->as_sequence;
2324 type->tp_as_mapping = &et->as_mapping;
2325 type->tp_as_buffer = &et->as_buffer;
2326 type->tp_name = PyString_AS_STRING(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002327
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002328 /* Set tp_base and tp_bases */
2329 type->tp_bases = bases;
2330 Py_INCREF(base);
2331 type->tp_base = base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002332
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002333 /* Initialize tp_dict from passed-in dict */
2334 type->tp_dict = dict = PyDict_Copy(dict);
2335 if (dict == NULL) {
2336 Py_DECREF(type);
2337 return NULL;
2338 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002339
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002340 /* Set __module__ in the dict */
2341 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2342 tmp = PyEval_GetGlobals();
2343 if (tmp != NULL) {
2344 tmp = PyDict_GetItemString(tmp, "__name__");
2345 if (tmp != NULL) {
2346 if (PyDict_SetItemString(dict, "__module__",
2347 tmp) < 0)
2348 return NULL;
2349 }
2350 }
2351 }
Guido van Rossumc3542212001-08-16 09:18:56 +00002352
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002353 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2354 and is a string. The __doc__ accessor will first look for tp_doc;
2355 if that fails, it will still look into __dict__.
2356 */
2357 {
2358 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2359 if (doc != NULL && PyString_Check(doc)) {
2360 const size_t n = (size_t)PyString_GET_SIZE(doc);
2361 char *tp_doc = (char *)PyObject_MALLOC(n+1);
2362 if (tp_doc == NULL) {
2363 Py_DECREF(type);
2364 return NULL;
2365 }
2366 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
2367 type->tp_doc = tp_doc;
2368 }
2369 }
Tim Peters2f93e282001-10-04 05:27:00 +00002370
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002371 /* Special-case __new__: if it's a plain function,
2372 make it a static function */
2373 tmp = PyDict_GetItemString(dict, "__new__");
2374 if (tmp != NULL && PyFunction_Check(tmp)) {
2375 tmp = PyStaticMethod_New(tmp);
2376 if (tmp == NULL) {
2377 Py_DECREF(type);
2378 return NULL;
2379 }
2380 PyDict_SetItemString(dict, "__new__", tmp);
2381 Py_DECREF(tmp);
2382 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002383
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002384 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2385 mp = PyHeapType_GET_MEMBERS(et);
2386 slotoffset = base->tp_basicsize;
2387 if (slots != NULL) {
2388 for (i = 0; i < nslots; i++, mp++) {
2389 mp->name = PyString_AS_STRING(
2390 PyTuple_GET_ITEM(slots, i));
2391 mp->type = T_OBJECT_EX;
2392 mp->offset = slotoffset;
Žiga Seilnacht89032082007-03-11 15:54:54 +00002393
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002394 /* __dict__ and __weakref__ are already filtered out */
2395 assert(strcmp(mp->name, "__dict__") != 0);
2396 assert(strcmp(mp->name, "__weakref__") != 0);
Žiga Seilnacht89032082007-03-11 15:54:54 +00002397
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002398 slotoffset += sizeof(PyObject *);
2399 }
2400 }
2401 if (add_dict) {
2402 if (base->tp_itemsize)
2403 type->tp_dictoffset = -(long)sizeof(PyObject *);
2404 else
2405 type->tp_dictoffset = slotoffset;
2406 slotoffset += sizeof(PyObject *);
2407 }
2408 if (add_weak) {
2409 assert(!base->tp_itemsize);
2410 type->tp_weaklistoffset = slotoffset;
2411 slotoffset += sizeof(PyObject *);
2412 }
2413 type->tp_basicsize = slotoffset;
2414 type->tp_itemsize = base->tp_itemsize;
2415 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002416
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002417 if (type->tp_weaklistoffset && type->tp_dictoffset)
2418 type->tp_getset = subtype_getsets_full;
2419 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2420 type->tp_getset = subtype_getsets_weakref_only;
2421 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2422 type->tp_getset = subtype_getsets_dict_only;
2423 else
2424 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002425
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002426 /* Special case some slots */
2427 if (type->tp_dictoffset != 0 || nslots > 0) {
2428 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2429 type->tp_getattro = PyObject_GenericGetAttr;
2430 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2431 type->tp_setattro = PyObject_GenericSetAttr;
2432 }
2433 type->tp_dealloc = subtype_dealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002434
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002435 /* Enable GC unless there are really no instance variables possible */
2436 if (!(type->tp_basicsize == sizeof(PyObject) &&
2437 type->tp_itemsize == 0))
2438 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum9475a232001-10-05 20:51:39 +00002439
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002440 /* Always override allocation strategy to use regular heap */
2441 type->tp_alloc = PyType_GenericAlloc;
2442 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2443 type->tp_free = PyObject_GC_Del;
2444 type->tp_traverse = subtype_traverse;
2445 type->tp_clear = subtype_clear;
2446 }
2447 else
2448 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002449
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002450 /* Initialize the rest */
2451 if (PyType_Ready(type) < 0) {
2452 Py_DECREF(type);
2453 return NULL;
2454 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002455
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002456 /* Put the proper slots in place */
2457 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002458
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002459 return (PyObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002460}
2461
2462/* Internal API to look for a name through the MRO.
2463 This returns a borrowed reference, and doesn't set an exception! */
2464PyObject *
2465_PyType_Lookup(PyTypeObject *type, PyObject *name)
2466{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002467 Py_ssize_t i, n;
2468 PyObject *mro, *res, *base, *dict;
2469 unsigned int h;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002470
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002471 if (MCACHE_CACHEABLE_NAME(name) &&
2472 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2473 /* fast path */
2474 h = MCACHE_HASH_METHOD(type, name);
2475 if (method_cache[h].version == type->tp_version_tag &&
2476 method_cache[h].name == name)
2477 return method_cache[h].value;
2478 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002479
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002480 /* Look in tp_dict of types in MRO */
2481 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002482
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002483 /* If mro is NULL, the type is either not yet initialized
2484 by PyType_Ready(), or already cleared by type_clear().
2485 Either way the safest thing to do is to return NULL. */
2486 if (mro == NULL)
2487 return NULL;
Guido van Rossum23094982002-06-10 14:30:43 +00002488
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002489 res = NULL;
2490 assert(PyTuple_Check(mro));
2491 n = PyTuple_GET_SIZE(mro);
2492 for (i = 0; i < n; i++) {
2493 base = PyTuple_GET_ITEM(mro, i);
2494 if (PyClass_Check(base))
2495 dict = ((PyClassObject *)base)->cl_dict;
2496 else {
2497 assert(PyType_Check(base));
2498 dict = ((PyTypeObject *)base)->tp_dict;
2499 }
2500 assert(dict && PyDict_Check(dict));
2501 res = PyDict_GetItem(dict, name);
2502 if (res != NULL)
2503 break;
2504 }
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002505
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002506 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2507 h = MCACHE_HASH_METHOD(type, name);
2508 method_cache[h].version = type->tp_version_tag;
2509 method_cache[h].value = res; /* borrowed */
2510 Py_INCREF(name);
2511 Py_DECREF(method_cache[h].name);
2512 method_cache[h].name = name;
2513 }
2514 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002515}
2516
2517/* This is similar to PyObject_GenericGetAttr(),
2518 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2519static PyObject *
2520type_getattro(PyTypeObject *type, PyObject *name)
2521{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002522 PyTypeObject *metatype = Py_TYPE(type);
2523 PyObject *meta_attribute, *attribute;
2524 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002525
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002526 /* Initialize this type (we'll assume the metatype is initialized) */
2527 if (type->tp_dict == NULL) {
2528 if (PyType_Ready(type) < 0)
2529 return NULL;
2530 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002531
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002532 /* No readable descriptor found yet */
2533 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002534
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002535 /* Look for the attribute in the metatype */
2536 meta_attribute = _PyType_Lookup(metatype, name);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002537
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002538 if (meta_attribute != NULL) {
2539 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002540
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002541 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2542 /* Data descriptors implement tp_descr_set to intercept
2543 * writes. Assume the attribute is not overridden in
2544 * type's tp_dict (and bases): call the descriptor now.
2545 */
2546 return meta_get(meta_attribute, (PyObject *)type,
2547 (PyObject *)metatype);
2548 }
2549 Py_INCREF(meta_attribute);
2550 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002551
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002552 /* No data descriptor found on metatype. Look in tp_dict of this
2553 * type and its bases */
2554 attribute = _PyType_Lookup(type, name);
2555 if (attribute != NULL) {
2556 /* Implement descriptor functionality, if any */
2557 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002558
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002559 Py_XDECREF(meta_attribute);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002560
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002561 if (local_get != NULL) {
2562 /* NULL 2nd argument indicates the descriptor was
2563 * found on the target object itself (or a base) */
2564 return local_get(attribute, (PyObject *)NULL,
2565 (PyObject *)type);
2566 }
Tim Peters34592512002-07-11 06:23:50 +00002567
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002568 Py_INCREF(attribute);
2569 return attribute;
2570 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002571
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002572 /* No attribute found in local __dict__ (or bases): use the
2573 * descriptor from the metatype, if any */
2574 if (meta_get != NULL) {
2575 PyObject *res;
2576 res = meta_get(meta_attribute, (PyObject *)type,
2577 (PyObject *)metatype);
2578 Py_DECREF(meta_attribute);
2579 return res;
2580 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002581
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002582 /* If an ordinary attribute was found on the metatype, return it now */
2583 if (meta_attribute != NULL) {
2584 return meta_attribute;
2585 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002586
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002587 /* Give up */
2588 PyErr_Format(PyExc_AttributeError,
2589 "type object '%.50s' has no attribute '%.400s'",
2590 type->tp_name, PyString_AS_STRING(name));
2591 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002592}
2593
2594static int
2595type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2596{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002597 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2598 PyErr_Format(
2599 PyExc_TypeError,
2600 "can't set attributes of built-in/extension type '%s'",
2601 type->tp_name);
2602 return -1;
2603 }
2604 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2605 return -1;
2606 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002607}
2608
2609static void
2610type_dealloc(PyTypeObject *type)
2611{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002612 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002613
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002614 /* Assert this is a heap-allocated type object */
2615 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2616 _PyObject_GC_UNTRACK(type);
2617 PyObject_ClearWeakRefs((PyObject *)type);
2618 et = (PyHeapTypeObject *)type;
2619 Py_XDECREF(type->tp_base);
2620 Py_XDECREF(type->tp_dict);
2621 Py_XDECREF(type->tp_bases);
2622 Py_XDECREF(type->tp_mro);
2623 Py_XDECREF(type->tp_cache);
2624 Py_XDECREF(type->tp_subclasses);
2625 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2626 * of most other objects. It's okay to cast it to char *.
2627 */
2628 PyObject_Free((char *)type->tp_doc);
2629 Py_XDECREF(et->ht_name);
2630 Py_XDECREF(et->ht_slots);
2631 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002632}
2633
Guido van Rossum1c450732001-10-08 15:18:27 +00002634static PyObject *
2635type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2636{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002637 PyObject *list, *raw, *ref;
2638 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002639
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002640 list = PyList_New(0);
2641 if (list == NULL)
2642 return NULL;
2643 raw = type->tp_subclasses;
2644 if (raw == NULL)
2645 return list;
2646 assert(PyList_Check(raw));
2647 n = PyList_GET_SIZE(raw);
2648 for (i = 0; i < n; i++) {
2649 ref = PyList_GET_ITEM(raw, i);
2650 assert(PyWeakref_CheckRef(ref));
2651 ref = PyWeakref_GET_OBJECT(ref);
2652 if (ref != Py_None) {
2653 if (PyList_Append(list, ref) < 0) {
2654 Py_DECREF(list);
2655 return NULL;
2656 }
2657 }
2658 }
2659 return list;
Guido van Rossum1c450732001-10-08 15:18:27 +00002660}
2661
Tim Peters6d6c1a32001-08-02 04:15:00 +00002662static PyMethodDef type_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002663 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2664 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2665 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2666 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2667 {"__instancecheck__", type___instancecheck__, METH_O,
2668 PyDoc_STR("__instancecheck__() -> check if an object is an instance")},
2669 {"__subclasscheck__", type___subclasscheck__, METH_O,
Alexander Belopolskyb8de9fa2010-08-16 20:30:26 +00002670 PyDoc_STR("__subclasscheck__() -> check if a class is a subclass")},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002671 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002672};
2673
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002674PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002675"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002676"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002677
Guido van Rossum048eb752001-10-02 21:24:57 +00002678static int
2679type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2680{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002681 /* Because of type_is_gc(), the collector only calls this
2682 for heaptypes. */
2683 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002684
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002685 Py_VISIT(type->tp_dict);
2686 Py_VISIT(type->tp_cache);
2687 Py_VISIT(type->tp_mro);
2688 Py_VISIT(type->tp_bases);
2689 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002690
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002691 /* There's no need to visit type->tp_subclasses or
2692 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2693 in cycles; tp_subclasses is a list of weak references,
2694 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002695
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002696 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002697}
2698
2699static int
2700type_clear(PyTypeObject *type)
2701{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002702 /* Because of type_is_gc(), the collector only calls this
2703 for heaptypes. */
2704 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002705
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002706 /* The only field we need to clear is tp_mro, which is part of a
2707 hard cycle (its first element is the class itself) that won't
2708 be broken otherwise (it's a tuple and tuples don't have a
2709 tp_clear handler). None of the other fields need to be
2710 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002711
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002712 tp_dict:
2713 It is a dict, so the collector will call its tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002714
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002715 tp_cache:
2716 Not used; if it were, it would be a dict.
Guido van Rossuma3862092002-06-10 15:24:42 +00002717
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002718 tp_bases, tp_base:
2719 If these are involved in a cycle, there must be at least
2720 one other, mutable object in the cycle, e.g. a base
2721 class's dict; the cycle will be broken that way.
Guido van Rossuma3862092002-06-10 15:24:42 +00002722
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002723 tp_subclasses:
2724 A list of weak references can't be part of a cycle; and
2725 lists have their own tp_clear.
Guido van Rossuma3862092002-06-10 15:24:42 +00002726
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002727 slots (in PyHeapTypeObject):
2728 A tuple of strings can't be part of a cycle.
2729 */
Guido van Rossuma3862092002-06-10 15:24:42 +00002730
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002731 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002732
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002733 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00002734}
2735
2736static int
2737type_is_gc(PyTypeObject *type)
2738{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002739 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002740}
2741
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002742PyTypeObject PyType_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002743 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2744 "type", /* tp_name */
2745 sizeof(PyHeapTypeObject), /* tp_basicsize */
2746 sizeof(PyMemberDef), /* tp_itemsize */
2747 (destructor)type_dealloc, /* tp_dealloc */
2748 0, /* tp_print */
2749 0, /* tp_getattr */
2750 0, /* tp_setattr */
2751 0, /* tp_compare */
2752 (reprfunc)type_repr, /* tp_repr */
2753 0, /* tp_as_number */
2754 0, /* tp_as_sequence */
2755 0, /* tp_as_mapping */
2756 (hashfunc)_Py_HashPointer, /* tp_hash */
2757 (ternaryfunc)type_call, /* tp_call */
2758 0, /* tp_str */
2759 (getattrofunc)type_getattro, /* tp_getattro */
2760 (setattrofunc)type_setattro, /* tp_setattro */
2761 0, /* tp_as_buffer */
2762 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2763 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2764 type_doc, /* tp_doc */
2765 (traverseproc)type_traverse, /* tp_traverse */
2766 (inquiry)type_clear, /* tp_clear */
2767 type_richcompare, /* tp_richcompare */
2768 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2769 0, /* tp_iter */
2770 0, /* tp_iternext */
2771 type_methods, /* tp_methods */
2772 type_members, /* tp_members */
2773 type_getsets, /* tp_getset */
2774 0, /* tp_base */
2775 0, /* tp_dict */
2776 0, /* tp_descr_get */
2777 0, /* tp_descr_set */
2778 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2779 type_init, /* tp_init */
2780 0, /* tp_alloc */
2781 type_new, /* tp_new */
2782 PyObject_GC_Del, /* tp_free */
2783 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002784};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002785
2786
2787/* The base type of all types (eventually)... except itself. */
2788
Guido van Rossum143b5642007-03-23 04:58:42 +00002789/* You may wonder why object.__new__() only complains about arguments
2790 when object.__init__() is not overridden, and vice versa.
2791
2792 Consider the use cases:
2793
2794 1. When neither is overridden, we want to hear complaints about
2795 excess (i.e., any) arguments, since their presence could
2796 indicate there's a bug.
2797
2798 2. When defining an Immutable type, we are likely to override only
2799 __new__(), since __init__() is called too late to initialize an
2800 Immutable object. Since __new__() defines the signature for the
2801 type, it would be a pain to have to override __init__() just to
2802 stop it from complaining about excess arguments.
2803
2804 3. When defining a Mutable type, we are likely to override only
2805 __init__(). So here the converse reasoning applies: we don't
2806 want to have to override __new__() just to stop it from
2807 complaining.
2808
2809 4. When __init__() is overridden, and the subclass __init__() calls
2810 object.__init__(), the latter should complain about excess
2811 arguments; ditto for __new__().
2812
2813 Use cases 2 and 3 make it unattractive to unconditionally check for
2814 excess arguments. The best solution that addresses all four use
2815 cases is as follows: __init__() complains about excess arguments
2816 unless __new__() is overridden and __init__() is not overridden
2817 (IOW, if __init__() is overridden or __new__() is not overridden);
2818 symmetrically, __new__() complains about excess arguments unless
2819 __init__() is overridden and __new__() is not overridden
2820 (IOW, if __new__() is overridden or __init__() is not overridden).
2821
2822 However, for backwards compatibility, this breaks too much code.
2823 Therefore, in 2.6, we'll *warn* about excess arguments when both
2824 methods are overridden; for all other cases we'll use the above
2825 rules.
2826
2827*/
2828
2829/* Forward */
2830static PyObject *
2831object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2832
2833static int
2834excess_args(PyObject *args, PyObject *kwds)
2835{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002836 return PyTuple_GET_SIZE(args) ||
2837 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
Guido van Rossum143b5642007-03-23 04:58:42 +00002838}
2839
Tim Peters6d6c1a32001-08-02 04:15:00 +00002840static int
2841object_init(PyObject *self, PyObject *args, PyObject *kwds)
2842{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002843 int err = 0;
2844 if (excess_args(args, kwds)) {
2845 PyTypeObject *type = Py_TYPE(self);
2846 if (type->tp_init != object_init &&
2847 type->tp_new != object_new)
2848 {
2849 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2850 "object.__init__() takes no parameters",
2851 1);
2852 }
2853 else if (type->tp_init != object_init ||
2854 type->tp_new == object_new)
2855 {
2856 PyErr_SetString(PyExc_TypeError,
2857 "object.__init__() takes no parameters");
2858 err = -1;
2859 }
2860 }
2861 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002862}
2863
Guido van Rossum298e4212003-02-13 16:30:16 +00002864static PyObject *
2865object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2866{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002867 int err = 0;
2868 if (excess_args(args, kwds)) {
2869 if (type->tp_new != object_new &&
2870 type->tp_init != object_init)
2871 {
2872 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2873 "object.__new__() takes no parameters",
2874 1);
2875 }
2876 else if (type->tp_new != object_new ||
2877 type->tp_init == object_init)
2878 {
2879 PyErr_SetString(PyExc_TypeError,
2880 "object.__new__() takes no parameters");
2881 err = -1;
2882 }
2883 }
2884 if (err < 0)
2885 return NULL;
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00002886
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002887 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2888 static PyObject *comma = NULL;
2889 PyObject *abstract_methods = NULL;
2890 PyObject *builtins;
2891 PyObject *sorted;
2892 PyObject *sorted_methods = NULL;
2893 PyObject *joined = NULL;
2894 const char *joined_str;
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00002895
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002896 /* Compute ", ".join(sorted(type.__abstractmethods__))
2897 into joined. */
2898 abstract_methods = type_abstractmethods(type, NULL);
2899 if (abstract_methods == NULL)
2900 goto error;
2901 builtins = PyEval_GetBuiltins();
2902 if (builtins == NULL)
2903 goto error;
2904 sorted = PyDict_GetItemString(builtins, "sorted");
2905 if (sorted == NULL)
2906 goto error;
2907 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2908 abstract_methods,
2909 NULL);
2910 if (sorted_methods == NULL)
2911 goto error;
2912 if (comma == NULL) {
2913 comma = PyString_InternFromString(", ");
2914 if (comma == NULL)
2915 goto error;
2916 }
2917 joined = PyObject_CallMethod(comma, "join",
2918 "O", sorted_methods);
2919 if (joined == NULL)
2920 goto error;
2921 joined_str = PyString_AsString(joined);
2922 if (joined_str == NULL)
2923 goto error;
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00002924
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002925 PyErr_Format(PyExc_TypeError,
2926 "Can't instantiate abstract class %s "
2927 "with abstract methods %s",
2928 type->tp_name,
2929 joined_str);
2930 error:
2931 Py_XDECREF(joined);
2932 Py_XDECREF(sorted_methods);
2933 Py_XDECREF(abstract_methods);
2934 return NULL;
2935 }
2936 return type->tp_alloc(type, 0);
Guido van Rossum298e4212003-02-13 16:30:16 +00002937}
2938
Tim Peters6d6c1a32001-08-02 04:15:00 +00002939static void
2940object_dealloc(PyObject *self)
2941{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002942 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002943}
2944
Guido van Rossum8e248182001-08-12 05:17:56 +00002945static PyObject *
2946object_repr(PyObject *self)
2947{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002948 PyTypeObject *type;
2949 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002950
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002951 type = Py_TYPE(self);
2952 mod = type_module(type, NULL);
2953 if (mod == NULL)
2954 PyErr_Clear();
2955 else if (!PyString_Check(mod)) {
2956 Py_DECREF(mod);
2957 mod = NULL;
2958 }
2959 name = type_name(type, NULL);
2960 if (name == NULL)
2961 return NULL;
2962 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
2963 rtn = PyString_FromFormat("<%s.%s object at %p>",
2964 PyString_AS_STRING(mod),
2965 PyString_AS_STRING(name),
2966 self);
2967 else
2968 rtn = PyString_FromFormat("<%s object at %p>",
2969 type->tp_name, self);
2970 Py_XDECREF(mod);
2971 Py_DECREF(name);
2972 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002973}
2974
Guido van Rossumb8f63662001-08-15 23:57:02 +00002975static PyObject *
2976object_str(PyObject *self)
2977{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002978 unaryfunc f;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002979
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002980 f = Py_TYPE(self)->tp_repr;
2981 if (f == NULL)
2982 f = object_repr;
2983 return f(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002984}
2985
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002986static PyObject *
2987object_get_class(PyObject *self, void *closure)
2988{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002989 Py_INCREF(Py_TYPE(self));
2990 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002991}
2992
2993static int
2994equiv_structs(PyTypeObject *a, PyTypeObject *b)
2995{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002996 return a == b ||
2997 (a != NULL &&
2998 b != NULL &&
2999 a->tp_basicsize == b->tp_basicsize &&
3000 a->tp_itemsize == b->tp_itemsize &&
3001 a->tp_dictoffset == b->tp_dictoffset &&
3002 a->tp_weaklistoffset == b->tp_weaklistoffset &&
3003 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3004 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003005}
3006
3007static int
3008same_slots_added(PyTypeObject *a, PyTypeObject *b)
3009{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003010 PyTypeObject *base = a->tp_base;
3011 Py_ssize_t size;
3012 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003013
Benjamin Petersoncf94b8b2011-01-17 19:30:29 +00003014 assert(base == b->tp_base);
3015 assert(equiv_structs(a, base) && equiv_structs(b, base));
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003016 size = base->tp_basicsize;
3017 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3018 size += sizeof(PyObject *);
3019 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3020 size += sizeof(PyObject *);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00003021
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003022 /* Check slots compliance */
3023 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3024 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3025 if (slots_a && slots_b) {
3026 if (PyObject_Compare(slots_a, slots_b) != 0)
3027 return 0;
3028 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3029 }
3030 return size == a->tp_basicsize && size == b->tp_basicsize;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003031}
3032
3033static int
Anthony Baxtera6286212006-04-11 07:42:36 +00003034compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003035{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003036 PyTypeObject *newbase, *oldbase;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003037
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003038 if (newto->tp_dealloc != oldto->tp_dealloc ||
3039 newto->tp_free != oldto->tp_free)
3040 {
3041 PyErr_Format(PyExc_TypeError,
3042 "%s assignment: "
3043 "'%s' deallocator differs from '%s'",
3044 attr,
3045 newto->tp_name,
3046 oldto->tp_name);
3047 return 0;
3048 }
3049 newbase = newto;
3050 oldbase = oldto;
3051 while (equiv_structs(newbase, newbase->tp_base))
3052 newbase = newbase->tp_base;
3053 while (equiv_structs(oldbase, oldbase->tp_base))
3054 oldbase = oldbase->tp_base;
3055 if (newbase != oldbase &&
3056 (newbase->tp_base != oldbase->tp_base ||
3057 !same_slots_added(newbase, oldbase))) {
3058 PyErr_Format(PyExc_TypeError,
3059 "%s assignment: "
3060 "'%s' object layout differs from '%s'",
3061 attr,
3062 newto->tp_name,
3063 oldto->tp_name);
3064 return 0;
3065 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003066
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003067 return 1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003068}
3069
3070static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003071object_set_class(PyObject *self, PyObject *value, void *closure)
3072{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003073 PyTypeObject *oldto = Py_TYPE(self);
3074 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003075
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003076 if (value == NULL) {
3077 PyErr_SetString(PyExc_TypeError,
3078 "can't delete __class__ attribute");
3079 return -1;
3080 }
3081 if (!PyType_Check(value)) {
3082 PyErr_Format(PyExc_TypeError,
3083 "__class__ must be set to new-style class, not '%s' object",
3084 Py_TYPE(value)->tp_name);
3085 return -1;
3086 }
3087 newto = (PyTypeObject *)value;
3088 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3089 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3090 {
3091 PyErr_Format(PyExc_TypeError,
3092 "__class__ assignment: only for heap types");
3093 return -1;
3094 }
3095 if (compatible_for_assignment(newto, oldto, "__class__")) {
3096 Py_INCREF(newto);
3097 Py_TYPE(self) = newto;
3098 Py_DECREF(oldto);
3099 return 0;
3100 }
3101 else {
3102 return -1;
3103 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003104}
3105
3106static PyGetSetDef object_getsets[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003107 {"__class__", object_get_class, object_set_class,
3108 PyDoc_STR("the object's class")},
3109 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003110};
3111
Guido van Rossumc53f0092003-02-18 22:05:12 +00003112
Guido van Rossum036f9992003-02-21 22:02:54 +00003113/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Georg Brandldffbf5f2008-05-20 07:49:57 +00003114 We fall back to helpers in copy_reg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003115 - pickle protocols < 2
3116 - calculating the list of slot names (done only once per class)
3117 - the __newobj__ function (which is used as a token but never called)
3118*/
3119
3120static PyObject *
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003121import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003122{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003123 static PyObject *copyreg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00003124
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003125 if (!copyreg_str) {
3126 copyreg_str = PyString_InternFromString("copy_reg");
3127 if (copyreg_str == NULL)
3128 return NULL;
3129 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003130
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003131 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003132}
3133
3134static PyObject *
3135slotnames(PyObject *cls)
3136{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003137 PyObject *clsdict;
3138 PyObject *copyreg;
3139 PyObject *slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003140
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003141 if (!PyType_Check(cls)) {
3142 Py_INCREF(Py_None);
3143 return Py_None;
3144 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003145
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003146 clsdict = ((PyTypeObject *)cls)->tp_dict;
3147 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
3148 if (slotnames != NULL && PyList_Check(slotnames)) {
3149 Py_INCREF(slotnames);
3150 return slotnames;
3151 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003152
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003153 copyreg = import_copyreg();
3154 if (copyreg == NULL)
3155 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003156
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003157 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
3158 Py_DECREF(copyreg);
3159 if (slotnames != NULL &&
3160 slotnames != Py_None &&
3161 !PyList_Check(slotnames))
3162 {
3163 PyErr_SetString(PyExc_TypeError,
3164 "copy_reg._slotnames didn't return a list or None");
3165 Py_DECREF(slotnames);
3166 slotnames = NULL;
3167 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003168
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003169 return slotnames;
Guido van Rossum036f9992003-02-21 22:02:54 +00003170}
3171
3172static PyObject *
3173reduce_2(PyObject *obj)
3174{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003175 PyObject *cls, *getnewargs;
3176 PyObject *args = NULL, *args2 = NULL;
3177 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3178 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3179 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3180 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00003181
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003182 cls = PyObject_GetAttrString(obj, "__class__");
3183 if (cls == NULL)
3184 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003185
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003186 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
3187 if (getnewargs != NULL) {
3188 args = PyObject_CallObject(getnewargs, NULL);
3189 Py_DECREF(getnewargs);
3190 if (args != NULL && !PyTuple_Check(args)) {
3191 PyErr_Format(PyExc_TypeError,
3192 "__getnewargs__ should return a tuple, "
3193 "not '%.200s'", Py_TYPE(args)->tp_name);
3194 goto end;
3195 }
3196 }
3197 else {
3198 PyErr_Clear();
3199 args = PyTuple_New(0);
3200 }
3201 if (args == NULL)
3202 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003203
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003204 getstate = PyObject_GetAttrString(obj, "__getstate__");
3205 if (getstate != NULL) {
3206 state = PyObject_CallObject(getstate, NULL);
3207 Py_DECREF(getstate);
3208 if (state == NULL)
3209 goto end;
3210 }
3211 else {
3212 PyErr_Clear();
3213 state = PyObject_GetAttrString(obj, "__dict__");
3214 if (state == NULL) {
3215 PyErr_Clear();
3216 state = Py_None;
3217 Py_INCREF(state);
3218 }
3219 names = slotnames(cls);
3220 if (names == NULL)
3221 goto end;
3222 if (names != Py_None) {
3223 assert(PyList_Check(names));
3224 slots = PyDict_New();
3225 if (slots == NULL)
3226 goto end;
3227 n = 0;
3228 /* Can't pre-compute the list size; the list
3229 is stored on the class so accessible to other
3230 threads, which may be run by DECREF */
3231 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3232 PyObject *name, *value;
3233 name = PyList_GET_ITEM(names, i);
3234 value = PyObject_GetAttr(obj, name);
3235 if (value == NULL)
3236 PyErr_Clear();
3237 else {
3238 int err = PyDict_SetItem(slots, name,
3239 value);
3240 Py_DECREF(value);
3241 if (err)
3242 goto end;
3243 n++;
3244 }
3245 }
3246 if (n) {
3247 state = Py_BuildValue("(NO)", state, slots);
3248 if (state == NULL)
3249 goto end;
3250 }
3251 }
3252 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003253
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003254 if (!PyList_Check(obj)) {
3255 listitems = Py_None;
3256 Py_INCREF(listitems);
3257 }
3258 else {
3259 listitems = PyObject_GetIter(obj);
3260 if (listitems == NULL)
3261 goto end;
3262 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003263
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003264 if (!PyDict_Check(obj)) {
3265 dictitems = Py_None;
3266 Py_INCREF(dictitems);
3267 }
3268 else {
3269 dictitems = PyObject_CallMethod(obj, "iteritems", "");
3270 if (dictitems == NULL)
3271 goto end;
3272 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003273
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003274 copyreg = import_copyreg();
3275 if (copyreg == NULL)
3276 goto end;
3277 newobj = PyObject_GetAttrString(copyreg, "__newobj__");
3278 if (newobj == NULL)
3279 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003280
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003281 n = PyTuple_GET_SIZE(args);
3282 args2 = PyTuple_New(n+1);
3283 if (args2 == NULL)
3284 goto end;
3285 PyTuple_SET_ITEM(args2, 0, cls);
3286 cls = NULL;
3287 for (i = 0; i < n; i++) {
3288 PyObject *v = PyTuple_GET_ITEM(args, i);
3289 Py_INCREF(v);
3290 PyTuple_SET_ITEM(args2, i+1, v);
3291 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003292
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003293 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003294
3295 end:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003296 Py_XDECREF(cls);
3297 Py_XDECREF(args);
3298 Py_XDECREF(args2);
3299 Py_XDECREF(slots);
3300 Py_XDECREF(state);
3301 Py_XDECREF(names);
3302 Py_XDECREF(listitems);
3303 Py_XDECREF(dictitems);
3304 Py_XDECREF(copyreg);
3305 Py_XDECREF(newobj);
3306 return res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003307}
3308
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003309/*
3310 * There were two problems when object.__reduce__ and object.__reduce_ex__
3311 * were implemented in the same function:
3312 * - trying to pickle an object with a custom __reduce__ method that
3313 * fell back to object.__reduce__ in certain circumstances led to
3314 * infinite recursion at Python level and eventual RuntimeError.
3315 * - Pickling objects that lied about their type by overwriting the
3316 * __class__ descriptor could lead to infinite recursion at C level
3317 * and eventual segfault.
3318 *
3319 * Because of backwards compatibility, the two methods still have to
3320 * behave in the same way, even if this is not required by the pickle
3321 * protocol. This common functionality was moved to the _common_reduce
3322 * function.
3323 */
3324static PyObject *
3325_common_reduce(PyObject *self, int proto)
3326{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003327 PyObject *copyreg, *res;
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003328
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003329 if (proto >= 2)
3330 return reduce_2(self);
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003331
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003332 copyreg = import_copyreg();
3333 if (!copyreg)
3334 return NULL;
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003335
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003336 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3337 Py_DECREF(copyreg);
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003338
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003339 return res;
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003340}
3341
3342static PyObject *
3343object_reduce(PyObject *self, PyObject *args)
3344{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003345 int proto = 0;
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003346
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003347 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3348 return NULL;
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003349
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003350 return _common_reduce(self, proto);
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003351}
3352
Guido van Rossum036f9992003-02-21 22:02:54 +00003353static PyObject *
3354object_reduce_ex(PyObject *self, PyObject *args)
3355{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003356 PyObject *reduce, *res;
3357 int proto = 0;
Guido van Rossum036f9992003-02-21 22:02:54 +00003358
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003359 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3360 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00003361
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003362 reduce = PyObject_GetAttrString(self, "__reduce__");
3363 if (reduce == NULL)
3364 PyErr_Clear();
3365 else {
3366 PyObject *cls, *clsreduce, *objreduce;
3367 int override;
3368 cls = PyObject_GetAttrString(self, "__class__");
3369 if (cls == NULL) {
3370 Py_DECREF(reduce);
3371 return NULL;
3372 }
3373 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3374 Py_DECREF(cls);
3375 if (clsreduce == NULL) {
3376 Py_DECREF(reduce);
3377 return NULL;
3378 }
3379 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3380 "__reduce__");
3381 override = (clsreduce != objreduce);
3382 Py_DECREF(clsreduce);
3383 if (override) {
3384 res = PyObject_CallObject(reduce, NULL);
3385 Py_DECREF(reduce);
3386 return res;
3387 }
3388 else
3389 Py_DECREF(reduce);
3390 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003391
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003392 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003393}
3394
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00003395static PyObject *
3396object_subclasshook(PyObject *cls, PyObject *args)
3397{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003398 Py_INCREF(Py_NotImplemented);
3399 return Py_NotImplemented;
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00003400}
3401
3402PyDoc_STRVAR(object_subclasshook_doc,
3403"Abstract classes can override this to customize issubclass().\n"
3404"\n"
3405"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3406"It should return True, False or NotImplemented. If it returns\n"
3407"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3408"overrides the normal algorithm (and the outcome is cached).\n");
3409
Eric Smitha9f7d622008-02-17 19:46:49 +00003410/*
3411 from PEP 3101, this code implements:
3412
3413 class object:
3414 def __format__(self, format_spec):
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003415 if isinstance(format_spec, str):
3416 return format(str(self), format_spec)
3417 elif isinstance(format_spec, unicode):
3418 return format(unicode(self), format_spec)
Eric Smitha9f7d622008-02-17 19:46:49 +00003419*/
3420static PyObject *
3421object_format(PyObject *self, PyObject *args)
3422{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003423 PyObject *format_spec;
3424 PyObject *self_as_str = NULL;
3425 PyObject *result = NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003426 Py_ssize_t format_len;
Eric Smitha9f7d622008-02-17 19:46:49 +00003427
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003428 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3429 return NULL;
Benjamin Peterson78821dd2009-01-25 17:15:10 +00003430#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003431 if (PyUnicode_Check(format_spec)) {
3432 format_len = PyUnicode_GET_SIZE(format_spec);
3433 self_as_str = PyObject_Unicode(self);
3434 } else if (PyString_Check(format_spec)) {
Benjamin Peterson78821dd2009-01-25 17:15:10 +00003435#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003436 if (PyString_Check(format_spec)) {
Benjamin Peterson78821dd2009-01-25 17:15:10 +00003437#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003438 format_len = PyString_GET_SIZE(format_spec);
3439 self_as_str = PyObject_Str(self);
3440 } else {
3441 PyErr_SetString(PyExc_TypeError,
3442 "argument to __format__ must be unicode or str");
3443 return NULL;
3444 }
Eric Smitha9f7d622008-02-17 19:46:49 +00003445
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003446 if (self_as_str != NULL) {
3447 /* Issue 7994: If we're converting to a string, we
3448 should reject format specifications */
3449 if (format_len > 0) {
3450 if (PyErr_WarnEx(PyExc_PendingDeprecationWarning,
3451 "object.__format__ with a non-empty format "
3452 "string is deprecated", 1) < 0) {
3453 goto done;
3454 }
3455 /* Eventually this will become an error:
3456 PyErr_Format(PyExc_TypeError,
3457 "non-empty format string passed to object.__format__");
3458 goto done;
3459 */
Eric Smitha9f7d622008-02-17 19:46:49 +00003460 }
Benjamin Peterson67783b12010-06-05 01:00:10 +00003461 result = PyObject_Format(self_as_str, format_spec);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003462 }
Eric Smitha9f7d622008-02-17 19:46:49 +00003463
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003464done:
3465 Py_XDECREF(self_as_str);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003466
3467 return result;
Eric Smitha9f7d622008-02-17 19:46:49 +00003468}
3469
Robert Schuppenies51df0642008-06-01 16:16:17 +00003470static PyObject *
3471object_sizeof(PyObject *self, PyObject *args)
3472{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003473 Py_ssize_t res, isize;
Robert Schuppenies51df0642008-06-01 16:16:17 +00003474
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003475 res = 0;
3476 isize = self->ob_type->tp_itemsize;
3477 if (isize > 0)
3478 res = self->ob_type->ob_size * isize;
3479 res += self->ob_type->tp_basicsize;
Robert Schuppenies51df0642008-06-01 16:16:17 +00003480
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003481 return PyInt_FromSsize_t(res);
Robert Schuppenies51df0642008-06-01 16:16:17 +00003482}
3483
Guido van Rossum3926a632001-09-25 16:25:58 +00003484static PyMethodDef object_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003485 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3486 PyDoc_STR("helper for pickle")},
3487 {"__reduce__", object_reduce, METH_VARARGS,
3488 PyDoc_STR("helper for pickle")},
3489 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3490 object_subclasshook_doc},
3491 {"__format__", object_format, METH_VARARGS,
3492 PyDoc_STR("default object formatter")},
3493 {"__sizeof__", object_sizeof, METH_NOARGS,
3494 PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")},
3495 {0}
Guido van Rossum3926a632001-09-25 16:25:58 +00003496};
3497
Guido van Rossum036f9992003-02-21 22:02:54 +00003498
Tim Peters6d6c1a32001-08-02 04:15:00 +00003499PyTypeObject PyBaseObject_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003500 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3501 "object", /* tp_name */
3502 sizeof(PyObject), /* tp_basicsize */
3503 0, /* tp_itemsize */
3504 object_dealloc, /* tp_dealloc */
3505 0, /* tp_print */
3506 0, /* tp_getattr */
3507 0, /* tp_setattr */
3508 0, /* tp_compare */
3509 object_repr, /* tp_repr */
3510 0, /* tp_as_number */
3511 0, /* tp_as_sequence */
3512 0, /* tp_as_mapping */
3513 (hashfunc)_Py_HashPointer, /* tp_hash */
3514 0, /* tp_call */
3515 object_str, /* tp_str */
3516 PyObject_GenericGetAttr, /* tp_getattro */
3517 PyObject_GenericSetAttr, /* tp_setattro */
3518 0, /* tp_as_buffer */
3519 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3520 PyDoc_STR("The most base type"), /* tp_doc */
3521 0, /* tp_traverse */
3522 0, /* tp_clear */
3523 0, /* tp_richcompare */
3524 0, /* tp_weaklistoffset */
3525 0, /* tp_iter */
3526 0, /* tp_iternext */
3527 object_methods, /* tp_methods */
3528 0, /* tp_members */
3529 object_getsets, /* tp_getset */
3530 0, /* tp_base */
3531 0, /* tp_dict */
3532 0, /* tp_descr_get */
3533 0, /* tp_descr_set */
3534 0, /* tp_dictoffset */
3535 object_init, /* tp_init */
3536 PyType_GenericAlloc, /* tp_alloc */
3537 object_new, /* tp_new */
3538 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003539};
3540
3541
3542/* Initialize the __dict__ in a type object */
3543
3544static int
3545add_methods(PyTypeObject *type, PyMethodDef *meth)
3546{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003547 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003548
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003549 for (; meth->ml_name != NULL; meth++) {
3550 PyObject *descr;
3551 if (PyDict_GetItemString(dict, meth->ml_name) &&
3552 !(meth->ml_flags & METH_COEXIST))
3553 continue;
3554 if (meth->ml_flags & METH_CLASS) {
3555 if (meth->ml_flags & METH_STATIC) {
3556 PyErr_SetString(PyExc_ValueError,
3557 "method cannot be both class and static");
3558 return -1;
3559 }
3560 descr = PyDescr_NewClassMethod(type, meth);
3561 }
3562 else if (meth->ml_flags & METH_STATIC) {
3563 PyObject *cfunc = PyCFunction_New(meth, NULL);
3564 if (cfunc == NULL)
3565 return -1;
3566 descr = PyStaticMethod_New(cfunc);
3567 Py_DECREF(cfunc);
3568 }
3569 else {
3570 descr = PyDescr_NewMethod(type, meth);
3571 }
3572 if (descr == NULL)
3573 return -1;
3574 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
3575 return -1;
3576 Py_DECREF(descr);
3577 }
3578 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003579}
3580
3581static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003582add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003583{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003584 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003585
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003586 for (; memb->name != NULL; memb++) {
3587 PyObject *descr;
3588 if (PyDict_GetItemString(dict, memb->name))
3589 continue;
3590 descr = PyDescr_NewMember(type, memb);
3591 if (descr == NULL)
3592 return -1;
3593 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3594 return -1;
3595 Py_DECREF(descr);
3596 }
3597 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003598}
3599
3600static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003601add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003602{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003603 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003604
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003605 for (; gsp->name != NULL; gsp++) {
3606 PyObject *descr;
3607 if (PyDict_GetItemString(dict, gsp->name))
3608 continue;
3609 descr = PyDescr_NewGetSet(type, gsp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003610
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003611 if (descr == NULL)
3612 return -1;
3613 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3614 return -1;
3615 Py_DECREF(descr);
3616 }
3617 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003618}
3619
Antoine Pitrou789be0c2009-04-02 21:18:34 +00003620#define BUFFER_FLAGS (Py_TPFLAGS_HAVE_GETCHARBUFFER | Py_TPFLAGS_HAVE_NEWBUFFER)
3621
Guido van Rossum13d52f02001-08-10 21:24:08 +00003622static void
3623inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003624{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003625 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003626
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003627 /* Special flag magic */
3628 if (!type->tp_as_buffer && base->tp_as_buffer) {
3629 type->tp_flags &= ~BUFFER_FLAGS;
3630 type->tp_flags |=
3631 base->tp_flags & BUFFER_FLAGS;
3632 }
3633 if (!type->tp_as_sequence && base->tp_as_sequence) {
3634 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3635 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3636 }
3637 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3638 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3639 if ((!type->tp_as_number && base->tp_as_number) ||
3640 (!type->tp_as_sequence && base->tp_as_sequence)) {
3641 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3642 if (!type->tp_as_number && !type->tp_as_sequence) {
3643 type->tp_flags |= base->tp_flags &
3644 Py_TPFLAGS_HAVE_INPLACEOPS;
3645 }
3646 }
3647 /* Wow */
3648 }
3649 if (!type->tp_as_number && base->tp_as_number) {
3650 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3651 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3652 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00003653
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003654 /* Copying basicsize is connected to the GC flags */
3655 oldsize = base->tp_basicsize;
3656 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3657 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3658 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3659 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3660 (!type->tp_traverse && !type->tp_clear)) {
3661 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3662 if (type->tp_traverse == NULL)
3663 type->tp_traverse = base->tp_traverse;
3664 if (type->tp_clear == NULL)
3665 type->tp_clear = base->tp_clear;
3666 }
3667 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3668 /* The condition below could use some explanation.
3669 It appears that tp_new is not inherited for static types
3670 whose base class is 'object'; this seems to be a precaution
3671 so that old extension types don't suddenly become
3672 callable (object.__new__ wouldn't insure the invariants
3673 that the extension type's own factory function ensures).
3674 Heap types, of course, are under our control, so they do
3675 inherit tp_new; static extension types that specify some
3676 other built-in type as the default are considered
3677 new-style-aware so they also inherit object.__new__. */
3678 if (base != &PyBaseObject_Type ||
3679 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3680 if (type->tp_new == NULL)
3681 type->tp_new = base->tp_new;
3682 }
3683 }
3684 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003685
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003686 /* Copy other non-function slots */
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003687
3688#undef COPYVAL
3689#define COPYVAL(SLOT) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003690 if (type->SLOT == 0) type->SLOT = base->SLOT
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003691
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003692 COPYVAL(tp_itemsize);
3693 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3694 COPYVAL(tp_weaklistoffset);
3695 }
3696 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3697 COPYVAL(tp_dictoffset);
3698 }
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003699
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003700 /* Setup fast subclass flags */
3701 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3702 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3703 else if (PyType_IsSubtype(base, &PyType_Type))
3704 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3705 else if (PyType_IsSubtype(base, &PyInt_Type))
3706 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3707 else if (PyType_IsSubtype(base, &PyLong_Type))
3708 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3709 else if (PyType_IsSubtype(base, &PyString_Type))
3710 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003711#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003712 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3713 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003714#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003715 else if (PyType_IsSubtype(base, &PyTuple_Type))
3716 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3717 else if (PyType_IsSubtype(base, &PyList_Type))
3718 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3719 else if (PyType_IsSubtype(base, &PyDict_Type))
3720 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003721}
3722
Nick Coghlan48361f52008-08-11 15:45:58 +00003723static int
3724overrides_name(PyTypeObject *type, char *name)
3725{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003726 PyObject *dict = type->tp_dict;
Nick Coghlan48361f52008-08-11 15:45:58 +00003727
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003728 assert(dict != NULL);
3729 if (PyDict_GetItemString(dict, name) != NULL) {
3730 return 1;
3731 }
3732 return 0;
Nick Coghlan48361f52008-08-11 15:45:58 +00003733}
3734
3735#define OVERRIDES_HASH(x) overrides_name(x, "__hash__")
Nick Coghlan48361f52008-08-11 15:45:58 +00003736#define OVERRIDES_EQ(x) overrides_name(x, "__eq__")
3737
Guido van Rossum13d52f02001-08-10 21:24:08 +00003738static void
3739inherit_slots(PyTypeObject *type, PyTypeObject *base)
3740{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003741 PyTypeObject *basebase;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003742
3743#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003744#undef COPYSLOT
3745#undef COPYNUM
3746#undef COPYSEQ
3747#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003748#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003749
3750#define SLOTDEFINED(SLOT) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003751 (base->SLOT != 0 && \
3752 (basebase == NULL || base->SLOT != basebase->SLOT))
Guido van Rossum13d52f02001-08-10 21:24:08 +00003753
Tim Peters6d6c1a32001-08-02 04:15:00 +00003754#define COPYSLOT(SLOT) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003755 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003756
3757#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3758#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3759#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003760#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003761
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003762 /* This won't inherit indirect slots (from tp_as_number etc.)
3763 if type doesn't provide the space. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003764
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003765 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3766 basebase = base->tp_base;
3767 if (basebase->tp_as_number == NULL)
3768 basebase = NULL;
3769 COPYNUM(nb_add);
3770 COPYNUM(nb_subtract);
3771 COPYNUM(nb_multiply);
3772 COPYNUM(nb_divide);
3773 COPYNUM(nb_remainder);
3774 COPYNUM(nb_divmod);
3775 COPYNUM(nb_power);
3776 COPYNUM(nb_negative);
3777 COPYNUM(nb_positive);
3778 COPYNUM(nb_absolute);
3779 COPYNUM(nb_nonzero);
3780 COPYNUM(nb_invert);
3781 COPYNUM(nb_lshift);
3782 COPYNUM(nb_rshift);
3783 COPYNUM(nb_and);
3784 COPYNUM(nb_xor);
3785 COPYNUM(nb_or);
3786 COPYNUM(nb_coerce);
3787 COPYNUM(nb_int);
3788 COPYNUM(nb_long);
3789 COPYNUM(nb_float);
3790 COPYNUM(nb_oct);
3791 COPYNUM(nb_hex);
3792 COPYNUM(nb_inplace_add);
3793 COPYNUM(nb_inplace_subtract);
3794 COPYNUM(nb_inplace_multiply);
3795 COPYNUM(nb_inplace_divide);
3796 COPYNUM(nb_inplace_remainder);
3797 COPYNUM(nb_inplace_power);
3798 COPYNUM(nb_inplace_lshift);
3799 COPYNUM(nb_inplace_rshift);
3800 COPYNUM(nb_inplace_and);
3801 COPYNUM(nb_inplace_xor);
3802 COPYNUM(nb_inplace_or);
3803 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3804 COPYNUM(nb_true_divide);
3805 COPYNUM(nb_floor_divide);
3806 COPYNUM(nb_inplace_true_divide);
3807 COPYNUM(nb_inplace_floor_divide);
3808 }
3809 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3810 COPYNUM(nb_index);
3811 }
3812 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003813
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003814 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3815 basebase = base->tp_base;
3816 if (basebase->tp_as_sequence == NULL)
3817 basebase = NULL;
3818 COPYSEQ(sq_length);
3819 COPYSEQ(sq_concat);
3820 COPYSEQ(sq_repeat);
3821 COPYSEQ(sq_item);
3822 COPYSEQ(sq_slice);
3823 COPYSEQ(sq_ass_item);
3824 COPYSEQ(sq_ass_slice);
3825 COPYSEQ(sq_contains);
3826 COPYSEQ(sq_inplace_concat);
3827 COPYSEQ(sq_inplace_repeat);
3828 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003829
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003830 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3831 basebase = base->tp_base;
3832 if (basebase->tp_as_mapping == NULL)
3833 basebase = NULL;
3834 COPYMAP(mp_length);
3835 COPYMAP(mp_subscript);
3836 COPYMAP(mp_ass_subscript);
3837 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003838
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003839 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3840 basebase = base->tp_base;
3841 if (basebase->tp_as_buffer == NULL)
3842 basebase = NULL;
3843 COPYBUF(bf_getreadbuffer);
3844 COPYBUF(bf_getwritebuffer);
3845 COPYBUF(bf_getsegcount);
3846 COPYBUF(bf_getcharbuffer);
3847 COPYBUF(bf_getbuffer);
3848 COPYBUF(bf_releasebuffer);
3849 }
Tim Petersfc57ccb2001-10-12 02:38:24 +00003850
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003851 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003852
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003853 COPYSLOT(tp_dealloc);
3854 COPYSLOT(tp_print);
3855 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3856 type->tp_getattr = base->tp_getattr;
3857 type->tp_getattro = base->tp_getattro;
3858 }
3859 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3860 type->tp_setattr = base->tp_setattr;
3861 type->tp_setattro = base->tp_setattro;
3862 }
3863 /* tp_compare see tp_richcompare */
3864 COPYSLOT(tp_repr);
3865 /* tp_hash see tp_richcompare */
3866 COPYSLOT(tp_call);
3867 COPYSLOT(tp_str);
3868 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
3869 if (type->tp_compare == NULL &&
3870 type->tp_richcompare == NULL &&
3871 type->tp_hash == NULL)
3872 {
3873 type->tp_compare = base->tp_compare;
3874 type->tp_richcompare = base->tp_richcompare;
3875 type->tp_hash = base->tp_hash;
3876 /* Check for changes to inherited methods in Py3k*/
3877 if (Py_Py3kWarningFlag) {
3878 if (base->tp_hash &&
3879 (base->tp_hash != PyObject_HashNotImplemented) &&
3880 !OVERRIDES_HASH(type)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003881 if (OVERRIDES_EQ(type)) {
Mark Dickinsone4b83e02010-06-05 12:14:43 +00003882 if (PyErr_WarnPy3k("Overriding "
3883 "__eq__ blocks inheritance "
3884 "of __hash__ in 3.x",
3885 1) < 0)
3886 /* XXX This isn't right. If the warning is turned
3887 into an exception, we should be communicating
3888 the error back to the caller, but figuring out
Mark Dickinson77acee92010-06-05 12:51:21 +00003889 how to clean up in that case is tricky. See
Mark Dickinsone4b83e02010-06-05 12:14:43 +00003890 issue 8627 for more. */
3891 PyErr_Clear();
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003892 }
3893 }
3894 }
3895 }
3896 }
3897 else {
3898 COPYSLOT(tp_compare);
3899 }
3900 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3901 COPYSLOT(tp_iter);
3902 COPYSLOT(tp_iternext);
3903 }
3904 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3905 COPYSLOT(tp_descr_get);
3906 COPYSLOT(tp_descr_set);
3907 COPYSLOT(tp_dictoffset);
3908 COPYSLOT(tp_init);
3909 COPYSLOT(tp_alloc);
3910 COPYSLOT(tp_is_gc);
3911 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3912 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3913 /* They agree about gc. */
3914 COPYSLOT(tp_free);
3915 }
3916 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3917 type->tp_free == NULL &&
3918 base->tp_free == _PyObject_Del) {
3919 /* A bit of magic to plug in the correct default
3920 * tp_free function when a derived class adds gc,
3921 * didn't define tp_free, and the base uses the
3922 * default non-gc tp_free.
3923 */
3924 type->tp_free = PyObject_GC_Del;
3925 }
3926 /* else they didn't agree about gc, and there isn't something
3927 * obvious to be done -- the type is on its own.
3928 */
3929 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003930}
3931
Jeremy Hylton938ace62002-07-17 16:30:39 +00003932static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003933
Tim Peters6d6c1a32001-08-02 04:15:00 +00003934int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003935PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003936{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003937 PyObject *dict, *bases;
3938 PyTypeObject *base;
3939 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003940
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003941 if (type->tp_flags & Py_TPFLAGS_READY) {
3942 assert(type->tp_dict != NULL);
3943 return 0;
3944 }
3945 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003946
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003947 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003948
Tim Peters36eb4df2003-03-23 03:33:13 +00003949#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003950 /* PyType_Ready is the closest thing we have to a choke point
3951 * for type objects, so is the best place I can think of to try
3952 * to get type objects into the doubly-linked list of all objects.
3953 * Still, not all type objects go thru PyType_Ready.
3954 */
3955 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003956#endif
3957
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003958 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3959 base = type->tp_base;
3960 if (base == NULL && type != &PyBaseObject_Type) {
3961 base = type->tp_base = &PyBaseObject_Type;
3962 Py_INCREF(base);
3963 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003964
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003965 /* Now the only way base can still be NULL is if type is
3966 * &PyBaseObject_Type.
3967 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003968
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003969 /* Initialize the base class */
3970 if (base && base->tp_dict == NULL) {
3971 if (PyType_Ready(base) < 0)
3972 goto error;
3973 }
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003974
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003975 /* Initialize ob_type if NULL. This means extensions that want to be
3976 compilable separately on Windows can call PyType_Ready() instead of
3977 initializing the ob_type field of their type objects. */
3978 /* The test for base != NULL is really unnecessary, since base is only
3979 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3980 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3981 know that. */
3982 if (Py_TYPE(type) == NULL && base != NULL)
3983 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003984
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003985 /* Initialize tp_bases */
3986 bases = type->tp_bases;
3987 if (bases == NULL) {
3988 if (base == NULL)
3989 bases = PyTuple_New(0);
3990 else
3991 bases = PyTuple_Pack(1, base);
3992 if (bases == NULL)
3993 goto error;
3994 type->tp_bases = bases;
3995 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003996
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003997 /* Initialize tp_dict */
3998 dict = type->tp_dict;
3999 if (dict == NULL) {
4000 dict = PyDict_New();
4001 if (dict == NULL)
4002 goto error;
4003 type->tp_dict = dict;
4004 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004005
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004006 /* Add type-specific descriptors to tp_dict */
4007 if (add_operators(type) < 0)
4008 goto error;
4009 if (type->tp_methods != NULL) {
4010 if (add_methods(type, type->tp_methods) < 0)
4011 goto error;
4012 }
4013 if (type->tp_members != NULL) {
4014 if (add_members(type, type->tp_members) < 0)
4015 goto error;
4016 }
4017 if (type->tp_getset != NULL) {
4018 if (add_getset(type, type->tp_getset) < 0)
4019 goto error;
4020 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004021
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004022 /* Calculate method resolution order */
4023 if (mro_internal(type) < 0) {
4024 goto error;
4025 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004026
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004027 /* Inherit special flags from dominant base */
4028 if (type->tp_base != NULL)
4029 inherit_special(type, type->tp_base);
Guido van Rossum13d52f02001-08-10 21:24:08 +00004030
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004031 /* Initialize tp_dict properly */
4032 bases = type->tp_mro;
4033 assert(bases != NULL);
4034 assert(PyTuple_Check(bases));
4035 n = PyTuple_GET_SIZE(bases);
4036 for (i = 1; i < n; i++) {
4037 PyObject *b = PyTuple_GET_ITEM(bases, i);
4038 if (PyType_Check(b))
4039 inherit_slots(type, (PyTypeObject *)b);
4040 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004041
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004042 /* Sanity check for tp_free. */
4043 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4044 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4045 /* This base class needs to call tp_free, but doesn't have
4046 * one, or its tp_free is for non-gc'ed objects.
4047 */
4048 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4049 "gc and is a base type but has inappropriate "
4050 "tp_free slot",
4051 type->tp_name);
4052 goto error;
4053 }
Tim Peters3cfe7542003-05-21 21:29:48 +00004054
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004055 /* if the type dictionary doesn't contain a __doc__, set it from
4056 the tp_doc slot.
4057 */
4058 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
4059 if (type->tp_doc != NULL) {
4060 PyObject *doc = PyString_FromString(type->tp_doc);
4061 if (doc == NULL)
4062 goto error;
4063 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
4064 Py_DECREF(doc);
4065 } else {
4066 PyDict_SetItemString(type->tp_dict,
4067 "__doc__", Py_None);
4068 }
4069 }
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004070
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004071 /* Some more special stuff */
4072 base = type->tp_base;
4073 if (base != NULL) {
4074 if (type->tp_as_number == NULL)
4075 type->tp_as_number = base->tp_as_number;
4076 if (type->tp_as_sequence == NULL)
4077 type->tp_as_sequence = base->tp_as_sequence;
4078 if (type->tp_as_mapping == NULL)
4079 type->tp_as_mapping = base->tp_as_mapping;
4080 if (type->tp_as_buffer == NULL)
4081 type->tp_as_buffer = base->tp_as_buffer;
4082 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004083
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004084 /* Link into each base class's list of subclasses */
4085 bases = type->tp_bases;
4086 n = PyTuple_GET_SIZE(bases);
4087 for (i = 0; i < n; i++) {
4088 PyObject *b = PyTuple_GET_ITEM(bases, i);
4089 if (PyType_Check(b) &&
4090 add_subclass((PyTypeObject *)b, type) < 0)
4091 goto error;
4092 }
Guido van Rossum1c450732001-10-08 15:18:27 +00004093
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004094 /* All done -- set the ready flag */
4095 assert(type->tp_dict != NULL);
4096 type->tp_flags =
4097 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4098 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004099
4100 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004101 type->tp_flags &= ~Py_TPFLAGS_READYING;
4102 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004103}
4104
Guido van Rossum1c450732001-10-08 15:18:27 +00004105static int
4106add_subclass(PyTypeObject *base, PyTypeObject *type)
4107{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004108 Py_ssize_t i;
4109 int result;
4110 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004111
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004112 list = base->tp_subclasses;
4113 if (list == NULL) {
4114 base->tp_subclasses = list = PyList_New(0);
4115 if (list == NULL)
4116 return -1;
4117 }
4118 assert(PyList_Check(list));
4119 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4120 i = PyList_GET_SIZE(list);
4121 while (--i >= 0) {
4122 ref = PyList_GET_ITEM(list, i);
4123 assert(PyWeakref_CheckRef(ref));
4124 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4125 return PyList_SetItem(list, i, newobj);
4126 }
4127 result = PyList_Append(list, newobj);
4128 Py_DECREF(newobj);
4129 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004130}
4131
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004132static void
4133remove_subclass(PyTypeObject *base, PyTypeObject *type)
4134{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004135 Py_ssize_t i;
4136 PyObject *list, *ref;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004137
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004138 list = base->tp_subclasses;
4139 if (list == NULL) {
4140 return;
4141 }
4142 assert(PyList_Check(list));
4143 i = PyList_GET_SIZE(list);
4144 while (--i >= 0) {
4145 ref = PyList_GET_ITEM(list, i);
4146 assert(PyWeakref_CheckRef(ref));
4147 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4148 /* this can't fail, right? */
4149 PySequence_DelItem(list, i);
4150 return;
4151 }
4152 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004153}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004154
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004155static int
4156check_num_args(PyObject *ob, int n)
4157{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004158 if (!PyTuple_CheckExact(ob)) {
4159 PyErr_SetString(PyExc_SystemError,
4160 "PyArg_UnpackTuple() argument list is not a tuple");
4161 return 0;
4162 }
4163 if (n == PyTuple_GET_SIZE(ob))
4164 return 1;
4165 PyErr_Format(
4166 PyExc_TypeError,
4167 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4168 return 0;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004169}
4170
Tim Peters6d6c1a32001-08-02 04:15:00 +00004171/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4172
4173/* There's a wrapper *function* for each distinct function typedef used
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004174 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004175 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4176 Most tables have only one entry; the tables for binary operators have two
4177 entries, one regular and one with reversed arguments. */
4178
4179static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004180wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004181{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004182 lenfunc func = (lenfunc)wrapped;
4183 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004184
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004185 if (!check_num_args(args, 0))
4186 return NULL;
4187 res = (*func)(self);
4188 if (res == -1 && PyErr_Occurred())
4189 return NULL;
4190 return PyInt_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004191}
4192
Tim Peters6d6c1a32001-08-02 04:15:00 +00004193static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004194wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4195{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004196 inquiry func = (inquiry)wrapped;
4197 int res;
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004198
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004199 if (!check_num_args(args, 0))
4200 return NULL;
4201 res = (*func)(self);
4202 if (res == -1 && PyErr_Occurred())
4203 return NULL;
4204 return PyBool_FromLong((long)res);
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004205}
4206
4207static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004208wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4209{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004210 binaryfunc func = (binaryfunc)wrapped;
4211 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004212
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004213 if (!check_num_args(args, 1))
4214 return NULL;
4215 other = PyTuple_GET_ITEM(args, 0);
4216 return (*func)(self, other);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004217}
4218
4219static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004220wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4221{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004222 binaryfunc func = (binaryfunc)wrapped;
4223 PyObject *other;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004224
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004225 if (!check_num_args(args, 1))
4226 return NULL;
4227 other = PyTuple_GET_ITEM(args, 0);
4228 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
4229 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
4230 Py_INCREF(Py_NotImplemented);
4231 return Py_NotImplemented;
4232 }
4233 return (*func)(self, other);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004234}
4235
4236static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004237wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4238{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004239 binaryfunc func = (binaryfunc)wrapped;
4240 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004241
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004242 if (!check_num_args(args, 1))
4243 return NULL;
4244 other = PyTuple_GET_ITEM(args, 0);
4245 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
4246 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
4247 Py_INCREF(Py_NotImplemented);
4248 return Py_NotImplemented;
4249 }
4250 return (*func)(other, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004251}
4252
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004253static PyObject *
4254wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
4255{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004256 coercion func = (coercion)wrapped;
4257 PyObject *other, *res;
4258 int ok;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004259
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004260 if (!check_num_args(args, 1))
4261 return NULL;
4262 other = PyTuple_GET_ITEM(args, 0);
4263 ok = func(&self, &other);
4264 if (ok < 0)
4265 return NULL;
4266 if (ok > 0) {
4267 Py_INCREF(Py_NotImplemented);
4268 return Py_NotImplemented;
4269 }
4270 res = PyTuple_New(2);
4271 if (res == NULL) {
4272 Py_DECREF(self);
4273 Py_DECREF(other);
4274 return NULL;
4275 }
4276 PyTuple_SET_ITEM(res, 0, self);
4277 PyTuple_SET_ITEM(res, 1, other);
4278 return res;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004279}
4280
Tim Peters6d6c1a32001-08-02 04:15:00 +00004281static PyObject *
4282wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4283{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004284 ternaryfunc func = (ternaryfunc)wrapped;
4285 PyObject *other;
4286 PyObject *third = Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004287
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004288 /* Note: This wrapper only works for __pow__() */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004289
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004290 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4291 return NULL;
4292 return (*func)(self, other, third);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004293}
4294
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004295static PyObject *
4296wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4297{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004298 ternaryfunc func = (ternaryfunc)wrapped;
4299 PyObject *other;
4300 PyObject *third = Py_None;
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004301
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004302 /* Note: This wrapper only works for __pow__() */
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004303
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004304 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4305 return NULL;
4306 return (*func)(other, self, third);
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004307}
4308
Tim Peters6d6c1a32001-08-02 04:15:00 +00004309static PyObject *
4310wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4311{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004312 unaryfunc func = (unaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004313
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004314 if (!check_num_args(args, 0))
4315 return NULL;
4316 return (*func)(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004317}
4318
Tim Peters6d6c1a32001-08-02 04:15:00 +00004319static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00004320wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004321{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004322 ssizeargfunc func = (ssizeargfunc)wrapped;
4323 PyObject* o;
4324 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004325
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004326 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4327 return NULL;
4328 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4329 if (i == -1 && PyErr_Occurred())
4330 return NULL;
4331 return (*func)(self, i);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004332}
4333
Martin v. Löwis18e16552006-02-15 17:27:45 +00004334static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004335getindex(PyObject *self, PyObject *arg)
4336{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004337 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004338
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004339 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4340 if (i == -1 && PyErr_Occurred())
4341 return -1;
4342 if (i < 0) {
4343 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4344 if (sq && sq->sq_length) {
4345 Py_ssize_t n = (*sq->sq_length)(self);
4346 if (n < 0)
4347 return -1;
4348 i += n;
4349 }
4350 }
4351 return i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004352}
4353
4354static PyObject *
4355wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4356{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004357 ssizeargfunc func = (ssizeargfunc)wrapped;
4358 PyObject *arg;
4359 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004360
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004361 if (PyTuple_GET_SIZE(args) == 1) {
4362 arg = PyTuple_GET_ITEM(args, 0);
4363 i = getindex(self, arg);
4364 if (i == -1 && PyErr_Occurred())
4365 return NULL;
4366 return (*func)(self, i);
4367 }
4368 check_num_args(args, 1);
4369 assert(PyErr_Occurred());
4370 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004371}
4372
Tim Peters6d6c1a32001-08-02 04:15:00 +00004373static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004374wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004375{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004376 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
4377 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004378
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004379 if (!PyArg_ParseTuple(args, "nn", &i, &j))
4380 return NULL;
4381 return (*func)(self, i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004382}
4383
Tim Peters6d6c1a32001-08-02 04:15:00 +00004384static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004385wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004386{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004387 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4388 Py_ssize_t i;
4389 int res;
4390 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004391
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004392 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4393 return NULL;
4394 i = getindex(self, arg);
4395 if (i == -1 && PyErr_Occurred())
4396 return NULL;
4397 res = (*func)(self, i, value);
4398 if (res == -1 && PyErr_Occurred())
4399 return NULL;
4400 Py_INCREF(Py_None);
4401 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004402}
4403
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004404static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004405wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004406{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004407 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4408 Py_ssize_t i;
4409 int res;
4410 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004411
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004412 if (!check_num_args(args, 1))
4413 return NULL;
4414 arg = PyTuple_GET_ITEM(args, 0);
4415 i = getindex(self, arg);
4416 if (i == -1 && PyErr_Occurred())
4417 return NULL;
4418 res = (*func)(self, i, NULL);
4419 if (res == -1 && PyErr_Occurred())
4420 return NULL;
4421 Py_INCREF(Py_None);
4422 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004423}
4424
Tim Peters6d6c1a32001-08-02 04:15:00 +00004425static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004426wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004427{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004428 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4429 Py_ssize_t i, j;
4430 int res;
4431 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004432
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004433 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
4434 return NULL;
4435 res = (*func)(self, i, j, value);
4436 if (res == -1 && PyErr_Occurred())
4437 return NULL;
4438 Py_INCREF(Py_None);
4439 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004440}
4441
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004442static PyObject *
4443wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
4444{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004445 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4446 Py_ssize_t i, j;
4447 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004448
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004449 if (!PyArg_ParseTuple(args, "nn", &i, &j))
4450 return NULL;
4451 res = (*func)(self, i, j, NULL);
4452 if (res == -1 && PyErr_Occurred())
4453 return NULL;
4454 Py_INCREF(Py_None);
4455 return Py_None;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004456}
4457
Tim Peters6d6c1a32001-08-02 04:15:00 +00004458/* XXX objobjproc is a misnomer; should be objargpred */
4459static PyObject *
4460wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4461{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004462 objobjproc func = (objobjproc)wrapped;
4463 int res;
4464 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004465
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004466 if (!check_num_args(args, 1))
4467 return NULL;
4468 value = PyTuple_GET_ITEM(args, 0);
4469 res = (*func)(self, value);
4470 if (res == -1 && PyErr_Occurred())
4471 return NULL;
4472 else
4473 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004474}
4475
Tim Peters6d6c1a32001-08-02 04:15:00 +00004476static PyObject *
4477wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4478{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004479 objobjargproc func = (objobjargproc)wrapped;
4480 int res;
4481 PyObject *key, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004482
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004483 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4484 return NULL;
4485 res = (*func)(self, key, value);
4486 if (res == -1 && PyErr_Occurred())
4487 return NULL;
4488 Py_INCREF(Py_None);
4489 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004490}
4491
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004492static PyObject *
4493wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4494{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004495 objobjargproc func = (objobjargproc)wrapped;
4496 int res;
4497 PyObject *key;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004498
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004499 if (!check_num_args(args, 1))
4500 return NULL;
4501 key = PyTuple_GET_ITEM(args, 0);
4502 res = (*func)(self, key, NULL);
4503 if (res == -1 && PyErr_Occurred())
4504 return NULL;
4505 Py_INCREF(Py_None);
4506 return Py_None;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004507}
4508
Tim Peters6d6c1a32001-08-02 04:15:00 +00004509static PyObject *
4510wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
4511{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004512 cmpfunc func = (cmpfunc)wrapped;
4513 int res;
4514 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004515
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004516 if (!check_num_args(args, 1))
4517 return NULL;
4518 other = PyTuple_GET_ITEM(args, 0);
4519 if (Py_TYPE(other)->tp_compare != func &&
4520 !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
4521 PyErr_Format(
4522 PyExc_TypeError,
4523 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
4524 Py_TYPE(self)->tp_name,
4525 Py_TYPE(self)->tp_name,
4526 Py_TYPE(other)->tp_name);
4527 return NULL;
4528 }
4529 res = (*func)(self, other);
4530 if (PyErr_Occurred())
4531 return NULL;
4532 return PyInt_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004533}
4534
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004535/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004536 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004537static int
4538hackcheck(PyObject *self, setattrofunc func, char *what)
4539{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004540 PyTypeObject *type = Py_TYPE(self);
4541 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4542 type = type->tp_base;
4543 /* If type is NULL now, this is a really weird type.
4544 In the spirit of backwards compatibility (?), just shut up. */
4545 if (type && type->tp_setattro != func) {
4546 PyErr_Format(PyExc_TypeError,
4547 "can't apply this %s to %s object",
4548 what,
4549 type->tp_name);
4550 return 0;
4551 }
4552 return 1;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004553}
4554
Tim Peters6d6c1a32001-08-02 04:15:00 +00004555static PyObject *
4556wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4557{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004558 setattrofunc func = (setattrofunc)wrapped;
4559 int res;
4560 PyObject *name, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004561
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004562 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4563 return NULL;
4564 if (!hackcheck(self, func, "__setattr__"))
4565 return NULL;
4566 res = (*func)(self, name, value);
4567 if (res < 0)
4568 return NULL;
4569 Py_INCREF(Py_None);
4570 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004571}
4572
4573static PyObject *
4574wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4575{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004576 setattrofunc func = (setattrofunc)wrapped;
4577 int res;
4578 PyObject *name;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004579
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004580 if (!check_num_args(args, 1))
4581 return NULL;
4582 name = PyTuple_GET_ITEM(args, 0);
4583 if (!hackcheck(self, func, "__delattr__"))
4584 return NULL;
4585 res = (*func)(self, name, NULL);
4586 if (res < 0)
4587 return NULL;
4588 Py_INCREF(Py_None);
4589 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004590}
4591
Tim Peters6d6c1a32001-08-02 04:15:00 +00004592static PyObject *
4593wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4594{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004595 hashfunc func = (hashfunc)wrapped;
4596 long res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004597
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004598 if (!check_num_args(args, 0))
4599 return NULL;
4600 res = (*func)(self);
4601 if (res == -1 && PyErr_Occurred())
4602 return NULL;
4603 return PyInt_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004604}
4605
Tim Peters6d6c1a32001-08-02 04:15:00 +00004606static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004607wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004608{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004609 ternaryfunc func = (ternaryfunc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004610
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004611 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004612}
4613
Tim Peters6d6c1a32001-08-02 04:15:00 +00004614static PyObject *
4615wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4616{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004617 richcmpfunc func = (richcmpfunc)wrapped;
4618 PyObject *other;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004619
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004620 if (!check_num_args(args, 1))
4621 return NULL;
4622 other = PyTuple_GET_ITEM(args, 0);
4623 return (*func)(self, other, op);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004624}
4625
4626#undef RICHCMP_WRAPPER
4627#define RICHCMP_WRAPPER(NAME, OP) \
4628static PyObject * \
4629richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4630{ \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004631 return wrap_richcmpfunc(self, args, wrapped, OP); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004632}
4633
Jack Jansen8e938b42001-08-08 15:29:49 +00004634RICHCMP_WRAPPER(lt, Py_LT)
4635RICHCMP_WRAPPER(le, Py_LE)
4636RICHCMP_WRAPPER(eq, Py_EQ)
4637RICHCMP_WRAPPER(ne, Py_NE)
4638RICHCMP_WRAPPER(gt, Py_GT)
4639RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004640
Tim Peters6d6c1a32001-08-02 04:15:00 +00004641static PyObject *
4642wrap_next(PyObject *self, PyObject *args, void *wrapped)
4643{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004644 unaryfunc func = (unaryfunc)wrapped;
4645 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004646
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004647 if (!check_num_args(args, 0))
4648 return NULL;
4649 res = (*func)(self);
4650 if (res == NULL && !PyErr_Occurred())
4651 PyErr_SetNone(PyExc_StopIteration);
4652 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004653}
4654
Tim Peters6d6c1a32001-08-02 04:15:00 +00004655static PyObject *
4656wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4657{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004658 descrgetfunc func = (descrgetfunc)wrapped;
4659 PyObject *obj;
4660 PyObject *type = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004661
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004662 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4663 return NULL;
4664 if (obj == Py_None)
4665 obj = NULL;
4666 if (type == Py_None)
4667 type = NULL;
4668 if (type == NULL &&obj == NULL) {
4669 PyErr_SetString(PyExc_TypeError,
4670 "__get__(None, None) is invalid");
4671 return NULL;
4672 }
4673 return (*func)(self, obj, type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004674}
4675
Tim Peters6d6c1a32001-08-02 04:15:00 +00004676static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004677wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004678{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004679 descrsetfunc func = (descrsetfunc)wrapped;
4680 PyObject *obj, *value;
4681 int ret;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004682
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004683 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4684 return NULL;
4685 ret = (*func)(self, obj, value);
4686 if (ret < 0)
4687 return NULL;
4688 Py_INCREF(Py_None);
4689 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004690}
Guido van Rossum22b13872002-08-06 21:41:44 +00004691
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004692static PyObject *
4693wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4694{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004695 descrsetfunc func = (descrsetfunc)wrapped;
4696 PyObject *obj;
4697 int ret;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004698
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004699 if (!check_num_args(args, 1))
4700 return NULL;
4701 obj = PyTuple_GET_ITEM(args, 0);
4702 ret = (*func)(self, obj, NULL);
4703 if (ret < 0)
4704 return NULL;
4705 Py_INCREF(Py_None);
4706 return Py_None;
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004707}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004708
Tim Peters6d6c1a32001-08-02 04:15:00 +00004709static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004710wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004711{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004712 initproc func = (initproc)wrapped;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004713
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004714 if (func(self, args, kwds) < 0)
4715 return NULL;
4716 Py_INCREF(Py_None);
4717 return Py_None;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004718}
4719
Tim Peters6d6c1a32001-08-02 04:15:00 +00004720static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004721tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004722{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004723 PyTypeObject *type, *subtype, *staticbase;
4724 PyObject *arg0, *res;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004725
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004726 if (self == NULL || !PyType_Check(self))
4727 Py_FatalError("__new__() called with non-type 'self'");
4728 type = (PyTypeObject *)self;
4729 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4730 PyErr_Format(PyExc_TypeError,
4731 "%s.__new__(): not enough arguments",
4732 type->tp_name);
4733 return NULL;
4734 }
4735 arg0 = PyTuple_GET_ITEM(args, 0);
4736 if (!PyType_Check(arg0)) {
4737 PyErr_Format(PyExc_TypeError,
4738 "%s.__new__(X): X is not a type object (%s)",
4739 type->tp_name,
4740 Py_TYPE(arg0)->tp_name);
4741 return NULL;
4742 }
4743 subtype = (PyTypeObject *)arg0;
4744 if (!PyType_IsSubtype(subtype, type)) {
4745 PyErr_Format(PyExc_TypeError,
4746 "%s.__new__(%s): %s is not a subtype of %s",
4747 type->tp_name,
4748 subtype->tp_name,
4749 subtype->tp_name,
4750 type->tp_name);
4751 return NULL;
4752 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004753
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004754 /* Check that the use doesn't do something silly and unsafe like
4755 object.__new__(dict). To do this, we check that the
4756 most derived base that's not a heap type is this type. */
4757 staticbase = subtype;
4758 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4759 staticbase = staticbase->tp_base;
4760 /* If staticbase is NULL now, it is a really weird type.
4761 In the spirit of backwards compatibility (?), just shut up. */
4762 if (staticbase && staticbase->tp_new != type->tp_new) {
4763 PyErr_Format(PyExc_TypeError,
4764 "%s.__new__(%s) is not safe, use %s.__new__()",
4765 type->tp_name,
4766 subtype->tp_name,
4767 staticbase == NULL ? "?" : staticbase->tp_name);
4768 return NULL;
4769 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004770
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004771 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4772 if (args == NULL)
4773 return NULL;
4774 res = type->tp_new(subtype, args, kwds);
4775 Py_DECREF(args);
4776 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004777}
4778
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004779static struct PyMethodDef tp_new_methoddef[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004780 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4781 PyDoc_STR("T.__new__(S, ...) -> "
4782 "a new object with type S, a subtype of T")},
4783 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004784};
4785
4786static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004787add_tp_new_wrapper(PyTypeObject *type)
4788{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004789 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004790
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004791 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
4792 return 0;
4793 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4794 if (func == NULL)
4795 return -1;
4796 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
4797 Py_DECREF(func);
4798 return -1;
4799 }
4800 Py_DECREF(func);
4801 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004802}
4803
Guido van Rossumf040ede2001-08-07 16:40:56 +00004804/* Slot wrappers that call the corresponding __foo__ slot. See comments
4805 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004806
Guido van Rossumdc91b992001-08-08 22:26:22 +00004807#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004808static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004809FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004810{ \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004811 static PyObject *cache_str; \
4812 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004813}
4814
Guido van Rossumdc91b992001-08-08 22:26:22 +00004815#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004816static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004817FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004818{ \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004819 static PyObject *cache_str; \
4820 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004821}
4822
Guido van Rossumcd118802003-01-06 22:57:47 +00004823/* Boolean helper for SLOT1BINFULL().
4824 right.__class__ is a nontrivial subclass of left.__class__. */
4825static int
4826method_is_overloaded(PyObject *left, PyObject *right, char *name)
4827{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004828 PyObject *a, *b;
4829 int ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004830
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004831 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
4832 if (b == NULL) {
4833 PyErr_Clear();
4834 /* If right doesn't have it, it's not overloaded */
4835 return 0;
4836 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004837
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004838 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
4839 if (a == NULL) {
4840 PyErr_Clear();
4841 Py_DECREF(b);
4842 /* If right has it but left doesn't, it's overloaded */
4843 return 1;
4844 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004845
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004846 ok = PyObject_RichCompareBool(a, b, Py_NE);
4847 Py_DECREF(a);
4848 Py_DECREF(b);
4849 if (ok < 0) {
4850 PyErr_Clear();
4851 return 0;
4852 }
Guido van Rossumcd118802003-01-06 22:57:47 +00004853
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004854 return ok;
Guido van Rossumcd118802003-01-06 22:57:47 +00004855}
4856
Guido van Rossumdc91b992001-08-08 22:26:22 +00004857
4858#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004859static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004860FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004861{ \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004862 static PyObject *cache_str, *rcache_str; \
4863 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4864 Py_TYPE(other)->tp_as_number != NULL && \
4865 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4866 if (Py_TYPE(self)->tp_as_number != NULL && \
4867 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4868 PyObject *r; \
4869 if (do_other && \
4870 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4871 method_is_overloaded(self, other, ROPSTR)) { \
4872 r = call_maybe( \
4873 other, ROPSTR, &rcache_str, "(O)", self); \
4874 if (r != Py_NotImplemented) \
4875 return r; \
4876 Py_DECREF(r); \
4877 do_other = 0; \
4878 } \
4879 r = call_maybe( \
4880 self, OPSTR, &cache_str, "(O)", other); \
4881 if (r != Py_NotImplemented || \
4882 Py_TYPE(other) == Py_TYPE(self)) \
4883 return r; \
4884 Py_DECREF(r); \
4885 } \
4886 if (do_other) { \
4887 return call_maybe( \
4888 other, ROPSTR, &rcache_str, "(O)", self); \
4889 } \
4890 Py_INCREF(Py_NotImplemented); \
4891 return Py_NotImplemented; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004892}
4893
4894#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004895 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
Guido van Rossumdc91b992001-08-08 22:26:22 +00004896
4897#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4898static PyObject * \
4899FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4900{ \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004901 static PyObject *cache_str; \
4902 return call_method(self, OPSTR, &cache_str, \
4903 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004904}
4905
Martin v. Löwis18e16552006-02-15 17:27:45 +00004906static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004907slot_sq_length(PyObject *self)
4908{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004909 static PyObject *len_str;
4910 PyObject *res = call_method(self, "__len__", &len_str, "()");
4911 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004912
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004913 if (res == NULL)
4914 return -1;
4915 len = PyInt_AsSsize_t(res);
4916 Py_DECREF(res);
4917 if (len < 0) {
4918 if (!PyErr_Occurred())
4919 PyErr_SetString(PyExc_ValueError,
4920 "__len__() should return >= 0");
4921 return -1;
4922 }
4923 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004924}
4925
Guido van Rossumf4593e02001-10-03 12:09:30 +00004926/* Super-optimized version of slot_sq_item.
4927 Other slots could do the same... */
4928static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004929slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004930{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004931 static PyObject *getitem_str;
4932 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4933 descrgetfunc f;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004934
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004935 if (getitem_str == NULL) {
4936 getitem_str = PyString_InternFromString("__getitem__");
4937 if (getitem_str == NULL)
4938 return NULL;
4939 }
4940 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
4941 if (func != NULL) {
4942 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
4943 Py_INCREF(func);
4944 else {
4945 func = f(func, self, (PyObject *)(Py_TYPE(self)));
4946 if (func == NULL) {
4947 return NULL;
4948 }
4949 }
4950 ival = PyInt_FromSsize_t(i);
4951 if (ival != NULL) {
4952 args = PyTuple_New(1);
4953 if (args != NULL) {
4954 PyTuple_SET_ITEM(args, 0, ival);
4955 retval = PyObject_Call(func, args, NULL);
4956 Py_XDECREF(args);
4957 Py_XDECREF(func);
4958 return retval;
4959 }
4960 }
4961 }
4962 else {
4963 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4964 }
4965 Py_XDECREF(args);
4966 Py_XDECREF(ival);
4967 Py_XDECREF(func);
4968 return NULL;
Guido van Rossumf4593e02001-10-03 12:09:30 +00004969}
4970
Benjamin Peterson712ee922008-08-24 18:10:20 +00004971static PyObject*
4972slot_sq_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j)
4973{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004974 static PyObject *getslice_str;
4975
4976 if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
4977 "use __getitem__", 1) < 0)
4978 return NULL;
4979 return call_method(self, "__getslice__", &getslice_str,
4980 "nn", i, j);
Benjamin Peterson712ee922008-08-24 18:10:20 +00004981}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004982
4983static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004984slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004985{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004986 PyObject *res;
4987 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004988
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004989 if (value == NULL)
4990 res = call_method(self, "__delitem__", &delitem_str,
4991 "(n)", index);
4992 else
4993 res = call_method(self, "__setitem__", &setitem_str,
4994 "(nO)", index, value);
4995 if (res == NULL)
4996 return -1;
4997 Py_DECREF(res);
4998 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004999}
5000
5001static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005002slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005003{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005004 PyObject *res;
5005 static PyObject *delslice_str, *setslice_str;
5006
5007 if (value == NULL) {
5008 if (PyErr_WarnPy3k("in 3.x, __delslice__ has been removed; "
5009 "use __delitem__", 1) < 0)
5010 return -1;
5011 res = call_method(self, "__delslice__", &delslice_str,
5012 "(nn)", i, j);
5013 }
5014 else {
5015 if (PyErr_WarnPy3k("in 3.x, __setslice__ has been removed; "
5016 "use __setitem__", 1) < 0)
5017 return -1;
5018 res = call_method(self, "__setslice__", &setslice_str,
5019 "(nnO)", i, j, value);
5020 }
5021 if (res == NULL)
5022 return -1;
5023 Py_DECREF(res);
5024 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005025}
5026
5027static int
5028slot_sq_contains(PyObject *self, PyObject *value)
5029{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005030 PyObject *func, *res, *args;
5031 int result = -1;
Tim Petersbf9b2442003-03-23 05:35:36 +00005032
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005033 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005034
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005035 func = lookup_maybe(self, "__contains__", &contains_str);
5036 if (func != NULL) {
5037 args = PyTuple_Pack(1, value);
5038 if (args == NULL)
5039 res = NULL;
5040 else {
5041 res = PyObject_Call(func, args, NULL);
5042 Py_DECREF(args);
5043 }
5044 Py_DECREF(func);
5045 if (res != NULL) {
5046 result = PyObject_IsTrue(res);
5047 Py_DECREF(res);
5048 }
5049 }
5050 else if (! PyErr_Occurred()) {
5051 /* Possible results: -1 and 1 */
5052 result = (int)_PySequence_IterSearch(self, value,
5053 PY_ITERSEARCH_CONTAINS);
5054 }
5055 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005056}
5057
Tim Peters6d6c1a32001-08-02 04:15:00 +00005058#define slot_mp_length slot_sq_length
5059
Guido van Rossumdc91b992001-08-08 22:26:22 +00005060SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005061
5062static int
5063slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5064{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005065 PyObject *res;
5066 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005067
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005068 if (value == NULL)
5069 res = call_method(self, "__delitem__", &delitem_str,
5070 "(O)", key);
5071 else
5072 res = call_method(self, "__setitem__", &setitem_str,
5073 "(OO)", key, value);
5074 if (res == NULL)
5075 return -1;
5076 Py_DECREF(res);
5077 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005078}
5079
Guido van Rossumdc91b992001-08-08 22:26:22 +00005080SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5081SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5082SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
5083SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
5084SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5085SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5086
Jeremy Hylton938ace62002-07-17 16:30:39 +00005087static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005088
5089SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005090 nb_power, "__pow__", "__rpow__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005091
5092static PyObject *
5093slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5094{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005095 static PyObject *pow_str;
Guido van Rossum2730b132001-08-28 18:22:14 +00005096
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005097 if (modulus == Py_None)
5098 return slot_nb_power_binary(self, other);
5099 /* Three-arg power doesn't use __rpow__. But ternary_op
5100 can call this when the second argument's type uses
5101 slot_nb_power, so check before calling self.__pow__. */
5102 if (Py_TYPE(self)->tp_as_number != NULL &&
5103 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
5104 return call_method(self, "__pow__", &pow_str,
5105 "(OO)", other, modulus);
5106 }
5107 Py_INCREF(Py_NotImplemented);
5108 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005109}
5110
5111SLOT0(slot_nb_negative, "__neg__")
5112SLOT0(slot_nb_positive, "__pos__")
5113SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005114
5115static int
5116slot_nb_nonzero(PyObject *self)
5117{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005118 PyObject *func, *args;
5119 static PyObject *nonzero_str, *len_str;
5120 int result = -1;
5121 int using_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005122
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005123 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
5124 if (func == NULL) {
5125 if (PyErr_Occurred())
5126 return -1;
5127 func = lookup_maybe(self, "__len__", &len_str);
5128 if (func == NULL)
5129 return PyErr_Occurred() ? -1 : 1;
5130 using_len = 1;
5131 }
5132 args = PyTuple_New(0);
5133 if (args != NULL) {
5134 PyObject *temp = PyObject_Call(func, args, NULL);
5135 Py_DECREF(args);
5136 if (temp != NULL) {
5137 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
5138 result = PyObject_IsTrue(temp);
5139 else {
5140 PyErr_Format(PyExc_TypeError,
5141 "%s should return "
5142 "bool or int, returned %s",
5143 (using_len ? "__len__"
5144 : "__nonzero__"),
5145 temp->ob_type->tp_name);
5146 result = -1;
5147 }
5148 Py_DECREF(temp);
5149 }
5150 }
5151 Py_DECREF(func);
5152 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005153}
5154
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005155
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005156static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005157slot_nb_index(PyObject *self)
5158{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005159 static PyObject *index_str;
5160 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005161}
5162
5163
Guido van Rossumdc91b992001-08-08 22:26:22 +00005164SLOT0(slot_nb_invert, "__invert__")
5165SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5166SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5167SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5168SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5169SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005170
5171static int
5172slot_nb_coerce(PyObject **a, PyObject **b)
5173{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005174 static PyObject *coerce_str;
5175 PyObject *self = *a, *other = *b;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005176
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005177 if (self->ob_type->tp_as_number != NULL &&
5178 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5179 PyObject *r;
5180 r = call_maybe(
5181 self, "__coerce__", &coerce_str, "(O)", other);
5182 if (r == NULL)
5183 return -1;
5184 if (r == Py_NotImplemented) {
5185 Py_DECREF(r);
5186 }
5187 else {
5188 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5189 PyErr_SetString(PyExc_TypeError,
5190 "__coerce__ didn't return a 2-tuple");
5191 Py_DECREF(r);
5192 return -1;
5193 }
5194 *a = PyTuple_GET_ITEM(r, 0);
5195 Py_INCREF(*a);
5196 *b = PyTuple_GET_ITEM(r, 1);
5197 Py_INCREF(*b);
5198 Py_DECREF(r);
5199 return 0;
5200 }
5201 }
5202 if (other->ob_type->tp_as_number != NULL &&
5203 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5204 PyObject *r;
5205 r = call_maybe(
5206 other, "__coerce__", &coerce_str, "(O)", self);
5207 if (r == NULL)
5208 return -1;
5209 if (r == Py_NotImplemented) {
5210 Py_DECREF(r);
5211 return 1;
5212 }
5213 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5214 PyErr_SetString(PyExc_TypeError,
5215 "__coerce__ didn't return a 2-tuple");
5216 Py_DECREF(r);
5217 return -1;
5218 }
5219 *a = PyTuple_GET_ITEM(r, 1);
5220 Py_INCREF(*a);
5221 *b = PyTuple_GET_ITEM(r, 0);
5222 Py_INCREF(*b);
5223 Py_DECREF(r);
5224 return 0;
5225 }
5226 return 1;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005227}
5228
Guido van Rossumdc91b992001-08-08 22:26:22 +00005229SLOT0(slot_nb_int, "__int__")
5230SLOT0(slot_nb_long, "__long__")
5231SLOT0(slot_nb_float, "__float__")
5232SLOT0(slot_nb_oct, "__oct__")
5233SLOT0(slot_nb_hex, "__hex__")
5234SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5235SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5236SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
5237SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
5238SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Martin v. Löwisfd963262007-02-09 12:19:32 +00005239/* Can't use SLOT1 here, because nb_inplace_power is ternary */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005240static PyObject *
5241slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5242{
5243 static PyObject *cache_str;
5244 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
Martin v. Löwisfd963262007-02-09 12:19:32 +00005245}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005246SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5247SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5248SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5249SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5250SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5251SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005252 "__floordiv__", "__rfloordiv__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00005253SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5254SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5255SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005256
5257static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00005258half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005259{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005260 PyObject *func, *args, *res;
5261 static PyObject *cmp_str;
5262 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005263
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005264 func = lookup_method(self, "__cmp__", &cmp_str);
5265 if (func == NULL) {
5266 PyErr_Clear();
5267 }
5268 else {
5269 args = PyTuple_Pack(1, other);
5270 if (args == NULL)
5271 res = NULL;
5272 else {
5273 res = PyObject_Call(func, args, NULL);
5274 Py_DECREF(args);
5275 }
5276 Py_DECREF(func);
5277 if (res != Py_NotImplemented) {
5278 if (res == NULL)
5279 return -2;
5280 c = PyInt_AsLong(res);
5281 Py_DECREF(res);
5282 if (c == -1 && PyErr_Occurred())
5283 return -2;
5284 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
5285 }
5286 Py_DECREF(res);
5287 }
5288 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005289}
5290
Guido van Rossumab3b0342001-09-18 20:38:53 +00005291/* This slot is published for the benefit of try_3way_compare in object.c */
5292int
5293_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00005294{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005295 int c;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005296
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005297 if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
5298 c = half_compare(self, other);
5299 if (c <= 1)
5300 return c;
5301 }
5302 if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
5303 c = half_compare(other, self);
5304 if (c < -1)
5305 return -2;
5306 if (c <= 1)
5307 return -c;
5308 }
5309 return (void *)self < (void *)other ? -1 :
5310 (void *)self > (void *)other ? 1 : 0;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005311}
5312
5313static PyObject *
5314slot_tp_repr(PyObject *self)
5315{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005316 PyObject *func, *res;
5317 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005318
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005319 func = lookup_method(self, "__repr__", &repr_str);
5320 if (func != NULL) {
5321 res = PyEval_CallObject(func, NULL);
5322 Py_DECREF(func);
5323 return res;
5324 }
5325 PyErr_Clear();
5326 return PyString_FromFormat("<%s object at %p>",
5327 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005328}
5329
5330static PyObject *
5331slot_tp_str(PyObject *self)
5332{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005333 PyObject *func, *res;
5334 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005335
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005336 func = lookup_method(self, "__str__", &str_str);
5337 if (func != NULL) {
5338 res = PyEval_CallObject(func, NULL);
5339 Py_DECREF(func);
5340 return res;
5341 }
5342 else {
5343 PyErr_Clear();
5344 return slot_tp_repr(self);
5345 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005346}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005347
5348static long
5349slot_tp_hash(PyObject *self)
5350{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005351 PyObject *func;
5352 static PyObject *hash_str, *eq_str, *cmp_str;
5353 long h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005354
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005355 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005356
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005357 if (func != NULL && func != Py_None) {
5358 PyObject *res = PyEval_CallObject(func, NULL);
5359 Py_DECREF(func);
5360 if (res == NULL)
5361 return -1;
5362 if (PyLong_Check(res))
5363 h = PyLong_Type.tp_hash(res);
5364 else
5365 h = PyInt_AsLong(res);
5366 Py_DECREF(res);
5367 }
5368 else {
5369 Py_XDECREF(func); /* may be None */
5370 PyErr_Clear();
5371 func = lookup_method(self, "__eq__", &eq_str);
5372 if (func == NULL) {
5373 PyErr_Clear();
5374 func = lookup_method(self, "__cmp__", &cmp_str);
5375 }
5376 if (func != NULL) {
5377 Py_DECREF(func);
5378 return PyObject_HashNotImplemented(self);
5379 }
5380 PyErr_Clear();
5381 h = _Py_HashPointer((void *)self);
5382 }
5383 if (h == -1 && !PyErr_Occurred())
5384 h = -2;
5385 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005386}
5387
5388static PyObject *
5389slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5390{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005391 static PyObject *call_str;
5392 PyObject *meth = lookup_method(self, "__call__", &call_str);
5393 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005394
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005395 if (meth == NULL)
5396 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00005397
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005398 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00005399
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005400 Py_DECREF(meth);
5401 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005402}
5403
Guido van Rossum14a6f832001-10-17 13:59:09 +00005404/* There are two slot dispatch functions for tp_getattro.
5405
5406 - slot_tp_getattro() is used when __getattribute__ is overridden
5407 but no __getattr__ hook is present;
5408
5409 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5410
Guido van Rossumc334df52002-04-04 23:44:47 +00005411 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5412 detects the absence of __getattr__ and then installs the simpler slot if
5413 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005414
Tim Peters6d6c1a32001-08-02 04:15:00 +00005415static PyObject *
5416slot_tp_getattro(PyObject *self, PyObject *name)
5417{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005418 static PyObject *getattribute_str = NULL;
5419 return call_method(self, "__getattribute__", &getattribute_str,
5420 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005421}
5422
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005423static PyObject *
Benjamin Peterson273c2332008-11-17 22:39:09 +00005424call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5425{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005426 PyObject *res, *descr = NULL;
5427 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
Benjamin Peterson273c2332008-11-17 22:39:09 +00005428
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005429 if (f != NULL) {
5430 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5431 if (descr == NULL)
5432 return NULL;
5433 else
5434 attr = descr;
5435 }
5436 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5437 Py_XDECREF(descr);
5438 return res;
Benjamin Peterson273c2332008-11-17 22:39:09 +00005439}
5440
5441static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005442slot_tp_getattr_hook(PyObject *self, PyObject *name)
5443{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005444 PyTypeObject *tp = Py_TYPE(self);
5445 PyObject *getattr, *getattribute, *res;
5446 static PyObject *getattribute_str = NULL;
5447 static PyObject *getattr_str = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005448
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005449 if (getattr_str == NULL) {
5450 getattr_str = PyString_InternFromString("__getattr__");
5451 if (getattr_str == NULL)
5452 return NULL;
5453 }
5454 if (getattribute_str == NULL) {
5455 getattribute_str =
5456 PyString_InternFromString("__getattribute__");
5457 if (getattribute_str == NULL)
5458 return NULL;
5459 }
5460 /* speed hack: we could use lookup_maybe, but that would resolve the
5461 method fully for each attribute lookup for classes with
5462 __getattr__, even when the attribute is present. So we use
5463 _PyType_Lookup and create the method only when needed, with
5464 call_attribute. */
5465 getattr = _PyType_Lookup(tp, getattr_str);
5466 if (getattr == NULL) {
5467 /* No __getattr__ hook: use a simpler dispatcher */
5468 tp->tp_getattro = slot_tp_getattro;
5469 return slot_tp_getattro(self, name);
5470 }
5471 Py_INCREF(getattr);
5472 /* speed hack: we could use lookup_maybe, but that would resolve the
5473 method fully for each attribute lookup for classes with
5474 __getattr__, even when self has the default __getattribute__
5475 method. So we use _PyType_Lookup and create the method only when
5476 needed, with call_attribute. */
5477 getattribute = _PyType_Lookup(tp, getattribute_str);
5478 if (getattribute == NULL ||
5479 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5480 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5481 (void *)PyObject_GenericGetAttr))
5482 res = PyObject_GenericGetAttr(self, name);
5483 else {
5484 Py_INCREF(getattribute);
5485 res = call_attribute(self, getattribute, name);
5486 Py_DECREF(getattribute);
5487 }
5488 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5489 PyErr_Clear();
5490 res = call_attribute(self, getattr, name);
5491 }
5492 Py_DECREF(getattr);
5493 return res;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005494}
5495
Tim Peters6d6c1a32001-08-02 04:15:00 +00005496static int
5497slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5498{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005499 PyObject *res;
5500 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005501
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005502 if (value == NULL)
5503 res = call_method(self, "__delattr__", &delattr_str,
5504 "(O)", name);
5505 else
5506 res = call_method(self, "__setattr__", &setattr_str,
5507 "(OO)", name, value);
5508 if (res == NULL)
5509 return -1;
5510 Py_DECREF(res);
5511 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005512}
5513
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005514static char *name_op[] = {
5515 "__lt__",
5516 "__le__",
5517 "__eq__",
5518 "__ne__",
5519 "__gt__",
5520 "__ge__",
5521};
5522
Tim Peters6d6c1a32001-08-02 04:15:00 +00005523static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005524half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005525{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005526 PyObject *func, *args, *res;
5527 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005528
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005529 func = lookup_method(self, name_op[op], &op_str[op]);
5530 if (func == NULL) {
5531 PyErr_Clear();
5532 Py_INCREF(Py_NotImplemented);
5533 return Py_NotImplemented;
5534 }
5535 args = PyTuple_Pack(1, other);
5536 if (args == NULL)
5537 res = NULL;
5538 else {
5539 res = PyObject_Call(func, args, NULL);
5540 Py_DECREF(args);
5541 }
5542 Py_DECREF(func);
5543 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005544}
5545
Guido van Rossumb8f63662001-08-15 23:57:02 +00005546static PyObject *
5547slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5548{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005549 PyObject *res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005550
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005551 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
5552 res = half_richcompare(self, other, op);
5553 if (res != Py_NotImplemented)
5554 return res;
5555 Py_DECREF(res);
5556 }
5557 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
5558 res = half_richcompare(other, self, _Py_SwappedOp[op]);
5559 if (res != Py_NotImplemented) {
5560 return res;
5561 }
5562 Py_DECREF(res);
5563 }
5564 Py_INCREF(Py_NotImplemented);
5565 return Py_NotImplemented;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005566}
5567
5568static PyObject *
5569slot_tp_iter(PyObject *self)
5570{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005571 PyObject *func, *res;
5572 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005573
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005574 func = lookup_method(self, "__iter__", &iter_str);
5575 if (func != NULL) {
5576 PyObject *args;
5577 args = res = PyTuple_New(0);
5578 if (args != NULL) {
5579 res = PyObject_Call(func, args, NULL);
5580 Py_DECREF(args);
5581 }
5582 Py_DECREF(func);
5583 return res;
5584 }
5585 PyErr_Clear();
5586 func = lookup_method(self, "__getitem__", &getitem_str);
5587 if (func == NULL) {
5588 PyErr_Format(PyExc_TypeError,
5589 "'%.200s' object is not iterable",
5590 Py_TYPE(self)->tp_name);
5591 return NULL;
5592 }
5593 Py_DECREF(func);
5594 return PySeqIter_New(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005595}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005596
5597static PyObject *
5598slot_tp_iternext(PyObject *self)
5599{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005600 static PyObject *next_str;
5601 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005602}
5603
Guido van Rossum1a493502001-08-17 16:47:50 +00005604static PyObject *
5605slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5606{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005607 PyTypeObject *tp = Py_TYPE(self);
5608 PyObject *get;
5609 static PyObject *get_str = NULL;
Guido van Rossum1a493502001-08-17 16:47:50 +00005610
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005611 if (get_str == NULL) {
5612 get_str = PyString_InternFromString("__get__");
5613 if (get_str == NULL)
5614 return NULL;
5615 }
5616 get = _PyType_Lookup(tp, get_str);
5617 if (get == NULL) {
5618 /* Avoid further slowdowns */
5619 if (tp->tp_descr_get == slot_tp_descr_get)
5620 tp->tp_descr_get = NULL;
5621 Py_INCREF(self);
5622 return self;
5623 }
5624 if (obj == NULL)
5625 obj = Py_None;
5626 if (type == NULL)
5627 type = Py_None;
5628 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005629}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005630
5631static int
5632slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5633{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005634 PyObject *res;
5635 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005636
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005637 if (value == NULL)
5638 res = call_method(self, "__delete__", &del_str,
5639 "(O)", target);
5640 else
5641 res = call_method(self, "__set__", &set_str,
5642 "(OO)", target, value);
5643 if (res == NULL)
5644 return -1;
5645 Py_DECREF(res);
5646 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005647}
5648
5649static int
5650slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5651{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005652 static PyObject *init_str;
5653 PyObject *meth = lookup_method(self, "__init__", &init_str);
5654 PyObject *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005655
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005656 if (meth == NULL)
5657 return -1;
5658 res = PyObject_Call(meth, args, kwds);
5659 Py_DECREF(meth);
5660 if (res == NULL)
5661 return -1;
5662 if (res != Py_None) {
5663 PyErr_Format(PyExc_TypeError,
5664 "__init__() should return None, not '%.200s'",
5665 Py_TYPE(res)->tp_name);
5666 Py_DECREF(res);
5667 return -1;
5668 }
5669 Py_DECREF(res);
5670 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005671}
5672
5673static PyObject *
5674slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5675{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005676 static PyObject *new_str;
5677 PyObject *func;
5678 PyObject *newargs, *x;
5679 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005680
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005681 if (new_str == NULL) {
5682 new_str = PyString_InternFromString("__new__");
5683 if (new_str == NULL)
5684 return NULL;
5685 }
5686 func = PyObject_GetAttr((PyObject *)type, new_str);
5687 if (func == NULL)
5688 return NULL;
5689 assert(PyTuple_Check(args));
5690 n = PyTuple_GET_SIZE(args);
5691 newargs = PyTuple_New(n+1);
5692 if (newargs == NULL)
5693 return NULL;
5694 Py_INCREF(type);
5695 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5696 for (i = 0; i < n; i++) {
5697 x = PyTuple_GET_ITEM(args, i);
5698 Py_INCREF(x);
5699 PyTuple_SET_ITEM(newargs, i+1, x);
5700 }
5701 x = PyObject_Call(func, newargs, kwds);
5702 Py_DECREF(newargs);
5703 Py_DECREF(func);
5704 return x;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005705}
5706
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005707static void
5708slot_tp_del(PyObject *self)
5709{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005710 static PyObject *del_str = NULL;
5711 PyObject *del, *res;
5712 PyObject *error_type, *error_value, *error_traceback;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005713
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005714 /* Temporarily resurrect the object. */
5715 assert(self->ob_refcnt == 0);
5716 self->ob_refcnt = 1;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005717
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005718 /* Save the current exception, if any. */
5719 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005720
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005721 /* Execute __del__ method, if any. */
5722 del = lookup_maybe(self, "__del__", &del_str);
5723 if (del != NULL) {
5724 res = PyEval_CallObject(del, NULL);
5725 if (res == NULL)
5726 PyErr_WriteUnraisable(del);
5727 else
5728 Py_DECREF(res);
5729 Py_DECREF(del);
5730 }
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005731
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005732 /* Restore the saved exception. */
5733 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005734
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005735 /* Undo the temporary resurrection; can't use DECREF here, it would
5736 * cause a recursive call.
5737 */
5738 assert(self->ob_refcnt > 0);
5739 if (--self->ob_refcnt == 0)
5740 return; /* this is the normal path out */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005741
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005742 /* __del__ resurrected it! Make it look like the original Py_DECREF
5743 * never happened.
5744 */
5745 {
5746 Py_ssize_t refcnt = self->ob_refcnt;
5747 _Py_NewReference(self);
5748 self->ob_refcnt = refcnt;
5749 }
5750 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5751 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5752 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5753 * we need to undo that. */
5754 _Py_DEC_REFTOTAL;
5755 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5756 * chain, so no more to do there.
5757 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5758 * _Py_NewReference bumped tp_allocs: both of those need to be
5759 * undone.
5760 */
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005761#ifdef COUNT_ALLOCS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005762 --Py_TYPE(self)->tp_frees;
5763 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005764#endif
5765}
5766
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005767
5768/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005769 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005770 structure, which incorporates the additional structures used for numbers,
5771 sequences and mappings.
5772 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005773 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005774 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5775 terminated with an all-zero entry. (This table is further initialized and
5776 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005777
Guido van Rossum6d204072001-10-21 00:44:31 +00005778typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005779
5780#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005781#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005782#undef ETSLOT
5783#undef SQSLOT
5784#undef MPSLOT
5785#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005786#undef UNSLOT
5787#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005788#undef BINSLOT
5789#undef RBINSLOT
5790
Guido van Rossum6d204072001-10-21 00:44:31 +00005791#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005792 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5793 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005794#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005795 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5796 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005797#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005798 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5799 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005800#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005801 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005802#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005803 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005804#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005805 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005806#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005807 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5808 "x." NAME "() <==> " DOC)
Guido van Rossum6d204072001-10-21 00:44:31 +00005809#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005810 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5811 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005812#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005813 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5814 "x." NAME "(y) <==> x" DOC "y")
Guido van Rossum6d204072001-10-21 00:44:31 +00005815#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005816 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5817 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005818#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005819 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5820 "x." NAME "(y) <==> " DOC)
Anthony Baxter56616992005-06-03 14:12:21 +00005821#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005822 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5823 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005824
5825static slotdef slotdefs[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005826 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5827 "x.__len__() <==> len(x)"),
5828 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5829 The logic in abstract.c always falls back to nb_add/nb_multiply in
5830 this case. Defining both the nb_* and the sq_* slots to call the
5831 user-defined methods has unexpected side-effects, as shown by
5832 test_descr.notimplemented() */
5833 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5834 "x.__add__(y) <==> x+y"),
5835 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5836 "x.__mul__(n) <==> x*n"),
5837 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5838 "x.__rmul__(n) <==> n*x"),
5839 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5840 "x.__getitem__(y) <==> x[y]"),
5841 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
5842 "x.__getslice__(i, j) <==> x[i:j]\n\
5843 \n\
5844 Use of negative indices is not supported."),
5845 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5846 "x.__setitem__(i, y) <==> x[i]=y"),
5847 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5848 "x.__delitem__(y) <==> del x[y]"),
5849 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
5850 wrap_ssizessizeobjargproc,
5851 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
5852 \n\
5853 Use of negative indices is not supported."),
5854 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
5855 "x.__delslice__(i, j) <==> del x[i:j]\n\
5856 \n\
5857 Use of negative indices is not supported."),
5858 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5859 "x.__contains__(y) <==> y in x"),
5860 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5861 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5862 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5863 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005864
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005865 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5866 "x.__len__() <==> len(x)"),
5867 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5868 wrap_binaryfunc,
5869 "x.__getitem__(y) <==> x[y]"),
5870 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5871 wrap_objobjargproc,
5872 "x.__setitem__(i, y) <==> x[i]=y"),
5873 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5874 wrap_delitem,
5875 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005876
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005877 BINSLOT("__add__", nb_add, slot_nb_add,
5878 "+"),
5879 RBINSLOT("__radd__", nb_add, slot_nb_add,
5880 "+"),
5881 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5882 "-"),
5883 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5884 "-"),
5885 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5886 "*"),
5887 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5888 "*"),
5889 BINSLOT("__div__", nb_divide, slot_nb_divide,
5890 "/"),
5891 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5892 "/"),
5893 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5894 "%"),
5895 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5896 "%"),
5897 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5898 "divmod(x, y)"),
5899 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5900 "divmod(y, x)"),
5901 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5902 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5903 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5904 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5905 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5906 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5907 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5908 "abs(x)"),
5909 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
5910 "x != 0"),
5911 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5912 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5913 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5914 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5915 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5916 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5917 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5918 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5919 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5920 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5921 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5922 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5923 "x.__coerce__(y) <==> coerce(x, y)"),
5924 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5925 "int(x)"),
5926 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5927 "long(x)"),
5928 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5929 "float(x)"),
5930 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5931 "oct(x)"),
5932 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5933 "hex(x)"),
5934 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5935 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5936 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5937 wrap_binaryfunc, "+"),
5938 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5939 wrap_binaryfunc, "-"),
5940 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5941 wrap_binaryfunc, "*"),
5942 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5943 wrap_binaryfunc, "/"),
5944 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5945 wrap_binaryfunc, "%"),
5946 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
5947 wrap_binaryfunc, "**"),
5948 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5949 wrap_binaryfunc, "<<"),
5950 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5951 wrap_binaryfunc, ">>"),
5952 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5953 wrap_binaryfunc, "&"),
5954 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5955 wrap_binaryfunc, "^"),
5956 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5957 wrap_binaryfunc, "|"),
5958 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5959 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5960 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5961 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5962 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5963 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5964 IBSLOT("__itruediv__", nb_inplace_true_divide,
5965 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005966
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005967 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5968 "x.__str__() <==> str(x)"),
5969 TPSLOT("__str__", tp_print, NULL, NULL, ""),
5970 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5971 "x.__repr__() <==> repr(x)"),
5972 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
5973 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5974 "x.__cmp__(y) <==> cmp(x,y)"),
5975 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5976 "x.__hash__() <==> hash(x)"),
5977 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5978 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5979 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5980 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5981 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5982 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5983 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5984 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5985 "x.__setattr__('name', value) <==> x.name = value"),
5986 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5987 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5988 "x.__delattr__('name') <==> del x.name"),
5989 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5990 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5991 "x.__lt__(y) <==> x<y"),
5992 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5993 "x.__le__(y) <==> x<=y"),
5994 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5995 "x.__eq__(y) <==> x==y"),
5996 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5997 "x.__ne__(y) <==> x!=y"),
5998 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5999 "x.__gt__(y) <==> x>y"),
6000 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
6001 "x.__ge__(y) <==> x>=y"),
6002 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
6003 "x.__iter__() <==> iter(x)"),
6004 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
6005 "x.next() -> the next value, or raise StopIteration"),
6006 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
6007 "descr.__get__(obj[, type]) -> value"),
6008 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
6009 "descr.__set__(obj, value)"),
6010 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
6011 wrap_descr_delete, "descr.__delete__(obj)"),
6012 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
6013 "x.__init__(...) initializes x; "
Alexander Belopolskyb8de9fa2010-08-16 20:30:26 +00006014 "see help(type(x)) for signature",
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006015 PyWrapperFlag_KEYWORDS),
6016 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
6017 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
6018 {NULL}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006019};
6020
Guido van Rossumc334df52002-04-04 23:44:47 +00006021/* Given a type pointer and an offset gotten from a slotdef entry, return a
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006022 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00006023 the offset to the type pointer, since it takes care to indirect through the
6024 proper indirection pointer (as_buffer, etc.); it returns NULL if the
6025 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006026static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00006027slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006028{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006029 char *ptr;
6030 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006031
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006032 /* Note: this depends on the order of the members of PyHeapTypeObject! */
6033 assert(offset >= 0);
6034 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
6035 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
6036 ptr = (char *)type->tp_as_sequence;
6037 offset -= offsetof(PyHeapTypeObject, as_sequence);
6038 }
6039 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
6040 ptr = (char *)type->tp_as_mapping;
6041 offset -= offsetof(PyHeapTypeObject, as_mapping);
6042 }
6043 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
6044 ptr = (char *)type->tp_as_number;
6045 offset -= offsetof(PyHeapTypeObject, as_number);
6046 }
6047 else {
6048 ptr = (char *)type;
6049 }
6050 if (ptr != NULL)
6051 ptr += offset;
6052 return (void **)ptr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006053}
Guido van Rossumf040ede2001-08-07 16:40:56 +00006054
Guido van Rossumc334df52002-04-04 23:44:47 +00006055/* Length of array of slotdef pointers used to store slots with the
6056 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
6057 the same __name__, for any __name__. Since that's a static property, it is
6058 appropriate to declare fixed-size arrays for this. */
6059#define MAX_EQUIV 10
6060
6061/* Return a slot pointer for a given name, but ONLY if the attribute has
6062 exactly one slot function. The name must be an interned string. */
6063static void **
6064resolve_slotdups(PyTypeObject *type, PyObject *name)
6065{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006066 /* XXX Maybe this could be optimized more -- but is it worth it? */
Guido van Rossumc334df52002-04-04 23:44:47 +00006067
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006068 /* pname and ptrs act as a little cache */
6069 static PyObject *pname;
6070 static slotdef *ptrs[MAX_EQUIV];
6071 slotdef *p, **pp;
6072 void **res, **ptr;
Guido van Rossumc334df52002-04-04 23:44:47 +00006073
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006074 if (pname != name) {
6075 /* Collect all slotdefs that match name into ptrs. */
6076 pname = name;
6077 pp = ptrs;
6078 for (p = slotdefs; p->name_strobj; p++) {
6079 if (p->name_strobj == name)
6080 *pp++ = p;
6081 }
6082 *pp = NULL;
6083 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006084
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006085 /* Look in all matching slots of the type; if exactly one of these has
6086 a filled-in slot, return its value. Otherwise return NULL. */
6087 res = NULL;
6088 for (pp = ptrs; *pp; pp++) {
6089 ptr = slotptr(type, (*pp)->offset);
6090 if (ptr == NULL || *ptr == NULL)
6091 continue;
6092 if (res != NULL)
6093 return NULL;
6094 res = ptr;
6095 }
6096 return res;
Guido van Rossumc334df52002-04-04 23:44:47 +00006097}
6098
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006099/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00006100 does some incredibly complex thinking and then sticks something into the
6101 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
6102 interests, and then stores a generic wrapper or a specific function into
6103 the slot.) Return a pointer to the next slotdef with a different offset,
6104 because that's convenient for fixup_slot_dispatchers(). */
6105static slotdef *
6106update_one_slot(PyTypeObject *type, slotdef *p)
6107{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006108 PyObject *descr;
6109 PyWrapperDescrObject *d;
6110 void *generic = NULL, *specific = NULL;
6111 int use_generic = 0;
6112 int offset = p->offset;
6113 void **ptr = slotptr(type, offset);
Guido van Rossumc334df52002-04-04 23:44:47 +00006114
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006115 if (ptr == NULL) {
6116 do {
6117 ++p;
6118 } while (p->offset == offset);
6119 return p;
6120 }
6121 do {
6122 descr = _PyType_Lookup(type, p->name_strobj);
6123 if (descr == NULL) {
6124 if (ptr == (void**)&type->tp_iternext) {
6125 specific = _PyObject_NextNotImplemented;
6126 }
6127 continue;
6128 }
6129 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
6130 void **tptr = resolve_slotdups(type, p->name_strobj);
6131 if (tptr == NULL || tptr == ptr)
6132 generic = p->function;
6133 d = (PyWrapperDescrObject *)descr;
6134 if (d->d_base->wrapper == p->wrapper &&
6135 PyType_IsSubtype(type, d->d_type))
6136 {
6137 if (specific == NULL ||
6138 specific == d->d_wrapped)
6139 specific = d->d_wrapped;
6140 else
6141 use_generic = 1;
6142 }
6143 }
6144 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6145 PyCFunction_GET_FUNCTION(descr) ==
6146 (PyCFunction)tp_new_wrapper &&
6147 ptr == (void**)&type->tp_new)
6148 {
6149 /* The __new__ wrapper is not a wrapper descriptor,
6150 so must be special-cased differently.
6151 If we don't do this, creating an instance will
6152 always use slot_tp_new which will look up
6153 __new__ in the MRO which will call tp_new_wrapper
6154 which will look through the base classes looking
6155 for a static base and call its tp_new (usually
6156 PyType_GenericNew), after performing various
6157 sanity checks and constructing a new argument
6158 list. Cut all that nonsense short -- this speeds
6159 up instance creation tremendously. */
6160 specific = (void *)type->tp_new;
6161 /* XXX I'm not 100% sure that there isn't a hole
6162 in this reasoning that requires additional
6163 sanity checks. I'll buy the first person to
6164 point out a bug in this reasoning a beer. */
6165 }
6166 else if (descr == Py_None &&
6167 ptr == (void**)&type->tp_hash) {
6168 /* We specifically allow __hash__ to be set to None
6169 to prevent inheritance of the default
6170 implementation from object.__hash__ */
6171 specific = PyObject_HashNotImplemented;
6172 }
6173 else {
6174 use_generic = 1;
6175 generic = p->function;
6176 }
6177 } while ((++p)->offset == offset);
6178 if (specific && !use_generic)
6179 *ptr = specific;
6180 else
6181 *ptr = generic;
6182 return p;
Guido van Rossumc334df52002-04-04 23:44:47 +00006183}
6184
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006185/* In the type, update the slots whose slotdefs are gathered in the pp array.
6186 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006187static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006188update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006189{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006190 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006191
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006192 for (; *pp; pp++)
6193 update_one_slot(type, *pp);
6194 return 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006195}
6196
Guido van Rossumc334df52002-04-04 23:44:47 +00006197/* Comparison function for qsort() to compare slotdefs by their offset, and
6198 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006199static int
6200slotdef_cmp(const void *aa, const void *bb)
6201{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006202 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
6203 int c = a->offset - b->offset;
6204 if (c != 0)
6205 return c;
6206 else
6207 /* Cannot use a-b, as this gives off_t,
6208 which may lose precision when converted to int. */
6209 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006210}
6211
Guido van Rossumc334df52002-04-04 23:44:47 +00006212/* Initialize the slotdefs table by adding interned string objects for the
6213 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006214static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006215init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006216{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006217 slotdef *p;
6218 static int initialized = 0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006219
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006220 if (initialized)
6221 return;
6222 for (p = slotdefs; p->name; p++) {
6223 p->name_strobj = PyString_InternFromString(p->name);
6224 if (!p->name_strobj)
6225 Py_FatalError("Out of memory interning slotdef names");
6226 }
6227 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
6228 slotdef_cmp);
6229 initialized = 1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006230}
6231
Guido van Rossumc334df52002-04-04 23:44:47 +00006232/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006233static int
6234update_slot(PyTypeObject *type, PyObject *name)
6235{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006236 slotdef *ptrs[MAX_EQUIV];
6237 slotdef *p;
6238 slotdef **pp;
6239 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006240
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006241 /* Clear the VALID_VERSION flag of 'type' and all its
6242 subclasses. This could possibly be unified with the
6243 update_subclasses() recursion below, but carefully:
6244 they each have their own conditions on which to stop
6245 recursing into subclasses. */
6246 PyType_Modified(type);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00006247
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006248 init_slotdefs();
6249 pp = ptrs;
6250 for (p = slotdefs; p->name; p++) {
6251 /* XXX assume name is interned! */
6252 if (p->name_strobj == name)
6253 *pp++ = p;
6254 }
6255 *pp = NULL;
6256 for (pp = ptrs; *pp; pp++) {
6257 p = *pp;
6258 offset = p->offset;
6259 while (p > slotdefs && (p-1)->offset == offset)
6260 --p;
6261 *pp = p;
6262 }
6263 if (ptrs[0] == NULL)
6264 return 0; /* Not an attribute that affects any slots */
6265 return update_subclasses(type, name,
6266 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006267}
6268
Guido van Rossumc334df52002-04-04 23:44:47 +00006269/* Store the proper functions in the slot dispatches at class (type)
6270 definition time, based upon which operations the class overrides in its
6271 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006272static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006273fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006274{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006275 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006276
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006277 init_slotdefs();
6278 for (p = slotdefs; p->name; )
6279 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006280}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006281
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006282static void
6283update_all_slots(PyTypeObject* type)
6284{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006285 slotdef *p;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006286
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006287 init_slotdefs();
6288 for (p = slotdefs; p->name; p++) {
6289 /* update_slot returns int but can't actually fail */
6290 update_slot(type, p->name_strobj);
6291 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006292}
6293
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006294/* recurse_down_subclasses() and update_subclasses() are mutually
6295 recursive functions to call a callback for all subclasses,
6296 but refraining from recursing into subclasses that define 'name'. */
6297
6298static int
6299update_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006300 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006301{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006302 if (callback(type, data) < 0)
6303 return -1;
6304 return recurse_down_subclasses(type, name, callback, data);
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006305}
6306
6307static int
6308recurse_down_subclasses(PyTypeObject *type, PyObject *name,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006309 update_callback callback, void *data)
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006310{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006311 PyTypeObject *subclass;
6312 PyObject *ref, *subclasses, *dict;
6313 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006314
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006315 subclasses = type->tp_subclasses;
6316 if (subclasses == NULL)
6317 return 0;
6318 assert(PyList_Check(subclasses));
6319 n = PyList_GET_SIZE(subclasses);
6320 for (i = 0; i < n; i++) {
6321 ref = PyList_GET_ITEM(subclasses, i);
6322 assert(PyWeakref_CheckRef(ref));
6323 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6324 assert(subclass != NULL);
6325 if ((PyObject *)subclass == Py_None)
6326 continue;
6327 assert(PyType_Check(subclass));
6328 /* Avoid recursing down into unaffected classes */
6329 dict = subclass->tp_dict;
6330 if (dict != NULL && PyDict_Check(dict) &&
6331 PyDict_GetItem(dict, name) != NULL)
6332 continue;
6333 if (update_subclasses(subclass, name, callback, data) < 0)
6334 return -1;
6335 }
6336 return 0;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006337}
6338
Guido van Rossum6d204072001-10-21 00:44:31 +00006339/* This function is called by PyType_Ready() to populate the type's
6340 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006341 function slot (like tp_repr) that's defined in the type, one or more
6342 corresponding descriptors are added in the type's tp_dict dictionary
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006343 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006344 cause more than one descriptor to be added (for example, the nb_add
6345 slot adds both __add__ and __radd__ descriptors) and some function
6346 slots compete for the same descriptor (for example both sq_item and
6347 mp_subscript generate a __getitem__ descriptor).
6348
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006349 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006350 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006351 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006352 between competing slots: the members of PyHeapTypeObject are listed
6353 from most general to least general, so the most general slot is
6354 preferred. In particular, because as_mapping comes before as_sequence,
6355 for a type that defines both mp_subscript and sq_item, mp_subscript
6356 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006357
6358 This only adds new descriptors and doesn't overwrite entries in
6359 tp_dict that were previously defined. The descriptors contain a
6360 reference to the C function they must call, so that it's safe if they
6361 are copied into a subtype's __dict__ and the subtype has a different
6362 C function in its slot -- calling the method defined by the
6363 descriptor will call the C function that was used to create it,
6364 rather than the C function present in the slot when it is called.
6365 (This is important because a subtype may have a C function in the
6366 slot that calls the method from the dictionary, and we want to avoid
6367 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006368
6369static int
6370add_operators(PyTypeObject *type)
6371{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006372 PyObject *dict = type->tp_dict;
6373 slotdef *p;
6374 PyObject *descr;
6375 void **ptr;
Guido van Rossum6d204072001-10-21 00:44:31 +00006376
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006377 init_slotdefs();
6378 for (p = slotdefs; p->name; p++) {
6379 if (p->wrapper == NULL)
6380 continue;
6381 ptr = slotptr(type, p->offset);
6382 if (!ptr || !*ptr)
6383 continue;
6384 if (PyDict_GetItem(dict, p->name_strobj))
6385 continue;
6386 if (*ptr == PyObject_HashNotImplemented) {
6387 /* Classes may prevent the inheritance of the tp_hash
6388 slot by storing PyObject_HashNotImplemented in it. Make it
6389 visible as a None value for the __hash__ attribute. */
6390 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6391 return -1;
6392 }
6393 else {
6394 descr = PyDescr_NewWrapper(type, p, *ptr);
6395 if (descr == NULL)
6396 return -1;
6397 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6398 return -1;
6399 Py_DECREF(descr);
6400 }
6401 }
6402 if (type->tp_new != NULL) {
6403 if (add_tp_new_wrapper(type) < 0)
6404 return -1;
6405 }
6406 return 0;
Guido van Rossum6d204072001-10-21 00:44:31 +00006407}
6408
Guido van Rossum705f0f52001-08-24 16:47:00 +00006409
6410/* Cooperative 'super' */
6411
6412typedef struct {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006413 PyObject_HEAD
6414 PyTypeObject *type;
6415 PyObject *obj;
6416 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006417} superobject;
6418
Guido van Rossum6f799372001-09-20 20:46:19 +00006419static PyMemberDef super_members[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006420 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6421 "the class invoking super()"},
6422 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6423 "the instance invoking super(); may be None"},
6424 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6425 "the type of the instance invoking super(); may be None"},
6426 {0}
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006427};
6428
Guido van Rossum705f0f52001-08-24 16:47:00 +00006429static void
6430super_dealloc(PyObject *self)
6431{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006432 superobject *su = (superobject *)self;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006433
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006434 _PyObject_GC_UNTRACK(self);
6435 Py_XDECREF(su->obj);
6436 Py_XDECREF(su->type);
6437 Py_XDECREF(su->obj_type);
6438 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006439}
6440
6441static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006442super_repr(PyObject *self)
6443{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006444 superobject *su = (superobject *)self;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006445
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006446 if (su->obj_type)
6447 return PyString_FromFormat(
6448 "<super: <class '%s'>, <%s object>>",
6449 su->type ? su->type->tp_name : "NULL",
6450 su->obj_type->tp_name);
6451 else
6452 return PyString_FromFormat(
6453 "<super: <class '%s'>, NULL>",
6454 su->type ? su->type->tp_name : "NULL");
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006455}
6456
6457static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006458super_getattro(PyObject *self, PyObject *name)
6459{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006460 superobject *su = (superobject *)self;
6461 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006462
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006463 if (!skip) {
6464 /* We want __class__ to return the class of the super object
6465 (i.e. super, or a subclass), not the class of su->obj. */
6466 skip = (PyString_Check(name) &&
6467 PyString_GET_SIZE(name) == 9 &&
6468 strcmp(PyString_AS_STRING(name), "__class__") == 0);
6469 }
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006470
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006471 if (!skip) {
6472 PyObject *mro, *res, *tmp, *dict;
6473 PyTypeObject *starttype;
6474 descrgetfunc f;
6475 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006476
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006477 starttype = su->obj_type;
6478 mro = starttype->tp_mro;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006479
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006480 if (mro == NULL)
6481 n = 0;
6482 else {
6483 assert(PyTuple_Check(mro));
6484 n = PyTuple_GET_SIZE(mro);
6485 }
6486 for (i = 0; i < n; i++) {
6487 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6488 break;
6489 }
6490 i++;
6491 res = NULL;
6492 for (; i < n; i++) {
6493 tmp = PyTuple_GET_ITEM(mro, i);
6494 if (PyType_Check(tmp))
6495 dict = ((PyTypeObject *)tmp)->tp_dict;
6496 else if (PyClass_Check(tmp))
6497 dict = ((PyClassObject *)tmp)->cl_dict;
6498 else
6499 continue;
6500 res = PyDict_GetItem(dict, name);
6501 if (res != NULL) {
6502 Py_INCREF(res);
6503 f = Py_TYPE(res)->tp_descr_get;
6504 if (f != NULL) {
6505 tmp = f(res,
6506 /* Only pass 'obj' param if
6507 this is instance-mode super
6508 (See SF ID #743627)
6509 */
6510 (su->obj == (PyObject *)
6511 su->obj_type
6512 ? (PyObject *)NULL
6513 : su->obj),
6514 (PyObject *)starttype);
6515 Py_DECREF(res);
6516 res = tmp;
6517 }
6518 return res;
6519 }
6520 }
6521 }
6522 return PyObject_GenericGetAttr(self, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006523}
6524
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006525static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006526supercheck(PyTypeObject *type, PyObject *obj)
6527{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006528 /* Check that a super() call makes sense. Return a type object.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006529
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006530 obj can be a new-style class, or an instance of one:
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006531
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006532 - If it is a class, it must be a subclass of 'type'. This case is
6533 used for class methods; the return value is obj.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006534
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006535 - If it is an instance, it must be an instance of 'type'. This is
6536 the normal case; the return value is obj.__class__.
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006537
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006538 But... when obj is an instance, we want to allow for the case where
6539 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6540 This will allow using super() with a proxy for obj.
6541 */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006542
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006543 /* Check for first bullet above (special case) */
6544 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6545 Py_INCREF(obj);
6546 return (PyTypeObject *)obj;
6547 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006548
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006549 /* Normal case */
6550 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6551 Py_INCREF(Py_TYPE(obj));
6552 return Py_TYPE(obj);
6553 }
6554 else {
6555 /* Try the slow way */
6556 static PyObject *class_str = NULL;
6557 PyObject *class_attr;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006558
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006559 if (class_str == NULL) {
6560 class_str = PyString_FromString("__class__");
6561 if (class_str == NULL)
6562 return NULL;
6563 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006564
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006565 class_attr = PyObject_GetAttr(obj, class_str);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006566
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006567 if (class_attr != NULL &&
6568 PyType_Check(class_attr) &&
6569 (PyTypeObject *)class_attr != Py_TYPE(obj))
6570 {
6571 int ok = PyType_IsSubtype(
6572 (PyTypeObject *)class_attr, type);
6573 if (ok)
6574 return (PyTypeObject *)class_attr;
6575 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006576
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006577 if (class_attr == NULL)
6578 PyErr_Clear();
6579 else
6580 Py_DECREF(class_attr);
6581 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006582
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006583 PyErr_SetString(PyExc_TypeError,
6584 "super(type, obj): "
6585 "obj must be an instance or subtype of type");
6586 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006587}
6588
Guido van Rossum705f0f52001-08-24 16:47:00 +00006589static PyObject *
6590super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6591{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006592 superobject *su = (superobject *)self;
6593 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006594
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006595 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6596 /* Not binding to an object, or already bound */
6597 Py_INCREF(self);
6598 return self;
6599 }
6600 if (Py_TYPE(su) != &PySuper_Type)
6601 /* If su is an instance of a (strict) subclass of super,
6602 call its type */
6603 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6604 su->type, obj, NULL);
6605 else {
6606 /* Inline the common case */
6607 PyTypeObject *obj_type = supercheck(su->type, obj);
6608 if (obj_type == NULL)
6609 return NULL;
6610 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6611 NULL, NULL);
6612 if (newobj == NULL)
6613 return NULL;
6614 Py_INCREF(su->type);
6615 Py_INCREF(obj);
6616 newobj->type = su->type;
6617 newobj->obj = obj;
6618 newobj->obj_type = obj_type;
6619 return (PyObject *)newobj;
6620 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006621}
6622
6623static int
6624super_init(PyObject *self, PyObject *args, PyObject *kwds)
6625{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006626 superobject *su = (superobject *)self;
6627 PyTypeObject *type;
6628 PyObject *obj = NULL;
6629 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006630
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006631 if (!_PyArg_NoKeywords("super", kwds))
6632 return -1;
6633 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
6634 return -1;
6635 if (obj == Py_None)
6636 obj = NULL;
6637 if (obj != NULL) {
6638 obj_type = supercheck(type, obj);
6639 if (obj_type == NULL)
6640 return -1;
6641 Py_INCREF(obj);
6642 }
6643 Py_INCREF(type);
6644 su->type = type;
6645 su->obj = obj;
6646 su->obj_type = obj_type;
6647 return 0;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006648}
6649
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006650PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00006651"super(type) -> unbound super object\n"
6652"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006653"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006654"Typical use to call a cooperative superclass method:\n"
6655"class C(B):\n"
6656" def meth(self, arg):\n"
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006657" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006658
Guido van Rossum048eb752001-10-02 21:24:57 +00006659static int
6660super_traverse(PyObject *self, visitproc visit, void *arg)
6661{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006662 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006663
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006664 Py_VISIT(su->obj);
6665 Py_VISIT(su->type);
6666 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006667
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006668 return 0;
Guido van Rossum048eb752001-10-02 21:24:57 +00006669}
6670
Guido van Rossum705f0f52001-08-24 16:47:00 +00006671PyTypeObject PySuper_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006672 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6673 "super", /* tp_name */
6674 sizeof(superobject), /* tp_basicsize */
6675 0, /* tp_itemsize */
6676 /* methods */
6677 super_dealloc, /* tp_dealloc */
6678 0, /* tp_print */
6679 0, /* tp_getattr */
6680 0, /* tp_setattr */
6681 0, /* tp_compare */
6682 super_repr, /* tp_repr */
6683 0, /* tp_as_number */
6684 0, /* tp_as_sequence */
6685 0, /* tp_as_mapping */
6686 0, /* tp_hash */
6687 0, /* tp_call */
6688 0, /* tp_str */
6689 super_getattro, /* tp_getattro */
6690 0, /* tp_setattro */
6691 0, /* tp_as_buffer */
6692 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6693 Py_TPFLAGS_BASETYPE, /* tp_flags */
6694 super_doc, /* tp_doc */
6695 super_traverse, /* tp_traverse */
6696 0, /* tp_clear */
6697 0, /* tp_richcompare */
6698 0, /* tp_weaklistoffset */
6699 0, /* tp_iter */
6700 0, /* tp_iternext */
6701 0, /* tp_methods */
6702 super_members, /* tp_members */
6703 0, /* tp_getset */
6704 0, /* tp_base */
6705 0, /* tp_dict */
6706 super_descr_get, /* tp_descr_get */
6707 0, /* tp_descr_set */
6708 0, /* tp_dictoffset */
6709 super_init, /* tp_init */
6710 PyType_GenericAlloc, /* tp_alloc */
6711 PyType_GenericNew, /* tp_new */
6712 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006713};