blob: 70fd1f22fb3097393dc62b35f7fa0be7b3afd496 [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. */
15#define MCACHE_MAX_ATTR_SIZE 100
16#define MCACHE_SIZE_EXP 10
17#define MCACHE_HASH(version, name_hash) \
18 (((unsigned int)(version) * (unsigned int)(name_hash)) \
19 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
20#define MCACHE_HASH_METHOD(type, name) \
21 MCACHE_HASH((type)->tp_version_tag, \
Christian Heimes593daf52008-05-26 12:51:38 +000022 ((PyBytesObject *)(name))->ob_shash)
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000023#define MCACHE_CACHEABLE_NAME(name) \
Christian Heimes593daf52008-05-26 12:51:38 +000024 PyBytes_CheckExact(name) && \
25 PyBytes_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000026
27struct method_cache_entry {
28 unsigned int version;
29 PyObject *name; /* reference to exactly a str or None */
30 PyObject *value; /* borrowed */
31};
32
33static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
34static unsigned int next_version_tag = 0;
Christian Heimes908caac2008-01-27 23:34:59 +000035
36unsigned int
37PyType_ClearCache(void)
38{
39 Py_ssize_t i;
40 unsigned int cur_version_tag = next_version_tag - 1;
41
42 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
43 method_cache[i].version = 0;
44 Py_CLEAR(method_cache[i].name);
45 method_cache[i].value = NULL;
46 }
47 next_version_tag = 0;
48 /* mark all version tags as invalid */
Georg Brandl74a1dea2008-05-28 11:21:39 +000049 PyType_Modified(&PyBaseObject_Type);
Christian Heimes908caac2008-01-27 23:34:59 +000050 return cur_version_tag;
51}
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{
56 /* Invalidate any cached data for the specified type and all
57 subclasses. This function is called after the base
58 classes, mro, or attributes of the type are altered.
59
60 Invariants:
61
62 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
63 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
64 objects coming from non-recompiled extension modules)
65
66 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
67 it must first be set on all super types.
68
69 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
70 type (so it must first clear it on all subclasses). The
71 tp_version_tag value is meaningless unless this flag is set.
72 We don't assign new version tags eagerly, but only as
73 needed.
74 */
75 PyObject *raw, *ref;
76 Py_ssize_t i, n;
77
Neal Norwitze7bb9182008-01-27 17:10:14 +000078 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000079 return;
80
81 raw = type->tp_subclasses;
82 if (raw != NULL) {
83 n = PyList_GET_SIZE(raw);
84 for (i = 0; i < n; i++) {
85 ref = PyList_GET_ITEM(raw, i);
86 ref = PyWeakref_GET_OBJECT(ref);
87 if (ref != Py_None) {
Georg Brandl74a1dea2008-05-28 11:21:39 +000088 PyType_Modified((PyTypeObject *)ref);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000089 }
90 }
91 }
92 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
93}
94
95static void
96type_mro_modified(PyTypeObject *type, PyObject *bases) {
97 /*
98 Check that all base classes or elements of the mro of type are
99 able to be cached. This function is called after the base
100 classes or mro of the type are altered.
101
102 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
103 inherits from an old-style class, either directly or if it
104 appears in the MRO of a new-style class. No support either for
105 custom MROs that include types that are not officially super
106 types.
107
108 Called from mro_internal, which will subsequently be called on
109 each subclass when their mro is recursively updated.
110 */
111 Py_ssize_t i, n;
112 int clear = 0;
113
Neal Norwitze7bb9182008-01-27 17:10:14 +0000114 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000115 return;
116
117 n = PyTuple_GET_SIZE(bases);
118 for (i = 0; i < n; i++) {
119 PyObject *b = PyTuple_GET_ITEM(bases, i);
120 PyTypeObject *cls;
121
122 if (!PyType_Check(b) ) {
123 clear = 1;
124 break;
125 }
126
127 cls = (PyTypeObject *)b;
128
129 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
130 !PyType_IsSubtype(type, cls)) {
131 clear = 1;
132 break;
133 }
134 }
135
136 if (clear)
137 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
138 Py_TPFLAGS_VALID_VERSION_TAG);
139}
140
141static int
142assign_version_tag(PyTypeObject *type)
143{
144 /* Ensure that the tp_version_tag is valid and set
145 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
146 must first be done on all super classes. Return 0 if this
147 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
148 */
149 Py_ssize_t i, n;
Georg Brandl5ec330c2008-05-28 15:41:36 +0000150 PyObject *bases, *tmp;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000151
152 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
153 return 1;
154 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
155 return 0;
156 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
157 return 0;
158
159 type->tp_version_tag = next_version_tag++;
160 /* for stress-testing: next_version_tag &= 0xFF; */
161
162 if (type->tp_version_tag == 0) {
163 /* wrap-around or just starting Python - clear the whole
164 cache by filling names with references to Py_None.
165 Values are also set to NULL for added protection, as they
166 are borrowed reference */
167 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
168 method_cache[i].value = NULL;
Georg Brandl5ec330c2008-05-28 15:41:36 +0000169 tmp = method_cache[i].name;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000170 Py_INCREF(Py_None);
Georg Brandl5ec330c2008-05-28 15:41:36 +0000171 method_cache[i].name = Py_None;
172 Py_XDECREF(tmp);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000173 }
174 /* mark all version tags as invalid */
Georg Brandl74a1dea2008-05-28 11:21:39 +0000175 PyType_Modified(&PyBaseObject_Type);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000176 return 1;
177 }
178 bases = type->tp_bases;
179 n = PyTuple_GET_SIZE(bases);
180 for (i = 0; i < n; i++) {
181 PyObject *b = PyTuple_GET_ITEM(bases, i);
182 assert(PyType_Check(b));
183 if (!assign_version_tag((PyTypeObject *)b))
184 return 0;
185 }
186 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
187 return 1;
188}
189
190
Guido van Rossum6f799372001-09-20 20:46:19 +0000191static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000192 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
193 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
194 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +0000195 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000196 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
197 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
198 {"__dictoffset__", T_LONG,
199 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000200 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
201 {0}
202};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000204static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000205type_name(PyTypeObject *type, void *context)
206{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000207 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000208
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000209 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +0000210 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000211
Georg Brandlc255c7b2006-02-20 22:27:28 +0000212 Py_INCREF(et->ht_name);
213 return et->ht_name;
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000214 }
215 else {
216 s = strrchr(type->tp_name, '.');
217 if (s == NULL)
218 s = type->tp_name;
219 else
220 s++;
Christian Heimes593daf52008-05-26 12:51:38 +0000221 return PyBytes_FromString(s);
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000222 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000223}
224
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000225static int
226type_set_name(PyTypeObject *type, PyObject *value, void *context)
227{
Guido van Rossume5c691a2003-03-07 15:13:17 +0000228 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000229
230 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
231 PyErr_Format(PyExc_TypeError,
232 "can't set %s.__name__", type->tp_name);
233 return -1;
234 }
235 if (!value) {
236 PyErr_Format(PyExc_TypeError,
237 "can't delete %s.__name__", type->tp_name);
238 return -1;
239 }
Christian Heimes593daf52008-05-26 12:51:38 +0000240 if (!PyBytes_Check(value)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000241 PyErr_Format(PyExc_TypeError,
242 "can only assign string to %s.__name__, not '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +0000243 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000244 return -1;
245 }
Christian Heimes593daf52008-05-26 12:51:38 +0000246 if (strlen(PyBytes_AS_STRING(value))
247 != (size_t)PyBytes_GET_SIZE(value)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000248 PyErr_Format(PyExc_ValueError,
249 "__name__ must not contain null bytes");
250 return -1;
251 }
252
Guido van Rossume5c691a2003-03-07 15:13:17 +0000253 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000254
255 Py_INCREF(value);
256
Georg Brandlc255c7b2006-02-20 22:27:28 +0000257 Py_DECREF(et->ht_name);
258 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000259
Christian Heimes593daf52008-05-26 12:51:38 +0000260 type->tp_name = PyBytes_AS_STRING(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000261
262 return 0;
263}
264
Guido van Rossumc3542212001-08-16 09:18:56 +0000265static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000266type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000267{
Guido van Rossumc3542212001-08-16 09:18:56 +0000268 PyObject *mod;
269 char *s;
270
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000271 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
272 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +0000273 if (!mod) {
274 PyErr_Format(PyExc_AttributeError, "__module__");
275 return 0;
276 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000277 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +0000278 return mod;
279 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000280 else {
281 s = strrchr(type->tp_name, '.');
282 if (s != NULL)
Christian Heimes593daf52008-05-26 12:51:38 +0000283 return PyBytes_FromStringAndSize(
Armin Rigo7ccbca92006-10-04 12:17:45 +0000284 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Christian Heimes593daf52008-05-26 12:51:38 +0000285 return PyBytes_FromString("__builtin__");
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000286 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000287}
288
Guido van Rossum3926a632001-09-25 16:25:58 +0000289static int
290type_set_module(PyTypeObject *type, PyObject *value, void *context)
291{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000292 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000293 PyErr_Format(PyExc_TypeError,
294 "can't set %s.__module__", type->tp_name);
295 return -1;
296 }
297 if (!value) {
298 PyErr_Format(PyExc_TypeError,
299 "can't delete %s.__module__", type->tp_name);
300 return -1;
301 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000302
Georg Brandl74a1dea2008-05-28 11:21:39 +0000303 PyType_Modified(type);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000304
Guido van Rossum3926a632001-09-25 16:25:58 +0000305 return PyDict_SetItemString(type->tp_dict, "__module__", value);
306}
307
Tim Peters6d6c1a32001-08-02 04:15:00 +0000308static PyObject *
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +0000309type_abstractmethods(PyTypeObject *type, void *context)
310{
311 PyObject *mod = PyDict_GetItemString(type->tp_dict,
312 "__abstractmethods__");
313 if (!mod) {
314 PyErr_Format(PyExc_AttributeError, "__abstractmethods__");
315 return NULL;
316 }
317 Py_XINCREF(mod);
318 return mod;
319}
320
321static int
322type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
323{
324 /* __abstractmethods__ should only be set once on a type, in
325 abc.ABCMeta.__new__, so this function doesn't do anything
326 special to update subclasses.
327 */
328 int res = PyDict_SetItemString(type->tp_dict,
329 "__abstractmethods__", value);
330 if (res == 0) {
Georg Brandl74a1dea2008-05-28 11:21:39 +0000331 PyType_Modified(type);
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +0000332 if (value && PyObject_IsTrue(value)) {
333 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
334 }
335 else {
336 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
337 }
338 }
339 return res;
340}
341
342static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000343type_get_bases(PyTypeObject *type, void *context)
344{
345 Py_INCREF(type->tp_bases);
346 return type->tp_bases;
347}
348
349static PyTypeObject *best_base(PyObject *);
350static int mro_internal(PyTypeObject *);
351static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
352static int add_subclass(PyTypeObject*, PyTypeObject*);
353static void remove_subclass(PyTypeObject *, PyTypeObject *);
354static void update_all_slots(PyTypeObject *);
355
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000356typedef int (*update_callback)(PyTypeObject *, void *);
357static int update_subclasses(PyTypeObject *type, PyObject *name,
358 update_callback callback, void *data);
359static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
360 update_callback callback, void *data);
361
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000362static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000363mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000364{
365 PyTypeObject *subclass;
366 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000367 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000368
369 subclasses = type->tp_subclasses;
370 if (subclasses == NULL)
371 return 0;
372 assert(PyList_Check(subclasses));
373 n = PyList_GET_SIZE(subclasses);
374 for (i = 0; i < n; i++) {
375 ref = PyList_GET_ITEM(subclasses, i);
376 assert(PyWeakref_CheckRef(ref));
377 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
378 assert(subclass != NULL);
379 if ((PyObject *)subclass == Py_None)
380 continue;
381 assert(PyType_Check(subclass));
382 old_mro = subclass->tp_mro;
383 if (mro_internal(subclass) < 0) {
384 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000385 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000386 }
387 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000388 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000389 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000390 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000391 if (!tuple)
392 return -1;
393 if (PyList_Append(temp, tuple) < 0)
394 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000395 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000396 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000397 if (mro_subclasses(subclass, temp) < 0)
398 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000399 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000400 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000401}
402
403static int
404type_set_bases(PyTypeObject *type, PyObject *value, void *context)
405{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000406 Py_ssize_t i;
407 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000408 PyObject *ob, *temp;
Armin Rigoc0ba52d2007-04-19 14:44:48 +0000409 PyTypeObject *new_base, *old_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000410 PyObject *old_bases, *old_mro;
411
412 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
413 PyErr_Format(PyExc_TypeError,
414 "can't set %s.__bases__", type->tp_name);
415 return -1;
416 }
417 if (!value) {
418 PyErr_Format(PyExc_TypeError,
419 "can't delete %s.__bases__", type->tp_name);
420 return -1;
421 }
422 if (!PyTuple_Check(value)) {
423 PyErr_Format(PyExc_TypeError,
424 "can only assign tuple to %s.__bases__, not %s",
Christian Heimese93237d2007-12-19 02:37:44 +0000425 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000426 return -1;
427 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000428 if (PyTuple_GET_SIZE(value) == 0) {
429 PyErr_Format(PyExc_TypeError,
430 "can only assign non-empty tuple to %s.__bases__, not ()",
431 type->tp_name);
432 return -1;
433 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000434 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
435 ob = PyTuple_GET_ITEM(value, i);
436 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
437 PyErr_Format(
438 PyExc_TypeError,
439 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +0000440 type->tp_name, Py_TYPE(ob)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000441 return -1;
442 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000443 if (PyType_Check(ob)) {
444 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
445 PyErr_SetString(PyExc_TypeError,
446 "a __bases__ item causes an inheritance cycle");
447 return -1;
448 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000449 }
450 }
451
452 new_base = best_base(value);
453
454 if (!new_base) {
455 return -1;
456 }
457
458 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
459 return -1;
460
461 Py_INCREF(new_base);
462 Py_INCREF(value);
463
464 old_bases = type->tp_bases;
465 old_base = type->tp_base;
466 old_mro = type->tp_mro;
467
468 type->tp_bases = value;
469 type->tp_base = new_base;
470
471 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000472 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000473 }
474
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000475 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000476 if (!temp)
477 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000478
479 r = mro_subclasses(type, temp);
480
481 if (r < 0) {
482 for (i = 0; i < PyList_Size(temp); i++) {
483 PyTypeObject* cls;
484 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000485 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
486 "", 2, 2, &cls, &mro);
Armin Rigo796fc992007-04-19 14:56:48 +0000487 Py_INCREF(mro);
488 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000489 cls->tp_mro = mro;
Armin Rigo796fc992007-04-19 14:56:48 +0000490 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000491 }
492 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000493 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000494 }
495
496 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000497
498 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000499 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000500 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000501 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000502
503 /* for now, sod that: just remove from all old_bases,
504 add to all new_bases */
505
506 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
507 ob = PyTuple_GET_ITEM(old_bases, i);
508 if (PyType_Check(ob)) {
509 remove_subclass(
510 (PyTypeObject*)ob, type);
511 }
512 }
513
514 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
515 ob = PyTuple_GET_ITEM(value, i);
516 if (PyType_Check(ob)) {
517 if (add_subclass((PyTypeObject*)ob, type) < 0)
518 r = -1;
519 }
520 }
521
522 update_all_slots(type);
523
524 Py_DECREF(old_bases);
525 Py_DECREF(old_base);
526 Py_DECREF(old_mro);
527
528 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000529
530 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000531 Py_DECREF(type->tp_bases);
532 Py_DECREF(type->tp_base);
533 if (type->tp_mro != old_mro) {
534 Py_DECREF(type->tp_mro);
535 }
536
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000537 type->tp_bases = old_bases;
538 type->tp_base = old_base;
539 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000540
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000541 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000542}
543
544static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000545type_dict(PyTypeObject *type, void *context)
546{
547 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548 Py_INCREF(Py_None);
549 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000550 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000551 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000552}
553
Tim Peters24008312002-03-17 18:56:20 +0000554static PyObject *
555type_get_doc(PyTypeObject *type, void *context)
556{
557 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000558 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Christian Heimes593daf52008-05-26 12:51:38 +0000559 return PyBytes_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000560 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000561 if (result == NULL) {
562 result = Py_None;
563 Py_INCREF(result);
564 }
Christian Heimese93237d2007-12-19 02:37:44 +0000565 else if (Py_TYPE(result)->tp_descr_get) {
566 result = Py_TYPE(result)->tp_descr_get(result, NULL,
Tim Peters2b858972002-04-18 04:12:28 +0000567 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000568 }
569 else {
570 Py_INCREF(result);
571 }
Tim Peters24008312002-03-17 18:56:20 +0000572 return result;
573}
574
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000575static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000576 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
577 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000578 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +0000579 {"__abstractmethods__", (getter)type_abstractmethods,
580 (setter)type_set_abstractmethods, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000581 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000582 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000583 {0}
584};
585
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000586static int
587type_compare(PyObject *v, PyObject *w)
588{
589 /* This is called with type objects only. So we
590 can just compare the addresses. */
591 Py_uintptr_t vv = (Py_uintptr_t)v;
592 Py_uintptr_t ww = (Py_uintptr_t)w;
593 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
594}
595
Steven Bethardae42f332008-03-18 17:26:10 +0000596static PyObject*
597type_richcompare(PyObject *v, PyObject *w, int op)
598{
599 PyObject *result;
600 Py_uintptr_t vv, ww;
601 int c;
602
603 /* Make sure both arguments are types. */
604 if (!PyType_Check(v) || !PyType_Check(w)) {
605 result = Py_NotImplemented;
606 goto out;
607 }
608
609 /* Py3K warning if comparison isn't == or != */
610 if (Py_Py3kWarningFlag && op != Py_EQ && op != Py_NE &&
Benjamin Peterson9f4f4812008-04-27 03:01:45 +0000611 PyErr_WarnEx(PyExc_DeprecationWarning,
Georg Brandld5b635f2008-03-25 08:29:14 +0000612 "type inequality comparisons not supported "
Benjamin Peterson9f4f4812008-04-27 03:01:45 +0000613 "in 3.x", 1) < 0) {
Steven Bethardae42f332008-03-18 17:26:10 +0000614 return NULL;
615 }
616
617 /* Compare addresses */
618 vv = (Py_uintptr_t)v;
619 ww = (Py_uintptr_t)w;
620 switch (op) {
621 case Py_LT: c = vv < ww; break;
622 case Py_LE: c = vv <= ww; break;
623 case Py_EQ: c = vv == ww; break;
624 case Py_NE: c = vv != ww; break;
625 case Py_GT: c = vv > ww; break;
626 case Py_GE: c = vv >= ww; break;
627 default:
628 result = Py_NotImplemented;
629 goto out;
630 }
631 result = c ? Py_True : Py_False;
632
633 /* incref and return */
634 out:
635 Py_INCREF(result);
636 return result;
637}
638
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000639static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000640type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000641{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000642 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000643 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000644
645 mod = type_module(type, NULL);
646 if (mod == NULL)
647 PyErr_Clear();
Christian Heimes593daf52008-05-26 12:51:38 +0000648 else if (!PyBytes_Check(mod)) {
Guido van Rossumc3542212001-08-16 09:18:56 +0000649 Py_DECREF(mod);
650 mod = NULL;
651 }
652 name = type_name(type, NULL);
653 if (name == NULL)
654 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000655
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000656 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
657 kind = "class";
658 else
659 kind = "type";
660
Christian Heimes593daf52008-05-26 12:51:38 +0000661 if (mod != NULL && strcmp(PyBytes_AS_STRING(mod), "__builtin__")) {
662 rtn = PyBytes_FromFormat("<%s '%s.%s'>",
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000663 kind,
Christian Heimes593daf52008-05-26 12:51:38 +0000664 PyBytes_AS_STRING(mod),
665 PyBytes_AS_STRING(name));
Barry Warsaw7ce36942001-08-24 18:34:26 +0000666 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000667 else
Christian Heimes593daf52008-05-26 12:51:38 +0000668 rtn = PyBytes_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000669
Guido van Rossumc3542212001-08-16 09:18:56 +0000670 Py_XDECREF(mod);
671 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000672 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000673}
674
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675static PyObject *
676type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
677{
678 PyObject *obj;
679
680 if (type->tp_new == NULL) {
681 PyErr_Format(PyExc_TypeError,
682 "cannot create '%.100s' instances",
683 type->tp_name);
684 return NULL;
685 }
686
Tim Peters3f996e72001-09-13 19:18:27 +0000687 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000688 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000689 /* Ugly exception: when the call was type(something),
690 don't call tp_init on the result. */
691 if (type == &PyType_Type &&
692 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
693 (kwds == NULL ||
694 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
695 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000696 /* If the returned object is not an instance of type,
697 it won't be initialized. */
698 if (!PyType_IsSubtype(obj->ob_type, type))
699 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000701 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
702 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000703 type->tp_init(obj, args, kwds) < 0) {
704 Py_DECREF(obj);
705 obj = NULL;
706 }
707 }
708 return obj;
709}
710
711PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000712PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000713{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000714 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000715 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
716 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000717
718 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000719 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000720 else
Anthony Baxtera6286212006-04-11 07:42:36 +0000721 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000722
Neil Schemenauerc806c882001-08-29 23:54:54 +0000723 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000724 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000725
Neil Schemenauerc806c882001-08-29 23:54:54 +0000726 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000727
Tim Peters6d6c1a32001-08-02 04:15:00 +0000728 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
729 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000730
Tim Peters6d6c1a32001-08-02 04:15:00 +0000731 if (type->tp_itemsize == 0)
732 PyObject_INIT(obj, type);
733 else
734 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000735
Tim Peters6d6c1a32001-08-02 04:15:00 +0000736 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000737 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000738 return obj;
739}
740
741PyObject *
742PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
743{
744 return type->tp_alloc(type, 0);
745}
746
Guido van Rossum9475a232001-10-05 20:51:39 +0000747/* Helpers for subtyping */
748
749static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000750traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
751{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000752 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000753 PyMemberDef *mp;
754
Christian Heimese93237d2007-12-19 02:37:44 +0000755 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000756 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000757 for (i = 0; i < n; i++, mp++) {
758 if (mp->type == T_OBJECT_EX) {
759 char *addr = (char *)self + mp->offset;
760 PyObject *obj = *(PyObject **)addr;
761 if (obj != NULL) {
762 int err = visit(obj, arg);
763 if (err)
764 return err;
765 }
766 }
767 }
768 return 0;
769}
770
771static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000772subtype_traverse(PyObject *self, visitproc visit, void *arg)
773{
774 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000775 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000776
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000777 /* Find the nearest base with a different tp_traverse,
778 and traverse slots while we're at it */
Christian Heimese93237d2007-12-19 02:37:44 +0000779 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000780 base = type;
781 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
Christian Heimese93237d2007-12-19 02:37:44 +0000782 if (Py_SIZE(base)) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000783 int err = traverse_slots(base, self, visit, arg);
784 if (err)
785 return err;
786 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000787 base = base->tp_base;
788 assert(base);
789 }
790
791 if (type->tp_dictoffset != base->tp_dictoffset) {
792 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Woutersc6e55062006-04-15 21:47:09 +0000793 if (dictptr && *dictptr)
794 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000795 }
796
Thomas Woutersc6e55062006-04-15 21:47:09 +0000797 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000798 /* For a heaptype, the instances count as references
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000799 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000800 can find cycles involving this link. */
Thomas Woutersc6e55062006-04-15 21:47:09 +0000801 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000802
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000803 if (basetraverse)
804 return basetraverse(self, visit, arg);
805 return 0;
806}
807
808static void
809clear_slots(PyTypeObject *type, PyObject *self)
810{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000811 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000812 PyMemberDef *mp;
813
Christian Heimese93237d2007-12-19 02:37:44 +0000814 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000815 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000816 for (i = 0; i < n; i++, mp++) {
817 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
818 char *addr = (char *)self + mp->offset;
819 PyObject *obj = *(PyObject **)addr;
820 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000821 *(PyObject **)addr = NULL;
Thomas Woutersedf17d82006-04-15 17:28:34 +0000822 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000823 }
824 }
825 }
826}
827
828static int
829subtype_clear(PyObject *self)
830{
831 PyTypeObject *type, *base;
832 inquiry baseclear;
833
834 /* Find the nearest base with a different tp_clear
835 and clear slots while we're at it */
Christian Heimese93237d2007-12-19 02:37:44 +0000836 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000837 base = type;
838 while ((baseclear = base->tp_clear) == subtype_clear) {
Christian Heimese93237d2007-12-19 02:37:44 +0000839 if (Py_SIZE(base))
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000840 clear_slots(base, self);
841 base = base->tp_base;
842 assert(base);
843 }
844
Guido van Rossuma3862092002-06-10 15:24:42 +0000845 /* There's no need to clear the instance dict (if any);
846 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000847
848 if (baseclear)
849 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000850 return 0;
851}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000852
853static void
854subtype_dealloc(PyObject *self)
855{
Guido van Rossum14227b42001-12-06 02:35:58 +0000856 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000857 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000858
Guido van Rossum22b13872002-08-06 21:41:44 +0000859 /* Extract the type; we expect it to be a heap type */
Christian Heimese93237d2007-12-19 02:37:44 +0000860 type = Py_TYPE(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000861 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000862
Guido van Rossum22b13872002-08-06 21:41:44 +0000863 /* Test whether the type has GC exactly once */
864
865 if (!PyType_IS_GC(type)) {
866 /* It's really rare to find a dynamic type that doesn't have
867 GC; it can only happen when deriving from 'object' and not
868 adding any slots or instance variables. This allows
869 certain simplifications: there's no need to call
870 clear_slots(), or DECREF the dict, or clear weakrefs. */
871
872 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000873 if (type->tp_del) {
874 type->tp_del(self);
875 if (self->ob_refcnt > 0)
876 return;
877 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000878
879 /* Find the nearest base with a different tp_dealloc */
880 base = type;
881 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimese93237d2007-12-19 02:37:44 +0000882 assert(Py_SIZE(base) == 0);
Guido van Rossum22b13872002-08-06 21:41:44 +0000883 base = base->tp_base;
884 assert(base);
885 }
886
887 /* Call the base tp_dealloc() */
888 assert(basedealloc);
889 basedealloc(self);
890
891 /* Can't reference self beyond this point */
892 Py_DECREF(type);
893
894 /* Done */
895 return;
896 }
897
898 /* We get here only if the type has GC */
899
900 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000901 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000902 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000903 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000904 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000905 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000906 /* DO NOT restore GC tracking at this point. weakref callbacks
907 * (if any, and whether directly here or indirectly in something we
908 * call) may trigger GC, and if self is tracked at that point, it
909 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000910 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000911
Guido van Rossum59195fd2003-06-13 20:54:40 +0000912 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000913 base = type;
914 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000915 base = base->tp_base;
916 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000917 }
918
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000919 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000920 the finalizer (__del__), clearing slots, or clearing the instance
921 dict. */
922
Guido van Rossum1987c662003-05-29 14:29:23 +0000923 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
924 PyObject_ClearWeakRefs(self);
925
926 /* Maybe call finalizer; exit early if resurrected */
927 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000928 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000929 type->tp_del(self);
930 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000931 goto endlabel; /* resurrected */
932 else
933 _PyObject_GC_UNTRACK(self);
Brett Cannonf5bee302007-01-23 23:21:22 +0000934 /* New weakrefs could be created during the finalizer call.
935 If this occurs, clear them out without calling their
936 finalizers since they might rely on part of the object
937 being finalized that has already been destroyed. */
938 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
939 /* Modeled after GET_WEAKREFS_LISTPTR() */
940 PyWeakReference **list = (PyWeakReference **) \
941 PyObject_GET_WEAKREFS_LISTPTR(self);
942 while (*list)
943 _PyWeakref_ClearRef(*list);
944 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000945 }
946
Guido van Rossum59195fd2003-06-13 20:54:40 +0000947 /* Clear slots up to the nearest base with a different tp_dealloc */
948 base = type;
949 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimese93237d2007-12-19 02:37:44 +0000950 if (Py_SIZE(base))
Guido van Rossum59195fd2003-06-13 20:54:40 +0000951 clear_slots(base, self);
952 base = base->tp_base;
953 assert(base);
954 }
955
Tim Peters6d6c1a32001-08-02 04:15:00 +0000956 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000957 if (type->tp_dictoffset && !base->tp_dictoffset) {
958 PyObject **dictptr = _PyObject_GetDictPtr(self);
959 if (dictptr != NULL) {
960 PyObject *dict = *dictptr;
961 if (dict != NULL) {
962 Py_DECREF(dict);
963 *dictptr = NULL;
964 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000965 }
966 }
967
Tim Peters0bd743c2003-11-13 22:50:00 +0000968 /* Call the base tp_dealloc(); first retrack self if
969 * basedealloc knows about gc.
970 */
971 if (PyType_IS_GC(base))
972 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000973 assert(basedealloc);
974 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000975
976 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000977 Py_DECREF(type);
978
Guido van Rossum0906e072002-08-07 20:42:09 +0000979 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000980 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000981 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000982 --_PyTrash_delete_nesting;
983
984 /* Explanation of the weirdness around the trashcan macros:
985
986 Q. What do the trashcan macros do?
987
988 A. Read the comment titled "Trashcan mechanism" in object.h.
989 For one, this explains why there must be a call to GC-untrack
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000990 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000991 trashcan code, the answers to the following questions don't make
992 sense.
993
994 Q. Why do we GC-untrack before the trashcan and then immediately
995 GC-track again afterward?
996
997 A. In the case that the base class is GC-aware, the base class
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000998 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000999 UNTRACK macro, this will crash when the object is already
1000 untracked. Because we don't know what the base class does, the
1001 only safe thing is to make sure the object is tracked when we
1002 call the base class dealloc. But... The trashcan begin macro
1003 requires that the object is *untracked* before it is called. So
1004 the dance becomes:
1005
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001006 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001007 trashcan begin
1008 GC track
1009
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001010 Q. Why did the last question say "immediately GC-track again"?
1011 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001012
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001013 A. Because the code *used* to re-track immediately. Bad Idea.
1014 self has a refcount of 0, and if gc ever gets its hands on it
1015 (which can happen if any weakref callback gets invoked), it
1016 looks like trash to gc too, and gc also tries to delete self
1017 then. But we're already deleting self. Double dealloction is
1018 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001019
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001020 Q. Why the bizarre (net-zero) manipulation of
1021 _PyTrash_delete_nesting around the trashcan macros?
1022
1023 A. Some base classes (e.g. list) also use the trashcan mechanism.
1024 The following scenario used to be possible:
1025
1026 - suppose the trashcan level is one below the trashcan limit
1027
1028 - subtype_dealloc() is called
1029
1030 - the trashcan limit is not yet reached, so the trashcan level
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001031 is incremented and the code between trashcan begin and end is
1032 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001033
1034 - this destroys much of the object's contents, including its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001035 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001036
1037 - basedealloc() is called; this is really list_dealloc(), or
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001038 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001039
1040 - the trashcan limit is now reached, so the object is put on the
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001041 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001042
1043 - basedealloc() returns
1044
1045 - subtype_dealloc() decrefs the object's type
1046
1047 - subtype_dealloc() returns
1048
1049 - later, the trashcan code starts deleting the objects from its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001050 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001051
1052 - subtype_dealloc() is called *AGAIN* for the same object
1053
1054 - at the very least (if the destroyed slots and __dict__ don't
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001055 cause problems) the object's type gets decref'ed a second
1056 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001057
1058 The remedy is to make sure that if the code between trashcan
1059 begin and end in subtype_dealloc() is called, the code between
1060 trashcan begin and end in basedealloc() will also be called.
1061 This is done by decrementing the level after passing into the
1062 trashcan block, and incrementing it just before leaving the
1063 block.
1064
1065 But now it's possible that a chain of objects consisting solely
1066 of objects whose deallocator is subtype_dealloc() will defeat
1067 the trashcan mechanism completely: the decremented level means
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001068 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001069 *increment* the level *before* entering the trashcan block, and
1070 matchingly decrement it after leaving. This means the trashcan
1071 code will trigger a little early, but that's no big deal.
1072
1073 Q. Are there any live examples of code in need of all this
1074 complexity?
1075
1076 A. Yes. See SF bug 668433 for code that crashed (when Python was
1077 compiled in debug mode) before the trashcan level manipulations
1078 were added. For more discussion, see SF patches 581742, 575073
1079 and bug 574207.
1080 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001081}
1082
Jeremy Hylton938ace62002-07-17 16:30:39 +00001083static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001084
Tim Peters6d6c1a32001-08-02 04:15:00 +00001085/* type test with subclassing support */
1086
1087int
1088PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1089{
1090 PyObject *mro;
1091
Guido van Rossum9478d072001-09-07 18:52:13 +00001092 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1093 return b == a || b == &PyBaseObject_Type;
1094
Tim Peters6d6c1a32001-08-02 04:15:00 +00001095 mro = a->tp_mro;
1096 if (mro != NULL) {
1097 /* Deal with multiple inheritance without recursion
1098 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001099 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001100 assert(PyTuple_Check(mro));
1101 n = PyTuple_GET_SIZE(mro);
1102 for (i = 0; i < n; i++) {
1103 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1104 return 1;
1105 }
1106 return 0;
1107 }
1108 else {
1109 /* a is not completely initilized yet; follow tp_base */
1110 do {
1111 if (a == b)
1112 return 1;
1113 a = a->tp_base;
1114 } while (a != NULL);
1115 return b == &PyBaseObject_Type;
1116 }
1117}
1118
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001119/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001120 without looking in the instance dictionary
1121 (so we can't use PyObject_GetAttr) but still binding
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001122 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001123 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001124 static variable used to cache the interned Python string.
1125
1126 Two variants:
1127
1128 - lookup_maybe() returns NULL without raising an exception
1129 when the _PyType_Lookup() call fails;
1130
1131 - lookup_method() always raises an exception upon errors.
1132*/
Guido van Rossum60718732001-08-28 17:47:51 +00001133
1134static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001135lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001136{
1137 PyObject *res;
1138
1139 if (*attrobj == NULL) {
Christian Heimes593daf52008-05-26 12:51:38 +00001140 *attrobj = PyBytes_InternFromString(attrstr);
Guido van Rossum60718732001-08-28 17:47:51 +00001141 if (*attrobj == NULL)
1142 return NULL;
1143 }
Christian Heimese93237d2007-12-19 02:37:44 +00001144 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001145 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +00001146 descrgetfunc f;
Christian Heimese93237d2007-12-19 02:37:44 +00001147 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
Guido van Rossum60718732001-08-28 17:47:51 +00001148 Py_INCREF(res);
1149 else
Christian Heimese93237d2007-12-19 02:37:44 +00001150 res = f(res, self, (PyObject *)(Py_TYPE(self)));
Guido van Rossum60718732001-08-28 17:47:51 +00001151 }
1152 return res;
1153}
1154
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001155static PyObject *
1156lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1157{
1158 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1159 if (res == NULL && !PyErr_Occurred())
1160 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1161 return res;
1162}
1163
Guido van Rossum2730b132001-08-28 18:22:14 +00001164/* A variation of PyObject_CallMethod that uses lookup_method()
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001165 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001166 as lookup_method to cache the interned name string object. */
1167
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001168static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001169call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1170{
1171 va_list va;
1172 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001173 va_start(va, format);
1174
Guido van Rossumda21c012001-10-03 00:50:18 +00001175 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001176 if (func == NULL) {
1177 va_end(va);
1178 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +00001179 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001180 return NULL;
1181 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001182
1183 if (format && *format)
1184 args = Py_VaBuildValue(format, va);
1185 else
1186 args = PyTuple_New(0);
1187
1188 va_end(va);
1189
1190 if (args == NULL)
1191 return NULL;
1192
1193 assert(PyTuple_Check(args));
1194 retval = PyObject_Call(func, args, NULL);
1195
1196 Py_DECREF(args);
1197 Py_DECREF(func);
1198
1199 return retval;
1200}
1201
1202/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1203
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001204static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001205call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1206{
1207 va_list va;
1208 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001209 va_start(va, format);
1210
Guido van Rossumda21c012001-10-03 00:50:18 +00001211 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +00001212 if (func == NULL) {
1213 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001214 if (!PyErr_Occurred()) {
1215 Py_INCREF(Py_NotImplemented);
1216 return Py_NotImplemented;
1217 }
Guido van Rossum717ce002001-09-14 16:58:08 +00001218 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001219 }
1220
1221 if (format && *format)
1222 args = Py_VaBuildValue(format, va);
1223 else
1224 args = PyTuple_New(0);
1225
1226 va_end(va);
1227
Guido van Rossum717ce002001-09-14 16:58:08 +00001228 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00001229 return NULL;
1230
Guido van Rossum717ce002001-09-14 16:58:08 +00001231 assert(PyTuple_Check(args));
1232 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001233
1234 Py_DECREF(args);
1235 Py_DECREF(func);
1236
1237 return retval;
1238}
1239
Tim Petersa91e9642001-11-14 23:32:33 +00001240static int
1241fill_classic_mro(PyObject *mro, PyObject *cls)
1242{
1243 PyObject *bases, *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001244 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001245
1246 assert(PyList_Check(mro));
1247 assert(PyClass_Check(cls));
1248 i = PySequence_Contains(mro, cls);
1249 if (i < 0)
1250 return -1;
1251 if (!i) {
1252 if (PyList_Append(mro, cls) < 0)
1253 return -1;
1254 }
1255 bases = ((PyClassObject *)cls)->cl_bases;
1256 assert(bases && PyTuple_Check(bases));
1257 n = PyTuple_GET_SIZE(bases);
1258 for (i = 0; i < n; i++) {
1259 base = PyTuple_GET_ITEM(bases, i);
1260 if (fill_classic_mro(mro, base) < 0)
1261 return -1;
1262 }
1263 return 0;
1264}
1265
1266static PyObject *
1267classic_mro(PyObject *cls)
1268{
1269 PyObject *mro;
1270
1271 assert(PyClass_Check(cls));
1272 mro = PyList_New(0);
1273 if (mro != NULL) {
1274 if (fill_classic_mro(mro, cls) == 0)
1275 return mro;
1276 Py_DECREF(mro);
1277 }
1278 return NULL;
1279}
1280
Tim Petersea7f75d2002-12-07 21:39:16 +00001281/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001282 Method resolution order algorithm C3 described in
1283 "A Monotonic Superclass Linearization for Dylan",
1284 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001285 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001286 (OOPSLA 1996)
1287
Guido van Rossum98f33732002-11-25 21:36:54 +00001288 Some notes about the rules implied by C3:
1289
Tim Petersea7f75d2002-12-07 21:39:16 +00001290 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001291 It isn't legal to repeat a class in a list of base classes.
1292
1293 The next three properties are the 3 constraints in "C3".
1294
Tim Petersea7f75d2002-12-07 21:39:16 +00001295 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001296 If A precedes B in C's MRO, then A will precede B in the MRO of all
1297 subclasses of C.
1298
1299 Monotonicity.
1300 The MRO of a class must be an extension without reordering of the
1301 MRO of each of its superclasses.
1302
1303 Extended Precedence Graph (EPG).
1304 Linearization is consistent if there is a path in the EPG from
1305 each class to all its successors in the linearization. See
1306 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001307 */
1308
Tim Petersea7f75d2002-12-07 21:39:16 +00001309static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001310tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001311 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001312 size = PyList_GET_SIZE(list);
1313
1314 for (j = whence+1; j < size; j++) {
1315 if (PyList_GET_ITEM(list, j) == o)
1316 return 1;
1317 }
1318 return 0;
1319}
1320
Guido van Rossum98f33732002-11-25 21:36:54 +00001321static PyObject *
1322class_name(PyObject *cls)
1323{
1324 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1325 if (name == NULL) {
1326 PyErr_Clear();
1327 Py_XDECREF(name);
1328 name = PyObject_Repr(cls);
1329 }
1330 if (name == NULL)
1331 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00001332 if (!PyBytes_Check(name)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001333 Py_DECREF(name);
1334 return NULL;
1335 }
1336 return name;
1337}
1338
1339static int
1340check_duplicates(PyObject *list)
1341{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001342 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001343 /* Let's use a quadratic time algorithm,
1344 assuming that the bases lists is short.
1345 */
1346 n = PyList_GET_SIZE(list);
1347 for (i = 0; i < n; i++) {
1348 PyObject *o = PyList_GET_ITEM(list, i);
1349 for (j = i + 1; j < n; j++) {
1350 if (PyList_GET_ITEM(list, j) == o) {
1351 o = class_name(o);
1352 PyErr_Format(PyExc_TypeError,
1353 "duplicate base class %s",
Christian Heimes593daf52008-05-26 12:51:38 +00001354 o ? PyBytes_AS_STRING(o) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001355 Py_XDECREF(o);
1356 return -1;
1357 }
1358 }
1359 }
1360 return 0;
1361}
1362
1363/* Raise a TypeError for an MRO order disagreement.
1364
1365 It's hard to produce a good error message. In the absence of better
1366 insight into error reporting, report the classes that were candidates
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001367 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001368 order in which they should be put in the MRO, but it's hard to
1369 diagnose what constraint can't be satisfied.
1370*/
1371
1372static void
1373set_mro_error(PyObject *to_merge, int *remain)
1374{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001375 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001376 char buf[1000];
1377 PyObject *k, *v;
1378 PyObject *set = PyDict_New();
Georg Brandl5c170fd2006-03-17 19:03:25 +00001379 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001380
1381 to_merge_size = PyList_GET_SIZE(to_merge);
1382 for (i = 0; i < to_merge_size; i++) {
1383 PyObject *L = PyList_GET_ITEM(to_merge, i);
1384 if (remain[i] < PyList_GET_SIZE(L)) {
1385 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Georg Brandl5c170fd2006-03-17 19:03:25 +00001386 if (PyDict_SetItem(set, c, Py_None) < 0) {
1387 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001388 return;
Georg Brandl5c170fd2006-03-17 19:03:25 +00001389 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001390 }
1391 }
1392 n = PyDict_Size(set);
1393
Raymond Hettingerf394df42003-04-06 19:13:41 +00001394 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1395consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001396 i = 0;
Skip Montanaro429433b2006-04-18 00:35:43 +00001397 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001398 PyObject *name = class_name(k);
1399 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
Christian Heimes593daf52008-05-26 12:51:38 +00001400 name ? PyBytes_AS_STRING(name) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001401 Py_XDECREF(name);
Skip Montanaro429433b2006-04-18 00:35:43 +00001402 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001403 buf[off++] = ',';
1404 buf[off] = '\0';
1405 }
1406 }
1407 PyErr_SetString(PyExc_TypeError, buf);
1408 Py_DECREF(set);
1409}
1410
Tim Petersea7f75d2002-12-07 21:39:16 +00001411static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001412pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001413 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001414 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001415 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001416
Guido van Rossum1f121312002-11-14 19:49:16 +00001417 to_merge_size = PyList_GET_SIZE(to_merge);
1418
Guido van Rossum98f33732002-11-25 21:36:54 +00001419 /* remain stores an index into each sublist of to_merge.
1420 remain[i] is the index of the next base in to_merge[i]
1421 that is not included in acc.
1422 */
Anthony Baxtera6286212006-04-11 07:42:36 +00001423 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001424 if (remain == NULL)
1425 return -1;
1426 for (i = 0; i < to_merge_size; i++)
1427 remain[i] = 0;
1428
1429 again:
1430 empty_cnt = 0;
1431 for (i = 0; i < to_merge_size; i++) {
1432 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001433
Guido van Rossum1f121312002-11-14 19:49:16 +00001434 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1435
1436 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1437 empty_cnt++;
1438 continue;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001439 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001440
Guido van Rossum98f33732002-11-25 21:36:54 +00001441 /* Choose next candidate for MRO.
1442
1443 The input sequences alone can determine the choice.
1444 If not, choose the class which appears in the MRO
1445 of the earliest direct superclass of the new class.
1446 */
1447
Guido van Rossum1f121312002-11-14 19:49:16 +00001448 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1449 for (j = 0; j < to_merge_size; j++) {
1450 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001451 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001452 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001453 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001454 }
1455 ok = PyList_Append(acc, candidate);
1456 if (ok < 0) {
1457 PyMem_Free(remain);
1458 return -1;
1459 }
1460 for (j = 0; j < to_merge_size; j++) {
1461 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001462 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1463 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001464 remain[j]++;
1465 }
1466 }
1467 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001468 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001469 }
1470
Guido van Rossum98f33732002-11-25 21:36:54 +00001471 if (empty_cnt == to_merge_size) {
1472 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001473 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001474 }
1475 set_mro_error(to_merge, remain);
1476 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001477 return -1;
1478}
1479
Tim Peters6d6c1a32001-08-02 04:15:00 +00001480static PyObject *
1481mro_implementation(PyTypeObject *type)
1482{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001483 Py_ssize_t i, n;
1484 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001485 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001486 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001487
Neal Norwitze7bb9182008-01-27 17:10:14 +00001488 if (type->tp_dict == NULL) {
1489 if (PyType_Ready(type) < 0)
Guido van Rossum63517572002-06-18 16:44:57 +00001490 return NULL;
1491 }
1492
Guido van Rossum98f33732002-11-25 21:36:54 +00001493 /* Find a superclass linearization that honors the constraints
1494 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001495 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001496
1497 to_merge is a list of lists, where each list is a superclass
1498 linearization implied by a base class. The last element of
1499 to_merge is the declared list of bases.
1500 */
1501
Tim Peters6d6c1a32001-08-02 04:15:00 +00001502 bases = type->tp_bases;
1503 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001504
1505 to_merge = PyList_New(n+1);
1506 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001507 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001508
Tim Peters6d6c1a32001-08-02 04:15:00 +00001509 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001510 PyObject *base = PyTuple_GET_ITEM(bases, i);
1511 PyObject *parentMRO;
1512 if (PyType_Check(base))
1513 parentMRO = PySequence_List(
1514 ((PyTypeObject*)base)->tp_mro);
1515 else
1516 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001517 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001518 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001519 return NULL;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001520 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001521
1522 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001523 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001524
1525 bases_aslist = PySequence_List(bases);
1526 if (bases_aslist == NULL) {
1527 Py_DECREF(to_merge);
1528 return NULL;
1529 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001530 /* This is just a basic sanity check. */
1531 if (check_duplicates(bases_aslist) < 0) {
1532 Py_DECREF(to_merge);
1533 Py_DECREF(bases_aslist);
1534 return NULL;
1535 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001536 PyList_SET_ITEM(to_merge, n, bases_aslist);
1537
1538 result = Py_BuildValue("[O]", (PyObject *)type);
1539 if (result == NULL) {
1540 Py_DECREF(to_merge);
1541 return NULL;
1542 }
1543
1544 ok = pmerge(result, to_merge);
1545 Py_DECREF(to_merge);
1546 if (ok < 0) {
1547 Py_DECREF(result);
1548 return NULL;
1549 }
1550
Tim Peters6d6c1a32001-08-02 04:15:00 +00001551 return result;
1552}
1553
1554static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001555mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001556{
1557 PyTypeObject *type = (PyTypeObject *)self;
1558
Tim Peters6d6c1a32001-08-02 04:15:00 +00001559 return mro_implementation(type);
1560}
1561
1562static int
1563mro_internal(PyTypeObject *type)
1564{
1565 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001566 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001567
Christian Heimese93237d2007-12-19 02:37:44 +00001568 if (Py_TYPE(type) == &PyType_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001569 result = mro_implementation(type);
1570 }
1571 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001572 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001573 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001574 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001575 if (mro == NULL)
1576 return -1;
1577 result = PyObject_CallObject(mro, NULL);
1578 Py_DECREF(mro);
1579 }
1580 if (result == NULL)
1581 return -1;
1582 tuple = PySequence_Tuple(result);
1583 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001584 if (tuple == NULL)
1585 return -1;
1586 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001587 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001588 PyObject *cls;
1589 PyTypeObject *solid;
1590
1591 solid = solid_base(type);
1592
1593 len = PyTuple_GET_SIZE(tuple);
1594
1595 for (i = 0; i < len; i++) {
1596 PyTypeObject *t;
1597 cls = PyTuple_GET_ITEM(tuple, i);
1598 if (PyClass_Check(cls))
1599 continue;
1600 else if (!PyType_Check(cls)) {
1601 PyErr_Format(PyExc_TypeError,
1602 "mro() returned a non-class ('%.500s')",
Christian Heimese93237d2007-12-19 02:37:44 +00001603 Py_TYPE(cls)->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001604 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001605 return -1;
1606 }
1607 t = (PyTypeObject*)cls;
1608 if (!PyType_IsSubtype(solid, solid_base(t))) {
1609 PyErr_Format(PyExc_TypeError,
1610 "mro() returned base with unsuitable layout ('%.500s')",
1611 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001612 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001613 return -1;
1614 }
1615 }
1616 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001617 type->tp_mro = tuple;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001618
1619 type_mro_modified(type, type->tp_mro);
1620 /* corner case: the old-style super class might have been hidden
1621 from the custom MRO */
1622 type_mro_modified(type, type->tp_bases);
1623
Georg Brandl74a1dea2008-05-28 11:21:39 +00001624 PyType_Modified(type);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001625
Tim Peters6d6c1a32001-08-02 04:15:00 +00001626 return 0;
1627}
1628
1629
1630/* Calculate the best base amongst multiple base classes.
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001631 This is the first one that's on the path to the "solid base". */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001632
1633static PyTypeObject *
1634best_base(PyObject *bases)
1635{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001636 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001637 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001638 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001639
1640 assert(PyTuple_Check(bases));
1641 n = PyTuple_GET_SIZE(bases);
1642 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001643 base = NULL;
1644 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001646 base_proto = PyTuple_GET_ITEM(bases, i);
1647 if (PyClass_Check(base_proto))
1648 continue;
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001649 if (!PyType_Check(base_proto)) {
1650 PyErr_SetString(
1651 PyExc_TypeError,
1652 "bases must be types");
1653 return NULL;
1654 }
Tim Petersa91e9642001-11-14 23:32:33 +00001655 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001656 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001657 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001658 return NULL;
1659 }
1660 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001661 if (winner == NULL) {
1662 winner = candidate;
1663 base = base_i;
1664 }
1665 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001666 ;
1667 else if (PyType_IsSubtype(candidate, winner)) {
1668 winner = candidate;
1669 base = base_i;
1670 }
1671 else {
1672 PyErr_SetString(
1673 PyExc_TypeError,
1674 "multiple bases have "
1675 "instance lay-out conflict");
1676 return NULL;
1677 }
1678 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001679 if (base == NULL)
1680 PyErr_SetString(PyExc_TypeError,
1681 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001682 return base;
1683}
1684
1685static int
1686extra_ivars(PyTypeObject *type, PyTypeObject *base)
1687{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001688 size_t t_size = type->tp_basicsize;
1689 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690
Guido van Rossum9676b222001-08-17 20:32:36 +00001691 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001692 if (type->tp_itemsize || base->tp_itemsize) {
1693 /* If itemsize is involved, stricter rules */
1694 return t_size != b_size ||
1695 type->tp_itemsize != base->tp_itemsize;
1696 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001697 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001698 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1699 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001700 t_size -= sizeof(PyObject *);
1701 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001702 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1703 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001704 t_size -= sizeof(PyObject *);
1705
1706 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001707}
1708
1709static PyTypeObject *
1710solid_base(PyTypeObject *type)
1711{
1712 PyTypeObject *base;
1713
1714 if (type->tp_base)
1715 base = solid_base(type->tp_base);
1716 else
1717 base = &PyBaseObject_Type;
1718 if (extra_ivars(type, base))
1719 return type;
1720 else
1721 return base;
1722}
1723
Jeremy Hylton938ace62002-07-17 16:30:39 +00001724static void object_dealloc(PyObject *);
1725static int object_init(PyObject *, PyObject *, PyObject *);
1726static int update_slot(PyTypeObject *, PyObject *);
1727static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001728
Armin Rigo9790a272007-05-02 19:23:31 +00001729/*
1730 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1731 * inherited from various builtin types. The builtin base usually provides
1732 * its own __dict__ descriptor, so we use that when we can.
1733 */
1734static PyTypeObject *
1735get_builtin_base_with_dict(PyTypeObject *type)
1736{
1737 while (type->tp_base != NULL) {
1738 if (type->tp_dictoffset != 0 &&
1739 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1740 return type;
1741 type = type->tp_base;
1742 }
1743 return NULL;
1744}
1745
1746static PyObject *
1747get_dict_descriptor(PyTypeObject *type)
1748{
1749 static PyObject *dict_str;
1750 PyObject *descr;
1751
1752 if (dict_str == NULL) {
Christian Heimes593daf52008-05-26 12:51:38 +00001753 dict_str = PyBytes_InternFromString("__dict__");
Armin Rigo9790a272007-05-02 19:23:31 +00001754 if (dict_str == NULL)
1755 return NULL;
1756 }
1757 descr = _PyType_Lookup(type, dict_str);
1758 if (descr == NULL || !PyDescr_IsData(descr))
1759 return NULL;
1760
1761 return descr;
1762}
1763
1764static void
1765raise_dict_descr_error(PyObject *obj)
1766{
1767 PyErr_Format(PyExc_TypeError,
1768 "this __dict__ descriptor does not support "
1769 "'%.200s' objects", obj->ob_type->tp_name);
1770}
1771
Tim Peters6d6c1a32001-08-02 04:15:00 +00001772static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001773subtype_dict(PyObject *obj, void *context)
1774{
Armin Rigo9790a272007-05-02 19:23:31 +00001775 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001776 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001777 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001778
Armin Rigo9790a272007-05-02 19:23:31 +00001779 base = get_builtin_base_with_dict(obj->ob_type);
1780 if (base != NULL) {
1781 descrgetfunc func;
1782 PyObject *descr = get_dict_descriptor(base);
1783 if (descr == NULL) {
1784 raise_dict_descr_error(obj);
1785 return NULL;
1786 }
1787 func = descr->ob_type->tp_descr_get;
1788 if (func == NULL) {
1789 raise_dict_descr_error(obj);
1790 return NULL;
1791 }
1792 return func(descr, obj, (PyObject *)(obj->ob_type));
1793 }
1794
1795 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001796 if (dictptr == NULL) {
1797 PyErr_SetString(PyExc_AttributeError,
1798 "This object has no __dict__");
1799 return NULL;
1800 }
1801 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001802 if (dict == NULL)
1803 *dictptr = dict = PyDict_New();
1804 Py_XINCREF(dict);
1805 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001806}
1807
Guido van Rossum6661be32001-10-26 04:26:12 +00001808static int
1809subtype_setdict(PyObject *obj, PyObject *value, void *context)
1810{
Armin Rigo9790a272007-05-02 19:23:31 +00001811 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001812 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001813 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001814
Armin Rigo9790a272007-05-02 19:23:31 +00001815 base = get_builtin_base_with_dict(obj->ob_type);
1816 if (base != NULL) {
1817 descrsetfunc func;
1818 PyObject *descr = get_dict_descriptor(base);
1819 if (descr == NULL) {
1820 raise_dict_descr_error(obj);
1821 return -1;
1822 }
1823 func = descr->ob_type->tp_descr_set;
1824 if (func == NULL) {
1825 raise_dict_descr_error(obj);
1826 return -1;
1827 }
1828 return func(descr, obj, value);
1829 }
1830
1831 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001832 if (dictptr == NULL) {
1833 PyErr_SetString(PyExc_AttributeError,
1834 "This object has no __dict__");
1835 return -1;
1836 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001837 if (value != NULL && !PyDict_Check(value)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001838 PyErr_Format(PyExc_TypeError,
1839 "__dict__ must be set to a dictionary, "
Christian Heimese93237d2007-12-19 02:37:44 +00001840 "not a '%.200s'", Py_TYPE(value)->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001841 return -1;
1842 }
1843 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001844 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001845 *dictptr = value;
1846 Py_XDECREF(dict);
1847 return 0;
1848}
1849
Guido van Rossumad47da02002-08-12 19:05:44 +00001850static PyObject *
1851subtype_getweakref(PyObject *obj, void *context)
1852{
1853 PyObject **weaklistptr;
1854 PyObject *result;
1855
Christian Heimese93237d2007-12-19 02:37:44 +00001856 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001857 PyErr_SetString(PyExc_AttributeError,
Fred Drake7a36f5f2006-08-04 05:17:21 +00001858 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001859 return NULL;
1860 }
Christian Heimese93237d2007-12-19 02:37:44 +00001861 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1862 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1863 (size_t)(Py_TYPE(obj)->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001864 weaklistptr = (PyObject **)
Christian Heimese93237d2007-12-19 02:37:44 +00001865 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001866 if (*weaklistptr == NULL)
1867 result = Py_None;
1868 else
1869 result = *weaklistptr;
1870 Py_INCREF(result);
1871 return result;
1872}
1873
Guido van Rossum373c7412003-01-07 13:41:37 +00001874/* Three variants on the subtype_getsets list. */
1875
1876static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001877 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001878 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001879 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001880 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001881 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001882};
1883
Guido van Rossum373c7412003-01-07 13:41:37 +00001884static PyGetSetDef subtype_getsets_dict_only[] = {
1885 {"__dict__", subtype_dict, subtype_setdict,
1886 PyDoc_STR("dictionary for instance variables (if defined)")},
1887 {0}
1888};
1889
1890static PyGetSetDef subtype_getsets_weakref_only[] = {
1891 {"__weakref__", subtype_getweakref, NULL,
1892 PyDoc_STR("list of weak references to the object (if defined)")},
1893 {0}
1894};
1895
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001896static int
1897valid_identifier(PyObject *s)
1898{
Guido van Rossum03013a02002-07-16 14:30:28 +00001899 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001900 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001901
Christian Heimes593daf52008-05-26 12:51:38 +00001902 if (!PyBytes_Check(s)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001903 PyErr_Format(PyExc_TypeError,
1904 "__slots__ items must be strings, not '%.200s'",
Christian Heimese93237d2007-12-19 02:37:44 +00001905 Py_TYPE(s)->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001906 return 0;
1907 }
Christian Heimes593daf52008-05-26 12:51:38 +00001908 p = (unsigned char *) PyBytes_AS_STRING(s);
1909 n = PyBytes_GET_SIZE(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001910 /* We must reject an empty name. As a hack, we bump the
1911 length to 1 so that the loop will balk on the trailing \0. */
1912 if (n == 0)
1913 n = 1;
1914 for (i = 0; i < n; i++, p++) {
1915 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1916 PyErr_SetString(PyExc_TypeError,
1917 "__slots__ must be identifiers");
1918 return 0;
1919 }
1920 }
1921 return 1;
1922}
1923
Martin v. Löwisd919a592002-10-14 21:07:28 +00001924#ifdef Py_USING_UNICODE
1925/* Replace Unicode objects in slots. */
1926
1927static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001928_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001929{
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001930 PyObject *tmp = NULL;
1931 PyObject *slot_name, *new_name;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001932 Py_ssize_t i;
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001933
Martin v. Löwisd919a592002-10-14 21:07:28 +00001934 for (i = 0; i < nslots; i++) {
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001935 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1936 if (tmp == NULL) {
1937 tmp = PySequence_List(slots);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001938 if (tmp == NULL)
1939 return NULL;
1940 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001941 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1942 NULL);
1943 if (new_name == NULL) {
Martin v. Löwisd919a592002-10-14 21:07:28 +00001944 Py_DECREF(tmp);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001945 return NULL;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001946 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001947 Py_INCREF(new_name);
1948 PyList_SET_ITEM(tmp, i, new_name);
1949 Py_DECREF(slot_name);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001950 }
1951 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001952 if (tmp != NULL) {
1953 slots = PyList_AsTuple(tmp);
1954 Py_DECREF(tmp);
1955 }
1956 return slots;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001957}
1958#endif
1959
Guido van Rossumf102e242007-03-23 18:53:03 +00001960/* Forward */
1961static int
1962object_init(PyObject *self, PyObject *args, PyObject *kwds);
1963
1964static int
1965type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1966{
1967 int res;
1968
1969 assert(args != NULL && PyTuple_Check(args));
1970 assert(kwds == NULL || PyDict_Check(kwds));
1971
1972 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1973 PyErr_SetString(PyExc_TypeError,
1974 "type.__init__() takes no keyword arguments");
1975 return -1;
1976 }
1977
1978 if (args != NULL && PyTuple_Check(args) &&
1979 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1980 PyErr_SetString(PyExc_TypeError,
1981 "type.__init__() takes 1 or 3 arguments");
1982 return -1;
1983 }
1984
1985 /* Call object.__init__(self) now. */
1986 /* XXX Could call super(type, cls).__init__() but what's the point? */
1987 args = PyTuple_GetSlice(args, 0, 0);
1988 res = object_init(cls, args, NULL);
1989 Py_DECREF(args);
1990 return res;
1991}
1992
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001993static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001994type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1995{
1996 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001997 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001998 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001999 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002000 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00002001 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002002 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00002003 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002004
Tim Peters3abca122001-10-27 19:37:48 +00002005 assert(args != NULL && PyTuple_Check(args));
2006 assert(kwds == NULL || PyDict_Check(kwds));
2007
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00002008 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00002009 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002010 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2011 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002012
2013 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2014 PyObject *x = PyTuple_GET_ITEM(args, 0);
Christian Heimese93237d2007-12-19 02:37:44 +00002015 Py_INCREF(Py_TYPE(x));
2016 return (PyObject *) Py_TYPE(x);
Tim Peters3abca122001-10-27 19:37:48 +00002017 }
2018
2019 /* SF bug 475327 -- if that didn't trigger, we need 3
2020 arguments. but PyArg_ParseTupleAndKeywords below may give
2021 a msg saying type() needs exactly 3. */
2022 if (nargs + nkwds != 3) {
2023 PyErr_SetString(PyExc_TypeError,
2024 "type() takes 1 or 3 arguments");
2025 return NULL;
2026 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002027 }
2028
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00002029 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002030 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
2031 &name,
2032 &PyTuple_Type, &bases,
2033 &PyDict_Type, &dict))
2034 return NULL;
2035
Armin Rigoc0ba52d2007-04-19 14:44:48 +00002036 /* Determine the proper metatype to deal with this,
2037 and check for metatype conflicts while we're at it.
2038 Note that if some other metatype wins to contract,
2039 it's possible that its instances are not types. */
2040 nbases = PyTuple_GET_SIZE(bases);
2041 winner = metatype;
2042 for (i = 0; i < nbases; i++) {
2043 tmp = PyTuple_GET_ITEM(bases, i);
2044 tmptype = tmp->ob_type;
2045 if (tmptype == &PyClass_Type)
2046 continue; /* Special case classic classes */
2047 if (PyType_IsSubtype(winner, tmptype))
2048 continue;
2049 if (PyType_IsSubtype(tmptype, winner)) {
2050 winner = tmptype;
2051 continue;
Jeremy Hyltonfa955692007-02-27 18:29:45 +00002052 }
Armin Rigoc0ba52d2007-04-19 14:44:48 +00002053 PyErr_SetString(PyExc_TypeError,
2054 "metaclass conflict: "
2055 "the metaclass of a derived class "
2056 "must be a (non-strict) subclass "
2057 "of the metaclasses of all its bases");
2058 return NULL;
2059 }
2060 if (winner != metatype) {
2061 if (winner->tp_new != type_new) /* Pass it to the winner */
2062 return winner->tp_new(winner, args, kwds);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00002063 metatype = winner;
2064 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002065
2066 /* Adjust for empty tuple bases */
2067 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002068 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002069 if (bases == NULL)
2070 return NULL;
2071 nbases = 1;
2072 }
2073 else
2074 Py_INCREF(bases);
2075
2076 /* XXX From here until type is allocated, "return NULL" leaks bases! */
2077
2078 /* Calculate best base, and check that all bases are type objects */
2079 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002080 if (base == NULL) {
2081 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002082 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002083 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002084 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2085 PyErr_Format(PyExc_TypeError,
2086 "type '%.100s' is not an acceptable base type",
2087 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002088 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002089 return NULL;
2090 }
2091
Tim Peters6d6c1a32001-08-02 04:15:00 +00002092 /* Check for a __slots__ sequence variable in dict, and count it */
2093 slots = PyDict_GetItemString(dict, "__slots__");
2094 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00002095 add_dict = 0;
2096 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00002097 may_add_dict = base->tp_dictoffset == 0;
2098 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2099 if (slots == NULL) {
2100 if (may_add_dict) {
2101 add_dict++;
2102 }
2103 if (may_add_weak) {
2104 add_weak++;
2105 }
2106 }
2107 else {
2108 /* Have slots */
2109
Tim Peters6d6c1a32001-08-02 04:15:00 +00002110 /* Make it into a tuple */
Christian Heimes593daf52008-05-26 12:51:38 +00002111 if (PyBytes_Check(slots) || PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002112 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002113 else
2114 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002115 if (slots == NULL) {
2116 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002117 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002118 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002119 assert(PyTuple_Check(slots));
2120
2121 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002122 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00002123 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00002124 PyErr_Format(PyExc_TypeError,
2125 "nonempty __slots__ "
2126 "not supported for subtype of '%s'",
2127 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00002128 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002129 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00002130 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00002131 return NULL;
2132 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002133
Martin v. Löwisd919a592002-10-14 21:07:28 +00002134#ifdef Py_USING_UNICODE
2135 tmp = _unicode_to_string(slots, nslots);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00002136 if (tmp == NULL)
2137 goto bad_slots;
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00002138 if (tmp != slots) {
2139 Py_DECREF(slots);
2140 slots = tmp;
2141 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00002142#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00002143 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002144 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00002145 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2146 char *s;
2147 if (!valid_identifier(tmp))
2148 goto bad_slots;
Christian Heimes593daf52008-05-26 12:51:38 +00002149 assert(PyBytes_Check(tmp));
2150 s = PyBytes_AS_STRING(tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00002151 if (strcmp(s, "__dict__") == 0) {
2152 if (!may_add_dict || add_dict) {
2153 PyErr_SetString(PyExc_TypeError,
2154 "__dict__ slot disallowed: "
2155 "we already got one");
2156 goto bad_slots;
2157 }
2158 add_dict++;
2159 }
2160 if (strcmp(s, "__weakref__") == 0) {
2161 if (!may_add_weak || add_weak) {
2162 PyErr_SetString(PyExc_TypeError,
2163 "__weakref__ slot disallowed: "
2164 "either we already got one, "
2165 "or __itemsize__ != 0");
2166 goto bad_slots;
2167 }
2168 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002169 }
2170 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002171
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002172 /* Copy slots into a list, mangle names and sort them.
2173 Sorted names are needed for __class__ assignment.
2174 Convert them back to tuple at the end.
2175 */
2176 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002177 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00002178 goto bad_slots;
2179 for (i = j = 0; i < nslots; i++) {
2180 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002181 tmp = PyTuple_GET_ITEM(slots, i);
Christian Heimes593daf52008-05-26 12:51:38 +00002182 s = PyBytes_AS_STRING(tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00002183 if ((add_dict && strcmp(s, "__dict__") == 0) ||
2184 (add_weak && strcmp(s, "__weakref__") == 0))
2185 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002186 tmp =_Py_Mangle(name, tmp);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002187 if (!tmp)
2188 goto bad_slots;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002189 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00002190 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002191 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002192 assert(j == nslots - add_dict - add_weak);
2193 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002194 Py_DECREF(slots);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002195 if (PyList_Sort(newslots) == -1) {
2196 Py_DECREF(bases);
2197 Py_DECREF(newslots);
2198 return NULL;
2199 }
2200 slots = PyList_AsTuple(newslots);
2201 Py_DECREF(newslots);
2202 if (slots == NULL) {
2203 Py_DECREF(bases);
2204 return NULL;
2205 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002206
Guido van Rossumad47da02002-08-12 19:05:44 +00002207 /* Secondary bases may provide weakrefs or dict */
2208 if (nbases > 1 &&
2209 ((may_add_dict && !add_dict) ||
2210 (may_add_weak && !add_weak))) {
2211 for (i = 0; i < nbases; i++) {
2212 tmp = PyTuple_GET_ITEM(bases, i);
2213 if (tmp == (PyObject *)base)
2214 continue; /* Skip primary base */
2215 if (PyClass_Check(tmp)) {
2216 /* Classic base class provides both */
2217 if (may_add_dict && !add_dict)
2218 add_dict++;
2219 if (may_add_weak && !add_weak)
2220 add_weak++;
2221 break;
2222 }
2223 assert(PyType_Check(tmp));
2224 tmptype = (PyTypeObject *)tmp;
2225 if (may_add_dict && !add_dict &&
2226 tmptype->tp_dictoffset != 0)
2227 add_dict++;
2228 if (may_add_weak && !add_weak &&
2229 tmptype->tp_weaklistoffset != 0)
2230 add_weak++;
2231 if (may_add_dict && !add_dict)
2232 continue;
2233 if (may_add_weak && !add_weak)
2234 continue;
2235 /* Nothing more to check */
2236 break;
2237 }
2238 }
Guido van Rossum9676b222001-08-17 20:32:36 +00002239 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002240
2241 /* XXX From here until type is safely allocated,
2242 "return NULL" may leak slots! */
2243
2244 /* Allocate the type object */
2245 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00002246 if (type == NULL) {
2247 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002248 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002249 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00002250 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002251
2252 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002253 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002254 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002255 et->ht_name = name;
2256 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002257
Guido van Rossumdc91b992001-08-08 22:26:22 +00002258 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002259 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2260 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002261 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2262 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002263
2264 /* It's a new-style number unless it specifically inherits any
2265 old-style numeric behavior */
2266 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
2267 (base->tp_as_number == NULL))
2268 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
2269
2270 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002271 type->tp_as_number = &et->as_number;
2272 type->tp_as_sequence = &et->as_sequence;
2273 type->tp_as_mapping = &et->as_mapping;
2274 type->tp_as_buffer = &et->as_buffer;
Christian Heimes593daf52008-05-26 12:51:38 +00002275 type->tp_name = PyBytes_AS_STRING(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002276
2277 /* Set tp_base and tp_bases */
2278 type->tp_bases = bases;
2279 Py_INCREF(base);
2280 type->tp_base = base;
2281
Guido van Rossum687ae002001-10-15 22:03:32 +00002282 /* Initialize tp_dict from passed-in dict */
2283 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002284 if (dict == NULL) {
2285 Py_DECREF(type);
2286 return NULL;
2287 }
2288
Guido van Rossumc3542212001-08-16 09:18:56 +00002289 /* Set __module__ in the dict */
2290 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2291 tmp = PyEval_GetGlobals();
2292 if (tmp != NULL) {
2293 tmp = PyDict_GetItemString(tmp, "__name__");
2294 if (tmp != NULL) {
2295 if (PyDict_SetItemString(dict, "__module__",
2296 tmp) < 0)
2297 return NULL;
2298 }
2299 }
2300 }
2301
Tim Peters2f93e282001-10-04 05:27:00 +00002302 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00002303 and is a string. The __doc__ accessor will first look for tp_doc;
2304 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00002305 */
2306 {
2307 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
Christian Heimes593daf52008-05-26 12:51:38 +00002308 if (doc != NULL && PyBytes_Check(doc)) {
2309 const size_t n = (size_t)PyBytes_GET_SIZE(doc);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002310 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002311 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00002312 Py_DECREF(type);
2313 return NULL;
2314 }
Christian Heimes593daf52008-05-26 12:51:38 +00002315 memcpy(tp_doc, PyBytes_AS_STRING(doc), n+1);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002316 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00002317 }
2318 }
2319
Tim Peters6d6c1a32001-08-02 04:15:00 +00002320 /* Special-case __new__: if it's a plain function,
2321 make it a static function */
2322 tmp = PyDict_GetItemString(dict, "__new__");
2323 if (tmp != NULL && PyFunction_Check(tmp)) {
2324 tmp = PyStaticMethod_New(tmp);
2325 if (tmp == NULL) {
2326 Py_DECREF(type);
2327 return NULL;
2328 }
2329 PyDict_SetItemString(dict, "__new__", tmp);
2330 Py_DECREF(tmp);
2331 }
2332
2333 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002334 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00002335 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002336 if (slots != NULL) {
2337 for (i = 0; i < nslots; i++, mp++) {
Christian Heimes593daf52008-05-26 12:51:38 +00002338 mp->name = PyBytes_AS_STRING(
Tim Peters6d6c1a32001-08-02 04:15:00 +00002339 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00002340 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002341 mp->offset = slotoffset;
Žiga Seilnacht89032082007-03-11 15:54:54 +00002342
2343 /* __dict__ and __weakref__ are already filtered out */
2344 assert(strcmp(mp->name, "__dict__") != 0);
2345 assert(strcmp(mp->name, "__weakref__") != 0);
2346
Tim Peters6d6c1a32001-08-02 04:15:00 +00002347 slotoffset += sizeof(PyObject *);
2348 }
2349 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002350 if (add_dict) {
2351 if (base->tp_itemsize)
2352 type->tp_dictoffset = -(long)sizeof(PyObject *);
2353 else
2354 type->tp_dictoffset = slotoffset;
2355 slotoffset += sizeof(PyObject *);
2356 }
2357 if (add_weak) {
2358 assert(!base->tp_itemsize);
2359 type->tp_weaklistoffset = slotoffset;
2360 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002361 }
2362 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002363 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002364 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002365
2366 if (type->tp_weaklistoffset && type->tp_dictoffset)
2367 type->tp_getset = subtype_getsets_full;
2368 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2369 type->tp_getset = subtype_getsets_weakref_only;
2370 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2371 type->tp_getset = subtype_getsets_dict_only;
2372 else
2373 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002374
2375 /* Special case some slots */
2376 if (type->tp_dictoffset != 0 || nslots > 0) {
2377 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2378 type->tp_getattro = PyObject_GenericGetAttr;
2379 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2380 type->tp_setattro = PyObject_GenericSetAttr;
2381 }
2382 type->tp_dealloc = subtype_dealloc;
2383
Guido van Rossum9475a232001-10-05 20:51:39 +00002384 /* Enable GC unless there are really no instance variables possible */
2385 if (!(type->tp_basicsize == sizeof(PyObject) &&
2386 type->tp_itemsize == 0))
2387 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2388
Tim Peters6d6c1a32001-08-02 04:15:00 +00002389 /* Always override allocation strategy to use regular heap */
2390 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002391 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002392 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002393 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002394 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002395 }
2396 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002397 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002398
2399 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002400 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002401 Py_DECREF(type);
2402 return NULL;
2403 }
2404
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002405 /* Put the proper slots in place */
2406 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002407
Tim Peters6d6c1a32001-08-02 04:15:00 +00002408 return (PyObject *)type;
2409}
2410
2411/* Internal API to look for a name through the MRO.
2412 This returns a borrowed reference, and doesn't set an exception! */
2413PyObject *
2414_PyType_Lookup(PyTypeObject *type, PyObject *name)
2415{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002416 Py_ssize_t i, n;
Georg Brandl5ec330c2008-05-28 15:41:36 +00002417 PyObject *mro, *res, *base, *dict, *tmp;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002418 unsigned int h;
2419
2420 if (MCACHE_CACHEABLE_NAME(name) &&
Neal Norwitze7bb9182008-01-27 17:10:14 +00002421 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002422 /* fast path */
2423 h = MCACHE_HASH_METHOD(type, name);
2424 if (method_cache[h].version == type->tp_version_tag &&
2425 method_cache[h].name == name)
2426 return method_cache[h].value;
2427 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002428
Guido van Rossum687ae002001-10-15 22:03:32 +00002429 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002430 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002431
2432 /* If mro is NULL, the type is either not yet initialized
2433 by PyType_Ready(), or already cleared by type_clear().
2434 Either way the safest thing to do is to return NULL. */
2435 if (mro == NULL)
2436 return NULL;
2437
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002438 res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002439 assert(PyTuple_Check(mro));
2440 n = PyTuple_GET_SIZE(mro);
2441 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002442 base = PyTuple_GET_ITEM(mro, i);
2443 if (PyClass_Check(base))
2444 dict = ((PyClassObject *)base)->cl_dict;
2445 else {
2446 assert(PyType_Check(base));
2447 dict = ((PyTypeObject *)base)->tp_dict;
2448 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002449 assert(dict && PyDict_Check(dict));
2450 res = PyDict_GetItem(dict, name);
2451 if (res != NULL)
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002452 break;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002453 }
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002454
2455 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2456 h = MCACHE_HASH_METHOD(type, name);
2457 method_cache[h].version = type->tp_version_tag;
2458 method_cache[h].value = res; /* borrowed */
Georg Brandl5ec330c2008-05-28 15:41:36 +00002459 tmp = method_cache[h].name;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002460 Py_INCREF(name);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002461 method_cache[h].name = name;
Georg Brandl5ec330c2008-05-28 15:41:36 +00002462 Py_DECREF(tmp);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002463 }
2464 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002465}
2466
2467/* This is similar to PyObject_GenericGetAttr(),
2468 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2469static PyObject *
2470type_getattro(PyTypeObject *type, PyObject *name)
2471{
Christian Heimese93237d2007-12-19 02:37:44 +00002472 PyTypeObject *metatype = Py_TYPE(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002473 PyObject *meta_attribute, *attribute;
2474 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002475
2476 /* Initialize this type (we'll assume the metatype is initialized) */
2477 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002478 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002479 return NULL;
2480 }
2481
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002482 /* No readable descriptor found yet */
2483 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002484
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002485 /* Look for the attribute in the metatype */
2486 meta_attribute = _PyType_Lookup(metatype, name);
2487
2488 if (meta_attribute != NULL) {
Christian Heimese93237d2007-12-19 02:37:44 +00002489 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002490
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002491 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2492 /* Data descriptors implement tp_descr_set to intercept
2493 * writes. Assume the attribute is not overridden in
2494 * type's tp_dict (and bases): call the descriptor now.
2495 */
2496 return meta_get(meta_attribute, (PyObject *)type,
2497 (PyObject *)metatype);
2498 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002499 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002500 }
2501
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002502 /* No data descriptor found on metatype. Look in tp_dict of this
2503 * type and its bases */
2504 attribute = _PyType_Lookup(type, name);
2505 if (attribute != NULL) {
2506 /* Implement descriptor functionality, if any */
Christian Heimese93237d2007-12-19 02:37:44 +00002507 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002508
2509 Py_XDECREF(meta_attribute);
2510
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002511 if (local_get != NULL) {
2512 /* NULL 2nd argument indicates the descriptor was
2513 * found on the target object itself (or a base) */
2514 return local_get(attribute, (PyObject *)NULL,
2515 (PyObject *)type);
2516 }
Tim Peters34592512002-07-11 06:23:50 +00002517
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002518 Py_INCREF(attribute);
2519 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002520 }
2521
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002522 /* No attribute found in local __dict__ (or bases): use the
2523 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002524 if (meta_get != NULL) {
2525 PyObject *res;
2526 res = meta_get(meta_attribute, (PyObject *)type,
2527 (PyObject *)metatype);
2528 Py_DECREF(meta_attribute);
2529 return res;
2530 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002531
2532 /* If an ordinary attribute was found on the metatype, return it now */
2533 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002534 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002535 }
2536
2537 /* Give up */
2538 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002539 "type object '%.50s' has no attribute '%.400s'",
Christian Heimes593daf52008-05-26 12:51:38 +00002540 type->tp_name, PyBytes_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002541 return NULL;
2542}
2543
2544static int
2545type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2546{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002547 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2548 PyErr_Format(
2549 PyExc_TypeError,
2550 "can't set attributes of built-in/extension type '%s'",
2551 type->tp_name);
2552 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002553 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002554 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2555 return -1;
2556 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002557}
2558
2559static void
2560type_dealloc(PyTypeObject *type)
2561{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002562 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002563
2564 /* Assert this is a heap-allocated type object */
2565 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002566 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002567 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002568 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002569 Py_XDECREF(type->tp_base);
2570 Py_XDECREF(type->tp_dict);
2571 Py_XDECREF(type->tp_bases);
2572 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002573 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002574 Py_XDECREF(type->tp_subclasses);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002575 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2576 * of most other objects. It's okay to cast it to char *.
2577 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002578 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002579 Py_XDECREF(et->ht_name);
2580 Py_XDECREF(et->ht_slots);
Christian Heimese93237d2007-12-19 02:37:44 +00002581 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002582}
2583
Guido van Rossum1c450732001-10-08 15:18:27 +00002584static PyObject *
2585type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2586{
2587 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002588 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002589
2590 list = PyList_New(0);
2591 if (list == NULL)
2592 return NULL;
2593 raw = type->tp_subclasses;
2594 if (raw == NULL)
2595 return list;
2596 assert(PyList_Check(raw));
2597 n = PyList_GET_SIZE(raw);
2598 for (i = 0; i < n; i++) {
2599 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002600 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002601 ref = PyWeakref_GET_OBJECT(ref);
2602 if (ref != Py_None) {
2603 if (PyList_Append(list, ref) < 0) {
2604 Py_DECREF(list);
2605 return NULL;
2606 }
2607 }
2608 }
2609 return list;
2610}
2611
Tim Peters6d6c1a32001-08-02 04:15:00 +00002612static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002613 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002614 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002615 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002616 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002617 {0}
2618};
2619
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002620PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002621"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002622"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002623
Guido van Rossum048eb752001-10-02 21:24:57 +00002624static int
2625type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2626{
Guido van Rossuma3862092002-06-10 15:24:42 +00002627 /* Because of type_is_gc(), the collector only calls this
2628 for heaptypes. */
2629 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002630
Thomas Woutersc6e55062006-04-15 21:47:09 +00002631 Py_VISIT(type->tp_dict);
2632 Py_VISIT(type->tp_cache);
2633 Py_VISIT(type->tp_mro);
2634 Py_VISIT(type->tp_bases);
2635 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002636
2637 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002638 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002639 in cycles; tp_subclasses is a list of weak references,
2640 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002641
Guido van Rossum048eb752001-10-02 21:24:57 +00002642 return 0;
2643}
2644
2645static int
2646type_clear(PyTypeObject *type)
2647{
Guido van Rossuma3862092002-06-10 15:24:42 +00002648 /* Because of type_is_gc(), the collector only calls this
2649 for heaptypes. */
2650 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002651
Guido van Rossuma3862092002-06-10 15:24:42 +00002652 /* The only field we need to clear is tp_mro, which is part of a
2653 hard cycle (its first element is the class itself) that won't
2654 be broken otherwise (it's a tuple and tuples don't have a
2655 tp_clear handler). None of the other fields need to be
2656 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002657
Guido van Rossuma3862092002-06-10 15:24:42 +00002658 tp_dict:
2659 It is a dict, so the collector will call its tp_clear.
2660
2661 tp_cache:
2662 Not used; if it were, it would be a dict.
2663
2664 tp_bases, tp_base:
2665 If these are involved in a cycle, there must be at least
2666 one other, mutable object in the cycle, e.g. a base
2667 class's dict; the cycle will be broken that way.
2668
2669 tp_subclasses:
2670 A list of weak references can't be part of a cycle; and
2671 lists have their own tp_clear.
2672
Guido van Rossume5c691a2003-03-07 15:13:17 +00002673 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002674 A tuple of strings can't be part of a cycle.
2675 */
2676
Thomas Woutersedf17d82006-04-15 17:28:34 +00002677 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002678
2679 return 0;
2680}
2681
2682static int
2683type_is_gc(PyTypeObject *type)
2684{
2685 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2686}
2687
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002688PyTypeObject PyType_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002689 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002690 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002691 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002692 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002693 (destructor)type_dealloc, /* tp_dealloc */
2694 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002695 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002696 0, /* tp_setattr */
2697 type_compare, /* tp_compare */
2698 (reprfunc)type_repr, /* tp_repr */
2699 0, /* tp_as_number */
2700 0, /* tp_as_sequence */
2701 0, /* tp_as_mapping */
2702 (hashfunc)_Py_HashPointer, /* tp_hash */
2703 (ternaryfunc)type_call, /* tp_call */
2704 0, /* tp_str */
2705 (getattrofunc)type_getattro, /* tp_getattro */
2706 (setattrofunc)type_setattro, /* tp_setattro */
2707 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002708 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002709 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002710 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002711 (traverseproc)type_traverse, /* tp_traverse */
2712 (inquiry)type_clear, /* tp_clear */
Steven Bethardae42f332008-03-18 17:26:10 +00002713 type_richcompare, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002714 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002715 0, /* tp_iter */
2716 0, /* tp_iternext */
2717 type_methods, /* tp_methods */
2718 type_members, /* tp_members */
2719 type_getsets, /* tp_getset */
2720 0, /* tp_base */
2721 0, /* tp_dict */
2722 0, /* tp_descr_get */
2723 0, /* tp_descr_set */
2724 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumf102e242007-03-23 18:53:03 +00002725 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726 0, /* tp_alloc */
2727 type_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002728 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002729 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002730};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002731
2732
2733/* The base type of all types (eventually)... except itself. */
2734
Guido van Rossum143b5642007-03-23 04:58:42 +00002735/* You may wonder why object.__new__() only complains about arguments
2736 when object.__init__() is not overridden, and vice versa.
2737
2738 Consider the use cases:
2739
2740 1. When neither is overridden, we want to hear complaints about
2741 excess (i.e., any) arguments, since their presence could
2742 indicate there's a bug.
2743
2744 2. When defining an Immutable type, we are likely to override only
2745 __new__(), since __init__() is called too late to initialize an
2746 Immutable object. Since __new__() defines the signature for the
2747 type, it would be a pain to have to override __init__() just to
2748 stop it from complaining about excess arguments.
2749
2750 3. When defining a Mutable type, we are likely to override only
2751 __init__(). So here the converse reasoning applies: we don't
2752 want to have to override __new__() just to stop it from
2753 complaining.
2754
2755 4. When __init__() is overridden, and the subclass __init__() calls
2756 object.__init__(), the latter should complain about excess
2757 arguments; ditto for __new__().
2758
2759 Use cases 2 and 3 make it unattractive to unconditionally check for
2760 excess arguments. The best solution that addresses all four use
2761 cases is as follows: __init__() complains about excess arguments
2762 unless __new__() is overridden and __init__() is not overridden
2763 (IOW, if __init__() is overridden or __new__() is not overridden);
2764 symmetrically, __new__() complains about excess arguments unless
2765 __init__() is overridden and __new__() is not overridden
2766 (IOW, if __new__() is overridden or __init__() is not overridden).
2767
2768 However, for backwards compatibility, this breaks too much code.
2769 Therefore, in 2.6, we'll *warn* about excess arguments when both
2770 methods are overridden; for all other cases we'll use the above
2771 rules.
2772
2773*/
2774
2775/* Forward */
2776static PyObject *
2777object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2778
2779static int
2780excess_args(PyObject *args, PyObject *kwds)
2781{
2782 return PyTuple_GET_SIZE(args) ||
2783 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2784}
2785
Tim Peters6d6c1a32001-08-02 04:15:00 +00002786static int
2787object_init(PyObject *self, PyObject *args, PyObject *kwds)
2788{
Guido van Rossum143b5642007-03-23 04:58:42 +00002789 int err = 0;
2790 if (excess_args(args, kwds)) {
Christian Heimese93237d2007-12-19 02:37:44 +00002791 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum143b5642007-03-23 04:58:42 +00002792 if (type->tp_init != object_init &&
2793 type->tp_new != object_new)
2794 {
2795 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2796 "object.__init__() takes no parameters",
2797 1);
2798 }
2799 else if (type->tp_init != object_init ||
2800 type->tp_new == object_new)
2801 {
2802 PyErr_SetString(PyExc_TypeError,
2803 "object.__init__() takes no parameters");
2804 err = -1;
2805 }
2806 }
2807 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002808}
2809
Guido van Rossum298e4212003-02-13 16:30:16 +00002810static PyObject *
2811object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2812{
Guido van Rossum143b5642007-03-23 04:58:42 +00002813 int err = 0;
2814 if (excess_args(args, kwds)) {
2815 if (type->tp_new != object_new &&
2816 type->tp_init != object_init)
2817 {
2818 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2819 "object.__new__() takes no parameters",
2820 1);
2821 }
2822 else if (type->tp_new != object_new ||
2823 type->tp_init == object_init)
2824 {
2825 PyErr_SetString(PyExc_TypeError,
2826 "object.__new__() takes no parameters");
2827 err = -1;
2828 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002829 }
Guido van Rossum143b5642007-03-23 04:58:42 +00002830 if (err < 0)
2831 return NULL;
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00002832
2833 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2834 static PyObject *comma = NULL;
2835 PyObject *abstract_methods = NULL;
2836 PyObject *builtins;
2837 PyObject *sorted;
2838 PyObject *sorted_methods = NULL;
2839 PyObject *joined = NULL;
2840 const char *joined_str;
2841
2842 /* Compute ", ".join(sorted(type.__abstractmethods__))
2843 into joined. */
2844 abstract_methods = type_abstractmethods(type, NULL);
2845 if (abstract_methods == NULL)
2846 goto error;
2847 builtins = PyEval_GetBuiltins();
2848 if (builtins == NULL)
2849 goto error;
2850 sorted = PyDict_GetItemString(builtins, "sorted");
2851 if (sorted == NULL)
2852 goto error;
2853 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2854 abstract_methods,
2855 NULL);
2856 if (sorted_methods == NULL)
2857 goto error;
2858 if (comma == NULL) {
Christian Heimes593daf52008-05-26 12:51:38 +00002859 comma = PyBytes_InternFromString(", ");
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00002860 if (comma == NULL)
2861 goto error;
2862 }
2863 joined = PyObject_CallMethod(comma, "join",
2864 "O", sorted_methods);
2865 if (joined == NULL)
2866 goto error;
Christian Heimes593daf52008-05-26 12:51:38 +00002867 joined_str = PyBytes_AsString(joined);
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00002868 if (joined_str == NULL)
2869 goto error;
2870
2871 PyErr_Format(PyExc_TypeError,
2872 "Can't instantiate abstract class %s "
2873 "with abstract methods %s",
2874 type->tp_name,
2875 joined_str);
2876 error:
2877 Py_XDECREF(joined);
2878 Py_XDECREF(sorted_methods);
2879 Py_XDECREF(abstract_methods);
2880 return NULL;
2881 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002882 return type->tp_alloc(type, 0);
2883}
2884
Tim Peters6d6c1a32001-08-02 04:15:00 +00002885static void
2886object_dealloc(PyObject *self)
2887{
Christian Heimese93237d2007-12-19 02:37:44 +00002888 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002889}
2890
Guido van Rossum8e248182001-08-12 05:17:56 +00002891static PyObject *
2892object_repr(PyObject *self)
2893{
Guido van Rossum76e69632001-08-16 18:52:43 +00002894 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002895 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002896
Christian Heimese93237d2007-12-19 02:37:44 +00002897 type = Py_TYPE(self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002898 mod = type_module(type, NULL);
2899 if (mod == NULL)
2900 PyErr_Clear();
Christian Heimes593daf52008-05-26 12:51:38 +00002901 else if (!PyBytes_Check(mod)) {
Guido van Rossum76e69632001-08-16 18:52:43 +00002902 Py_DECREF(mod);
2903 mod = NULL;
2904 }
2905 name = type_name(type, NULL);
2906 if (name == NULL)
2907 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00002908 if (mod != NULL && strcmp(PyBytes_AS_STRING(mod), "__builtin__"))
2909 rtn = PyBytes_FromFormat("<%s.%s object at %p>",
2910 PyBytes_AS_STRING(mod),
2911 PyBytes_AS_STRING(name),
Barry Warsaw7ce36942001-08-24 18:34:26 +00002912 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002913 else
Christian Heimes593daf52008-05-26 12:51:38 +00002914 rtn = PyBytes_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002915 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002916 Py_XDECREF(mod);
2917 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002918 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002919}
2920
Guido van Rossumb8f63662001-08-15 23:57:02 +00002921static PyObject *
2922object_str(PyObject *self)
2923{
2924 unaryfunc f;
2925
Christian Heimese93237d2007-12-19 02:37:44 +00002926 f = Py_TYPE(self)->tp_repr;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002927 if (f == NULL)
2928 f = object_repr;
2929 return f(self);
2930}
2931
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002932static PyObject *
2933object_get_class(PyObject *self, void *closure)
2934{
Christian Heimese93237d2007-12-19 02:37:44 +00002935 Py_INCREF(Py_TYPE(self));
2936 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002937}
2938
2939static int
2940equiv_structs(PyTypeObject *a, PyTypeObject *b)
2941{
2942 return a == b ||
2943 (a != NULL &&
2944 b != NULL &&
2945 a->tp_basicsize == b->tp_basicsize &&
2946 a->tp_itemsize == b->tp_itemsize &&
2947 a->tp_dictoffset == b->tp_dictoffset &&
2948 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2949 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2950 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2951}
2952
2953static int
2954same_slots_added(PyTypeObject *a, PyTypeObject *b)
2955{
2956 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002957 Py_ssize_t size;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002958 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002959
2960 if (base != b->tp_base)
2961 return 0;
2962 if (equiv_structs(a, base) && equiv_structs(b, base))
2963 return 1;
2964 size = base->tp_basicsize;
2965 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2966 size += sizeof(PyObject *);
2967 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2968 size += sizeof(PyObject *);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002969
2970 /* Check slots compliance */
2971 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2972 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2973 if (slots_a && slots_b) {
2974 if (PyObject_Compare(slots_a, slots_b) != 0)
2975 return 0;
2976 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2977 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002978 return size == a->tp_basicsize && size == b->tp_basicsize;
2979}
2980
2981static int
Anthony Baxtera6286212006-04-11 07:42:36 +00002982compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002983{
2984 PyTypeObject *newbase, *oldbase;
2985
Anthony Baxtera6286212006-04-11 07:42:36 +00002986 if (newto->tp_dealloc != oldto->tp_dealloc ||
2987 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002988 {
2989 PyErr_Format(PyExc_TypeError,
2990 "%s assignment: "
2991 "'%s' deallocator differs from '%s'",
2992 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002993 newto->tp_name,
2994 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002995 return 0;
2996 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002997 newbase = newto;
2998 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002999 while (equiv_structs(newbase, newbase->tp_base))
3000 newbase = newbase->tp_base;
3001 while (equiv_structs(oldbase, oldbase->tp_base))
3002 oldbase = oldbase->tp_base;
3003 if (newbase != oldbase &&
3004 (newbase->tp_base != oldbase->tp_base ||
3005 !same_slots_added(newbase, oldbase))) {
3006 PyErr_Format(PyExc_TypeError,
3007 "%s assignment: "
3008 "'%s' object layout differs from '%s'",
3009 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00003010 newto->tp_name,
3011 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003012 return 0;
3013 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003014
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003015 return 1;
3016}
3017
3018static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003019object_set_class(PyObject *self, PyObject *value, void *closure)
3020{
Christian Heimese93237d2007-12-19 02:37:44 +00003021 PyTypeObject *oldto = Py_TYPE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00003022 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003023
Guido van Rossumb6b89422002-04-15 01:03:30 +00003024 if (value == NULL) {
3025 PyErr_SetString(PyExc_TypeError,
3026 "can't delete __class__ attribute");
3027 return -1;
3028 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003029 if (!PyType_Check(value)) {
3030 PyErr_Format(PyExc_TypeError,
3031 "__class__ must be set to new-style class, not '%s' object",
Christian Heimese93237d2007-12-19 02:37:44 +00003032 Py_TYPE(value)->tp_name);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003033 return -1;
3034 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003035 newto = (PyTypeObject *)value;
3036 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3037 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00003038 {
3039 PyErr_Format(PyExc_TypeError,
3040 "__class__ assignment: only for heap types");
3041 return -1;
3042 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003043 if (compatible_for_assignment(newto, oldto, "__class__")) {
3044 Py_INCREF(newto);
Christian Heimese93237d2007-12-19 02:37:44 +00003045 Py_TYPE(self) = newto;
Anthony Baxtera6286212006-04-11 07:42:36 +00003046 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003047 return 0;
3048 }
3049 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00003050 return -1;
3051 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003052}
3053
3054static PyGetSetDef object_getsets[] = {
3055 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00003056 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003057 {0}
3058};
3059
Guido van Rossumc53f0092003-02-18 22:05:12 +00003060
Guido van Rossum036f9992003-02-21 22:02:54 +00003061/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Georg Brandldffbf5f2008-05-20 07:49:57 +00003062 We fall back to helpers in copy_reg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003063 - pickle protocols < 2
3064 - calculating the list of slot names (done only once per class)
3065 - the __newobj__ function (which is used as a token but never called)
3066*/
3067
3068static PyObject *
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003069import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003070{
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003071 static PyObject *copyreg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00003072
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003073 if (!copyreg_str) {
Christian Heimes593daf52008-05-26 12:51:38 +00003074 copyreg_str = PyBytes_InternFromString("copy_reg");
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003075 if (copyreg_str == NULL)
Guido van Rossum3926a632001-09-25 16:25:58 +00003076 return NULL;
3077 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003078
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003079 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003080}
3081
3082static PyObject *
3083slotnames(PyObject *cls)
3084{
3085 PyObject *clsdict;
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003086 PyObject *copyreg;
Guido van Rossum036f9992003-02-21 22:02:54 +00003087 PyObject *slotnames;
3088
3089 if (!PyType_Check(cls)) {
3090 Py_INCREF(Py_None);
3091 return Py_None;
3092 }
3093
3094 clsdict = ((PyTypeObject *)cls)->tp_dict;
3095 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00003096 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00003097 Py_INCREF(slotnames);
3098 return slotnames;
3099 }
3100
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003101 copyreg = import_copyreg();
3102 if (copyreg == NULL)
Guido van Rossum036f9992003-02-21 22:02:54 +00003103 return NULL;
3104
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003105 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
3106 Py_DECREF(copyreg);
Guido van Rossum036f9992003-02-21 22:02:54 +00003107 if (slotnames != NULL &&
3108 slotnames != Py_None &&
3109 !PyList_Check(slotnames))
3110 {
3111 PyErr_SetString(PyExc_TypeError,
Georg Brandldffbf5f2008-05-20 07:49:57 +00003112 "copy_reg._slotnames didn't return a list or None");
Guido van Rossum036f9992003-02-21 22:02:54 +00003113 Py_DECREF(slotnames);
3114 slotnames = NULL;
3115 }
3116
3117 return slotnames;
3118}
3119
3120static PyObject *
3121reduce_2(PyObject *obj)
3122{
3123 PyObject *cls, *getnewargs;
3124 PyObject *args = NULL, *args2 = NULL;
3125 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3126 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003127 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003128 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00003129
3130 cls = PyObject_GetAttrString(obj, "__class__");
3131 if (cls == NULL)
3132 return NULL;
3133
3134 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
3135 if (getnewargs != NULL) {
3136 args = PyObject_CallObject(getnewargs, NULL);
3137 Py_DECREF(getnewargs);
3138 if (args != NULL && !PyTuple_Check(args)) {
Georg Brandlccff7852006-06-18 22:17:29 +00003139 PyErr_Format(PyExc_TypeError,
3140 "__getnewargs__ should return a tuple, "
Christian Heimese93237d2007-12-19 02:37:44 +00003141 "not '%.200s'", Py_TYPE(args)->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00003142 goto end;
3143 }
3144 }
3145 else {
3146 PyErr_Clear();
3147 args = PyTuple_New(0);
3148 }
3149 if (args == NULL)
3150 goto end;
3151
3152 getstate = PyObject_GetAttrString(obj, "__getstate__");
3153 if (getstate != NULL) {
3154 state = PyObject_CallObject(getstate, NULL);
3155 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00003156 if (state == NULL)
3157 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003158 }
3159 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00003160 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00003161 state = PyObject_GetAttrString(obj, "__dict__");
3162 if (state == NULL) {
3163 PyErr_Clear();
3164 state = Py_None;
3165 Py_INCREF(state);
3166 }
3167 names = slotnames(cls);
3168 if (names == NULL)
3169 goto end;
3170 if (names != Py_None) {
3171 assert(PyList_Check(names));
3172 slots = PyDict_New();
3173 if (slots == NULL)
3174 goto end;
3175 n = 0;
3176 /* Can't pre-compute the list size; the list
3177 is stored on the class so accessible to other
3178 threads, which may be run by DECREF */
3179 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3180 PyObject *name, *value;
3181 name = PyList_GET_ITEM(names, i);
3182 value = PyObject_GetAttr(obj, name);
3183 if (value == NULL)
3184 PyErr_Clear();
3185 else {
3186 int err = PyDict_SetItem(slots, name,
3187 value);
3188 Py_DECREF(value);
3189 if (err)
3190 goto end;
3191 n++;
3192 }
3193 }
3194 if (n) {
3195 state = Py_BuildValue("(NO)", state, slots);
3196 if (state == NULL)
3197 goto end;
3198 }
3199 }
3200 }
3201
3202 if (!PyList_Check(obj)) {
3203 listitems = Py_None;
3204 Py_INCREF(listitems);
3205 }
3206 else {
3207 listitems = PyObject_GetIter(obj);
3208 if (listitems == NULL)
3209 goto end;
3210 }
3211
3212 if (!PyDict_Check(obj)) {
3213 dictitems = Py_None;
3214 Py_INCREF(dictitems);
3215 }
3216 else {
3217 dictitems = PyObject_CallMethod(obj, "iteritems", "");
3218 if (dictitems == NULL)
3219 goto end;
3220 }
3221
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003222 copyreg = import_copyreg();
3223 if (copyreg == NULL)
Guido van Rossum036f9992003-02-21 22:02:54 +00003224 goto end;
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003225 newobj = PyObject_GetAttrString(copyreg, "__newobj__");
Guido van Rossum036f9992003-02-21 22:02:54 +00003226 if (newobj == NULL)
3227 goto end;
3228
3229 n = PyTuple_GET_SIZE(args);
3230 args2 = PyTuple_New(n+1);
3231 if (args2 == NULL)
3232 goto end;
3233 PyTuple_SET_ITEM(args2, 0, cls);
3234 cls = NULL;
3235 for (i = 0; i < n; i++) {
3236 PyObject *v = PyTuple_GET_ITEM(args, i);
3237 Py_INCREF(v);
3238 PyTuple_SET_ITEM(args2, i+1, v);
3239 }
3240
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003241 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003242
3243 end:
3244 Py_XDECREF(cls);
3245 Py_XDECREF(args);
3246 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00003247 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00003248 Py_XDECREF(state);
3249 Py_XDECREF(names);
3250 Py_XDECREF(listitems);
3251 Py_XDECREF(dictitems);
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003252 Py_XDECREF(copyreg);
Guido van Rossum036f9992003-02-21 22:02:54 +00003253 Py_XDECREF(newobj);
3254 return res;
3255}
3256
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003257/*
3258 * There were two problems when object.__reduce__ and object.__reduce_ex__
3259 * were implemented in the same function:
3260 * - trying to pickle an object with a custom __reduce__ method that
3261 * fell back to object.__reduce__ in certain circumstances led to
3262 * infinite recursion at Python level and eventual RuntimeError.
3263 * - Pickling objects that lied about their type by overwriting the
3264 * __class__ descriptor could lead to infinite recursion at C level
3265 * and eventual segfault.
3266 *
3267 * Because of backwards compatibility, the two methods still have to
3268 * behave in the same way, even if this is not required by the pickle
3269 * protocol. This common functionality was moved to the _common_reduce
3270 * function.
3271 */
3272static PyObject *
3273_common_reduce(PyObject *self, int proto)
3274{
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003275 PyObject *copyreg, *res;
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003276
3277 if (proto >= 2)
3278 return reduce_2(self);
3279
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003280 copyreg = import_copyreg();
3281 if (!copyreg)
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003282 return NULL;
3283
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003284 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3285 Py_DECREF(copyreg);
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003286
3287 return res;
3288}
3289
3290static PyObject *
3291object_reduce(PyObject *self, PyObject *args)
3292{
3293 int proto = 0;
3294
3295 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3296 return NULL;
3297
3298 return _common_reduce(self, proto);
3299}
3300
Guido van Rossum036f9992003-02-21 22:02:54 +00003301static PyObject *
3302object_reduce_ex(PyObject *self, PyObject *args)
3303{
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003304 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003305 int proto = 0;
3306
3307 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3308 return NULL;
3309
3310 reduce = PyObject_GetAttrString(self, "__reduce__");
3311 if (reduce == NULL)
3312 PyErr_Clear();
3313 else {
3314 PyObject *cls, *clsreduce, *objreduce;
3315 int override;
3316 cls = PyObject_GetAttrString(self, "__class__");
3317 if (cls == NULL) {
3318 Py_DECREF(reduce);
3319 return NULL;
3320 }
3321 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3322 Py_DECREF(cls);
3323 if (clsreduce == NULL) {
3324 Py_DECREF(reduce);
3325 return NULL;
3326 }
3327 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3328 "__reduce__");
3329 override = (clsreduce != objreduce);
3330 Py_DECREF(clsreduce);
3331 if (override) {
3332 res = PyObject_CallObject(reduce, NULL);
3333 Py_DECREF(reduce);
3334 return res;
3335 }
3336 else
3337 Py_DECREF(reduce);
3338 }
3339
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003340 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003341}
3342
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00003343static PyObject *
3344object_subclasshook(PyObject *cls, PyObject *args)
3345{
3346 Py_INCREF(Py_NotImplemented);
3347 return Py_NotImplemented;
3348}
3349
3350PyDoc_STRVAR(object_subclasshook_doc,
3351"Abstract classes can override this to customize issubclass().\n"
3352"\n"
3353"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3354"It should return True, False or NotImplemented. If it returns\n"
3355"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3356"overrides the normal algorithm (and the outcome is cached).\n");
3357
Eric Smitha9f7d622008-02-17 19:46:49 +00003358/*
3359 from PEP 3101, this code implements:
3360
3361 class object:
3362 def __format__(self, format_spec):
3363 if isinstance(format_spec, str):
3364 return format(str(self), format_spec)
3365 elif isinstance(format_spec, unicode):
3366 return format(unicode(self), format_spec)
3367*/
3368static PyObject *
3369object_format(PyObject *self, PyObject *args)
3370{
3371 PyObject *format_spec;
3372 PyObject *self_as_str = NULL;
3373 PyObject *result = NULL;
3374 PyObject *format_meth = NULL;
3375
3376 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3377 return NULL;
3378 if (PyUnicode_Check(format_spec)) {
3379 self_as_str = PyObject_Unicode(self);
Christian Heimes593daf52008-05-26 12:51:38 +00003380 } else if (PyBytes_Check(format_spec)) {
Eric Smitha9f7d622008-02-17 19:46:49 +00003381 self_as_str = PyObject_Str(self);
3382 } else {
3383 PyErr_SetString(PyExc_TypeError, "argument to __format__ must be unicode or str");
3384 return NULL;
3385 }
3386
3387 if (self_as_str != NULL) {
3388 /* find the format function */
3389 format_meth = PyObject_GetAttrString(self_as_str, "__format__");
3390 if (format_meth != NULL) {
3391 /* and call it */
3392 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
3393 }
3394 }
3395
3396 Py_XDECREF(self_as_str);
3397 Py_XDECREF(format_meth);
3398
3399 return result;
3400}
3401
Guido van Rossum3926a632001-09-25 16:25:58 +00003402static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00003403 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3404 PyDoc_STR("helper for pickle")},
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003405 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003406 PyDoc_STR("helper for pickle")},
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00003407 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3408 object_subclasshook_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00003409 {"__format__", object_format, METH_VARARGS,
3410 PyDoc_STR("default object formatter")},
Guido van Rossum3926a632001-09-25 16:25:58 +00003411 {0}
3412};
3413
Guido van Rossum036f9992003-02-21 22:02:54 +00003414
Tim Peters6d6c1a32001-08-02 04:15:00 +00003415PyTypeObject PyBaseObject_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00003416 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003417 "object", /* tp_name */
3418 sizeof(PyObject), /* tp_basicsize */
3419 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003420 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003421 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003422 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423 0, /* tp_setattr */
3424 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003425 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003426 0, /* tp_as_number */
3427 0, /* tp_as_sequence */
3428 0, /* tp_as_mapping */
Guido van Rossum64c06e32007-11-22 00:55:51 +00003429 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003430 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003431 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003432 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003433 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003434 0, /* tp_as_buffer */
3435 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003436 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003437 0, /* tp_traverse */
3438 0, /* tp_clear */
3439 0, /* tp_richcompare */
3440 0, /* tp_weaklistoffset */
3441 0, /* tp_iter */
3442 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00003443 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003444 0, /* tp_members */
3445 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003446 0, /* tp_base */
3447 0, /* tp_dict */
3448 0, /* tp_descr_get */
3449 0, /* tp_descr_set */
3450 0, /* tp_dictoffset */
3451 object_init, /* tp_init */
3452 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003453 object_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003454 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003455};
3456
3457
3458/* Initialize the __dict__ in a type object */
3459
3460static int
3461add_methods(PyTypeObject *type, PyMethodDef *meth)
3462{
Guido van Rossum687ae002001-10-15 22:03:32 +00003463 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003464
3465 for (; meth->ml_name != NULL; meth++) {
3466 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003467 if (PyDict_GetItemString(dict, meth->ml_name) &&
3468 !(meth->ml_flags & METH_COEXIST))
3469 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003470 if (meth->ml_flags & METH_CLASS) {
3471 if (meth->ml_flags & METH_STATIC) {
3472 PyErr_SetString(PyExc_ValueError,
3473 "method cannot be both class and static");
3474 return -1;
3475 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003476 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003477 }
3478 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003479 PyObject *cfunc = PyCFunction_New(meth, NULL);
3480 if (cfunc == NULL)
3481 return -1;
3482 descr = PyStaticMethod_New(cfunc);
3483 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003484 }
3485 else {
3486 descr = PyDescr_NewMethod(type, meth);
3487 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003488 if (descr == NULL)
3489 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003490 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003491 return -1;
3492 Py_DECREF(descr);
3493 }
3494 return 0;
3495}
3496
3497static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003498add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003499{
Guido van Rossum687ae002001-10-15 22:03:32 +00003500 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003501
3502 for (; memb->name != NULL; memb++) {
3503 PyObject *descr;
3504 if (PyDict_GetItemString(dict, memb->name))
3505 continue;
3506 descr = PyDescr_NewMember(type, memb);
3507 if (descr == NULL)
3508 return -1;
3509 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3510 return -1;
3511 Py_DECREF(descr);
3512 }
3513 return 0;
3514}
3515
3516static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003517add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003518{
Guido van Rossum687ae002001-10-15 22:03:32 +00003519 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003520
3521 for (; gsp->name != NULL; gsp++) {
3522 PyObject *descr;
3523 if (PyDict_GetItemString(dict, gsp->name))
3524 continue;
3525 descr = PyDescr_NewGetSet(type, gsp);
3526
3527 if (descr == NULL)
3528 return -1;
3529 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3530 return -1;
3531 Py_DECREF(descr);
3532 }
3533 return 0;
3534}
3535
Guido van Rossum13d52f02001-08-10 21:24:08 +00003536static void
3537inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003538{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003539 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003540
Guido van Rossum13d52f02001-08-10 21:24:08 +00003541 /* Special flag magic */
3542 if (!type->tp_as_buffer && base->tp_as_buffer) {
3543 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
3544 type->tp_flags |=
3545 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
3546 }
3547 if (!type->tp_as_sequence && base->tp_as_sequence) {
3548 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3549 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3550 }
3551 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3552 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3553 if ((!type->tp_as_number && base->tp_as_number) ||
3554 (!type->tp_as_sequence && base->tp_as_sequence)) {
3555 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3556 if (!type->tp_as_number && !type->tp_as_sequence) {
3557 type->tp_flags |= base->tp_flags &
3558 Py_TPFLAGS_HAVE_INPLACEOPS;
3559 }
3560 }
3561 /* Wow */
3562 }
3563 if (!type->tp_as_number && base->tp_as_number) {
3564 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3565 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3566 }
3567
3568 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003569 oldsize = base->tp_basicsize;
3570 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3571 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3572 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003573 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3574 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003575 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003576 if (type->tp_traverse == NULL)
3577 type->tp_traverse = base->tp_traverse;
3578 if (type->tp_clear == NULL)
3579 type->tp_clear = base->tp_clear;
3580 }
3581 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00003582 /* The condition below could use some explanation.
3583 It appears that tp_new is not inherited for static types
3584 whose base class is 'object'; this seems to be a precaution
3585 so that old extension types don't suddenly become
3586 callable (object.__new__ wouldn't insure the invariants
3587 that the extension type's own factory function ensures).
3588 Heap types, of course, are under our control, so they do
3589 inherit tp_new; static extension types that specify some
3590 other built-in type as the default are considered
3591 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003592 if (base != &PyBaseObject_Type ||
3593 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3594 if (type->tp_new == NULL)
3595 type->tp_new = base->tp_new;
3596 }
3597 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003598 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003599
3600 /* Copy other non-function slots */
3601
3602#undef COPYVAL
3603#define COPYVAL(SLOT) \
3604 if (type->SLOT == 0) type->SLOT = base->SLOT
3605
3606 COPYVAL(tp_itemsize);
3607 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3608 COPYVAL(tp_weaklistoffset);
3609 }
3610 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3611 COPYVAL(tp_dictoffset);
3612 }
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003613
3614 /* Setup fast subclass flags */
3615 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3616 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3617 else if (PyType_IsSubtype(base, &PyType_Type))
3618 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3619 else if (PyType_IsSubtype(base, &PyInt_Type))
3620 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3621 else if (PyType_IsSubtype(base, &PyLong_Type))
3622 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
Christian Heimes593daf52008-05-26 12:51:38 +00003623 else if (PyType_IsSubtype(base, &PyBytes_Type))
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003624 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003625#ifdef Py_USING_UNICODE
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003626 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3627 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003628#endif
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003629 else if (PyType_IsSubtype(base, &PyTuple_Type))
3630 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3631 else if (PyType_IsSubtype(base, &PyList_Type))
3632 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3633 else if (PyType_IsSubtype(base, &PyDict_Type))
3634 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003635}
3636
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003637static char *hash_name_op[] = {
3638 "__eq__",
3639 "__cmp__",
3640 "__hash__",
3641 NULL
Guido van Rossum64c06e32007-11-22 00:55:51 +00003642};
3643
3644static int
3645overrides_hash(PyTypeObject *type)
3646{
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003647 char **p;
Guido van Rossum64c06e32007-11-22 00:55:51 +00003648 PyObject *dict = type->tp_dict;
3649
3650 assert(dict != NULL);
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003651 for (p = hash_name_op; *p; p++) {
3652 if (PyDict_GetItemString(dict, *p) != NULL)
Guido van Rossum64c06e32007-11-22 00:55:51 +00003653 return 1;
3654 }
3655 return 0;
3656}
3657
Guido van Rossum13d52f02001-08-10 21:24:08 +00003658static void
3659inherit_slots(PyTypeObject *type, PyTypeObject *base)
3660{
3661 PyTypeObject *basebase;
3662
3663#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003664#undef COPYSLOT
3665#undef COPYNUM
3666#undef COPYSEQ
3667#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003668#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003669
3670#define SLOTDEFINED(SLOT) \
3671 (base->SLOT != 0 && \
3672 (basebase == NULL || base->SLOT != basebase->SLOT))
3673
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003675 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003676
3677#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3678#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3679#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003680#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003681
Guido van Rossum13d52f02001-08-10 21:24:08 +00003682 /* This won't inherit indirect slots (from tp_as_number etc.)
3683 if type doesn't provide the space. */
3684
3685 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3686 basebase = base->tp_base;
3687 if (basebase->tp_as_number == NULL)
3688 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003689 COPYNUM(nb_add);
3690 COPYNUM(nb_subtract);
3691 COPYNUM(nb_multiply);
3692 COPYNUM(nb_divide);
3693 COPYNUM(nb_remainder);
3694 COPYNUM(nb_divmod);
3695 COPYNUM(nb_power);
3696 COPYNUM(nb_negative);
3697 COPYNUM(nb_positive);
3698 COPYNUM(nb_absolute);
3699 COPYNUM(nb_nonzero);
3700 COPYNUM(nb_invert);
3701 COPYNUM(nb_lshift);
3702 COPYNUM(nb_rshift);
3703 COPYNUM(nb_and);
3704 COPYNUM(nb_xor);
3705 COPYNUM(nb_or);
3706 COPYNUM(nb_coerce);
3707 COPYNUM(nb_int);
3708 COPYNUM(nb_long);
3709 COPYNUM(nb_float);
3710 COPYNUM(nb_oct);
3711 COPYNUM(nb_hex);
3712 COPYNUM(nb_inplace_add);
3713 COPYNUM(nb_inplace_subtract);
3714 COPYNUM(nb_inplace_multiply);
3715 COPYNUM(nb_inplace_divide);
3716 COPYNUM(nb_inplace_remainder);
3717 COPYNUM(nb_inplace_power);
3718 COPYNUM(nb_inplace_lshift);
3719 COPYNUM(nb_inplace_rshift);
3720 COPYNUM(nb_inplace_and);
3721 COPYNUM(nb_inplace_xor);
3722 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003723 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3724 COPYNUM(nb_true_divide);
3725 COPYNUM(nb_floor_divide);
3726 COPYNUM(nb_inplace_true_divide);
3727 COPYNUM(nb_inplace_floor_divide);
3728 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003729 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3730 COPYNUM(nb_index);
3731 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003732 }
3733
Guido van Rossum13d52f02001-08-10 21:24:08 +00003734 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3735 basebase = base->tp_base;
3736 if (basebase->tp_as_sequence == NULL)
3737 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003738 COPYSEQ(sq_length);
3739 COPYSEQ(sq_concat);
3740 COPYSEQ(sq_repeat);
3741 COPYSEQ(sq_item);
3742 COPYSEQ(sq_slice);
3743 COPYSEQ(sq_ass_item);
3744 COPYSEQ(sq_ass_slice);
3745 COPYSEQ(sq_contains);
3746 COPYSEQ(sq_inplace_concat);
3747 COPYSEQ(sq_inplace_repeat);
3748 }
3749
Guido van Rossum13d52f02001-08-10 21:24:08 +00003750 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3751 basebase = base->tp_base;
3752 if (basebase->tp_as_mapping == NULL)
3753 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003754 COPYMAP(mp_length);
3755 COPYMAP(mp_subscript);
3756 COPYMAP(mp_ass_subscript);
3757 }
3758
Tim Petersfc57ccb2001-10-12 02:38:24 +00003759 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3760 basebase = base->tp_base;
3761 if (basebase->tp_as_buffer == NULL)
3762 basebase = NULL;
3763 COPYBUF(bf_getreadbuffer);
3764 COPYBUF(bf_getwritebuffer);
3765 COPYBUF(bf_getsegcount);
3766 COPYBUF(bf_getcharbuffer);
Christian Heimes1a6387e2008-03-26 12:49:49 +00003767 COPYBUF(bf_getbuffer);
3768 COPYBUF(bf_releasebuffer);
Tim Petersfc57ccb2001-10-12 02:38:24 +00003769 }
3770
Guido van Rossum13d52f02001-08-10 21:24:08 +00003771 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003772
Tim Peters6d6c1a32001-08-02 04:15:00 +00003773 COPYSLOT(tp_dealloc);
3774 COPYSLOT(tp_print);
3775 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3776 type->tp_getattr = base->tp_getattr;
3777 type->tp_getattro = base->tp_getattro;
3778 }
3779 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3780 type->tp_setattr = base->tp_setattr;
3781 type->tp_setattro = base->tp_setattro;
3782 }
3783 /* tp_compare see tp_richcompare */
3784 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003785 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003786 COPYSLOT(tp_call);
3787 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003788 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003789 if (type->tp_compare == NULL &&
3790 type->tp_richcompare == NULL &&
Guido van Rossum64c06e32007-11-22 00:55:51 +00003791 type->tp_hash == NULL &&
3792 !overrides_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003793 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003794 type->tp_compare = base->tp_compare;
3795 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003796 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003797 }
3798 }
3799 else {
3800 COPYSLOT(tp_compare);
3801 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003802 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3803 COPYSLOT(tp_iter);
3804 COPYSLOT(tp_iternext);
3805 }
3806 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3807 COPYSLOT(tp_descr_get);
3808 COPYSLOT(tp_descr_set);
3809 COPYSLOT(tp_dictoffset);
3810 COPYSLOT(tp_init);
3811 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003812 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003813 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3814 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3815 /* They agree about gc. */
3816 COPYSLOT(tp_free);
3817 }
3818 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3819 type->tp_free == NULL &&
3820 base->tp_free == _PyObject_Del) {
3821 /* A bit of magic to plug in the correct default
3822 * tp_free function when a derived class adds gc,
3823 * didn't define tp_free, and the base uses the
3824 * default non-gc tp_free.
3825 */
3826 type->tp_free = PyObject_GC_Del;
3827 }
3828 /* else they didn't agree about gc, and there isn't something
3829 * obvious to be done -- the type is on its own.
3830 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003831 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003832}
3833
Jeremy Hylton938ace62002-07-17 16:30:39 +00003834static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003835
Tim Peters6d6c1a32001-08-02 04:15:00 +00003836int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003837PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003838{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003839 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003840 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003841 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003842
Guido van Rossumcab05802002-06-10 15:29:03 +00003843 if (type->tp_flags & Py_TPFLAGS_READY) {
3844 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003845 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003846 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003847 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003848
3849 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003850
Tim Peters36eb4df2003-03-23 03:33:13 +00003851#ifdef Py_TRACE_REFS
3852 /* PyType_Ready is the closest thing we have to a choke point
3853 * for type objects, so is the best place I can think of to try
3854 * to get type objects into the doubly-linked list of all objects.
3855 * Still, not all type objects go thru PyType_Ready.
3856 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003857 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003858#endif
3859
Tim Peters6d6c1a32001-08-02 04:15:00 +00003860 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3861 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003862 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003863 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003864 Py_INCREF(base);
3865 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003866
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003867 /* Now the only way base can still be NULL is if type is
3868 * &PyBaseObject_Type.
3869 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003870
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003871 /* Initialize the base class */
3872 if (base && base->tp_dict == NULL) {
3873 if (PyType_Ready(base) < 0)
3874 goto error;
3875 }
3876
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003877 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003878 compilable separately on Windows can call PyType_Ready() instead of
3879 initializing the ob_type field of their type objects. */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003880 /* The test for base != NULL is really unnecessary, since base is only
3881 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3882 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3883 know that. */
Christian Heimese93237d2007-12-19 02:37:44 +00003884 if (Py_TYPE(type) == NULL && base != NULL)
3885 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003886
Tim Peters6d6c1a32001-08-02 04:15:00 +00003887 /* Initialize tp_bases */
3888 bases = type->tp_bases;
3889 if (bases == NULL) {
3890 if (base == NULL)
3891 bases = PyTuple_New(0);
3892 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003893 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003894 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003895 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003896 type->tp_bases = bases;
3897 }
3898
Guido van Rossum687ae002001-10-15 22:03:32 +00003899 /* Initialize tp_dict */
3900 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003901 if (dict == NULL) {
3902 dict = PyDict_New();
3903 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003904 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003905 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003906 }
3907
Guido van Rossum687ae002001-10-15 22:03:32 +00003908 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003909 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003910 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003911 if (type->tp_methods != NULL) {
3912 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003913 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003914 }
3915 if (type->tp_members != NULL) {
3916 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003917 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003918 }
3919 if (type->tp_getset != NULL) {
3920 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003921 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003922 }
3923
Tim Peters6d6c1a32001-08-02 04:15:00 +00003924 /* Calculate method resolution order */
3925 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003926 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003927 }
3928
Guido van Rossum13d52f02001-08-10 21:24:08 +00003929 /* Inherit special flags from dominant base */
3930 if (type->tp_base != NULL)
3931 inherit_special(type, type->tp_base);
3932
Tim Peters6d6c1a32001-08-02 04:15:00 +00003933 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003934 bases = type->tp_mro;
3935 assert(bases != NULL);
3936 assert(PyTuple_Check(bases));
3937 n = PyTuple_GET_SIZE(bases);
3938 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003939 PyObject *b = PyTuple_GET_ITEM(bases, i);
3940 if (PyType_Check(b))
3941 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003942 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003943
Tim Peters3cfe7542003-05-21 21:29:48 +00003944 /* Sanity check for tp_free. */
3945 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3946 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003947 /* This base class needs to call tp_free, but doesn't have
3948 * one, or its tp_free is for non-gc'ed objects.
3949 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003950 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3951 "gc and is a base type but has inappropriate "
3952 "tp_free slot",
3953 type->tp_name);
3954 goto error;
3955 }
3956
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003957 /* if the type dictionary doesn't contain a __doc__, set it from
3958 the tp_doc slot.
3959 */
3960 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3961 if (type->tp_doc != NULL) {
Christian Heimes593daf52008-05-26 12:51:38 +00003962 PyObject *doc = PyBytes_FromString(type->tp_doc);
Neal Norwitze1fdb322006-07-21 05:32:28 +00003963 if (doc == NULL)
3964 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003965 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3966 Py_DECREF(doc);
3967 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003968 PyDict_SetItemString(type->tp_dict,
3969 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003970 }
3971 }
3972
Guido van Rossum64c06e32007-11-22 00:55:51 +00003973 /* Hack for tp_hash and __hash__.
3974 If after all that, tp_hash is still NULL, and __hash__ is not in
3975 tp_dict, set tp_dict['__hash__'] equal to None.
3976 This signals that __hash__ is not inherited.
3977 */
3978 if (type->tp_hash == NULL &&
3979 PyDict_GetItemString(type->tp_dict, "__hash__") == NULL &&
3980 PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3981 {
3982 goto error;
3983 }
3984
Guido van Rossum13d52f02001-08-10 21:24:08 +00003985 /* Some more special stuff */
3986 base = type->tp_base;
3987 if (base != NULL) {
3988 if (type->tp_as_number == NULL)
3989 type->tp_as_number = base->tp_as_number;
3990 if (type->tp_as_sequence == NULL)
3991 type->tp_as_sequence = base->tp_as_sequence;
3992 if (type->tp_as_mapping == NULL)
3993 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003994 if (type->tp_as_buffer == NULL)
3995 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003996 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003997
Guido van Rossum1c450732001-10-08 15:18:27 +00003998 /* Link into each base class's list of subclasses */
3999 bases = type->tp_bases;
4000 n = PyTuple_GET_SIZE(bases);
4001 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00004002 PyObject *b = PyTuple_GET_ITEM(bases, i);
4003 if (PyType_Check(b) &&
4004 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00004005 goto error;
4006 }
4007
Guido van Rossum13d52f02001-08-10 21:24:08 +00004008 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00004009 assert(type->tp_dict != NULL);
4010 type->tp_flags =
4011 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004012 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004013
4014 error:
4015 type->tp_flags &= ~Py_TPFLAGS_READYING;
4016 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004017}
4018
Guido van Rossum1c450732001-10-08 15:18:27 +00004019static int
4020add_subclass(PyTypeObject *base, PyTypeObject *type)
4021{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004022 Py_ssize_t i;
4023 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00004024 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004025
4026 list = base->tp_subclasses;
4027 if (list == NULL) {
4028 base->tp_subclasses = list = PyList_New(0);
4029 if (list == NULL)
4030 return -1;
4031 }
4032 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00004033 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00004034 i = PyList_GET_SIZE(list);
4035 while (--i >= 0) {
4036 ref = PyList_GET_ITEM(list, i);
4037 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00004038 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00004039 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00004040 }
Anthony Baxtera6286212006-04-11 07:42:36 +00004041 result = PyList_Append(list, newobj);
4042 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004043 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004044}
4045
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004046static void
4047remove_subclass(PyTypeObject *base, PyTypeObject *type)
4048{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004049 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004050 PyObject *list, *ref;
4051
4052 list = base->tp_subclasses;
4053 if (list == NULL) {
4054 return;
4055 }
4056 assert(PyList_Check(list));
4057 i = PyList_GET_SIZE(list);
4058 while (--i >= 0) {
4059 ref = PyList_GET_ITEM(list, i);
4060 assert(PyWeakref_CheckRef(ref));
4061 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4062 /* this can't fail, right? */
4063 PySequence_DelItem(list, i);
4064 return;
4065 }
4066 }
4067}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004068
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004069static int
4070check_num_args(PyObject *ob, int n)
4071{
4072 if (!PyTuple_CheckExact(ob)) {
4073 PyErr_SetString(PyExc_SystemError,
4074 "PyArg_UnpackTuple() argument list is not a tuple");
4075 return 0;
4076 }
4077 if (n == PyTuple_GET_SIZE(ob))
4078 return 1;
4079 PyErr_Format(
4080 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00004081 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004082 return 0;
4083}
4084
Tim Peters6d6c1a32001-08-02 04:15:00 +00004085/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4086
4087/* There's a wrapper *function* for each distinct function typedef used
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004088 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004089 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4090 Most tables have only one entry; the tables for binary operators have two
4091 entries, one regular and one with reversed arguments. */
4092
4093static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004094wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004095{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004096 lenfunc func = (lenfunc)wrapped;
4097 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004098
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004099 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004100 return NULL;
4101 res = (*func)(self);
4102 if (res == -1 && PyErr_Occurred())
4103 return NULL;
4104 return PyInt_FromLong((long)res);
4105}
4106
Tim Peters6d6c1a32001-08-02 04:15:00 +00004107static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004108wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4109{
4110 inquiry func = (inquiry)wrapped;
4111 int res;
4112
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004113 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004114 return NULL;
4115 res = (*func)(self);
4116 if (res == -1 && PyErr_Occurred())
4117 return NULL;
4118 return PyBool_FromLong((long)res);
4119}
4120
4121static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004122wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4123{
4124 binaryfunc func = (binaryfunc)wrapped;
4125 PyObject *other;
4126
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004127 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004128 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004129 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004130 return (*func)(self, other);
4131}
4132
4133static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004134wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4135{
4136 binaryfunc func = (binaryfunc)wrapped;
4137 PyObject *other;
4138
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004139 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004140 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004141 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004142 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004143 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004144 Py_INCREF(Py_NotImplemented);
4145 return Py_NotImplemented;
4146 }
4147 return (*func)(self, other);
4148}
4149
4150static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004151wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4152{
4153 binaryfunc func = (binaryfunc)wrapped;
4154 PyObject *other;
4155
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004156 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004157 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004158 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004159 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004160 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004161 Py_INCREF(Py_NotImplemented);
4162 return Py_NotImplemented;
4163 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004164 return (*func)(other, self);
4165}
4166
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004167static PyObject *
4168wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
4169{
4170 coercion func = (coercion)wrapped;
4171 PyObject *other, *res;
4172 int ok;
4173
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004174 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004175 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004176 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004177 ok = func(&self, &other);
4178 if (ok < 0)
4179 return NULL;
4180 if (ok > 0) {
4181 Py_INCREF(Py_NotImplemented);
4182 return Py_NotImplemented;
4183 }
4184 res = PyTuple_New(2);
4185 if (res == NULL) {
4186 Py_DECREF(self);
4187 Py_DECREF(other);
4188 return NULL;
4189 }
4190 PyTuple_SET_ITEM(res, 0, self);
4191 PyTuple_SET_ITEM(res, 1, other);
4192 return res;
4193}
4194
Tim Peters6d6c1a32001-08-02 04:15:00 +00004195static PyObject *
4196wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4197{
4198 ternaryfunc func = (ternaryfunc)wrapped;
4199 PyObject *other;
4200 PyObject *third = Py_None;
4201
4202 /* Note: This wrapper only works for __pow__() */
4203
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004204 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004205 return NULL;
4206 return (*func)(self, other, third);
4207}
4208
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004209static PyObject *
4210wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4211{
4212 ternaryfunc func = (ternaryfunc)wrapped;
4213 PyObject *other;
4214 PyObject *third = Py_None;
4215
4216 /* Note: This wrapper only works for __pow__() */
4217
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004218 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004219 return NULL;
4220 return (*func)(other, self, third);
4221}
4222
Tim Peters6d6c1a32001-08-02 04:15:00 +00004223static PyObject *
4224wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4225{
4226 unaryfunc func = (unaryfunc)wrapped;
4227
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004228 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004229 return NULL;
4230 return (*func)(self);
4231}
4232
Tim Peters6d6c1a32001-08-02 04:15:00 +00004233static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00004234wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004235{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004236 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00004237 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004238 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004239
Armin Rigo314861c2006-03-30 14:04:02 +00004240 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4241 return NULL;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004242 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Armin Rigo314861c2006-03-30 14:04:02 +00004243 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004244 return NULL;
4245 return (*func)(self, i);
4246}
4247
Martin v. Löwis18e16552006-02-15 17:27:45 +00004248static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004249getindex(PyObject *self, PyObject *arg)
4250{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004251 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004252
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004253 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004254 if (i == -1 && PyErr_Occurred())
4255 return -1;
4256 if (i < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00004257 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004258 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00004259 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004260 if (n < 0)
4261 return -1;
4262 i += n;
4263 }
4264 }
4265 return i;
4266}
4267
4268static PyObject *
4269wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4270{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004271 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004272 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004273 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004274
Guido van Rossumf4593e02001-10-03 12:09:30 +00004275 if (PyTuple_GET_SIZE(args) == 1) {
4276 arg = PyTuple_GET_ITEM(args, 0);
4277 i = getindex(self, arg);
4278 if (i == -1 && PyErr_Occurred())
4279 return NULL;
4280 return (*func)(self, i);
4281 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004282 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004283 assert(PyErr_Occurred());
4284 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004285}
4286
Tim Peters6d6c1a32001-08-02 04:15:00 +00004287static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004288wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004289{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004290 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
4291 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004292
Martin v. Löwis18e16552006-02-15 17:27:45 +00004293 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004294 return NULL;
4295 return (*func)(self, i, j);
4296}
4297
Tim Peters6d6c1a32001-08-02 04:15:00 +00004298static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004299wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004300{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004301 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4302 Py_ssize_t i;
4303 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004304 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004305
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004306 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004307 return NULL;
4308 i = getindex(self, arg);
4309 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004310 return NULL;
4311 res = (*func)(self, i, value);
4312 if (res == -1 && PyErr_Occurred())
4313 return NULL;
4314 Py_INCREF(Py_None);
4315 return Py_None;
4316}
4317
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004318static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004319wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004320{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004321 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4322 Py_ssize_t i;
4323 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004324 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004325
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004326 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004327 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004328 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004329 i = getindex(self, arg);
4330 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004331 return NULL;
4332 res = (*func)(self, i, NULL);
4333 if (res == -1 && PyErr_Occurred())
4334 return NULL;
4335 Py_INCREF(Py_None);
4336 return Py_None;
4337}
4338
Tim Peters6d6c1a32001-08-02 04:15:00 +00004339static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004340wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004341{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004342 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4343 Py_ssize_t i, j;
4344 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004345 PyObject *value;
4346
Martin v. Löwis18e16552006-02-15 17:27:45 +00004347 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004348 return NULL;
4349 res = (*func)(self, i, j, value);
4350 if (res == -1 && PyErr_Occurred())
4351 return NULL;
4352 Py_INCREF(Py_None);
4353 return Py_None;
4354}
4355
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004356static PyObject *
4357wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
4358{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004359 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4360 Py_ssize_t i, j;
4361 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004362
Martin v. Löwis18e16552006-02-15 17:27:45 +00004363 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004364 return NULL;
4365 res = (*func)(self, i, j, NULL);
4366 if (res == -1 && PyErr_Occurred())
4367 return NULL;
4368 Py_INCREF(Py_None);
4369 return Py_None;
4370}
4371
Tim Peters6d6c1a32001-08-02 04:15:00 +00004372/* XXX objobjproc is a misnomer; should be objargpred */
4373static PyObject *
4374wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4375{
4376 objobjproc func = (objobjproc)wrapped;
4377 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004378 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004379
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004380 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004381 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004382 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004383 res = (*func)(self, value);
4384 if (res == -1 && PyErr_Occurred())
4385 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004386 else
4387 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004388}
4389
Tim Peters6d6c1a32001-08-02 04:15:00 +00004390static PyObject *
4391wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4392{
4393 objobjargproc func = (objobjargproc)wrapped;
4394 int res;
4395 PyObject *key, *value;
4396
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004397 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004398 return NULL;
4399 res = (*func)(self, key, value);
4400 if (res == -1 && PyErr_Occurred())
4401 return NULL;
4402 Py_INCREF(Py_None);
4403 return Py_None;
4404}
4405
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004406static PyObject *
4407wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4408{
4409 objobjargproc func = (objobjargproc)wrapped;
4410 int res;
4411 PyObject *key;
4412
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004413 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004414 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004415 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004416 res = (*func)(self, key, NULL);
4417 if (res == -1 && PyErr_Occurred())
4418 return NULL;
4419 Py_INCREF(Py_None);
4420 return Py_None;
4421}
4422
Tim Peters6d6c1a32001-08-02 04:15:00 +00004423static PyObject *
4424wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
4425{
4426 cmpfunc func = (cmpfunc)wrapped;
4427 int res;
4428 PyObject *other;
4429
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004430 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004431 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004432 other = PyTuple_GET_ITEM(args, 0);
Christian Heimese93237d2007-12-19 02:37:44 +00004433 if (Py_TYPE(other)->tp_compare != func &&
4434 !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
Guido van Rossumceccae52001-09-18 20:03:57 +00004435 PyErr_Format(
4436 PyExc_TypeError,
4437 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +00004438 Py_TYPE(self)->tp_name,
4439 Py_TYPE(self)->tp_name,
4440 Py_TYPE(other)->tp_name);
Guido van Rossumceccae52001-09-18 20:03:57 +00004441 return NULL;
4442 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004443 res = (*func)(self, other);
4444 if (PyErr_Occurred())
4445 return NULL;
4446 return PyInt_FromLong((long)res);
4447}
4448
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004449/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004450 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004451static int
4452hackcheck(PyObject *self, setattrofunc func, char *what)
4453{
Christian Heimese93237d2007-12-19 02:37:44 +00004454 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004455 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4456 type = type->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004457 /* If type is NULL now, this is a really weird type.
4458 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004459 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004460 PyErr_Format(PyExc_TypeError,
4461 "can't apply this %s to %s object",
4462 what,
4463 type->tp_name);
4464 return 0;
4465 }
4466 return 1;
4467}
4468
Tim Peters6d6c1a32001-08-02 04:15:00 +00004469static PyObject *
4470wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4471{
4472 setattrofunc func = (setattrofunc)wrapped;
4473 int res;
4474 PyObject *name, *value;
4475
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004476 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004477 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004478 if (!hackcheck(self, func, "__setattr__"))
4479 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004480 res = (*func)(self, name, value);
4481 if (res < 0)
4482 return NULL;
4483 Py_INCREF(Py_None);
4484 return Py_None;
4485}
4486
4487static PyObject *
4488wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4489{
4490 setattrofunc func = (setattrofunc)wrapped;
4491 int res;
4492 PyObject *name;
4493
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004494 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004495 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004496 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004497 if (!hackcheck(self, func, "__delattr__"))
4498 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004499 res = (*func)(self, name, NULL);
4500 if (res < 0)
4501 return NULL;
4502 Py_INCREF(Py_None);
4503 return Py_None;
4504}
4505
Tim Peters6d6c1a32001-08-02 04:15:00 +00004506static PyObject *
4507wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4508{
4509 hashfunc func = (hashfunc)wrapped;
4510 long res;
4511
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004512 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004513 return NULL;
4514 res = (*func)(self);
4515 if (res == -1 && PyErr_Occurred())
4516 return NULL;
4517 return PyInt_FromLong(res);
4518}
4519
Tim Peters6d6c1a32001-08-02 04:15:00 +00004520static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004521wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004522{
4523 ternaryfunc func = (ternaryfunc)wrapped;
4524
Guido van Rossumc8e56452001-10-22 00:43:43 +00004525 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004526}
4527
Tim Peters6d6c1a32001-08-02 04:15:00 +00004528static PyObject *
4529wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4530{
4531 richcmpfunc func = (richcmpfunc)wrapped;
4532 PyObject *other;
4533
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004534 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004535 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004536 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004537 return (*func)(self, other, op);
4538}
4539
4540#undef RICHCMP_WRAPPER
4541#define RICHCMP_WRAPPER(NAME, OP) \
4542static PyObject * \
4543richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4544{ \
4545 return wrap_richcmpfunc(self, args, wrapped, OP); \
4546}
4547
Jack Jansen8e938b42001-08-08 15:29:49 +00004548RICHCMP_WRAPPER(lt, Py_LT)
4549RICHCMP_WRAPPER(le, Py_LE)
4550RICHCMP_WRAPPER(eq, Py_EQ)
4551RICHCMP_WRAPPER(ne, Py_NE)
4552RICHCMP_WRAPPER(gt, Py_GT)
4553RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004554
Tim Peters6d6c1a32001-08-02 04:15:00 +00004555static PyObject *
4556wrap_next(PyObject *self, PyObject *args, void *wrapped)
4557{
4558 unaryfunc func = (unaryfunc)wrapped;
4559 PyObject *res;
4560
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004561 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004562 return NULL;
4563 res = (*func)(self);
4564 if (res == NULL && !PyErr_Occurred())
4565 PyErr_SetNone(PyExc_StopIteration);
4566 return res;
4567}
4568
Tim Peters6d6c1a32001-08-02 04:15:00 +00004569static PyObject *
4570wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4571{
4572 descrgetfunc func = (descrgetfunc)wrapped;
4573 PyObject *obj;
4574 PyObject *type = NULL;
4575
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004576 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004577 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004578 if (obj == Py_None)
4579 obj = NULL;
4580 if (type == Py_None)
4581 type = NULL;
4582 if (type == NULL &&obj == NULL) {
4583 PyErr_SetString(PyExc_TypeError,
4584 "__get__(None, None) is invalid");
4585 return NULL;
4586 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004587 return (*func)(self, obj, type);
4588}
4589
Tim Peters6d6c1a32001-08-02 04:15:00 +00004590static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004591wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004592{
4593 descrsetfunc func = (descrsetfunc)wrapped;
4594 PyObject *obj, *value;
4595 int ret;
4596
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004597 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004598 return NULL;
4599 ret = (*func)(self, obj, value);
4600 if (ret < 0)
4601 return NULL;
4602 Py_INCREF(Py_None);
4603 return Py_None;
4604}
Guido van Rossum22b13872002-08-06 21:41:44 +00004605
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004606static PyObject *
4607wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4608{
4609 descrsetfunc func = (descrsetfunc)wrapped;
4610 PyObject *obj;
4611 int ret;
4612
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004613 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004614 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004615 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004616 ret = (*func)(self, obj, NULL);
4617 if (ret < 0)
4618 return NULL;
4619 Py_INCREF(Py_None);
4620 return Py_None;
4621}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004622
Tim Peters6d6c1a32001-08-02 04:15:00 +00004623static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004624wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004625{
4626 initproc func = (initproc)wrapped;
4627
Guido van Rossumc8e56452001-10-22 00:43:43 +00004628 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004629 return NULL;
4630 Py_INCREF(Py_None);
4631 return Py_None;
4632}
4633
Tim Peters6d6c1a32001-08-02 04:15:00 +00004634static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004635tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004636{
Barry Warsaw60f01882001-08-22 19:24:42 +00004637 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004638 PyObject *arg0, *res;
4639
4640 if (self == NULL || !PyType_Check(self))
4641 Py_FatalError("__new__() called with non-type 'self'");
4642 type = (PyTypeObject *)self;
4643 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004644 PyErr_Format(PyExc_TypeError,
4645 "%s.__new__(): not enough arguments",
4646 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004647 return NULL;
4648 }
4649 arg0 = PyTuple_GET_ITEM(args, 0);
4650 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004651 PyErr_Format(PyExc_TypeError,
4652 "%s.__new__(X): X is not a type object (%s)",
4653 type->tp_name,
Christian Heimese93237d2007-12-19 02:37:44 +00004654 Py_TYPE(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004655 return NULL;
4656 }
4657 subtype = (PyTypeObject *)arg0;
4658 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004659 PyErr_Format(PyExc_TypeError,
4660 "%s.__new__(%s): %s is not a subtype of %s",
4661 type->tp_name,
4662 subtype->tp_name,
4663 subtype->tp_name,
4664 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004665 return NULL;
4666 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004667
4668 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004669 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004670 most derived base that's not a heap type is this type. */
4671 staticbase = subtype;
4672 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4673 staticbase = staticbase->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004674 /* If staticbase is NULL now, it is a really weird type.
4675 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004676 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004677 PyErr_Format(PyExc_TypeError,
4678 "%s.__new__(%s) is not safe, use %s.__new__()",
4679 type->tp_name,
4680 subtype->tp_name,
4681 staticbase == NULL ? "?" : staticbase->tp_name);
4682 return NULL;
4683 }
4684
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004685 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4686 if (args == NULL)
4687 return NULL;
4688 res = type->tp_new(subtype, args, kwds);
4689 Py_DECREF(args);
4690 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004691}
4692
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004693static struct PyMethodDef tp_new_methoddef[] = {
Neal Norwitza84dcd72007-05-22 07:16:44 +00004694 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004695 PyDoc_STR("T.__new__(S, ...) -> "
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004696 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004697 {0}
4698};
4699
4700static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004701add_tp_new_wrapper(PyTypeObject *type)
4702{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004703 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004704
Guido van Rossum687ae002001-10-15 22:03:32 +00004705 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004706 return 0;
4707 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004708 if (func == NULL)
4709 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004710 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004711 Py_DECREF(func);
4712 return -1;
4713 }
4714 Py_DECREF(func);
4715 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004716}
4717
Guido van Rossumf040ede2001-08-07 16:40:56 +00004718/* Slot wrappers that call the corresponding __foo__ slot. See comments
4719 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004720
Guido van Rossumdc91b992001-08-08 22:26:22 +00004721#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004722static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004723FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004724{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004725 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004726 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004727}
4728
Guido van Rossumdc91b992001-08-08 22:26:22 +00004729#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004730static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004731FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004732{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004733 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004734 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004735}
4736
Guido van Rossumcd118802003-01-06 22:57:47 +00004737/* Boolean helper for SLOT1BINFULL().
4738 right.__class__ is a nontrivial subclass of left.__class__. */
4739static int
4740method_is_overloaded(PyObject *left, PyObject *right, char *name)
4741{
4742 PyObject *a, *b;
4743 int ok;
4744
Christian Heimese93237d2007-12-19 02:37:44 +00004745 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004746 if (b == NULL) {
4747 PyErr_Clear();
4748 /* If right doesn't have it, it's not overloaded */
4749 return 0;
4750 }
4751
Christian Heimese93237d2007-12-19 02:37:44 +00004752 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004753 if (a == NULL) {
4754 PyErr_Clear();
4755 Py_DECREF(b);
4756 /* If right has it but left doesn't, it's overloaded */
4757 return 1;
4758 }
4759
4760 ok = PyObject_RichCompareBool(a, b, Py_NE);
4761 Py_DECREF(a);
4762 Py_DECREF(b);
4763 if (ok < 0) {
4764 PyErr_Clear();
4765 return 0;
4766 }
4767
4768 return ok;
4769}
4770
Guido van Rossumdc91b992001-08-08 22:26:22 +00004771
4772#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004773static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004774FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004775{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004776 static PyObject *cache_str, *rcache_str; \
Christian Heimese93237d2007-12-19 02:37:44 +00004777 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4778 Py_TYPE(other)->tp_as_number != NULL && \
4779 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4780 if (Py_TYPE(self)->tp_as_number != NULL && \
4781 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004782 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004783 if (do_other && \
Christian Heimese93237d2007-12-19 02:37:44 +00004784 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004785 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004786 r = call_maybe( \
4787 other, ROPSTR, &rcache_str, "(O)", self); \
4788 if (r != Py_NotImplemented) \
4789 return r; \
4790 Py_DECREF(r); \
4791 do_other = 0; \
4792 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004793 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004794 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004795 if (r != Py_NotImplemented || \
Christian Heimese93237d2007-12-19 02:37:44 +00004796 Py_TYPE(other) == Py_TYPE(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004797 return r; \
4798 Py_DECREF(r); \
4799 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004800 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004801 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004802 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004803 } \
4804 Py_INCREF(Py_NotImplemented); \
4805 return Py_NotImplemented; \
4806}
4807
4808#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4809 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4810
4811#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4812static PyObject * \
4813FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4814{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004815 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004816 return call_method(self, OPSTR, &cache_str, \
4817 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004818}
4819
Martin v. Löwis18e16552006-02-15 17:27:45 +00004820static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004821slot_sq_length(PyObject *self)
4822{
Guido van Rossum2730b132001-08-28 18:22:14 +00004823 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004824 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004825 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004826
4827 if (res == NULL)
4828 return -1;
Neal Norwitz1872b1c2006-08-12 18:44:06 +00004829 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004830 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004831 if (len < 0) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00004832 if (!PyErr_Occurred())
4833 PyErr_SetString(PyExc_ValueError,
4834 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004835 return -1;
4836 }
Guido van Rossum26111622001-10-01 16:42:49 +00004837 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004838}
4839
Guido van Rossumf4593e02001-10-03 12:09:30 +00004840/* Super-optimized version of slot_sq_item.
4841 Other slots could do the same... */
4842static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004843slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004844{
4845 static PyObject *getitem_str;
4846 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4847 descrgetfunc f;
4848
4849 if (getitem_str == NULL) {
Christian Heimes593daf52008-05-26 12:51:38 +00004850 getitem_str = PyBytes_InternFromString("__getitem__");
Guido van Rossumf4593e02001-10-03 12:09:30 +00004851 if (getitem_str == NULL)
4852 return NULL;
4853 }
Christian Heimese93237d2007-12-19 02:37:44 +00004854 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004855 if (func != NULL) {
Christian Heimese93237d2007-12-19 02:37:44 +00004856 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004857 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004858 else {
Christian Heimese93237d2007-12-19 02:37:44 +00004859 func = f(func, self, (PyObject *)(Py_TYPE(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004860 if (func == NULL) {
4861 return NULL;
4862 }
4863 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004864 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004865 if (ival != NULL) {
4866 args = PyTuple_New(1);
4867 if (args != NULL) {
4868 PyTuple_SET_ITEM(args, 0, ival);
4869 retval = PyObject_Call(func, args, NULL);
4870 Py_XDECREF(args);
4871 Py_XDECREF(func);
4872 return retval;
4873 }
4874 }
4875 }
4876 else {
4877 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4878 }
4879 Py_XDECREF(args);
4880 Py_XDECREF(ival);
4881 Py_XDECREF(func);
4882 return NULL;
4883}
4884
Martin v. Löwis18e16552006-02-15 17:27:45 +00004885SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004886
4887static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004888slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004889{
4890 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004891 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004892
4893 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004894 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004895 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004896 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004897 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004898 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004899 if (res == NULL)
4900 return -1;
4901 Py_DECREF(res);
4902 return 0;
4903}
4904
4905static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004906slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004907{
4908 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004909 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004910
4911 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004912 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004913 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004914 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004915 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004916 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004917 if (res == NULL)
4918 return -1;
4919 Py_DECREF(res);
4920 return 0;
4921}
4922
4923static int
4924slot_sq_contains(PyObject *self, PyObject *value)
4925{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004926 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004927 int result = -1;
4928
Guido van Rossum60718732001-08-28 17:47:51 +00004929 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004930
Guido van Rossum55f20992001-10-01 17:18:22 +00004931 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004932 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004933 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004934 if (args == NULL)
4935 res = NULL;
4936 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004937 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004938 Py_DECREF(args);
4939 }
4940 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004941 if (res != NULL) {
4942 result = PyObject_IsTrue(res);
4943 Py_DECREF(res);
4944 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004945 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004946 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004947 /* Possible results: -1 and 1 */
4948 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004949 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004950 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004951 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004952}
4953
Tim Peters6d6c1a32001-08-02 04:15:00 +00004954#define slot_mp_length slot_sq_length
4955
Guido van Rossumdc91b992001-08-08 22:26:22 +00004956SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004957
4958static int
4959slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4960{
4961 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004962 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004963
4964 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004965 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004966 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004967 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004968 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004969 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004970 if (res == NULL)
4971 return -1;
4972 Py_DECREF(res);
4973 return 0;
4974}
4975
Guido van Rossumdc91b992001-08-08 22:26:22 +00004976SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4977SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4978SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4979SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4980SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4981SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4982
Jeremy Hylton938ace62002-07-17 16:30:39 +00004983static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004984
4985SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4986 nb_power, "__pow__", "__rpow__")
4987
4988static PyObject *
4989slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4990{
Guido van Rossum2730b132001-08-28 18:22:14 +00004991 static PyObject *pow_str;
4992
Guido van Rossumdc91b992001-08-08 22:26:22 +00004993 if (modulus == Py_None)
4994 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004995 /* Three-arg power doesn't use __rpow__. But ternary_op
4996 can call this when the second argument's type uses
4997 slot_nb_power, so check before calling self.__pow__. */
Christian Heimese93237d2007-12-19 02:37:44 +00004998 if (Py_TYPE(self)->tp_as_number != NULL &&
4999 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00005000 return call_method(self, "__pow__", &pow_str,
5001 "(OO)", other, modulus);
5002 }
5003 Py_INCREF(Py_NotImplemented);
5004 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005005}
5006
5007SLOT0(slot_nb_negative, "__neg__")
5008SLOT0(slot_nb_positive, "__pos__")
5009SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005010
5011static int
5012slot_nb_nonzero(PyObject *self)
5013{
Tim Petersea7f75d2002-12-07 21:39:16 +00005014 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00005015 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00005016 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005017
Guido van Rossum55f20992001-10-01 17:18:22 +00005018 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005019 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00005020 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00005021 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00005022 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00005023 if (func == NULL)
5024 return PyErr_Occurred() ? -1 : 1;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005025 }
Tim Petersea7f75d2002-12-07 21:39:16 +00005026 args = PyTuple_New(0);
5027 if (args != NULL) {
5028 PyObject *temp = PyObject_Call(func, args, NULL);
5029 Py_DECREF(args);
5030 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00005031 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00005032 result = PyObject_IsTrue(temp);
5033 else {
5034 PyErr_Format(PyExc_TypeError,
5035 "__nonzero__ should return "
5036 "bool or int, returned %s",
5037 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00005038 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00005039 }
Tim Petersea7f75d2002-12-07 21:39:16 +00005040 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00005041 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005042 }
Guido van Rossum55f20992001-10-01 17:18:22 +00005043 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00005044 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005045}
5046
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005047
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005048static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005049slot_nb_index(PyObject *self)
5050{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005051 static PyObject *index_str;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005052 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005053}
5054
5055
Guido van Rossumdc91b992001-08-08 22:26:22 +00005056SLOT0(slot_nb_invert, "__invert__")
5057SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5058SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5059SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5060SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5061SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005062
5063static int
5064slot_nb_coerce(PyObject **a, PyObject **b)
5065{
5066 static PyObject *coerce_str;
5067 PyObject *self = *a, *other = *b;
5068
5069 if (self->ob_type->tp_as_number != NULL &&
5070 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5071 PyObject *r;
5072 r = call_maybe(
5073 self, "__coerce__", &coerce_str, "(O)", other);
5074 if (r == NULL)
5075 return -1;
5076 if (r == Py_NotImplemented) {
5077 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005078 }
Guido van Rossum55f20992001-10-01 17:18:22 +00005079 else {
5080 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5081 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005082 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00005083 Py_DECREF(r);
5084 return -1;
5085 }
5086 *a = PyTuple_GET_ITEM(r, 0);
5087 Py_INCREF(*a);
5088 *b = PyTuple_GET_ITEM(r, 1);
5089 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005090 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00005091 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005092 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005093 }
5094 if (other->ob_type->tp_as_number != NULL &&
5095 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5096 PyObject *r;
5097 r = call_maybe(
5098 other, "__coerce__", &coerce_str, "(O)", self);
5099 if (r == NULL)
5100 return -1;
5101 if (r == Py_NotImplemented) {
5102 Py_DECREF(r);
5103 return 1;
5104 }
5105 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5106 PyErr_SetString(PyExc_TypeError,
5107 "__coerce__ didn't return a 2-tuple");
5108 Py_DECREF(r);
5109 return -1;
5110 }
5111 *a = PyTuple_GET_ITEM(r, 1);
5112 Py_INCREF(*a);
5113 *b = PyTuple_GET_ITEM(r, 0);
5114 Py_INCREF(*b);
5115 Py_DECREF(r);
5116 return 0;
5117 }
5118 return 1;
5119}
5120
Guido van Rossumdc91b992001-08-08 22:26:22 +00005121SLOT0(slot_nb_int, "__int__")
5122SLOT0(slot_nb_long, "__long__")
5123SLOT0(slot_nb_float, "__float__")
5124SLOT0(slot_nb_oct, "__oct__")
5125SLOT0(slot_nb_hex, "__hex__")
5126SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5127SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5128SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
5129SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
5130SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Martin v. Löwisfd963262007-02-09 12:19:32 +00005131/* Can't use SLOT1 here, because nb_inplace_power is ternary */
5132static PyObject *
5133slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5134{
5135 static PyObject *cache_str;
5136 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
5137}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005138SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5139SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5140SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5141SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5142SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5143SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
5144 "__floordiv__", "__rfloordiv__")
5145SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5146SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5147SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005148
5149static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00005150half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005151{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005152 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005153 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005154 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005155
Guido van Rossum60718732001-08-28 17:47:51 +00005156 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005157 if (func == NULL) {
5158 PyErr_Clear();
5159 }
5160 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005161 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005162 if (args == NULL)
5163 res = NULL;
5164 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005165 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005166 Py_DECREF(args);
5167 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00005168 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005169 if (res != Py_NotImplemented) {
5170 if (res == NULL)
5171 return -2;
5172 c = PyInt_AsLong(res);
5173 Py_DECREF(res);
5174 if (c == -1 && PyErr_Occurred())
5175 return -2;
5176 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
5177 }
5178 Py_DECREF(res);
5179 }
5180 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005181}
5182
Guido van Rossumab3b0342001-09-18 20:38:53 +00005183/* This slot is published for the benefit of try_3way_compare in object.c */
5184int
5185_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00005186{
5187 int c;
5188
Christian Heimese93237d2007-12-19 02:37:44 +00005189 if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005190 c = half_compare(self, other);
5191 if (c <= 1)
5192 return c;
5193 }
Christian Heimese93237d2007-12-19 02:37:44 +00005194 if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005195 c = half_compare(other, self);
5196 if (c < -1)
5197 return -2;
5198 if (c <= 1)
5199 return -c;
5200 }
5201 return (void *)self < (void *)other ? -1 :
5202 (void *)self > (void *)other ? 1 : 0;
5203}
5204
5205static PyObject *
5206slot_tp_repr(PyObject *self)
5207{
5208 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005209 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005210
Guido van Rossum60718732001-08-28 17:47:51 +00005211 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005212 if (func != NULL) {
5213 res = PyEval_CallObject(func, NULL);
5214 Py_DECREF(func);
5215 return res;
5216 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00005217 PyErr_Clear();
Christian Heimes593daf52008-05-26 12:51:38 +00005218 return PyBytes_FromFormat("<%s object at %p>",
Christian Heimese93237d2007-12-19 02:37:44 +00005219 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005220}
5221
5222static PyObject *
5223slot_tp_str(PyObject *self)
5224{
5225 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005226 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005227
Guido van Rossum60718732001-08-28 17:47:51 +00005228 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005229 if (func != NULL) {
5230 res = PyEval_CallObject(func, NULL);
5231 Py_DECREF(func);
5232 return res;
5233 }
5234 else {
5235 PyErr_Clear();
5236 return slot_tp_repr(self);
5237 }
5238}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005239
5240static long
5241slot_tp_hash(PyObject *self)
5242{
Tim Peters61ce0a92002-12-06 23:38:02 +00005243 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00005244 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005245 long h;
5246
Guido van Rossum60718732001-08-28 17:47:51 +00005247 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005248
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005249 if (func != NULL && func != Py_None) {
Tim Peters61ce0a92002-12-06 23:38:02 +00005250 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005251 Py_DECREF(func);
5252 if (res == NULL)
5253 return -1;
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00005254 if (PyLong_Check(res))
Armin Rigo51fc8c42006-08-09 14:55:26 +00005255 h = PyLong_Type.tp_hash(res);
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00005256 else
5257 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00005258 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005259 }
5260 else {
Georg Brandl30b78042007-12-20 21:03:02 +00005261 Py_XDECREF(func); /* may be None */
Guido van Rossumb8f63662001-08-15 23:57:02 +00005262 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005263 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005264 if (func == NULL) {
5265 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005266 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005267 }
5268 if (func != NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00005269 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
5270 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005271 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005272 return -1;
5273 }
5274 PyErr_Clear();
5275 h = _Py_HashPointer((void *)self);
5276 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005277 if (h == -1 && !PyErr_Occurred())
5278 h = -2;
5279 return h;
5280}
5281
5282static PyObject *
5283slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5284{
Guido van Rossum60718732001-08-28 17:47:51 +00005285 static PyObject *call_str;
5286 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005287 PyObject *res;
5288
5289 if (meth == NULL)
5290 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00005291
Tim Peters6d6c1a32001-08-02 04:15:00 +00005292 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00005293
Tim Peters6d6c1a32001-08-02 04:15:00 +00005294 Py_DECREF(meth);
5295 return res;
5296}
5297
Guido van Rossum14a6f832001-10-17 13:59:09 +00005298/* There are two slot dispatch functions for tp_getattro.
5299
5300 - slot_tp_getattro() is used when __getattribute__ is overridden
5301 but no __getattr__ hook is present;
5302
5303 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5304
Guido van Rossumc334df52002-04-04 23:44:47 +00005305 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5306 detects the absence of __getattr__ and then installs the simpler slot if
5307 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005308
Tim Peters6d6c1a32001-08-02 04:15:00 +00005309static PyObject *
5310slot_tp_getattro(PyObject *self, PyObject *name)
5311{
Guido van Rossum14a6f832001-10-17 13:59:09 +00005312 static PyObject *getattribute_str = NULL;
5313 return call_method(self, "__getattribute__", &getattribute_str,
5314 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005315}
5316
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005317static PyObject *
5318slot_tp_getattr_hook(PyObject *self, PyObject *name)
5319{
Christian Heimese93237d2007-12-19 02:37:44 +00005320 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005321 PyObject *getattr, *getattribute, *res;
5322 static PyObject *getattribute_str = NULL;
5323 static PyObject *getattr_str = NULL;
5324
5325 if (getattr_str == NULL) {
Christian Heimes593daf52008-05-26 12:51:38 +00005326 getattr_str = PyBytes_InternFromString("__getattr__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005327 if (getattr_str == NULL)
5328 return NULL;
5329 }
5330 if (getattribute_str == NULL) {
5331 getattribute_str =
Christian Heimes593daf52008-05-26 12:51:38 +00005332 PyBytes_InternFromString("__getattribute__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005333 if (getattribute_str == NULL)
5334 return NULL;
5335 }
5336 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005337 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005338 /* No __getattr__ hook: use a simpler dispatcher */
5339 tp->tp_getattro = slot_tp_getattro;
5340 return slot_tp_getattro(self, name);
5341 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005342 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005343 if (getattribute == NULL ||
Christian Heimese93237d2007-12-19 02:37:44 +00005344 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00005345 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5346 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005347 res = PyObject_GenericGetAttr(self, name);
5348 else
Georg Brandl684fd0c2006-05-25 19:15:31 +00005349 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005350 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005351 PyErr_Clear();
Georg Brandl684fd0c2006-05-25 19:15:31 +00005352 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005353 }
5354 return res;
5355}
5356
Tim Peters6d6c1a32001-08-02 04:15:00 +00005357static int
5358slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5359{
5360 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005361 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005362
5363 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00005364 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005365 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005366 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005367 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005368 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005369 if (res == NULL)
5370 return -1;
5371 Py_DECREF(res);
5372 return 0;
5373}
5374
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005375static char *name_op[] = {
5376 "__lt__",
5377 "__le__",
5378 "__eq__",
5379 "__ne__",
5380 "__gt__",
5381 "__ge__",
5382};
5383
Tim Peters6d6c1a32001-08-02 04:15:00 +00005384static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005385half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005386{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005387 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005388 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005389
Guido van Rossum60718732001-08-28 17:47:51 +00005390 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005391 if (func == NULL) {
5392 PyErr_Clear();
5393 Py_INCREF(Py_NotImplemented);
5394 return Py_NotImplemented;
5395 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005396 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005397 if (args == NULL)
5398 res = NULL;
5399 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005400 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005401 Py_DECREF(args);
5402 }
5403 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005404 return res;
5405}
5406
Guido van Rossumb8f63662001-08-15 23:57:02 +00005407static PyObject *
5408slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5409{
5410 PyObject *res;
5411
Christian Heimese93237d2007-12-19 02:37:44 +00005412 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005413 res = half_richcompare(self, other, op);
5414 if (res != Py_NotImplemented)
5415 return res;
5416 Py_DECREF(res);
5417 }
Christian Heimese93237d2007-12-19 02:37:44 +00005418 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00005419 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005420 if (res != Py_NotImplemented) {
5421 return res;
5422 }
5423 Py_DECREF(res);
5424 }
5425 Py_INCREF(Py_NotImplemented);
5426 return Py_NotImplemented;
5427}
5428
5429static PyObject *
5430slot_tp_iter(PyObject *self)
5431{
5432 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005433 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005434
Guido van Rossum60718732001-08-28 17:47:51 +00005435 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005436 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00005437 PyObject *args;
5438 args = res = PyTuple_New(0);
5439 if (args != NULL) {
5440 res = PyObject_Call(func, args, NULL);
5441 Py_DECREF(args);
5442 }
5443 Py_DECREF(func);
5444 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005445 }
5446 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005447 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005448 if (func == NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00005449 PyErr_Format(PyExc_TypeError,
5450 "'%.200s' object is not iterable",
Christian Heimese93237d2007-12-19 02:37:44 +00005451 Py_TYPE(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005452 return NULL;
5453 }
5454 Py_DECREF(func);
5455 return PySeqIter_New(self);
5456}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005457
5458static PyObject *
5459slot_tp_iternext(PyObject *self)
5460{
Guido van Rossum2730b132001-08-28 18:22:14 +00005461 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00005462 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005463}
5464
Guido van Rossum1a493502001-08-17 16:47:50 +00005465static PyObject *
5466slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5467{
Christian Heimese93237d2007-12-19 02:37:44 +00005468 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00005469 PyObject *get;
5470 static PyObject *get_str = NULL;
5471
5472 if (get_str == NULL) {
Christian Heimes593daf52008-05-26 12:51:38 +00005473 get_str = PyBytes_InternFromString("__get__");
Guido van Rossum1a493502001-08-17 16:47:50 +00005474 if (get_str == NULL)
5475 return NULL;
5476 }
5477 get = _PyType_Lookup(tp, get_str);
5478 if (get == NULL) {
5479 /* Avoid further slowdowns */
5480 if (tp->tp_descr_get == slot_tp_descr_get)
5481 tp->tp_descr_get = NULL;
5482 Py_INCREF(self);
5483 return self;
5484 }
Guido van Rossum2c252392001-08-24 10:13:31 +00005485 if (obj == NULL)
5486 obj = Py_None;
5487 if (type == NULL)
5488 type = Py_None;
Georg Brandl684fd0c2006-05-25 19:15:31 +00005489 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005490}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005491
5492static int
5493slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5494{
Guido van Rossum2c252392001-08-24 10:13:31 +00005495 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005496 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005497
5498 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00005499 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005500 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00005501 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005502 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005503 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005504 if (res == NULL)
5505 return -1;
5506 Py_DECREF(res);
5507 return 0;
5508}
5509
5510static int
5511slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5512{
Guido van Rossum60718732001-08-28 17:47:51 +00005513 static PyObject *init_str;
5514 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005515 PyObject *res;
5516
5517 if (meth == NULL)
5518 return -1;
5519 res = PyObject_Call(meth, args, kwds);
5520 Py_DECREF(meth);
5521 if (res == NULL)
5522 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005523 if (res != Py_None) {
Georg Brandlccff7852006-06-18 22:17:29 +00005524 PyErr_Format(PyExc_TypeError,
5525 "__init__() should return None, not '%.200s'",
Christian Heimese93237d2007-12-19 02:37:44 +00005526 Py_TYPE(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005527 Py_DECREF(res);
5528 return -1;
5529 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005530 Py_DECREF(res);
5531 return 0;
5532}
5533
5534static PyObject *
5535slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5536{
Guido van Rossum7bed2132002-08-08 21:57:53 +00005537 static PyObject *new_str;
5538 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005539 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005540 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005541
Guido van Rossum7bed2132002-08-08 21:57:53 +00005542 if (new_str == NULL) {
Christian Heimes593daf52008-05-26 12:51:38 +00005543 new_str = PyBytes_InternFromString("__new__");
Guido van Rossum7bed2132002-08-08 21:57:53 +00005544 if (new_str == NULL)
5545 return NULL;
5546 }
5547 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005548 if (func == NULL)
5549 return NULL;
5550 assert(PyTuple_Check(args));
5551 n = PyTuple_GET_SIZE(args);
5552 newargs = PyTuple_New(n+1);
5553 if (newargs == NULL)
5554 return NULL;
5555 Py_INCREF(type);
5556 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5557 for (i = 0; i < n; i++) {
5558 x = PyTuple_GET_ITEM(args, i);
5559 Py_INCREF(x);
5560 PyTuple_SET_ITEM(newargs, i+1, x);
5561 }
5562 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005563 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005564 Py_DECREF(func);
5565 return x;
5566}
5567
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005568static void
5569slot_tp_del(PyObject *self)
5570{
5571 static PyObject *del_str = NULL;
5572 PyObject *del, *res;
5573 PyObject *error_type, *error_value, *error_traceback;
5574
5575 /* Temporarily resurrect the object. */
5576 assert(self->ob_refcnt == 0);
5577 self->ob_refcnt = 1;
5578
5579 /* Save the current exception, if any. */
5580 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5581
5582 /* Execute __del__ method, if any. */
5583 del = lookup_maybe(self, "__del__", &del_str);
5584 if (del != NULL) {
5585 res = PyEval_CallObject(del, NULL);
5586 if (res == NULL)
5587 PyErr_WriteUnraisable(del);
5588 else
5589 Py_DECREF(res);
5590 Py_DECREF(del);
5591 }
5592
5593 /* Restore the saved exception. */
5594 PyErr_Restore(error_type, error_value, error_traceback);
5595
5596 /* Undo the temporary resurrection; can't use DECREF here, it would
5597 * cause a recursive call.
5598 */
5599 assert(self->ob_refcnt > 0);
5600 if (--self->ob_refcnt == 0)
5601 return; /* this is the normal path out */
5602
5603 /* __del__ resurrected it! Make it look like the original Py_DECREF
5604 * never happened.
5605 */
5606 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005607 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005608 _Py_NewReference(self);
5609 self->ob_refcnt = refcnt;
5610 }
Christian Heimese93237d2007-12-19 02:37:44 +00005611 assert(!PyType_IS_GC(Py_TYPE(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005612 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005613 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5614 * we need to undo that. */
5615 _Py_DEC_REFTOTAL;
5616 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5617 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005618 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5619 * _Py_NewReference bumped tp_allocs: both of those need to be
5620 * undone.
5621 */
5622#ifdef COUNT_ALLOCS
Christian Heimese93237d2007-12-19 02:37:44 +00005623 --Py_TYPE(self)->tp_frees;
5624 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005625#endif
5626}
5627
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005628
5629/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005630 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005631 structure, which incorporates the additional structures used for numbers,
5632 sequences and mappings.
5633 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005634 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005635 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5636 terminated with an all-zero entry. (This table is further initialized and
5637 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005638
Guido van Rossum6d204072001-10-21 00:44:31 +00005639typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005640
5641#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005642#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005643#undef ETSLOT
5644#undef SQSLOT
5645#undef MPSLOT
5646#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005647#undef UNSLOT
5648#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005649#undef BINSLOT
5650#undef RBINSLOT
5651
Guido van Rossum6d204072001-10-21 00:44:31 +00005652#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005653 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5654 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005655#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5656 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005657 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005658#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005659 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005660 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005661#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5662 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5663#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5664 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5665#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5666 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5667#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5668 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5669 "x." NAME "() <==> " DOC)
5670#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5671 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5672 "x." NAME "(y) <==> x" DOC "y")
5673#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5674 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5675 "x." NAME "(y) <==> x" DOC "y")
5676#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5677 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5678 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005679#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5680 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5681 "x." NAME "(y) <==> " DOC)
5682#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5683 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5684 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005685
5686static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005687 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005688 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005689 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5690 The logic in abstract.c always falls back to nb_add/nb_multiply in
5691 this case. Defining both the nb_* and the sq_* slots to call the
5692 user-defined methods has unexpected side-effects, as shown by
5693 test_descr.notimplemented() */
5694 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005695 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00005696 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005697 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005698 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005699 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005700 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5701 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005702 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005703 "x.__getslice__(i, j) <==> x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005704 \n\
5705 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005706 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005707 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005708 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005709 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005710 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005711 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005712 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005713 \n\
5714 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005715 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005716 "x.__delslice__(i, j) <==> del x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005717 \n\
5718 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005719 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5720 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005721 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005722 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005723 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005724 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005725
Martin v. Löwis18e16552006-02-15 17:27:45 +00005726 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005727 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005728 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005729 wrap_binaryfunc,
5730 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005731 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005732 wrap_objobjargproc,
5733 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005734 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005735 wrap_delitem,
5736 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005737
Guido van Rossum6d204072001-10-21 00:44:31 +00005738 BINSLOT("__add__", nb_add, slot_nb_add,
5739 "+"),
5740 RBINSLOT("__radd__", nb_add, slot_nb_add,
5741 "+"),
5742 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5743 "-"),
5744 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5745 "-"),
5746 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5747 "*"),
5748 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5749 "*"),
5750 BINSLOT("__div__", nb_divide, slot_nb_divide,
5751 "/"),
5752 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5753 "/"),
5754 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5755 "%"),
5756 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5757 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005758 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005759 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005760 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005761 "divmod(y, x)"),
5762 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5763 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5764 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5765 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5766 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5767 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5768 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5769 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005770 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005771 "x != 0"),
5772 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5773 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5774 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5775 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5776 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5777 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5778 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5779 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5780 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5781 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5782 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5783 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5784 "x.__coerce__(y) <==> coerce(x, y)"),
5785 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5786 "int(x)"),
5787 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5788 "long(x)"),
5789 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5790 "float(x)"),
5791 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5792 "oct(x)"),
5793 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5794 "hex(x)"),
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005795 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005796 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005797 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5798 wrap_binaryfunc, "+"),
5799 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5800 wrap_binaryfunc, "-"),
5801 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5802 wrap_binaryfunc, "*"),
5803 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5804 wrap_binaryfunc, "/"),
5805 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5806 wrap_binaryfunc, "%"),
5807 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005808 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005809 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5810 wrap_binaryfunc, "<<"),
5811 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5812 wrap_binaryfunc, ">>"),
5813 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5814 wrap_binaryfunc, "&"),
5815 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5816 wrap_binaryfunc, "^"),
5817 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5818 wrap_binaryfunc, "|"),
5819 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5820 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5821 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5822 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5823 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5824 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5825 IBSLOT("__itruediv__", nb_inplace_true_divide,
5826 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005827
Guido van Rossum6d204072001-10-21 00:44:31 +00005828 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5829 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005830 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005831 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5832 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005833 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005834 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5835 "x.__cmp__(y) <==> cmp(x,y)"),
5836 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5837 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005838 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5839 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005840 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005841 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5842 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5843 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5844 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5845 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5846 "x.__setattr__('name', value) <==> x.name = value"),
5847 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5848 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5849 "x.__delattr__('name') <==> del x.name"),
5850 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5851 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5852 "x.__lt__(y) <==> x<y"),
5853 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5854 "x.__le__(y) <==> x<=y"),
5855 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5856 "x.__eq__(y) <==> x==y"),
5857 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5858 "x.__ne__(y) <==> x!=y"),
5859 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5860 "x.__gt__(y) <==> x>y"),
5861 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5862 "x.__ge__(y) <==> x>=y"),
5863 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5864 "x.__iter__() <==> iter(x)"),
5865 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5866 "x.next() -> the next value, or raise StopIteration"),
5867 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5868 "descr.__get__(obj[, type]) -> value"),
5869 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5870 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005871 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5872 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005873 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005874 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005875 "see x.__class__.__doc__ for signature",
5876 PyWrapperFlag_KEYWORDS),
5877 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005878 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005879 {NULL}
5880};
5881
Guido van Rossumc334df52002-04-04 23:44:47 +00005882/* Given a type pointer and an offset gotten from a slotdef entry, return a
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005883 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005884 the offset to the type pointer, since it takes care to indirect through the
5885 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5886 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005887static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005888slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005889{
5890 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005891 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005892
Guido van Rossume5c691a2003-03-07 15:13:17 +00005893 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005894 assert(offset >= 0);
Skip Montanaro429433b2006-04-18 00:35:43 +00005895 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5896 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005897 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005898 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005899 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005900 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005901 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005902 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005903 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005904 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005905 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005906 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005907 }
5908 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005909 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005910 }
5911 if (ptr != NULL)
5912 ptr += offset;
5913 return (void **)ptr;
5914}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005915
Guido van Rossumc334df52002-04-04 23:44:47 +00005916/* Length of array of slotdef pointers used to store slots with the
5917 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5918 the same __name__, for any __name__. Since that's a static property, it is
5919 appropriate to declare fixed-size arrays for this. */
5920#define MAX_EQUIV 10
5921
5922/* Return a slot pointer for a given name, but ONLY if the attribute has
5923 exactly one slot function. The name must be an interned string. */
5924static void **
5925resolve_slotdups(PyTypeObject *type, PyObject *name)
5926{
5927 /* XXX Maybe this could be optimized more -- but is it worth it? */
5928
5929 /* pname and ptrs act as a little cache */
5930 static PyObject *pname;
5931 static slotdef *ptrs[MAX_EQUIV];
5932 slotdef *p, **pp;
5933 void **res, **ptr;
5934
5935 if (pname != name) {
5936 /* Collect all slotdefs that match name into ptrs. */
5937 pname = name;
5938 pp = ptrs;
5939 for (p = slotdefs; p->name_strobj; p++) {
5940 if (p->name_strobj == name)
5941 *pp++ = p;
5942 }
5943 *pp = NULL;
5944 }
5945
5946 /* Look in all matching slots of the type; if exactly one of these has
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005947 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005948 res = NULL;
5949 for (pp = ptrs; *pp; pp++) {
5950 ptr = slotptr(type, (*pp)->offset);
5951 if (ptr == NULL || *ptr == NULL)
5952 continue;
5953 if (res != NULL)
5954 return NULL;
5955 res = ptr;
5956 }
5957 return res;
5958}
5959
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005960/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005961 does some incredibly complex thinking and then sticks something into the
5962 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5963 interests, and then stores a generic wrapper or a specific function into
5964 the slot.) Return a pointer to the next slotdef with a different offset,
5965 because that's convenient for fixup_slot_dispatchers(). */
5966static slotdef *
5967update_one_slot(PyTypeObject *type, slotdef *p)
5968{
5969 PyObject *descr;
5970 PyWrapperDescrObject *d;
5971 void *generic = NULL, *specific = NULL;
5972 int use_generic = 0;
5973 int offset = p->offset;
5974 void **ptr = slotptr(type, offset);
5975
5976 if (ptr == NULL) {
5977 do {
5978 ++p;
5979 } while (p->offset == offset);
5980 return p;
5981 }
5982 do {
5983 descr = _PyType_Lookup(type, p->name_strobj);
5984 if (descr == NULL)
5985 continue;
Christian Heimese93237d2007-12-19 02:37:44 +00005986 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00005987 void **tptr = resolve_slotdups(type, p->name_strobj);
5988 if (tptr == NULL || tptr == ptr)
5989 generic = p->function;
5990 d = (PyWrapperDescrObject *)descr;
5991 if (d->d_base->wrapper == p->wrapper &&
5992 PyType_IsSubtype(type, d->d_type))
5993 {
5994 if (specific == NULL ||
5995 specific == d->d_wrapped)
5996 specific = d->d_wrapped;
5997 else
5998 use_generic = 1;
5999 }
6000 }
Christian Heimese93237d2007-12-19 02:37:44 +00006001 else if (Py_TYPE(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00006002 PyCFunction_GET_FUNCTION(descr) ==
6003 (PyCFunction)tp_new_wrapper &&
6004 strcmp(p->name, "__new__") == 0)
6005 {
6006 /* The __new__ wrapper is not a wrapper descriptor,
6007 so must be special-cased differently.
6008 If we don't do this, creating an instance will
6009 always use slot_tp_new which will look up
6010 __new__ in the MRO which will call tp_new_wrapper
6011 which will look through the base classes looking
6012 for a static base and call its tp_new (usually
6013 PyType_GenericNew), after performing various
6014 sanity checks and constructing a new argument
6015 list. Cut all that nonsense short -- this speeds
6016 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00006017 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00006018 /* XXX I'm not 100% sure that there isn't a hole
6019 in this reasoning that requires additional
6020 sanity checks. I'll buy the first person to
6021 point out a bug in this reasoning a beer. */
6022 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006023 else {
6024 use_generic = 1;
6025 generic = p->function;
6026 }
6027 } while ((++p)->offset == offset);
6028 if (specific && !use_generic)
6029 *ptr = specific;
6030 else
6031 *ptr = generic;
6032 return p;
6033}
6034
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006035/* In the type, update the slots whose slotdefs are gathered in the pp array.
6036 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006037static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006038update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006039{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006040 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006041
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006042 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00006043 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006044 return 0;
6045}
6046
Guido van Rossumc334df52002-04-04 23:44:47 +00006047/* Comparison function for qsort() to compare slotdefs by their offset, and
6048 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006049static int
6050slotdef_cmp(const void *aa, const void *bb)
6051{
6052 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
6053 int c = a->offset - b->offset;
6054 if (c != 0)
6055 return c;
6056 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00006057 /* Cannot use a-b, as this gives off_t,
6058 which may lose precision when converted to int. */
6059 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006060}
6061
Guido van Rossumc334df52002-04-04 23:44:47 +00006062/* Initialize the slotdefs table by adding interned string objects for the
6063 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006064static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006065init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006066{
6067 slotdef *p;
6068 static int initialized = 0;
6069
6070 if (initialized)
6071 return;
6072 for (p = slotdefs; p->name; p++) {
Christian Heimes593daf52008-05-26 12:51:38 +00006073 p->name_strobj = PyBytes_InternFromString(p->name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006074 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00006075 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006076 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006077 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
6078 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006079 initialized = 1;
6080}
6081
Guido van Rossumc334df52002-04-04 23:44:47 +00006082/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006083static int
6084update_slot(PyTypeObject *type, PyObject *name)
6085{
Guido van Rossumc334df52002-04-04 23:44:47 +00006086 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006087 slotdef *p;
6088 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006089 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006090
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00006091 /* Clear the VALID_VERSION flag of 'type' and all its
6092 subclasses. This could possibly be unified with the
6093 update_subclasses() recursion below, but carefully:
6094 they each have their own conditions on which to stop
6095 recursing into subclasses. */
Georg Brandl74a1dea2008-05-28 11:21:39 +00006096 PyType_Modified(type);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00006097
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006098 init_slotdefs();
6099 pp = ptrs;
6100 for (p = slotdefs; p->name; p++) {
6101 /* XXX assume name is interned! */
6102 if (p->name_strobj == name)
6103 *pp++ = p;
6104 }
6105 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006106 for (pp = ptrs; *pp; pp++) {
6107 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006108 offset = p->offset;
6109 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006110 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006111 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006112 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006113 if (ptrs[0] == NULL)
6114 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006115 return update_subclasses(type, name,
6116 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006117}
6118
Guido van Rossumc334df52002-04-04 23:44:47 +00006119/* Store the proper functions in the slot dispatches at class (type)
6120 definition time, based upon which operations the class overrides in its
6121 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006122static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006123fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006124{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006125 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006126
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006127 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00006128 for (p = slotdefs; p->name; )
6129 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006130}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006131
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006132static void
6133update_all_slots(PyTypeObject* type)
6134{
6135 slotdef *p;
6136
6137 init_slotdefs();
6138 for (p = slotdefs; p->name; p++) {
6139 /* update_slot returns int but can't actually fail */
6140 update_slot(type, p->name_strobj);
6141 }
6142}
6143
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006144/* recurse_down_subclasses() and update_subclasses() are mutually
6145 recursive functions to call a callback for all subclasses,
6146 but refraining from recursing into subclasses that define 'name'. */
6147
6148static int
6149update_subclasses(PyTypeObject *type, PyObject *name,
6150 update_callback callback, void *data)
6151{
6152 if (callback(type, data) < 0)
6153 return -1;
6154 return recurse_down_subclasses(type, name, callback, data);
6155}
6156
6157static int
6158recurse_down_subclasses(PyTypeObject *type, PyObject *name,
6159 update_callback callback, void *data)
6160{
6161 PyTypeObject *subclass;
6162 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006163 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006164
6165 subclasses = type->tp_subclasses;
6166 if (subclasses == NULL)
6167 return 0;
6168 assert(PyList_Check(subclasses));
6169 n = PyList_GET_SIZE(subclasses);
6170 for (i = 0; i < n; i++) {
6171 ref = PyList_GET_ITEM(subclasses, i);
6172 assert(PyWeakref_CheckRef(ref));
6173 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6174 assert(subclass != NULL);
6175 if ((PyObject *)subclass == Py_None)
6176 continue;
6177 assert(PyType_Check(subclass));
6178 /* Avoid recursing down into unaffected classes */
6179 dict = subclass->tp_dict;
6180 if (dict != NULL && PyDict_Check(dict) &&
6181 PyDict_GetItem(dict, name) != NULL)
6182 continue;
6183 if (update_subclasses(subclass, name, callback, data) < 0)
6184 return -1;
6185 }
6186 return 0;
6187}
6188
Guido van Rossum6d204072001-10-21 00:44:31 +00006189/* This function is called by PyType_Ready() to populate the type's
6190 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006191 function slot (like tp_repr) that's defined in the type, one or more
6192 corresponding descriptors are added in the type's tp_dict dictionary
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006193 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006194 cause more than one descriptor to be added (for example, the nb_add
6195 slot adds both __add__ and __radd__ descriptors) and some function
6196 slots compete for the same descriptor (for example both sq_item and
6197 mp_subscript generate a __getitem__ descriptor).
6198
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006199 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006200 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006201 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006202 between competing slots: the members of PyHeapTypeObject are listed
6203 from most general to least general, so the most general slot is
6204 preferred. In particular, because as_mapping comes before as_sequence,
6205 for a type that defines both mp_subscript and sq_item, mp_subscript
6206 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006207
6208 This only adds new descriptors and doesn't overwrite entries in
6209 tp_dict that were previously defined. The descriptors contain a
6210 reference to the C function they must call, so that it's safe if they
6211 are copied into a subtype's __dict__ and the subtype has a different
6212 C function in its slot -- calling the method defined by the
6213 descriptor will call the C function that was used to create it,
6214 rather than the C function present in the slot when it is called.
6215 (This is important because a subtype may have a C function in the
6216 slot that calls the method from the dictionary, and we want to avoid
6217 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006218
6219static int
6220add_operators(PyTypeObject *type)
6221{
6222 PyObject *dict = type->tp_dict;
6223 slotdef *p;
6224 PyObject *descr;
6225 void **ptr;
6226
6227 init_slotdefs();
6228 for (p = slotdefs; p->name; p++) {
6229 if (p->wrapper == NULL)
6230 continue;
6231 ptr = slotptr(type, p->offset);
6232 if (!ptr || !*ptr)
6233 continue;
6234 if (PyDict_GetItem(dict, p->name_strobj))
6235 continue;
6236 descr = PyDescr_NewWrapper(type, p, *ptr);
6237 if (descr == NULL)
6238 return -1;
6239 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6240 return -1;
6241 Py_DECREF(descr);
6242 }
6243 if (type->tp_new != NULL) {
6244 if (add_tp_new_wrapper(type) < 0)
6245 return -1;
6246 }
6247 return 0;
6248}
6249
Guido van Rossum705f0f52001-08-24 16:47:00 +00006250
6251/* Cooperative 'super' */
6252
6253typedef struct {
6254 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00006255 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006256 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006257 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006258} superobject;
6259
Guido van Rossum6f799372001-09-20 20:46:19 +00006260static PyMemberDef super_members[] = {
6261 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6262 "the class invoking super()"},
6263 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6264 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006265 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00006266 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006267 {0}
6268};
6269
Guido van Rossum705f0f52001-08-24 16:47:00 +00006270static void
6271super_dealloc(PyObject *self)
6272{
6273 superobject *su = (superobject *)self;
6274
Guido van Rossum048eb752001-10-02 21:24:57 +00006275 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006276 Py_XDECREF(su->obj);
6277 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006278 Py_XDECREF(su->obj_type);
Christian Heimese93237d2007-12-19 02:37:44 +00006279 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006280}
6281
6282static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006283super_repr(PyObject *self)
6284{
6285 superobject *su = (superobject *)self;
6286
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006287 if (su->obj_type)
Christian Heimes593daf52008-05-26 12:51:38 +00006288 return PyBytes_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00006289 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006290 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006291 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006292 else
Christian Heimes593daf52008-05-26 12:51:38 +00006293 return PyBytes_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00006294 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006295 su->type ? su->type->tp_name : "NULL");
6296}
6297
6298static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006299super_getattro(PyObject *self, PyObject *name)
6300{
6301 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006302 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006303
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006304 if (!skip) {
6305 /* We want __class__ to return the class of the super object
6306 (i.e. super, or a subclass), not the class of su->obj. */
Christian Heimes593daf52008-05-26 12:51:38 +00006307 skip = (PyBytes_Check(name) &&
6308 PyBytes_GET_SIZE(name) == 9 &&
6309 strcmp(PyBytes_AS_STRING(name), "__class__") == 0);
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006310 }
6311
6312 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00006313 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006314 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006315 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006316 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006317
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006318 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006319 mro = starttype->tp_mro;
6320
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006321 if (mro == NULL)
6322 n = 0;
6323 else {
6324 assert(PyTuple_Check(mro));
6325 n = PyTuple_GET_SIZE(mro);
6326 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006327 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00006328 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00006329 break;
6330 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006331 i++;
6332 res = NULL;
6333 for (; i < n; i++) {
6334 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00006335 if (PyType_Check(tmp))
6336 dict = ((PyTypeObject *)tmp)->tp_dict;
6337 else if (PyClass_Check(tmp))
6338 dict = ((PyClassObject *)tmp)->cl_dict;
6339 else
6340 continue;
6341 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00006342 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00006343 Py_INCREF(res);
Christian Heimese93237d2007-12-19 02:37:44 +00006344 f = Py_TYPE(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006345 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006346 tmp = f(res,
6347 /* Only pass 'obj' param if
6348 this is instance-mode super
6349 (See SF ID #743627)
6350 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00006351 (su->obj == (PyObject *)
6352 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006353 ? (PyObject *)NULL
6354 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00006355 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006356 Py_DECREF(res);
6357 res = tmp;
6358 }
6359 return res;
6360 }
6361 }
6362 }
6363 return PyObject_GenericGetAttr(self, name);
6364}
6365
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006366static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006367supercheck(PyTypeObject *type, PyObject *obj)
6368{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006369 /* Check that a super() call makes sense. Return a type object.
6370
6371 obj can be a new-style class, or an instance of one:
6372
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006373 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006374 used for class methods; the return value is obj.
6375
6376 - If it is an instance, it must be an instance of 'type'. This is
6377 the normal case; the return value is obj.__class__.
6378
6379 But... when obj is an instance, we want to allow for the case where
Christian Heimese93237d2007-12-19 02:37:44 +00006380 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006381 This will allow using super() with a proxy for obj.
6382 */
6383
Guido van Rossum8e80a722003-02-18 19:22:22 +00006384 /* Check for first bullet above (special case) */
6385 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6386 Py_INCREF(obj);
6387 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006388 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006389
6390 /* Normal case */
Christian Heimese93237d2007-12-19 02:37:44 +00006391 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6392 Py_INCREF(Py_TYPE(obj));
6393 return Py_TYPE(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006394 }
6395 else {
6396 /* Try the slow way */
6397 static PyObject *class_str = NULL;
6398 PyObject *class_attr;
6399
6400 if (class_str == NULL) {
Christian Heimes593daf52008-05-26 12:51:38 +00006401 class_str = PyBytes_FromString("__class__");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006402 if (class_str == NULL)
6403 return NULL;
6404 }
6405
6406 class_attr = PyObject_GetAttr(obj, class_str);
6407
6408 if (class_attr != NULL &&
6409 PyType_Check(class_attr) &&
Christian Heimese93237d2007-12-19 02:37:44 +00006410 (PyTypeObject *)class_attr != Py_TYPE(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006411 {
6412 int ok = PyType_IsSubtype(
6413 (PyTypeObject *)class_attr, type);
6414 if (ok)
6415 return (PyTypeObject *)class_attr;
6416 }
6417
6418 if (class_attr == NULL)
6419 PyErr_Clear();
6420 else
6421 Py_DECREF(class_attr);
6422 }
6423
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006424 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006425 "super(type, obj): "
6426 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006427 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006428}
6429
Guido van Rossum705f0f52001-08-24 16:47:00 +00006430static PyObject *
6431super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6432{
6433 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00006434 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006435
6436 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6437 /* Not binding to an object, or already bound */
6438 Py_INCREF(self);
6439 return self;
6440 }
Christian Heimese93237d2007-12-19 02:37:44 +00006441 if (Py_TYPE(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00006442 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006443 call its type */
Christian Heimese93237d2007-12-19 02:37:44 +00006444 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006445 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00006446 else {
6447 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006448 PyTypeObject *obj_type = supercheck(su->type, obj);
6449 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006450 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00006451 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006452 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00006453 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006454 return NULL;
6455 Py_INCREF(su->type);
6456 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00006457 newobj->type = su->type;
6458 newobj->obj = obj;
6459 newobj->obj_type = obj_type;
6460 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006461 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006462}
6463
6464static int
6465super_init(PyObject *self, PyObject *args, PyObject *kwds)
6466{
6467 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00006468 PyTypeObject *type;
6469 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006470 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006471
Georg Brandl5d59c092006-09-30 08:43:30 +00006472 if (!_PyArg_NoKeywords("super", kwds))
6473 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006474 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
6475 return -1;
6476 if (obj == Py_None)
6477 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006478 if (obj != NULL) {
6479 obj_type = supercheck(type, obj);
6480 if (obj_type == NULL)
6481 return -1;
6482 Py_INCREF(obj);
6483 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006484 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006485 su->type = type;
6486 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006487 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006488 return 0;
6489}
6490
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006491PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00006492"super(type) -> unbound super object\n"
6493"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006494"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006495"Typical use to call a cooperative superclass method:\n"
6496"class C(B):\n"
6497" def meth(self, arg):\n"
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006498" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006499
Guido van Rossum048eb752001-10-02 21:24:57 +00006500static int
6501super_traverse(PyObject *self, visitproc visit, void *arg)
6502{
6503 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006504
Thomas Woutersc6e55062006-04-15 21:47:09 +00006505 Py_VISIT(su->obj);
6506 Py_VISIT(su->type);
6507 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006508
6509 return 0;
6510}
6511
Guido van Rossum705f0f52001-08-24 16:47:00 +00006512PyTypeObject PySuper_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00006513 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00006514 "super", /* tp_name */
6515 sizeof(superobject), /* tp_basicsize */
6516 0, /* tp_itemsize */
6517 /* methods */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006518 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006519 0, /* tp_print */
6520 0, /* tp_getattr */
6521 0, /* tp_setattr */
6522 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006523 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006524 0, /* tp_as_number */
6525 0, /* tp_as_sequence */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006526 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006527 0, /* tp_hash */
6528 0, /* tp_call */
6529 0, /* tp_str */
6530 super_getattro, /* tp_getattro */
6531 0, /* tp_setattro */
6532 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006533 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6534 Py_TPFLAGS_BASETYPE, /* tp_flags */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006535 super_doc, /* tp_doc */
6536 super_traverse, /* tp_traverse */
6537 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006538 0, /* tp_richcompare */
6539 0, /* tp_weaklistoffset */
6540 0, /* tp_iter */
6541 0, /* tp_iternext */
6542 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006543 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006544 0, /* tp_getset */
6545 0, /* tp_base */
6546 0, /* tp_dict */
6547 super_descr_get, /* tp_descr_get */
6548 0, /* tp_descr_set */
6549 0, /* tp_dictoffset */
6550 super_init, /* tp_init */
6551 PyType_GenericAlloc, /* tp_alloc */
6552 PyType_GenericNew, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006553 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006554};