blob: 073ee311f56af07cb12a4a488a7e4202eeb1283e [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, \
22 ((PyStringObject *)(name))->ob_shash)
23#define MCACHE_CACHEABLE_NAME(name) \
24 PyString_CheckExact(name) && \
25 PyString_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
26
27struct method_cache_entry {
28 unsigned int version;
29 PyObject *name; /* reference to exactly a str or None */
30 PyObject *value; /* borrowed */
31};
32
33static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
34static unsigned int next_version_tag = 0;
Christian Heimes908caac2008-01-27 23:34:59 +000035static void type_modified(PyTypeObject *);
36
37unsigned int
38PyType_ClearCache(void)
39{
40 Py_ssize_t i;
41 unsigned int cur_version_tag = next_version_tag - 1;
42
43 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
44 method_cache[i].version = 0;
45 Py_CLEAR(method_cache[i].name);
46 method_cache[i].value = NULL;
47 }
48 next_version_tag = 0;
49 /* mark all version tags as invalid */
50 type_modified(&PyBaseObject_Type);
51 return cur_version_tag;
52}
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000053
54static void
55type_modified(PyTypeObject *type)
56{
57 /* Invalidate any cached data for the specified type and all
58 subclasses. This function is called after the base
59 classes, mro, or attributes of the type are altered.
60
61 Invariants:
62
63 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
64 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
65 objects coming from non-recompiled extension modules)
66
67 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
68 it must first be set on all super types.
69
70 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
71 type (so it must first clear it on all subclasses). The
72 tp_version_tag value is meaningless unless this flag is set.
73 We don't assign new version tags eagerly, but only as
74 needed.
75 */
76 PyObject *raw, *ref;
77 Py_ssize_t i, n;
78
Neal Norwitze7bb9182008-01-27 17:10:14 +000079 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000080 return;
81
82 raw = type->tp_subclasses;
83 if (raw != NULL) {
84 n = PyList_GET_SIZE(raw);
85 for (i = 0; i < n; i++) {
86 ref = PyList_GET_ITEM(raw, i);
87 ref = PyWeakref_GET_OBJECT(ref);
88 if (ref != Py_None) {
89 type_modified((PyTypeObject *)ref);
90 }
91 }
92 }
93 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
94}
95
96static void
97type_mro_modified(PyTypeObject *type, PyObject *bases) {
98 /*
99 Check that all base classes or elements of the mro of type are
100 able to be cached. This function is called after the base
101 classes or mro of the type are altered.
102
103 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
104 inherits from an old-style class, either directly or if it
105 appears in the MRO of a new-style class. No support either for
106 custom MROs that include types that are not officially super
107 types.
108
109 Called from mro_internal, which will subsequently be called on
110 each subclass when their mro is recursively updated.
111 */
112 Py_ssize_t i, n;
113 int clear = 0;
114
Neal Norwitze7bb9182008-01-27 17:10:14 +0000115 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000116 return;
117
118 n = PyTuple_GET_SIZE(bases);
119 for (i = 0; i < n; i++) {
120 PyObject *b = PyTuple_GET_ITEM(bases, i);
121 PyTypeObject *cls;
122
123 if (!PyType_Check(b) ) {
124 clear = 1;
125 break;
126 }
127
128 cls = (PyTypeObject *)b;
129
130 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
131 !PyType_IsSubtype(type, cls)) {
132 clear = 1;
133 break;
134 }
135 }
136
137 if (clear)
138 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
139 Py_TPFLAGS_VALID_VERSION_TAG);
140}
141
142static int
143assign_version_tag(PyTypeObject *type)
144{
145 /* Ensure that the tp_version_tag is valid and set
146 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
147 must first be done on all super classes. Return 0 if this
148 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
149 */
150 Py_ssize_t i, n;
151 PyObject *bases;
152
153 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
154 return 1;
155 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
156 return 0;
157 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
158 return 0;
159
160 type->tp_version_tag = next_version_tag++;
161 /* for stress-testing: next_version_tag &= 0xFF; */
162
163 if (type->tp_version_tag == 0) {
164 /* wrap-around or just starting Python - clear the whole
165 cache by filling names with references to Py_None.
166 Values are also set to NULL for added protection, as they
167 are borrowed reference */
168 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
169 method_cache[i].value = NULL;
170 Py_XDECREF(method_cache[i].name);
171 method_cache[i].name = Py_None;
172 Py_INCREF(Py_None);
173 }
174 /* mark all version tags as invalid */
175 type_modified(&PyBaseObject_Type);
176 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++;
221 return PyString_FromString(s);
222 }
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 }
240 if (!PyString_Check(value)) {
241 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 }
Tim Petersea7f75d2002-12-07 21:39:16 +0000246 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000247 != (size_t)PyString_GET_SIZE(value)) {
248 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
260 type->tp_name = PyString_AS_STRING(value);
261
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)
283 return PyString_FromStringAndSize(
Armin Rigo7ccbca92006-10-04 12:17:45 +0000284 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000285 return PyString_FromString("__builtin__");
286 }
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
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000303 type_modified(type);
304
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 *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000309type_get_bases(PyTypeObject *type, void *context)
310{
311 Py_INCREF(type->tp_bases);
312 return type->tp_bases;
313}
314
315static PyTypeObject *best_base(PyObject *);
316static int mro_internal(PyTypeObject *);
317static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
318static int add_subclass(PyTypeObject*, PyTypeObject*);
319static void remove_subclass(PyTypeObject *, PyTypeObject *);
320static void update_all_slots(PyTypeObject *);
321
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000322typedef int (*update_callback)(PyTypeObject *, void *);
323static int update_subclasses(PyTypeObject *type, PyObject *name,
324 update_callback callback, void *data);
325static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
326 update_callback callback, void *data);
327
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000328static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000329mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000330{
331 PyTypeObject *subclass;
332 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000333 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000334
335 subclasses = type->tp_subclasses;
336 if (subclasses == NULL)
337 return 0;
338 assert(PyList_Check(subclasses));
339 n = PyList_GET_SIZE(subclasses);
340 for (i = 0; i < n; i++) {
341 ref = PyList_GET_ITEM(subclasses, i);
342 assert(PyWeakref_CheckRef(ref));
343 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
344 assert(subclass != NULL);
345 if ((PyObject *)subclass == Py_None)
346 continue;
347 assert(PyType_Check(subclass));
348 old_mro = subclass->tp_mro;
349 if (mro_internal(subclass) < 0) {
350 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000351 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000352 }
353 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000354 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000355 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000356 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000357 if (!tuple)
358 return -1;
359 if (PyList_Append(temp, tuple) < 0)
360 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000361 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000362 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000363 if (mro_subclasses(subclass, temp) < 0)
364 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000365 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000366 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000367}
368
369static int
370type_set_bases(PyTypeObject *type, PyObject *value, void *context)
371{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000372 Py_ssize_t i;
373 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000374 PyObject *ob, *temp;
Armin Rigoc0ba52d2007-04-19 14:44:48 +0000375 PyTypeObject *new_base, *old_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000376 PyObject *old_bases, *old_mro;
377
378 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
379 PyErr_Format(PyExc_TypeError,
380 "can't set %s.__bases__", type->tp_name);
381 return -1;
382 }
383 if (!value) {
384 PyErr_Format(PyExc_TypeError,
385 "can't delete %s.__bases__", type->tp_name);
386 return -1;
387 }
388 if (!PyTuple_Check(value)) {
389 PyErr_Format(PyExc_TypeError,
390 "can only assign tuple to %s.__bases__, not %s",
Christian Heimese93237d2007-12-19 02:37:44 +0000391 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000392 return -1;
393 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000394 if (PyTuple_GET_SIZE(value) == 0) {
395 PyErr_Format(PyExc_TypeError,
396 "can only assign non-empty tuple to %s.__bases__, not ()",
397 type->tp_name);
398 return -1;
399 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000400 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
401 ob = PyTuple_GET_ITEM(value, i);
402 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
403 PyErr_Format(
404 PyExc_TypeError,
405 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +0000406 type->tp_name, Py_TYPE(ob)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000407 return -1;
408 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000409 if (PyType_Check(ob)) {
410 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
411 PyErr_SetString(PyExc_TypeError,
412 "a __bases__ item causes an inheritance cycle");
413 return -1;
414 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000415 }
416 }
417
418 new_base = best_base(value);
419
420 if (!new_base) {
421 return -1;
422 }
423
424 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
425 return -1;
426
427 Py_INCREF(new_base);
428 Py_INCREF(value);
429
430 old_bases = type->tp_bases;
431 old_base = type->tp_base;
432 old_mro = type->tp_mro;
433
434 type->tp_bases = value;
435 type->tp_base = new_base;
436
437 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000438 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000439 }
440
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000441 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000442 if (!temp)
443 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000444
445 r = mro_subclasses(type, temp);
446
447 if (r < 0) {
448 for (i = 0; i < PyList_Size(temp); i++) {
449 PyTypeObject* cls;
450 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000451 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
452 "", 2, 2, &cls, &mro);
Armin Rigo796fc992007-04-19 14:56:48 +0000453 Py_INCREF(mro);
454 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000455 cls->tp_mro = mro;
Armin Rigo796fc992007-04-19 14:56:48 +0000456 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000457 }
458 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000459 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000460 }
461
462 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000463
464 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000465 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000466 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000467 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000468
469 /* for now, sod that: just remove from all old_bases,
470 add to all new_bases */
471
472 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
473 ob = PyTuple_GET_ITEM(old_bases, i);
474 if (PyType_Check(ob)) {
475 remove_subclass(
476 (PyTypeObject*)ob, type);
477 }
478 }
479
480 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
481 ob = PyTuple_GET_ITEM(value, i);
482 if (PyType_Check(ob)) {
483 if (add_subclass((PyTypeObject*)ob, type) < 0)
484 r = -1;
485 }
486 }
487
488 update_all_slots(type);
489
490 Py_DECREF(old_bases);
491 Py_DECREF(old_base);
492 Py_DECREF(old_mro);
493
494 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000495
496 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000497 Py_DECREF(type->tp_bases);
498 Py_DECREF(type->tp_base);
499 if (type->tp_mro != old_mro) {
500 Py_DECREF(type->tp_mro);
501 }
502
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000503 type->tp_bases = old_bases;
504 type->tp_base = old_base;
505 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000506
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000507 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000508}
509
510static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000511type_dict(PyTypeObject *type, void *context)
512{
513 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000514 Py_INCREF(Py_None);
515 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000516 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000517 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000518}
519
Tim Peters24008312002-03-17 18:56:20 +0000520static PyObject *
521type_get_doc(PyTypeObject *type, void *context)
522{
523 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000524 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000525 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000526 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000527 if (result == NULL) {
528 result = Py_None;
529 Py_INCREF(result);
530 }
Christian Heimese93237d2007-12-19 02:37:44 +0000531 else if (Py_TYPE(result)->tp_descr_get) {
532 result = Py_TYPE(result)->tp_descr_get(result, NULL,
Tim Peters2b858972002-04-18 04:12:28 +0000533 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000534 }
535 else {
536 Py_INCREF(result);
537 }
Tim Peters24008312002-03-17 18:56:20 +0000538 return result;
539}
540
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000541static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000542 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
543 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000544 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000545 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000546 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000547 {0}
548};
549
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000550static int
551type_compare(PyObject *v, PyObject *w)
552{
553 /* This is called with type objects only. So we
554 can just compare the addresses. */
555 Py_uintptr_t vv = (Py_uintptr_t)v;
556 Py_uintptr_t ww = (Py_uintptr_t)w;
557 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
558}
559
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000560static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000561type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000563 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000564 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000565
566 mod = type_module(type, NULL);
567 if (mod == NULL)
568 PyErr_Clear();
569 else if (!PyString_Check(mod)) {
570 Py_DECREF(mod);
571 mod = NULL;
572 }
573 name = type_name(type, NULL);
574 if (name == NULL)
575 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000576
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000577 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
578 kind = "class";
579 else
580 kind = "type";
581
Barry Warsaw7ce36942001-08-24 18:34:26 +0000582 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000583 rtn = PyString_FromFormat("<%s '%s.%s'>",
584 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000585 PyString_AS_STRING(mod),
586 PyString_AS_STRING(name));
587 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000588 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000589 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000590
Guido van Rossumc3542212001-08-16 09:18:56 +0000591 Py_XDECREF(mod);
592 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000593 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000594}
595
Tim Peters6d6c1a32001-08-02 04:15:00 +0000596static PyObject *
597type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
598{
599 PyObject *obj;
600
601 if (type->tp_new == NULL) {
602 PyErr_Format(PyExc_TypeError,
603 "cannot create '%.100s' instances",
604 type->tp_name);
605 return NULL;
606 }
607
Tim Peters3f996e72001-09-13 19:18:27 +0000608 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000609 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000610 /* Ugly exception: when the call was type(something),
611 don't call tp_init on the result. */
612 if (type == &PyType_Type &&
613 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
614 (kwds == NULL ||
615 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
616 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000617 /* If the returned object is not an instance of type,
618 it won't be initialized. */
619 if (!PyType_IsSubtype(obj->ob_type, type))
620 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000621 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000622 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
623 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000624 type->tp_init(obj, args, kwds) < 0) {
625 Py_DECREF(obj);
626 obj = NULL;
627 }
628 }
629 return obj;
630}
631
632PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000633PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000634{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000635 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000636 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
637 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000638
639 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000640 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000641 else
Anthony Baxtera6286212006-04-11 07:42:36 +0000642 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000643
Neil Schemenauerc806c882001-08-29 23:54:54 +0000644 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000645 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000646
Neil Schemenauerc806c882001-08-29 23:54:54 +0000647 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000648
Tim Peters6d6c1a32001-08-02 04:15:00 +0000649 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
650 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000651
Tim Peters6d6c1a32001-08-02 04:15:00 +0000652 if (type->tp_itemsize == 0)
653 PyObject_INIT(obj, type);
654 else
655 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000656
Tim Peters6d6c1a32001-08-02 04:15:00 +0000657 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000658 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000659 return obj;
660}
661
662PyObject *
663PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
664{
665 return type->tp_alloc(type, 0);
666}
667
Guido van Rossum9475a232001-10-05 20:51:39 +0000668/* Helpers for subtyping */
669
670static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000671traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
672{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000673 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000674 PyMemberDef *mp;
675
Christian Heimese93237d2007-12-19 02:37:44 +0000676 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000677 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000678 for (i = 0; i < n; i++, mp++) {
679 if (mp->type == T_OBJECT_EX) {
680 char *addr = (char *)self + mp->offset;
681 PyObject *obj = *(PyObject **)addr;
682 if (obj != NULL) {
683 int err = visit(obj, arg);
684 if (err)
685 return err;
686 }
687 }
688 }
689 return 0;
690}
691
692static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000693subtype_traverse(PyObject *self, visitproc visit, void *arg)
694{
695 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000696 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000697
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000698 /* Find the nearest base with a different tp_traverse,
699 and traverse slots while we're at it */
Christian Heimese93237d2007-12-19 02:37:44 +0000700 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000701 base = type;
702 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
Christian Heimese93237d2007-12-19 02:37:44 +0000703 if (Py_SIZE(base)) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000704 int err = traverse_slots(base, self, visit, arg);
705 if (err)
706 return err;
707 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000708 base = base->tp_base;
709 assert(base);
710 }
711
712 if (type->tp_dictoffset != base->tp_dictoffset) {
713 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Woutersc6e55062006-04-15 21:47:09 +0000714 if (dictptr && *dictptr)
715 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000716 }
717
Thomas Woutersc6e55062006-04-15 21:47:09 +0000718 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000719 /* For a heaptype, the instances count as references
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000720 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000721 can find cycles involving this link. */
Thomas Woutersc6e55062006-04-15 21:47:09 +0000722 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000723
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000724 if (basetraverse)
725 return basetraverse(self, visit, arg);
726 return 0;
727}
728
729static void
730clear_slots(PyTypeObject *type, PyObject *self)
731{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000732 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000733 PyMemberDef *mp;
734
Christian Heimese93237d2007-12-19 02:37:44 +0000735 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000736 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000737 for (i = 0; i < n; i++, mp++) {
738 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
739 char *addr = (char *)self + mp->offset;
740 PyObject *obj = *(PyObject **)addr;
741 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000742 *(PyObject **)addr = NULL;
Thomas Woutersedf17d82006-04-15 17:28:34 +0000743 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000744 }
745 }
746 }
747}
748
749static int
750subtype_clear(PyObject *self)
751{
752 PyTypeObject *type, *base;
753 inquiry baseclear;
754
755 /* Find the nearest base with a different tp_clear
756 and clear slots while we're at it */
Christian Heimese93237d2007-12-19 02:37:44 +0000757 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000758 base = type;
759 while ((baseclear = base->tp_clear) == subtype_clear) {
Christian Heimese93237d2007-12-19 02:37:44 +0000760 if (Py_SIZE(base))
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000761 clear_slots(base, self);
762 base = base->tp_base;
763 assert(base);
764 }
765
Guido van Rossuma3862092002-06-10 15:24:42 +0000766 /* There's no need to clear the instance dict (if any);
767 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000768
769 if (baseclear)
770 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000771 return 0;
772}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000773
774static void
775subtype_dealloc(PyObject *self)
776{
Guido van Rossum14227b42001-12-06 02:35:58 +0000777 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000778 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000779
Guido van Rossum22b13872002-08-06 21:41:44 +0000780 /* Extract the type; we expect it to be a heap type */
Christian Heimese93237d2007-12-19 02:37:44 +0000781 type = Py_TYPE(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000782 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000783
Guido van Rossum22b13872002-08-06 21:41:44 +0000784 /* Test whether the type has GC exactly once */
785
786 if (!PyType_IS_GC(type)) {
787 /* It's really rare to find a dynamic type that doesn't have
788 GC; it can only happen when deriving from 'object' and not
789 adding any slots or instance variables. This allows
790 certain simplifications: there's no need to call
791 clear_slots(), or DECREF the dict, or clear weakrefs. */
792
793 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000794 if (type->tp_del) {
795 type->tp_del(self);
796 if (self->ob_refcnt > 0)
797 return;
798 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000799
800 /* Find the nearest base with a different tp_dealloc */
801 base = type;
802 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimese93237d2007-12-19 02:37:44 +0000803 assert(Py_SIZE(base) == 0);
Guido van Rossum22b13872002-08-06 21:41:44 +0000804 base = base->tp_base;
805 assert(base);
806 }
807
808 /* Call the base tp_dealloc() */
809 assert(basedealloc);
810 basedealloc(self);
811
812 /* Can't reference self beyond this point */
813 Py_DECREF(type);
814
815 /* Done */
816 return;
817 }
818
819 /* We get here only if the type has GC */
820
821 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000822 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000823 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000824 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000825 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000826 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000827 /* DO NOT restore GC tracking at this point. weakref callbacks
828 * (if any, and whether directly here or indirectly in something we
829 * call) may trigger GC, and if self is tracked at that point, it
830 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000831 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000832
Guido van Rossum59195fd2003-06-13 20:54:40 +0000833 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000834 base = type;
835 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000836 base = base->tp_base;
837 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000838 }
839
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000840 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000841 the finalizer (__del__), clearing slots, or clearing the instance
842 dict. */
843
Guido van Rossum1987c662003-05-29 14:29:23 +0000844 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
845 PyObject_ClearWeakRefs(self);
846
847 /* Maybe call finalizer; exit early if resurrected */
848 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000849 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000850 type->tp_del(self);
851 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000852 goto endlabel; /* resurrected */
853 else
854 _PyObject_GC_UNTRACK(self);
Brett Cannonf5bee302007-01-23 23:21:22 +0000855 /* New weakrefs could be created during the finalizer call.
856 If this occurs, clear them out without calling their
857 finalizers since they might rely on part of the object
858 being finalized that has already been destroyed. */
859 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
860 /* Modeled after GET_WEAKREFS_LISTPTR() */
861 PyWeakReference **list = (PyWeakReference **) \
862 PyObject_GET_WEAKREFS_LISTPTR(self);
863 while (*list)
864 _PyWeakref_ClearRef(*list);
865 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000866 }
867
Guido van Rossum59195fd2003-06-13 20:54:40 +0000868 /* Clear slots up to the nearest base with a different tp_dealloc */
869 base = type;
870 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimese93237d2007-12-19 02:37:44 +0000871 if (Py_SIZE(base))
Guido van Rossum59195fd2003-06-13 20:54:40 +0000872 clear_slots(base, self);
873 base = base->tp_base;
874 assert(base);
875 }
876
Tim Peters6d6c1a32001-08-02 04:15:00 +0000877 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000878 if (type->tp_dictoffset && !base->tp_dictoffset) {
879 PyObject **dictptr = _PyObject_GetDictPtr(self);
880 if (dictptr != NULL) {
881 PyObject *dict = *dictptr;
882 if (dict != NULL) {
883 Py_DECREF(dict);
884 *dictptr = NULL;
885 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000886 }
887 }
888
Tim Peters0bd743c2003-11-13 22:50:00 +0000889 /* Call the base tp_dealloc(); first retrack self if
890 * basedealloc knows about gc.
891 */
892 if (PyType_IS_GC(base))
893 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000894 assert(basedealloc);
895 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000896
897 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000898 Py_DECREF(type);
899
Guido van Rossum0906e072002-08-07 20:42:09 +0000900 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000901 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000902 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000903 --_PyTrash_delete_nesting;
904
905 /* Explanation of the weirdness around the trashcan macros:
906
907 Q. What do the trashcan macros do?
908
909 A. Read the comment titled "Trashcan mechanism" in object.h.
910 For one, this explains why there must be a call to GC-untrack
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000911 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000912 trashcan code, the answers to the following questions don't make
913 sense.
914
915 Q. Why do we GC-untrack before the trashcan and then immediately
916 GC-track again afterward?
917
918 A. In the case that the base class is GC-aware, the base class
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000919 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000920 UNTRACK macro, this will crash when the object is already
921 untracked. Because we don't know what the base class does, the
922 only safe thing is to make sure the object is tracked when we
923 call the base class dealloc. But... The trashcan begin macro
924 requires that the object is *untracked* before it is called. So
925 the dance becomes:
926
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000927 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000928 trashcan begin
929 GC track
930
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000931 Q. Why did the last question say "immediately GC-track again"?
932 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000933
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000934 A. Because the code *used* to re-track immediately. Bad Idea.
935 self has a refcount of 0, and if gc ever gets its hands on it
936 (which can happen if any weakref callback gets invoked), it
937 looks like trash to gc too, and gc also tries to delete self
938 then. But we're already deleting self. Double dealloction is
939 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +0000940
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000941 Q. Why the bizarre (net-zero) manipulation of
942 _PyTrash_delete_nesting around the trashcan macros?
943
944 A. Some base classes (e.g. list) also use the trashcan mechanism.
945 The following scenario used to be possible:
946
947 - suppose the trashcan level is one below the trashcan limit
948
949 - subtype_dealloc() is called
950
951 - the trashcan limit is not yet reached, so the trashcan level
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000952 is incremented and the code between trashcan begin and end is
953 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000954
955 - this destroys much of the object's contents, including its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000956 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000957
958 - basedealloc() is called; this is really list_dealloc(), or
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000959 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000960
961 - the trashcan limit is now reached, so the object is put on the
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000962 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000963
964 - basedealloc() returns
965
966 - subtype_dealloc() decrefs the object's type
967
968 - subtype_dealloc() returns
969
970 - later, the trashcan code starts deleting the objects from its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000971 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000972
973 - subtype_dealloc() is called *AGAIN* for the same object
974
975 - at the very least (if the destroyed slots and __dict__ don't
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000976 cause problems) the object's type gets decref'ed a second
977 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000978
979 The remedy is to make sure that if the code between trashcan
980 begin and end in subtype_dealloc() is called, the code between
981 trashcan begin and end in basedealloc() will also be called.
982 This is done by decrementing the level after passing into the
983 trashcan block, and incrementing it just before leaving the
984 block.
985
986 But now it's possible that a chain of objects consisting solely
987 of objects whose deallocator is subtype_dealloc() will defeat
988 the trashcan mechanism completely: the decremented level means
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000989 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000990 *increment* the level *before* entering the trashcan block, and
991 matchingly decrement it after leaving. This means the trashcan
992 code will trigger a little early, but that's no big deal.
993
994 Q. Are there any live examples of code in need of all this
995 complexity?
996
997 A. Yes. See SF bug 668433 for code that crashed (when Python was
998 compiled in debug mode) before the trashcan level manipulations
999 were added. For more discussion, see SF patches 581742, 575073
1000 and bug 574207.
1001 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001002}
1003
Jeremy Hylton938ace62002-07-17 16:30:39 +00001004static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001005
Tim Peters6d6c1a32001-08-02 04:15:00 +00001006/* type test with subclassing support */
1007
1008int
1009PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1010{
1011 PyObject *mro;
1012
Guido van Rossum9478d072001-09-07 18:52:13 +00001013 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1014 return b == a || b == &PyBaseObject_Type;
1015
Tim Peters6d6c1a32001-08-02 04:15:00 +00001016 mro = a->tp_mro;
1017 if (mro != NULL) {
1018 /* Deal with multiple inheritance without recursion
1019 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001020 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001021 assert(PyTuple_Check(mro));
1022 n = PyTuple_GET_SIZE(mro);
1023 for (i = 0; i < n; i++) {
1024 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1025 return 1;
1026 }
1027 return 0;
1028 }
1029 else {
1030 /* a is not completely initilized yet; follow tp_base */
1031 do {
1032 if (a == b)
1033 return 1;
1034 a = a->tp_base;
1035 } while (a != NULL);
1036 return b == &PyBaseObject_Type;
1037 }
1038}
1039
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001040/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001041 without looking in the instance dictionary
1042 (so we can't use PyObject_GetAttr) but still binding
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001043 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001044 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001045 static variable used to cache the interned Python string.
1046
1047 Two variants:
1048
1049 - lookup_maybe() returns NULL without raising an exception
1050 when the _PyType_Lookup() call fails;
1051
1052 - lookup_method() always raises an exception upon errors.
1053*/
Guido van Rossum60718732001-08-28 17:47:51 +00001054
1055static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001056lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001057{
1058 PyObject *res;
1059
1060 if (*attrobj == NULL) {
1061 *attrobj = PyString_InternFromString(attrstr);
1062 if (*attrobj == NULL)
1063 return NULL;
1064 }
Christian Heimese93237d2007-12-19 02:37:44 +00001065 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001066 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +00001067 descrgetfunc f;
Christian Heimese93237d2007-12-19 02:37:44 +00001068 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
Guido van Rossum60718732001-08-28 17:47:51 +00001069 Py_INCREF(res);
1070 else
Christian Heimese93237d2007-12-19 02:37:44 +00001071 res = f(res, self, (PyObject *)(Py_TYPE(self)));
Guido van Rossum60718732001-08-28 17:47:51 +00001072 }
1073 return res;
1074}
1075
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001076static PyObject *
1077lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1078{
1079 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1080 if (res == NULL && !PyErr_Occurred())
1081 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1082 return res;
1083}
1084
Guido van Rossum2730b132001-08-28 18:22:14 +00001085/* A variation of PyObject_CallMethod that uses lookup_method()
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001086 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001087 as lookup_method to cache the interned name string object. */
1088
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001089static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001090call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1091{
1092 va_list va;
1093 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001094 va_start(va, format);
1095
Guido van Rossumda21c012001-10-03 00:50:18 +00001096 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001097 if (func == NULL) {
1098 va_end(va);
1099 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +00001100 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001101 return NULL;
1102 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001103
1104 if (format && *format)
1105 args = Py_VaBuildValue(format, va);
1106 else
1107 args = PyTuple_New(0);
1108
1109 va_end(va);
1110
1111 if (args == NULL)
1112 return NULL;
1113
1114 assert(PyTuple_Check(args));
1115 retval = PyObject_Call(func, args, NULL);
1116
1117 Py_DECREF(args);
1118 Py_DECREF(func);
1119
1120 return retval;
1121}
1122
1123/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1124
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001125static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001126call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1127{
1128 va_list va;
1129 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001130 va_start(va, format);
1131
Guido van Rossumda21c012001-10-03 00:50:18 +00001132 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +00001133 if (func == NULL) {
1134 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001135 if (!PyErr_Occurred()) {
1136 Py_INCREF(Py_NotImplemented);
1137 return Py_NotImplemented;
1138 }
Guido van Rossum717ce002001-09-14 16:58:08 +00001139 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001140 }
1141
1142 if (format && *format)
1143 args = Py_VaBuildValue(format, va);
1144 else
1145 args = PyTuple_New(0);
1146
1147 va_end(va);
1148
Guido van Rossum717ce002001-09-14 16:58:08 +00001149 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00001150 return NULL;
1151
Guido van Rossum717ce002001-09-14 16:58:08 +00001152 assert(PyTuple_Check(args));
1153 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001154
1155 Py_DECREF(args);
1156 Py_DECREF(func);
1157
1158 return retval;
1159}
1160
Tim Petersa91e9642001-11-14 23:32:33 +00001161static int
1162fill_classic_mro(PyObject *mro, PyObject *cls)
1163{
1164 PyObject *bases, *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001165 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001166
1167 assert(PyList_Check(mro));
1168 assert(PyClass_Check(cls));
1169 i = PySequence_Contains(mro, cls);
1170 if (i < 0)
1171 return -1;
1172 if (!i) {
1173 if (PyList_Append(mro, cls) < 0)
1174 return -1;
1175 }
1176 bases = ((PyClassObject *)cls)->cl_bases;
1177 assert(bases && PyTuple_Check(bases));
1178 n = PyTuple_GET_SIZE(bases);
1179 for (i = 0; i < n; i++) {
1180 base = PyTuple_GET_ITEM(bases, i);
1181 if (fill_classic_mro(mro, base) < 0)
1182 return -1;
1183 }
1184 return 0;
1185}
1186
1187static PyObject *
1188classic_mro(PyObject *cls)
1189{
1190 PyObject *mro;
1191
1192 assert(PyClass_Check(cls));
1193 mro = PyList_New(0);
1194 if (mro != NULL) {
1195 if (fill_classic_mro(mro, cls) == 0)
1196 return mro;
1197 Py_DECREF(mro);
1198 }
1199 return NULL;
1200}
1201
Tim Petersea7f75d2002-12-07 21:39:16 +00001202/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001203 Method resolution order algorithm C3 described in
1204 "A Monotonic Superclass Linearization for Dylan",
1205 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001206 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001207 (OOPSLA 1996)
1208
Guido van Rossum98f33732002-11-25 21:36:54 +00001209 Some notes about the rules implied by C3:
1210
Tim Petersea7f75d2002-12-07 21:39:16 +00001211 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001212 It isn't legal to repeat a class in a list of base classes.
1213
1214 The next three properties are the 3 constraints in "C3".
1215
Tim Petersea7f75d2002-12-07 21:39:16 +00001216 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001217 If A precedes B in C's MRO, then A will precede B in the MRO of all
1218 subclasses of C.
1219
1220 Monotonicity.
1221 The MRO of a class must be an extension without reordering of the
1222 MRO of each of its superclasses.
1223
1224 Extended Precedence Graph (EPG).
1225 Linearization is consistent if there is a path in the EPG from
1226 each class to all its successors in the linearization. See
1227 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001228 */
1229
Tim Petersea7f75d2002-12-07 21:39:16 +00001230static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001231tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001232 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001233 size = PyList_GET_SIZE(list);
1234
1235 for (j = whence+1; j < size; j++) {
1236 if (PyList_GET_ITEM(list, j) == o)
1237 return 1;
1238 }
1239 return 0;
1240}
1241
Guido van Rossum98f33732002-11-25 21:36:54 +00001242static PyObject *
1243class_name(PyObject *cls)
1244{
1245 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1246 if (name == NULL) {
1247 PyErr_Clear();
1248 Py_XDECREF(name);
1249 name = PyObject_Repr(cls);
1250 }
1251 if (name == NULL)
1252 return NULL;
1253 if (!PyString_Check(name)) {
1254 Py_DECREF(name);
1255 return NULL;
1256 }
1257 return name;
1258}
1259
1260static int
1261check_duplicates(PyObject *list)
1262{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001263 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001264 /* Let's use a quadratic time algorithm,
1265 assuming that the bases lists is short.
1266 */
1267 n = PyList_GET_SIZE(list);
1268 for (i = 0; i < n; i++) {
1269 PyObject *o = PyList_GET_ITEM(list, i);
1270 for (j = i + 1; j < n; j++) {
1271 if (PyList_GET_ITEM(list, j) == o) {
1272 o = class_name(o);
1273 PyErr_Format(PyExc_TypeError,
1274 "duplicate base class %s",
1275 o ? PyString_AS_STRING(o) : "?");
1276 Py_XDECREF(o);
1277 return -1;
1278 }
1279 }
1280 }
1281 return 0;
1282}
1283
1284/* Raise a TypeError for an MRO order disagreement.
1285
1286 It's hard to produce a good error message. In the absence of better
1287 insight into error reporting, report the classes that were candidates
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001288 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001289 order in which they should be put in the MRO, but it's hard to
1290 diagnose what constraint can't be satisfied.
1291*/
1292
1293static void
1294set_mro_error(PyObject *to_merge, int *remain)
1295{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001296 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001297 char buf[1000];
1298 PyObject *k, *v;
1299 PyObject *set = PyDict_New();
Georg Brandl5c170fd2006-03-17 19:03:25 +00001300 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001301
1302 to_merge_size = PyList_GET_SIZE(to_merge);
1303 for (i = 0; i < to_merge_size; i++) {
1304 PyObject *L = PyList_GET_ITEM(to_merge, i);
1305 if (remain[i] < PyList_GET_SIZE(L)) {
1306 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Georg Brandl5c170fd2006-03-17 19:03:25 +00001307 if (PyDict_SetItem(set, c, Py_None) < 0) {
1308 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001309 return;
Georg Brandl5c170fd2006-03-17 19:03:25 +00001310 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001311 }
1312 }
1313 n = PyDict_Size(set);
1314
Raymond Hettingerf394df42003-04-06 19:13:41 +00001315 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1316consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001317 i = 0;
Skip Montanaro429433b2006-04-18 00:35:43 +00001318 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001319 PyObject *name = class_name(k);
1320 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1321 name ? PyString_AS_STRING(name) : "?");
1322 Py_XDECREF(name);
Skip Montanaro429433b2006-04-18 00:35:43 +00001323 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001324 buf[off++] = ',';
1325 buf[off] = '\0';
1326 }
1327 }
1328 PyErr_SetString(PyExc_TypeError, buf);
1329 Py_DECREF(set);
1330}
1331
Tim Petersea7f75d2002-12-07 21:39:16 +00001332static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001333pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001334 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001335 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001336 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001337
Guido van Rossum1f121312002-11-14 19:49:16 +00001338 to_merge_size = PyList_GET_SIZE(to_merge);
1339
Guido van Rossum98f33732002-11-25 21:36:54 +00001340 /* remain stores an index into each sublist of to_merge.
1341 remain[i] is the index of the next base in to_merge[i]
1342 that is not included in acc.
1343 */
Anthony Baxtera6286212006-04-11 07:42:36 +00001344 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001345 if (remain == NULL)
1346 return -1;
1347 for (i = 0; i < to_merge_size; i++)
1348 remain[i] = 0;
1349
1350 again:
1351 empty_cnt = 0;
1352 for (i = 0; i < to_merge_size; i++) {
1353 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001354
Guido van Rossum1f121312002-11-14 19:49:16 +00001355 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1356
1357 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1358 empty_cnt++;
1359 continue;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001360 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001361
Guido van Rossum98f33732002-11-25 21:36:54 +00001362 /* Choose next candidate for MRO.
1363
1364 The input sequences alone can determine the choice.
1365 If not, choose the class which appears in the MRO
1366 of the earliest direct superclass of the new class.
1367 */
1368
Guido van Rossum1f121312002-11-14 19:49:16 +00001369 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1370 for (j = 0; j < to_merge_size; j++) {
1371 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001372 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001373 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001374 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001375 }
1376 ok = PyList_Append(acc, candidate);
1377 if (ok < 0) {
1378 PyMem_Free(remain);
1379 return -1;
1380 }
1381 for (j = 0; j < to_merge_size; j++) {
1382 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001383 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1384 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001385 remain[j]++;
1386 }
1387 }
1388 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001389 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001390 }
1391
Guido van Rossum98f33732002-11-25 21:36:54 +00001392 if (empty_cnt == to_merge_size) {
1393 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001394 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001395 }
1396 set_mro_error(to_merge, remain);
1397 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001398 return -1;
1399}
1400
Tim Peters6d6c1a32001-08-02 04:15:00 +00001401static PyObject *
1402mro_implementation(PyTypeObject *type)
1403{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001404 Py_ssize_t i, n;
1405 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001406 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001407 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001408
Neal Norwitze7bb9182008-01-27 17:10:14 +00001409 if (type->tp_dict == NULL) {
1410 if (PyType_Ready(type) < 0)
Guido van Rossum63517572002-06-18 16:44:57 +00001411 return NULL;
1412 }
1413
Guido van Rossum98f33732002-11-25 21:36:54 +00001414 /* Find a superclass linearization that honors the constraints
1415 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001416 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001417
1418 to_merge is a list of lists, where each list is a superclass
1419 linearization implied by a base class. The last element of
1420 to_merge is the declared list of bases.
1421 */
1422
Tim Peters6d6c1a32001-08-02 04:15:00 +00001423 bases = type->tp_bases;
1424 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001425
1426 to_merge = PyList_New(n+1);
1427 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001428 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001429
Tim Peters6d6c1a32001-08-02 04:15:00 +00001430 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001431 PyObject *base = PyTuple_GET_ITEM(bases, i);
1432 PyObject *parentMRO;
1433 if (PyType_Check(base))
1434 parentMRO = PySequence_List(
1435 ((PyTypeObject*)base)->tp_mro);
1436 else
1437 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001438 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001439 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001440 return NULL;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001441 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001442
1443 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001444 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001445
1446 bases_aslist = PySequence_List(bases);
1447 if (bases_aslist == NULL) {
1448 Py_DECREF(to_merge);
1449 return NULL;
1450 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001451 /* This is just a basic sanity check. */
1452 if (check_duplicates(bases_aslist) < 0) {
1453 Py_DECREF(to_merge);
1454 Py_DECREF(bases_aslist);
1455 return NULL;
1456 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001457 PyList_SET_ITEM(to_merge, n, bases_aslist);
1458
1459 result = Py_BuildValue("[O]", (PyObject *)type);
1460 if (result == NULL) {
1461 Py_DECREF(to_merge);
1462 return NULL;
1463 }
1464
1465 ok = pmerge(result, to_merge);
1466 Py_DECREF(to_merge);
1467 if (ok < 0) {
1468 Py_DECREF(result);
1469 return NULL;
1470 }
1471
Tim Peters6d6c1a32001-08-02 04:15:00 +00001472 return result;
1473}
1474
1475static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001476mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001477{
1478 PyTypeObject *type = (PyTypeObject *)self;
1479
Tim Peters6d6c1a32001-08-02 04:15:00 +00001480 return mro_implementation(type);
1481}
1482
1483static int
1484mro_internal(PyTypeObject *type)
1485{
1486 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001487 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001488
Christian Heimese93237d2007-12-19 02:37:44 +00001489 if (Py_TYPE(type) == &PyType_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001490 result = mro_implementation(type);
1491 }
1492 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001493 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001494 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001495 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001496 if (mro == NULL)
1497 return -1;
1498 result = PyObject_CallObject(mro, NULL);
1499 Py_DECREF(mro);
1500 }
1501 if (result == NULL)
1502 return -1;
1503 tuple = PySequence_Tuple(result);
1504 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001505 if (tuple == NULL)
1506 return -1;
1507 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001508 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001509 PyObject *cls;
1510 PyTypeObject *solid;
1511
1512 solid = solid_base(type);
1513
1514 len = PyTuple_GET_SIZE(tuple);
1515
1516 for (i = 0; i < len; i++) {
1517 PyTypeObject *t;
1518 cls = PyTuple_GET_ITEM(tuple, i);
1519 if (PyClass_Check(cls))
1520 continue;
1521 else if (!PyType_Check(cls)) {
1522 PyErr_Format(PyExc_TypeError,
1523 "mro() returned a non-class ('%.500s')",
Christian Heimese93237d2007-12-19 02:37:44 +00001524 Py_TYPE(cls)->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001525 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001526 return -1;
1527 }
1528 t = (PyTypeObject*)cls;
1529 if (!PyType_IsSubtype(solid, solid_base(t))) {
1530 PyErr_Format(PyExc_TypeError,
1531 "mro() returned base with unsuitable layout ('%.500s')",
1532 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001533 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001534 return -1;
1535 }
1536 }
1537 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001538 type->tp_mro = tuple;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001539
1540 type_mro_modified(type, type->tp_mro);
1541 /* corner case: the old-style super class might have been hidden
1542 from the custom MRO */
1543 type_mro_modified(type, type->tp_bases);
1544
1545 type_modified(type);
1546
Tim Peters6d6c1a32001-08-02 04:15:00 +00001547 return 0;
1548}
1549
1550
1551/* Calculate the best base amongst multiple base classes.
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001552 This is the first one that's on the path to the "solid base". */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001553
1554static PyTypeObject *
1555best_base(PyObject *bases)
1556{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001557 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001558 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001559 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001560
1561 assert(PyTuple_Check(bases));
1562 n = PyTuple_GET_SIZE(bases);
1563 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001564 base = NULL;
1565 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001566 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001567 base_proto = PyTuple_GET_ITEM(bases, i);
1568 if (PyClass_Check(base_proto))
1569 continue;
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001570 if (!PyType_Check(base_proto)) {
1571 PyErr_SetString(
1572 PyExc_TypeError,
1573 "bases must be types");
1574 return NULL;
1575 }
Tim Petersa91e9642001-11-14 23:32:33 +00001576 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001577 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001578 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001579 return NULL;
1580 }
1581 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001582 if (winner == NULL) {
1583 winner = candidate;
1584 base = base_i;
1585 }
1586 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001587 ;
1588 else if (PyType_IsSubtype(candidate, winner)) {
1589 winner = candidate;
1590 base = base_i;
1591 }
1592 else {
1593 PyErr_SetString(
1594 PyExc_TypeError,
1595 "multiple bases have "
1596 "instance lay-out conflict");
1597 return NULL;
1598 }
1599 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001600 if (base == NULL)
1601 PyErr_SetString(PyExc_TypeError,
1602 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001603 return base;
1604}
1605
1606static int
1607extra_ivars(PyTypeObject *type, PyTypeObject *base)
1608{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001609 size_t t_size = type->tp_basicsize;
1610 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001611
Guido van Rossum9676b222001-08-17 20:32:36 +00001612 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001613 if (type->tp_itemsize || base->tp_itemsize) {
1614 /* If itemsize is involved, stricter rules */
1615 return t_size != b_size ||
1616 type->tp_itemsize != base->tp_itemsize;
1617 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001618 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001619 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1620 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001621 t_size -= sizeof(PyObject *);
1622 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001623 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1624 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001625 t_size -= sizeof(PyObject *);
1626
1627 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001628}
1629
1630static PyTypeObject *
1631solid_base(PyTypeObject *type)
1632{
1633 PyTypeObject *base;
1634
1635 if (type->tp_base)
1636 base = solid_base(type->tp_base);
1637 else
1638 base = &PyBaseObject_Type;
1639 if (extra_ivars(type, base))
1640 return type;
1641 else
1642 return base;
1643}
1644
Jeremy Hylton938ace62002-07-17 16:30:39 +00001645static void object_dealloc(PyObject *);
1646static int object_init(PyObject *, PyObject *, PyObject *);
1647static int update_slot(PyTypeObject *, PyObject *);
1648static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001649
Armin Rigo9790a272007-05-02 19:23:31 +00001650/*
1651 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1652 * inherited from various builtin types. The builtin base usually provides
1653 * its own __dict__ descriptor, so we use that when we can.
1654 */
1655static PyTypeObject *
1656get_builtin_base_with_dict(PyTypeObject *type)
1657{
1658 while (type->tp_base != NULL) {
1659 if (type->tp_dictoffset != 0 &&
1660 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1661 return type;
1662 type = type->tp_base;
1663 }
1664 return NULL;
1665}
1666
1667static PyObject *
1668get_dict_descriptor(PyTypeObject *type)
1669{
1670 static PyObject *dict_str;
1671 PyObject *descr;
1672
1673 if (dict_str == NULL) {
1674 dict_str = PyString_InternFromString("__dict__");
1675 if (dict_str == NULL)
1676 return NULL;
1677 }
1678 descr = _PyType_Lookup(type, dict_str);
1679 if (descr == NULL || !PyDescr_IsData(descr))
1680 return NULL;
1681
1682 return descr;
1683}
1684
1685static void
1686raise_dict_descr_error(PyObject *obj)
1687{
1688 PyErr_Format(PyExc_TypeError,
1689 "this __dict__ descriptor does not support "
1690 "'%.200s' objects", obj->ob_type->tp_name);
1691}
1692
Tim Peters6d6c1a32001-08-02 04:15:00 +00001693static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001694subtype_dict(PyObject *obj, void *context)
1695{
Armin Rigo9790a272007-05-02 19:23:31 +00001696 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001697 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001698 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001699
Armin Rigo9790a272007-05-02 19:23:31 +00001700 base = get_builtin_base_with_dict(obj->ob_type);
1701 if (base != NULL) {
1702 descrgetfunc func;
1703 PyObject *descr = get_dict_descriptor(base);
1704 if (descr == NULL) {
1705 raise_dict_descr_error(obj);
1706 return NULL;
1707 }
1708 func = descr->ob_type->tp_descr_get;
1709 if (func == NULL) {
1710 raise_dict_descr_error(obj);
1711 return NULL;
1712 }
1713 return func(descr, obj, (PyObject *)(obj->ob_type));
1714 }
1715
1716 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001717 if (dictptr == NULL) {
1718 PyErr_SetString(PyExc_AttributeError,
1719 "This object has no __dict__");
1720 return NULL;
1721 }
1722 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001723 if (dict == NULL)
1724 *dictptr = dict = PyDict_New();
1725 Py_XINCREF(dict);
1726 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001727}
1728
Guido van Rossum6661be32001-10-26 04:26:12 +00001729static int
1730subtype_setdict(PyObject *obj, PyObject *value, void *context)
1731{
Armin Rigo9790a272007-05-02 19:23:31 +00001732 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001733 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001734 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001735
Armin Rigo9790a272007-05-02 19:23:31 +00001736 base = get_builtin_base_with_dict(obj->ob_type);
1737 if (base != NULL) {
1738 descrsetfunc func;
1739 PyObject *descr = get_dict_descriptor(base);
1740 if (descr == NULL) {
1741 raise_dict_descr_error(obj);
1742 return -1;
1743 }
1744 func = descr->ob_type->tp_descr_set;
1745 if (func == NULL) {
1746 raise_dict_descr_error(obj);
1747 return -1;
1748 }
1749 return func(descr, obj, value);
1750 }
1751
1752 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001753 if (dictptr == NULL) {
1754 PyErr_SetString(PyExc_AttributeError,
1755 "This object has no __dict__");
1756 return -1;
1757 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001758 if (value != NULL && !PyDict_Check(value)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001759 PyErr_Format(PyExc_TypeError,
1760 "__dict__ must be set to a dictionary, "
Christian Heimese93237d2007-12-19 02:37:44 +00001761 "not a '%.200s'", Py_TYPE(value)->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001762 return -1;
1763 }
1764 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001765 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001766 *dictptr = value;
1767 Py_XDECREF(dict);
1768 return 0;
1769}
1770
Guido van Rossumad47da02002-08-12 19:05:44 +00001771static PyObject *
1772subtype_getweakref(PyObject *obj, void *context)
1773{
1774 PyObject **weaklistptr;
1775 PyObject *result;
1776
Christian Heimese93237d2007-12-19 02:37:44 +00001777 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001778 PyErr_SetString(PyExc_AttributeError,
Fred Drake7a36f5f2006-08-04 05:17:21 +00001779 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001780 return NULL;
1781 }
Christian Heimese93237d2007-12-19 02:37:44 +00001782 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1783 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1784 (size_t)(Py_TYPE(obj)->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001785 weaklistptr = (PyObject **)
Christian Heimese93237d2007-12-19 02:37:44 +00001786 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001787 if (*weaklistptr == NULL)
1788 result = Py_None;
1789 else
1790 result = *weaklistptr;
1791 Py_INCREF(result);
1792 return result;
1793}
1794
Guido van Rossum373c7412003-01-07 13:41:37 +00001795/* Three variants on the subtype_getsets list. */
1796
1797static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001798 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001799 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001800 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001801 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001802 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001803};
1804
Guido van Rossum373c7412003-01-07 13:41:37 +00001805static PyGetSetDef subtype_getsets_dict_only[] = {
1806 {"__dict__", subtype_dict, subtype_setdict,
1807 PyDoc_STR("dictionary for instance variables (if defined)")},
1808 {0}
1809};
1810
1811static PyGetSetDef subtype_getsets_weakref_only[] = {
1812 {"__weakref__", subtype_getweakref, NULL,
1813 PyDoc_STR("list of weak references to the object (if defined)")},
1814 {0}
1815};
1816
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001817static int
1818valid_identifier(PyObject *s)
1819{
Guido van Rossum03013a02002-07-16 14:30:28 +00001820 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001821 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001822
1823 if (!PyString_Check(s)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001824 PyErr_Format(PyExc_TypeError,
1825 "__slots__ items must be strings, not '%.200s'",
Christian Heimese93237d2007-12-19 02:37:44 +00001826 Py_TYPE(s)->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001827 return 0;
1828 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001829 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001830 n = PyString_GET_SIZE(s);
1831 /* We must reject an empty name. As a hack, we bump the
1832 length to 1 so that the loop will balk on the trailing \0. */
1833 if (n == 0)
1834 n = 1;
1835 for (i = 0; i < n; i++, p++) {
1836 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1837 PyErr_SetString(PyExc_TypeError,
1838 "__slots__ must be identifiers");
1839 return 0;
1840 }
1841 }
1842 return 1;
1843}
1844
Martin v. Löwisd919a592002-10-14 21:07:28 +00001845#ifdef Py_USING_UNICODE
1846/* Replace Unicode objects in slots. */
1847
1848static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001849_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001850{
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001851 PyObject *tmp = NULL;
1852 PyObject *slot_name, *new_name;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001853 Py_ssize_t i;
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001854
Martin v. Löwisd919a592002-10-14 21:07:28 +00001855 for (i = 0; i < nslots; i++) {
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001856 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1857 if (tmp == NULL) {
1858 tmp = PySequence_List(slots);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001859 if (tmp == NULL)
1860 return NULL;
1861 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001862 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1863 NULL);
1864 if (new_name == NULL) {
Martin v. Löwisd919a592002-10-14 21:07:28 +00001865 Py_DECREF(tmp);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001866 return NULL;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001867 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001868 Py_INCREF(new_name);
1869 PyList_SET_ITEM(tmp, i, new_name);
1870 Py_DECREF(slot_name);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001871 }
1872 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001873 if (tmp != NULL) {
1874 slots = PyList_AsTuple(tmp);
1875 Py_DECREF(tmp);
1876 }
1877 return slots;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001878}
1879#endif
1880
Guido van Rossumf102e242007-03-23 18:53:03 +00001881/* Forward */
1882static int
1883object_init(PyObject *self, PyObject *args, PyObject *kwds);
1884
1885static int
1886type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1887{
1888 int res;
1889
1890 assert(args != NULL && PyTuple_Check(args));
1891 assert(kwds == NULL || PyDict_Check(kwds));
1892
1893 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1894 PyErr_SetString(PyExc_TypeError,
1895 "type.__init__() takes no keyword arguments");
1896 return -1;
1897 }
1898
1899 if (args != NULL && PyTuple_Check(args) &&
1900 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1901 PyErr_SetString(PyExc_TypeError,
1902 "type.__init__() takes 1 or 3 arguments");
1903 return -1;
1904 }
1905
1906 /* Call object.__init__(self) now. */
1907 /* XXX Could call super(type, cls).__init__() but what's the point? */
1908 args = PyTuple_GetSlice(args, 0, 0);
1909 res = object_init(cls, args, NULL);
1910 Py_DECREF(args);
1911 return res;
1912}
1913
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001914static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001915type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1916{
1917 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001918 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001919 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001920 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001921 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001922 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001923 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001924 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001925
Tim Peters3abca122001-10-27 19:37:48 +00001926 assert(args != NULL && PyTuple_Check(args));
1927 assert(kwds == NULL || PyDict_Check(kwds));
1928
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001929 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001930 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001931 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1932 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001933
1934 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1935 PyObject *x = PyTuple_GET_ITEM(args, 0);
Christian Heimese93237d2007-12-19 02:37:44 +00001936 Py_INCREF(Py_TYPE(x));
1937 return (PyObject *) Py_TYPE(x);
Tim Peters3abca122001-10-27 19:37:48 +00001938 }
1939
1940 /* SF bug 475327 -- if that didn't trigger, we need 3
1941 arguments. but PyArg_ParseTupleAndKeywords below may give
1942 a msg saying type() needs exactly 3. */
1943 if (nargs + nkwds != 3) {
1944 PyErr_SetString(PyExc_TypeError,
1945 "type() takes 1 or 3 arguments");
1946 return NULL;
1947 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001948 }
1949
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001950 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001951 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1952 &name,
1953 &PyTuple_Type, &bases,
1954 &PyDict_Type, &dict))
1955 return NULL;
1956
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001957 /* Determine the proper metatype to deal with this,
1958 and check for metatype conflicts while we're at it.
1959 Note that if some other metatype wins to contract,
1960 it's possible that its instances are not types. */
1961 nbases = PyTuple_GET_SIZE(bases);
1962 winner = metatype;
1963 for (i = 0; i < nbases; i++) {
1964 tmp = PyTuple_GET_ITEM(bases, i);
1965 tmptype = tmp->ob_type;
1966 if (tmptype == &PyClass_Type)
1967 continue; /* Special case classic classes */
1968 if (PyType_IsSubtype(winner, tmptype))
1969 continue;
1970 if (PyType_IsSubtype(tmptype, winner)) {
1971 winner = tmptype;
1972 continue;
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001973 }
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001974 PyErr_SetString(PyExc_TypeError,
1975 "metaclass conflict: "
1976 "the metaclass of a derived class "
1977 "must be a (non-strict) subclass "
1978 "of the metaclasses of all its bases");
1979 return NULL;
1980 }
1981 if (winner != metatype) {
1982 if (winner->tp_new != type_new) /* Pass it to the winner */
1983 return winner->tp_new(winner, args, kwds);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001984 metatype = winner;
1985 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001986
1987 /* Adjust for empty tuple bases */
1988 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001989 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001990 if (bases == NULL)
1991 return NULL;
1992 nbases = 1;
1993 }
1994 else
1995 Py_INCREF(bases);
1996
1997 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1998
1999 /* Calculate best base, and check that all bases are type objects */
2000 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002001 if (base == NULL) {
2002 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002003 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002004 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002005 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2006 PyErr_Format(PyExc_TypeError,
2007 "type '%.100s' is not an acceptable base type",
2008 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002009 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002010 return NULL;
2011 }
2012
Tim Peters6d6c1a32001-08-02 04:15:00 +00002013 /* Check for a __slots__ sequence variable in dict, and count it */
2014 slots = PyDict_GetItemString(dict, "__slots__");
2015 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00002016 add_dict = 0;
2017 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00002018 may_add_dict = base->tp_dictoffset == 0;
2019 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2020 if (slots == NULL) {
2021 if (may_add_dict) {
2022 add_dict++;
2023 }
2024 if (may_add_weak) {
2025 add_weak++;
2026 }
2027 }
2028 else {
2029 /* Have slots */
2030
Tim Peters6d6c1a32001-08-02 04:15:00 +00002031 /* Make it into a tuple */
Neal Norwitzcbd9ee62007-04-14 05:25:50 +00002032 if (PyString_Check(slots) || PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002033 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002034 else
2035 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002036 if (slots == NULL) {
2037 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002039 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002040 assert(PyTuple_Check(slots));
2041
2042 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00002044 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00002045 PyErr_Format(PyExc_TypeError,
2046 "nonempty __slots__ "
2047 "not supported for subtype of '%s'",
2048 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00002049 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002050 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00002051 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00002052 return NULL;
2053 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002054
Martin v. Löwisd919a592002-10-14 21:07:28 +00002055#ifdef Py_USING_UNICODE
2056 tmp = _unicode_to_string(slots, nslots);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00002057 if (tmp == NULL)
2058 goto bad_slots;
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00002059 if (tmp != slots) {
2060 Py_DECREF(slots);
2061 slots = tmp;
2062 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00002063#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00002064 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002065 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00002066 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2067 char *s;
2068 if (!valid_identifier(tmp))
2069 goto bad_slots;
2070 assert(PyString_Check(tmp));
2071 s = PyString_AS_STRING(tmp);
2072 if (strcmp(s, "__dict__") == 0) {
2073 if (!may_add_dict || add_dict) {
2074 PyErr_SetString(PyExc_TypeError,
2075 "__dict__ slot disallowed: "
2076 "we already got one");
2077 goto bad_slots;
2078 }
2079 add_dict++;
2080 }
2081 if (strcmp(s, "__weakref__") == 0) {
2082 if (!may_add_weak || add_weak) {
2083 PyErr_SetString(PyExc_TypeError,
2084 "__weakref__ slot disallowed: "
2085 "either we already got one, "
2086 "or __itemsize__ != 0");
2087 goto bad_slots;
2088 }
2089 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002090 }
2091 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002092
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002093 /* Copy slots into a list, mangle names and sort them.
2094 Sorted names are needed for __class__ assignment.
2095 Convert them back to tuple at the end.
2096 */
2097 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002098 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00002099 goto bad_slots;
2100 for (i = j = 0; i < nslots; i++) {
2101 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002102 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00002103 s = PyString_AS_STRING(tmp);
2104 if ((add_dict && strcmp(s, "__dict__") == 0) ||
2105 (add_weak && strcmp(s, "__weakref__") == 0))
2106 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107 tmp =_Py_Mangle(name, tmp);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002108 if (!tmp)
2109 goto bad_slots;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002110 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00002111 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002112 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002113 assert(j == nslots - add_dict - add_weak);
2114 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002115 Py_DECREF(slots);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002116 if (PyList_Sort(newslots) == -1) {
2117 Py_DECREF(bases);
2118 Py_DECREF(newslots);
2119 return NULL;
2120 }
2121 slots = PyList_AsTuple(newslots);
2122 Py_DECREF(newslots);
2123 if (slots == NULL) {
2124 Py_DECREF(bases);
2125 return NULL;
2126 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002127
Guido van Rossumad47da02002-08-12 19:05:44 +00002128 /* Secondary bases may provide weakrefs or dict */
2129 if (nbases > 1 &&
2130 ((may_add_dict && !add_dict) ||
2131 (may_add_weak && !add_weak))) {
2132 for (i = 0; i < nbases; i++) {
2133 tmp = PyTuple_GET_ITEM(bases, i);
2134 if (tmp == (PyObject *)base)
2135 continue; /* Skip primary base */
2136 if (PyClass_Check(tmp)) {
2137 /* Classic base class provides both */
2138 if (may_add_dict && !add_dict)
2139 add_dict++;
2140 if (may_add_weak && !add_weak)
2141 add_weak++;
2142 break;
2143 }
2144 assert(PyType_Check(tmp));
2145 tmptype = (PyTypeObject *)tmp;
2146 if (may_add_dict && !add_dict &&
2147 tmptype->tp_dictoffset != 0)
2148 add_dict++;
2149 if (may_add_weak && !add_weak &&
2150 tmptype->tp_weaklistoffset != 0)
2151 add_weak++;
2152 if (may_add_dict && !add_dict)
2153 continue;
2154 if (may_add_weak && !add_weak)
2155 continue;
2156 /* Nothing more to check */
2157 break;
2158 }
2159 }
Guido van Rossum9676b222001-08-17 20:32:36 +00002160 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002161
2162 /* XXX From here until type is safely allocated,
2163 "return NULL" may leak slots! */
2164
2165 /* Allocate the type object */
2166 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00002167 if (type == NULL) {
2168 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002169 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002170 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00002171 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002172
2173 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002174 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002175 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002176 et->ht_name = name;
2177 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002178
Guido van Rossumdc91b992001-08-08 22:26:22 +00002179 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002180 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2181 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002182 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2183 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002184
2185 /* It's a new-style number unless it specifically inherits any
2186 old-style numeric behavior */
2187 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
2188 (base->tp_as_number == NULL))
2189 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
2190
2191 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002192 type->tp_as_number = &et->as_number;
2193 type->tp_as_sequence = &et->as_sequence;
2194 type->tp_as_mapping = &et->as_mapping;
2195 type->tp_as_buffer = &et->as_buffer;
2196 type->tp_name = PyString_AS_STRING(name);
2197
2198 /* Set tp_base and tp_bases */
2199 type->tp_bases = bases;
2200 Py_INCREF(base);
2201 type->tp_base = base;
2202
Guido van Rossum687ae002001-10-15 22:03:32 +00002203 /* Initialize tp_dict from passed-in dict */
2204 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002205 if (dict == NULL) {
2206 Py_DECREF(type);
2207 return NULL;
2208 }
2209
Guido van Rossumc3542212001-08-16 09:18:56 +00002210 /* Set __module__ in the dict */
2211 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2212 tmp = PyEval_GetGlobals();
2213 if (tmp != NULL) {
2214 tmp = PyDict_GetItemString(tmp, "__name__");
2215 if (tmp != NULL) {
2216 if (PyDict_SetItemString(dict, "__module__",
2217 tmp) < 0)
2218 return NULL;
2219 }
2220 }
2221 }
2222
Tim Peters2f93e282001-10-04 05:27:00 +00002223 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00002224 and is a string. The __doc__ accessor will first look for tp_doc;
2225 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00002226 */
2227 {
2228 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2229 if (doc != NULL && PyString_Check(doc)) {
2230 const size_t n = (size_t)PyString_GET_SIZE(doc);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002231 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002232 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00002233 Py_DECREF(type);
2234 return NULL;
2235 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002236 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002237 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00002238 }
2239 }
2240
Tim Peters6d6c1a32001-08-02 04:15:00 +00002241 /* Special-case __new__: if it's a plain function,
2242 make it a static function */
2243 tmp = PyDict_GetItemString(dict, "__new__");
2244 if (tmp != NULL && PyFunction_Check(tmp)) {
2245 tmp = PyStaticMethod_New(tmp);
2246 if (tmp == NULL) {
2247 Py_DECREF(type);
2248 return NULL;
2249 }
2250 PyDict_SetItemString(dict, "__new__", tmp);
2251 Py_DECREF(tmp);
2252 }
2253
2254 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002255 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00002256 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002257 if (slots != NULL) {
2258 for (i = 0; i < nslots; i++, mp++) {
2259 mp->name = PyString_AS_STRING(
2260 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00002261 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002262 mp->offset = slotoffset;
Žiga Seilnacht89032082007-03-11 15:54:54 +00002263
2264 /* __dict__ and __weakref__ are already filtered out */
2265 assert(strcmp(mp->name, "__dict__") != 0);
2266 assert(strcmp(mp->name, "__weakref__") != 0);
2267
Tim Peters6d6c1a32001-08-02 04:15:00 +00002268 slotoffset += sizeof(PyObject *);
2269 }
2270 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002271 if (add_dict) {
2272 if (base->tp_itemsize)
2273 type->tp_dictoffset = -(long)sizeof(PyObject *);
2274 else
2275 type->tp_dictoffset = slotoffset;
2276 slotoffset += sizeof(PyObject *);
2277 }
2278 if (add_weak) {
2279 assert(!base->tp_itemsize);
2280 type->tp_weaklistoffset = slotoffset;
2281 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002282 }
2283 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002284 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002285 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002286
2287 if (type->tp_weaklistoffset && type->tp_dictoffset)
2288 type->tp_getset = subtype_getsets_full;
2289 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2290 type->tp_getset = subtype_getsets_weakref_only;
2291 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2292 type->tp_getset = subtype_getsets_dict_only;
2293 else
2294 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002295
2296 /* Special case some slots */
2297 if (type->tp_dictoffset != 0 || nslots > 0) {
2298 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2299 type->tp_getattro = PyObject_GenericGetAttr;
2300 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2301 type->tp_setattro = PyObject_GenericSetAttr;
2302 }
2303 type->tp_dealloc = subtype_dealloc;
2304
Guido van Rossum9475a232001-10-05 20:51:39 +00002305 /* Enable GC unless there are really no instance variables possible */
2306 if (!(type->tp_basicsize == sizeof(PyObject) &&
2307 type->tp_itemsize == 0))
2308 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2309
Tim Peters6d6c1a32001-08-02 04:15:00 +00002310 /* Always override allocation strategy to use regular heap */
2311 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002312 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002313 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002314 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002315 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002316 }
2317 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002318 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002319
2320 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002321 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002322 Py_DECREF(type);
2323 return NULL;
2324 }
2325
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002326 /* Put the proper slots in place */
2327 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002328
Tim Peters6d6c1a32001-08-02 04:15:00 +00002329 return (PyObject *)type;
2330}
2331
2332/* Internal API to look for a name through the MRO.
2333 This returns a borrowed reference, and doesn't set an exception! */
2334PyObject *
2335_PyType_Lookup(PyTypeObject *type, PyObject *name)
2336{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002337 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002338 PyObject *mro, *res, *base, *dict;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002339 unsigned int h;
2340
2341 if (MCACHE_CACHEABLE_NAME(name) &&
Neal Norwitze7bb9182008-01-27 17:10:14 +00002342 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002343 /* fast path */
2344 h = MCACHE_HASH_METHOD(type, name);
2345 if (method_cache[h].version == type->tp_version_tag &&
2346 method_cache[h].name == name)
2347 return method_cache[h].value;
2348 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002349
Guido van Rossum687ae002001-10-15 22:03:32 +00002350 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002351 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002352
2353 /* If mro is NULL, the type is either not yet initialized
2354 by PyType_Ready(), or already cleared by type_clear().
2355 Either way the safest thing to do is to return NULL. */
2356 if (mro == NULL)
2357 return NULL;
2358
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002359 res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002360 assert(PyTuple_Check(mro));
2361 n = PyTuple_GET_SIZE(mro);
2362 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002363 base = PyTuple_GET_ITEM(mro, i);
2364 if (PyClass_Check(base))
2365 dict = ((PyClassObject *)base)->cl_dict;
2366 else {
2367 assert(PyType_Check(base));
2368 dict = ((PyTypeObject *)base)->tp_dict;
2369 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002370 assert(dict && PyDict_Check(dict));
2371 res = PyDict_GetItem(dict, name);
2372 if (res != NULL)
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002373 break;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002374 }
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002375
2376 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2377 h = MCACHE_HASH_METHOD(type, name);
2378 method_cache[h].version = type->tp_version_tag;
2379 method_cache[h].value = res; /* borrowed */
2380 Py_INCREF(name);
2381 Py_DECREF(method_cache[h].name);
2382 method_cache[h].name = name;
2383 }
2384 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002385}
2386
2387/* This is similar to PyObject_GenericGetAttr(),
2388 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2389static PyObject *
2390type_getattro(PyTypeObject *type, PyObject *name)
2391{
Christian Heimese93237d2007-12-19 02:37:44 +00002392 PyTypeObject *metatype = Py_TYPE(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002393 PyObject *meta_attribute, *attribute;
2394 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002395
2396 /* Initialize this type (we'll assume the metatype is initialized) */
2397 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002398 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002399 return NULL;
2400 }
2401
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002402 /* No readable descriptor found yet */
2403 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002404
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002405 /* Look for the attribute in the metatype */
2406 meta_attribute = _PyType_Lookup(metatype, name);
2407
2408 if (meta_attribute != NULL) {
Christian Heimese93237d2007-12-19 02:37:44 +00002409 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002410
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002411 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2412 /* Data descriptors implement tp_descr_set to intercept
2413 * writes. Assume the attribute is not overridden in
2414 * type's tp_dict (and bases): call the descriptor now.
2415 */
2416 return meta_get(meta_attribute, (PyObject *)type,
2417 (PyObject *)metatype);
2418 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002419 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002420 }
2421
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002422 /* No data descriptor found on metatype. Look in tp_dict of this
2423 * type and its bases */
2424 attribute = _PyType_Lookup(type, name);
2425 if (attribute != NULL) {
2426 /* Implement descriptor functionality, if any */
Christian Heimese93237d2007-12-19 02:37:44 +00002427 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002428
2429 Py_XDECREF(meta_attribute);
2430
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002431 if (local_get != NULL) {
2432 /* NULL 2nd argument indicates the descriptor was
2433 * found on the target object itself (or a base) */
2434 return local_get(attribute, (PyObject *)NULL,
2435 (PyObject *)type);
2436 }
Tim Peters34592512002-07-11 06:23:50 +00002437
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002438 Py_INCREF(attribute);
2439 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002440 }
2441
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002442 /* No attribute found in local __dict__ (or bases): use the
2443 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002444 if (meta_get != NULL) {
2445 PyObject *res;
2446 res = meta_get(meta_attribute, (PyObject *)type,
2447 (PyObject *)metatype);
2448 Py_DECREF(meta_attribute);
2449 return res;
2450 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002451
2452 /* If an ordinary attribute was found on the metatype, return it now */
2453 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002454 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002455 }
2456
2457 /* Give up */
2458 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002459 "type object '%.50s' has no attribute '%.400s'",
2460 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002461 return NULL;
2462}
2463
2464static int
2465type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2466{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002467 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2468 PyErr_Format(
2469 PyExc_TypeError,
2470 "can't set attributes of built-in/extension type '%s'",
2471 type->tp_name);
2472 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002473 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002474 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2475 return -1;
2476 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002477}
2478
2479static void
2480type_dealloc(PyTypeObject *type)
2481{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002482 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002483
2484 /* Assert this is a heap-allocated type object */
2485 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002486 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002487 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002488 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002489 Py_XDECREF(type->tp_base);
2490 Py_XDECREF(type->tp_dict);
2491 Py_XDECREF(type->tp_bases);
2492 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002493 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002494 Py_XDECREF(type->tp_subclasses);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002495 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2496 * of most other objects. It's okay to cast it to char *.
2497 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002498 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002499 Py_XDECREF(et->ht_name);
2500 Py_XDECREF(et->ht_slots);
Christian Heimese93237d2007-12-19 02:37:44 +00002501 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002502}
2503
Guido van Rossum1c450732001-10-08 15:18:27 +00002504static PyObject *
2505type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2506{
2507 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002508 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002509
2510 list = PyList_New(0);
2511 if (list == NULL)
2512 return NULL;
2513 raw = type->tp_subclasses;
2514 if (raw == NULL)
2515 return list;
2516 assert(PyList_Check(raw));
2517 n = PyList_GET_SIZE(raw);
2518 for (i = 0; i < n; i++) {
2519 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002520 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002521 ref = PyWeakref_GET_OBJECT(ref);
2522 if (ref != Py_None) {
2523 if (PyList_Append(list, ref) < 0) {
2524 Py_DECREF(list);
2525 return NULL;
2526 }
2527 }
2528 }
2529 return list;
2530}
2531
Tim Peters6d6c1a32001-08-02 04:15:00 +00002532static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002533 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002534 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002535 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002536 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002537 {0}
2538};
2539
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002540PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002541"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002542"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002543
Guido van Rossum048eb752001-10-02 21:24:57 +00002544static int
2545type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2546{
Guido van Rossuma3862092002-06-10 15:24:42 +00002547 /* Because of type_is_gc(), the collector only calls this
2548 for heaptypes. */
2549 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002550
Thomas Woutersc6e55062006-04-15 21:47:09 +00002551 Py_VISIT(type->tp_dict);
2552 Py_VISIT(type->tp_cache);
2553 Py_VISIT(type->tp_mro);
2554 Py_VISIT(type->tp_bases);
2555 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002556
2557 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002558 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002559 in cycles; tp_subclasses is a list of weak references,
2560 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002561
Guido van Rossum048eb752001-10-02 21:24:57 +00002562 return 0;
2563}
2564
2565static int
2566type_clear(PyTypeObject *type)
2567{
Guido van Rossuma3862092002-06-10 15:24:42 +00002568 /* Because of type_is_gc(), the collector only calls this
2569 for heaptypes. */
2570 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002571
Guido van Rossuma3862092002-06-10 15:24:42 +00002572 /* The only field we need to clear is tp_mro, which is part of a
2573 hard cycle (its first element is the class itself) that won't
2574 be broken otherwise (it's a tuple and tuples don't have a
2575 tp_clear handler). None of the other fields need to be
2576 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002577
Guido van Rossuma3862092002-06-10 15:24:42 +00002578 tp_dict:
2579 It is a dict, so the collector will call its tp_clear.
2580
2581 tp_cache:
2582 Not used; if it were, it would be a dict.
2583
2584 tp_bases, tp_base:
2585 If these are involved in a cycle, there must be at least
2586 one other, mutable object in the cycle, e.g. a base
2587 class's dict; the cycle will be broken that way.
2588
2589 tp_subclasses:
2590 A list of weak references can't be part of a cycle; and
2591 lists have their own tp_clear.
2592
Guido van Rossume5c691a2003-03-07 15:13:17 +00002593 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002594 A tuple of strings can't be part of a cycle.
2595 */
2596
Thomas Woutersedf17d82006-04-15 17:28:34 +00002597 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002598
2599 return 0;
2600}
2601
2602static int
2603type_is_gc(PyTypeObject *type)
2604{
2605 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2606}
2607
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002608PyTypeObject PyType_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002609 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002610 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002611 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002612 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002613 (destructor)type_dealloc, /* tp_dealloc */
2614 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002615 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002616 0, /* tp_setattr */
2617 type_compare, /* tp_compare */
2618 (reprfunc)type_repr, /* tp_repr */
2619 0, /* tp_as_number */
2620 0, /* tp_as_sequence */
2621 0, /* tp_as_mapping */
2622 (hashfunc)_Py_HashPointer, /* tp_hash */
2623 (ternaryfunc)type_call, /* tp_call */
2624 0, /* tp_str */
2625 (getattrofunc)type_getattro, /* tp_getattro */
2626 (setattrofunc)type_setattro, /* tp_setattro */
2627 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002628 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002629 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002630 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002631 (traverseproc)type_traverse, /* tp_traverse */
2632 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002633 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002634 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002635 0, /* tp_iter */
2636 0, /* tp_iternext */
2637 type_methods, /* tp_methods */
2638 type_members, /* tp_members */
2639 type_getsets, /* tp_getset */
2640 0, /* tp_base */
2641 0, /* tp_dict */
2642 0, /* tp_descr_get */
2643 0, /* tp_descr_set */
2644 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumf102e242007-03-23 18:53:03 +00002645 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002646 0, /* tp_alloc */
2647 type_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002648 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002649 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002650};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002651
2652
2653/* The base type of all types (eventually)... except itself. */
2654
Guido van Rossum143b5642007-03-23 04:58:42 +00002655/* You may wonder why object.__new__() only complains about arguments
2656 when object.__init__() is not overridden, and vice versa.
2657
2658 Consider the use cases:
2659
2660 1. When neither is overridden, we want to hear complaints about
2661 excess (i.e., any) arguments, since their presence could
2662 indicate there's a bug.
2663
2664 2. When defining an Immutable type, we are likely to override only
2665 __new__(), since __init__() is called too late to initialize an
2666 Immutable object. Since __new__() defines the signature for the
2667 type, it would be a pain to have to override __init__() just to
2668 stop it from complaining about excess arguments.
2669
2670 3. When defining a Mutable type, we are likely to override only
2671 __init__(). So here the converse reasoning applies: we don't
2672 want to have to override __new__() just to stop it from
2673 complaining.
2674
2675 4. When __init__() is overridden, and the subclass __init__() calls
2676 object.__init__(), the latter should complain about excess
2677 arguments; ditto for __new__().
2678
2679 Use cases 2 and 3 make it unattractive to unconditionally check for
2680 excess arguments. The best solution that addresses all four use
2681 cases is as follows: __init__() complains about excess arguments
2682 unless __new__() is overridden and __init__() is not overridden
2683 (IOW, if __init__() is overridden or __new__() is not overridden);
2684 symmetrically, __new__() complains about excess arguments unless
2685 __init__() is overridden and __new__() is not overridden
2686 (IOW, if __new__() is overridden or __init__() is not overridden).
2687
2688 However, for backwards compatibility, this breaks too much code.
2689 Therefore, in 2.6, we'll *warn* about excess arguments when both
2690 methods are overridden; for all other cases we'll use the above
2691 rules.
2692
2693*/
2694
2695/* Forward */
2696static PyObject *
2697object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2698
2699static int
2700excess_args(PyObject *args, PyObject *kwds)
2701{
2702 return PyTuple_GET_SIZE(args) ||
2703 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2704}
2705
Tim Peters6d6c1a32001-08-02 04:15:00 +00002706static int
2707object_init(PyObject *self, PyObject *args, PyObject *kwds)
2708{
Guido van Rossum143b5642007-03-23 04:58:42 +00002709 int err = 0;
2710 if (excess_args(args, kwds)) {
Christian Heimese93237d2007-12-19 02:37:44 +00002711 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum143b5642007-03-23 04:58:42 +00002712 if (type->tp_init != object_init &&
2713 type->tp_new != object_new)
2714 {
2715 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2716 "object.__init__() takes no parameters",
2717 1);
2718 }
2719 else if (type->tp_init != object_init ||
2720 type->tp_new == object_new)
2721 {
2722 PyErr_SetString(PyExc_TypeError,
2723 "object.__init__() takes no parameters");
2724 err = -1;
2725 }
2726 }
2727 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002728}
2729
Guido van Rossum298e4212003-02-13 16:30:16 +00002730static PyObject *
2731object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2732{
Guido van Rossum143b5642007-03-23 04:58:42 +00002733 int err = 0;
2734 if (excess_args(args, kwds)) {
2735 if (type->tp_new != object_new &&
2736 type->tp_init != object_init)
2737 {
2738 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2739 "object.__new__() takes no parameters",
2740 1);
2741 }
2742 else if (type->tp_new != object_new ||
2743 type->tp_init == object_init)
2744 {
2745 PyErr_SetString(PyExc_TypeError,
2746 "object.__new__() takes no parameters");
2747 err = -1;
2748 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002749 }
Guido van Rossum143b5642007-03-23 04:58:42 +00002750 if (err < 0)
2751 return NULL;
Guido van Rossum298e4212003-02-13 16:30:16 +00002752 return type->tp_alloc(type, 0);
2753}
2754
Tim Peters6d6c1a32001-08-02 04:15:00 +00002755static void
2756object_dealloc(PyObject *self)
2757{
Christian Heimese93237d2007-12-19 02:37:44 +00002758 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002759}
2760
Guido van Rossum8e248182001-08-12 05:17:56 +00002761static PyObject *
2762object_repr(PyObject *self)
2763{
Guido van Rossum76e69632001-08-16 18:52:43 +00002764 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002765 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002766
Christian Heimese93237d2007-12-19 02:37:44 +00002767 type = Py_TYPE(self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002768 mod = type_module(type, NULL);
2769 if (mod == NULL)
2770 PyErr_Clear();
2771 else if (!PyString_Check(mod)) {
2772 Py_DECREF(mod);
2773 mod = NULL;
2774 }
2775 name = type_name(type, NULL);
2776 if (name == NULL)
2777 return NULL;
2778 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002779 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002780 PyString_AS_STRING(mod),
2781 PyString_AS_STRING(name),
2782 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002783 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002784 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002785 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002786 Py_XDECREF(mod);
2787 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002788 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002789}
2790
Guido van Rossumb8f63662001-08-15 23:57:02 +00002791static PyObject *
2792object_str(PyObject *self)
2793{
2794 unaryfunc f;
2795
Christian Heimese93237d2007-12-19 02:37:44 +00002796 f = Py_TYPE(self)->tp_repr;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002797 if (f == NULL)
2798 f = object_repr;
2799 return f(self);
2800}
2801
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002802static PyObject *
2803object_get_class(PyObject *self, void *closure)
2804{
Christian Heimese93237d2007-12-19 02:37:44 +00002805 Py_INCREF(Py_TYPE(self));
2806 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002807}
2808
2809static int
2810equiv_structs(PyTypeObject *a, PyTypeObject *b)
2811{
2812 return a == b ||
2813 (a != NULL &&
2814 b != NULL &&
2815 a->tp_basicsize == b->tp_basicsize &&
2816 a->tp_itemsize == b->tp_itemsize &&
2817 a->tp_dictoffset == b->tp_dictoffset &&
2818 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2819 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2820 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2821}
2822
2823static int
2824same_slots_added(PyTypeObject *a, PyTypeObject *b)
2825{
2826 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002827 Py_ssize_t size;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002828 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002829
2830 if (base != b->tp_base)
2831 return 0;
2832 if (equiv_structs(a, base) && equiv_structs(b, base))
2833 return 1;
2834 size = base->tp_basicsize;
2835 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2836 size += sizeof(PyObject *);
2837 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2838 size += sizeof(PyObject *);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002839
2840 /* Check slots compliance */
2841 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2842 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2843 if (slots_a && slots_b) {
2844 if (PyObject_Compare(slots_a, slots_b) != 0)
2845 return 0;
2846 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2847 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002848 return size == a->tp_basicsize && size == b->tp_basicsize;
2849}
2850
2851static int
Anthony Baxtera6286212006-04-11 07:42:36 +00002852compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002853{
2854 PyTypeObject *newbase, *oldbase;
2855
Anthony Baxtera6286212006-04-11 07:42:36 +00002856 if (newto->tp_dealloc != oldto->tp_dealloc ||
2857 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002858 {
2859 PyErr_Format(PyExc_TypeError,
2860 "%s assignment: "
2861 "'%s' deallocator differs from '%s'",
2862 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002863 newto->tp_name,
2864 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002865 return 0;
2866 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002867 newbase = newto;
2868 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002869 while (equiv_structs(newbase, newbase->tp_base))
2870 newbase = newbase->tp_base;
2871 while (equiv_structs(oldbase, oldbase->tp_base))
2872 oldbase = oldbase->tp_base;
2873 if (newbase != oldbase &&
2874 (newbase->tp_base != oldbase->tp_base ||
2875 !same_slots_added(newbase, oldbase))) {
2876 PyErr_Format(PyExc_TypeError,
2877 "%s assignment: "
2878 "'%s' object layout differs from '%s'",
2879 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002880 newto->tp_name,
2881 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002882 return 0;
2883 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002884
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002885 return 1;
2886}
2887
2888static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002889object_set_class(PyObject *self, PyObject *value, void *closure)
2890{
Christian Heimese93237d2007-12-19 02:37:44 +00002891 PyTypeObject *oldto = Py_TYPE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00002892 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002893
Guido van Rossumb6b89422002-04-15 01:03:30 +00002894 if (value == NULL) {
2895 PyErr_SetString(PyExc_TypeError,
2896 "can't delete __class__ attribute");
2897 return -1;
2898 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002899 if (!PyType_Check(value)) {
2900 PyErr_Format(PyExc_TypeError,
2901 "__class__ must be set to new-style class, not '%s' object",
Christian Heimese93237d2007-12-19 02:37:44 +00002902 Py_TYPE(value)->tp_name);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002903 return -1;
2904 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002905 newto = (PyTypeObject *)value;
2906 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2907 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002908 {
2909 PyErr_Format(PyExc_TypeError,
2910 "__class__ assignment: only for heap types");
2911 return -1;
2912 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002913 if (compatible_for_assignment(newto, oldto, "__class__")) {
2914 Py_INCREF(newto);
Christian Heimese93237d2007-12-19 02:37:44 +00002915 Py_TYPE(self) = newto;
Anthony Baxtera6286212006-04-11 07:42:36 +00002916 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002917 return 0;
2918 }
2919 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002920 return -1;
2921 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002922}
2923
2924static PyGetSetDef object_getsets[] = {
2925 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002926 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002927 {0}
2928};
2929
Guido van Rossumc53f0092003-02-18 22:05:12 +00002930
Guido van Rossum036f9992003-02-21 22:02:54 +00002931/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2932 We fall back to helpers in copy_reg for:
2933 - pickle protocols < 2
2934 - calculating the list of slot names (done only once per class)
2935 - the __newobj__ function (which is used as a token but never called)
2936*/
2937
2938static PyObject *
2939import_copy_reg(void)
2940{
2941 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002942
2943 if (!copy_reg_str) {
2944 copy_reg_str = PyString_InternFromString("copy_reg");
2945 if (copy_reg_str == NULL)
2946 return NULL;
2947 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002948
2949 return PyImport_Import(copy_reg_str);
2950}
2951
2952static PyObject *
2953slotnames(PyObject *cls)
2954{
2955 PyObject *clsdict;
2956 PyObject *copy_reg;
2957 PyObject *slotnames;
2958
2959 if (!PyType_Check(cls)) {
2960 Py_INCREF(Py_None);
2961 return Py_None;
2962 }
2963
2964 clsdict = ((PyTypeObject *)cls)->tp_dict;
2965 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002966 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002967 Py_INCREF(slotnames);
2968 return slotnames;
2969 }
2970
2971 copy_reg = import_copy_reg();
2972 if (copy_reg == NULL)
2973 return NULL;
2974
2975 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2976 Py_DECREF(copy_reg);
2977 if (slotnames != NULL &&
2978 slotnames != Py_None &&
2979 !PyList_Check(slotnames))
2980 {
2981 PyErr_SetString(PyExc_TypeError,
2982 "copy_reg._slotnames didn't return a list or None");
2983 Py_DECREF(slotnames);
2984 slotnames = NULL;
2985 }
2986
2987 return slotnames;
2988}
2989
2990static PyObject *
2991reduce_2(PyObject *obj)
2992{
2993 PyObject *cls, *getnewargs;
2994 PyObject *args = NULL, *args2 = NULL;
2995 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2996 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2997 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002998 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002999
3000 cls = PyObject_GetAttrString(obj, "__class__");
3001 if (cls == NULL)
3002 return NULL;
3003
3004 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
3005 if (getnewargs != NULL) {
3006 args = PyObject_CallObject(getnewargs, NULL);
3007 Py_DECREF(getnewargs);
3008 if (args != NULL && !PyTuple_Check(args)) {
Georg Brandlccff7852006-06-18 22:17:29 +00003009 PyErr_Format(PyExc_TypeError,
3010 "__getnewargs__ should return a tuple, "
Christian Heimese93237d2007-12-19 02:37:44 +00003011 "not '%.200s'", Py_TYPE(args)->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00003012 goto end;
3013 }
3014 }
3015 else {
3016 PyErr_Clear();
3017 args = PyTuple_New(0);
3018 }
3019 if (args == NULL)
3020 goto end;
3021
3022 getstate = PyObject_GetAttrString(obj, "__getstate__");
3023 if (getstate != NULL) {
3024 state = PyObject_CallObject(getstate, NULL);
3025 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00003026 if (state == NULL)
3027 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003028 }
3029 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00003030 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00003031 state = PyObject_GetAttrString(obj, "__dict__");
3032 if (state == NULL) {
3033 PyErr_Clear();
3034 state = Py_None;
3035 Py_INCREF(state);
3036 }
3037 names = slotnames(cls);
3038 if (names == NULL)
3039 goto end;
3040 if (names != Py_None) {
3041 assert(PyList_Check(names));
3042 slots = PyDict_New();
3043 if (slots == NULL)
3044 goto end;
3045 n = 0;
3046 /* Can't pre-compute the list size; the list
3047 is stored on the class so accessible to other
3048 threads, which may be run by DECREF */
3049 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3050 PyObject *name, *value;
3051 name = PyList_GET_ITEM(names, i);
3052 value = PyObject_GetAttr(obj, name);
3053 if (value == NULL)
3054 PyErr_Clear();
3055 else {
3056 int err = PyDict_SetItem(slots, name,
3057 value);
3058 Py_DECREF(value);
3059 if (err)
3060 goto end;
3061 n++;
3062 }
3063 }
3064 if (n) {
3065 state = Py_BuildValue("(NO)", state, slots);
3066 if (state == NULL)
3067 goto end;
3068 }
3069 }
3070 }
3071
3072 if (!PyList_Check(obj)) {
3073 listitems = Py_None;
3074 Py_INCREF(listitems);
3075 }
3076 else {
3077 listitems = PyObject_GetIter(obj);
3078 if (listitems == NULL)
3079 goto end;
3080 }
3081
3082 if (!PyDict_Check(obj)) {
3083 dictitems = Py_None;
3084 Py_INCREF(dictitems);
3085 }
3086 else {
3087 dictitems = PyObject_CallMethod(obj, "iteritems", "");
3088 if (dictitems == NULL)
3089 goto end;
3090 }
3091
3092 copy_reg = import_copy_reg();
3093 if (copy_reg == NULL)
3094 goto end;
3095 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
3096 if (newobj == NULL)
3097 goto end;
3098
3099 n = PyTuple_GET_SIZE(args);
3100 args2 = PyTuple_New(n+1);
3101 if (args2 == NULL)
3102 goto end;
3103 PyTuple_SET_ITEM(args2, 0, cls);
3104 cls = NULL;
3105 for (i = 0; i < n; i++) {
3106 PyObject *v = PyTuple_GET_ITEM(args, i);
3107 Py_INCREF(v);
3108 PyTuple_SET_ITEM(args2, i+1, v);
3109 }
3110
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003111 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003112
3113 end:
3114 Py_XDECREF(cls);
3115 Py_XDECREF(args);
3116 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00003117 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00003118 Py_XDECREF(state);
3119 Py_XDECREF(names);
3120 Py_XDECREF(listitems);
3121 Py_XDECREF(dictitems);
3122 Py_XDECREF(copy_reg);
3123 Py_XDECREF(newobj);
3124 return res;
3125}
3126
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003127/*
3128 * There were two problems when object.__reduce__ and object.__reduce_ex__
3129 * were implemented in the same function:
3130 * - trying to pickle an object with a custom __reduce__ method that
3131 * fell back to object.__reduce__ in certain circumstances led to
3132 * infinite recursion at Python level and eventual RuntimeError.
3133 * - Pickling objects that lied about their type by overwriting the
3134 * __class__ descriptor could lead to infinite recursion at C level
3135 * and eventual segfault.
3136 *
3137 * Because of backwards compatibility, the two methods still have to
3138 * behave in the same way, even if this is not required by the pickle
3139 * protocol. This common functionality was moved to the _common_reduce
3140 * function.
3141 */
3142static PyObject *
3143_common_reduce(PyObject *self, int proto)
3144{
3145 PyObject *copy_reg, *res;
3146
3147 if (proto >= 2)
3148 return reduce_2(self);
3149
3150 copy_reg = import_copy_reg();
3151 if (!copy_reg)
3152 return NULL;
3153
3154 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
3155 Py_DECREF(copy_reg);
3156
3157 return res;
3158}
3159
3160static PyObject *
3161object_reduce(PyObject *self, PyObject *args)
3162{
3163 int proto = 0;
3164
3165 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3166 return NULL;
3167
3168 return _common_reduce(self, proto);
3169}
3170
Guido van Rossum036f9992003-02-21 22:02:54 +00003171static PyObject *
3172object_reduce_ex(PyObject *self, PyObject *args)
3173{
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003174 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003175 int proto = 0;
3176
3177 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3178 return NULL;
3179
3180 reduce = PyObject_GetAttrString(self, "__reduce__");
3181 if (reduce == NULL)
3182 PyErr_Clear();
3183 else {
3184 PyObject *cls, *clsreduce, *objreduce;
3185 int override;
3186 cls = PyObject_GetAttrString(self, "__class__");
3187 if (cls == NULL) {
3188 Py_DECREF(reduce);
3189 return NULL;
3190 }
3191 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3192 Py_DECREF(cls);
3193 if (clsreduce == NULL) {
3194 Py_DECREF(reduce);
3195 return NULL;
3196 }
3197 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3198 "__reduce__");
3199 override = (clsreduce != objreduce);
3200 Py_DECREF(clsreduce);
3201 if (override) {
3202 res = PyObject_CallObject(reduce, NULL);
3203 Py_DECREF(reduce);
3204 return res;
3205 }
3206 else
3207 Py_DECREF(reduce);
3208 }
3209
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003210 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003211}
3212
3213static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00003214 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3215 PyDoc_STR("helper for pickle")},
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003216 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003217 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00003218 {0}
3219};
3220
Guido van Rossum036f9992003-02-21 22:02:54 +00003221
Tim Peters6d6c1a32001-08-02 04:15:00 +00003222PyTypeObject PyBaseObject_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00003223 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003224 "object", /* tp_name */
3225 sizeof(PyObject), /* tp_basicsize */
3226 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003227 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003228 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003229 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003230 0, /* tp_setattr */
3231 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003232 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003233 0, /* tp_as_number */
3234 0, /* tp_as_sequence */
3235 0, /* tp_as_mapping */
Guido van Rossum64c06e32007-11-22 00:55:51 +00003236 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003237 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003238 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003239 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003240 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003241 0, /* tp_as_buffer */
3242 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003243 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003244 0, /* tp_traverse */
3245 0, /* tp_clear */
3246 0, /* tp_richcompare */
3247 0, /* tp_weaklistoffset */
3248 0, /* tp_iter */
3249 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00003250 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003251 0, /* tp_members */
3252 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003253 0, /* tp_base */
3254 0, /* tp_dict */
3255 0, /* tp_descr_get */
3256 0, /* tp_descr_set */
3257 0, /* tp_dictoffset */
3258 object_init, /* tp_init */
3259 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003260 object_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003261 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003262};
3263
3264
3265/* Initialize the __dict__ in a type object */
3266
3267static int
3268add_methods(PyTypeObject *type, PyMethodDef *meth)
3269{
Guido van Rossum687ae002001-10-15 22:03:32 +00003270 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003271
3272 for (; meth->ml_name != NULL; meth++) {
3273 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003274 if (PyDict_GetItemString(dict, meth->ml_name) &&
3275 !(meth->ml_flags & METH_COEXIST))
3276 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003277 if (meth->ml_flags & METH_CLASS) {
3278 if (meth->ml_flags & METH_STATIC) {
3279 PyErr_SetString(PyExc_ValueError,
3280 "method cannot be both class and static");
3281 return -1;
3282 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003283 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003284 }
3285 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003286 PyObject *cfunc = PyCFunction_New(meth, NULL);
3287 if (cfunc == NULL)
3288 return -1;
3289 descr = PyStaticMethod_New(cfunc);
3290 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003291 }
3292 else {
3293 descr = PyDescr_NewMethod(type, meth);
3294 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003295 if (descr == NULL)
3296 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003297 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003298 return -1;
3299 Py_DECREF(descr);
3300 }
3301 return 0;
3302}
3303
3304static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003305add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003306{
Guido van Rossum687ae002001-10-15 22:03:32 +00003307 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003308
3309 for (; memb->name != NULL; memb++) {
3310 PyObject *descr;
3311 if (PyDict_GetItemString(dict, memb->name))
3312 continue;
3313 descr = PyDescr_NewMember(type, memb);
3314 if (descr == NULL)
3315 return -1;
3316 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3317 return -1;
3318 Py_DECREF(descr);
3319 }
3320 return 0;
3321}
3322
3323static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003324add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003325{
Guido van Rossum687ae002001-10-15 22:03:32 +00003326 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003327
3328 for (; gsp->name != NULL; gsp++) {
3329 PyObject *descr;
3330 if (PyDict_GetItemString(dict, gsp->name))
3331 continue;
3332 descr = PyDescr_NewGetSet(type, gsp);
3333
3334 if (descr == NULL)
3335 return -1;
3336 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3337 return -1;
3338 Py_DECREF(descr);
3339 }
3340 return 0;
3341}
3342
Guido van Rossum13d52f02001-08-10 21:24:08 +00003343static void
3344inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003345{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003346 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003347
Guido van Rossum13d52f02001-08-10 21:24:08 +00003348 /* Special flag magic */
3349 if (!type->tp_as_buffer && base->tp_as_buffer) {
3350 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
3351 type->tp_flags |=
3352 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
3353 }
3354 if (!type->tp_as_sequence && base->tp_as_sequence) {
3355 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3356 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3357 }
3358 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3359 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3360 if ((!type->tp_as_number && base->tp_as_number) ||
3361 (!type->tp_as_sequence && base->tp_as_sequence)) {
3362 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3363 if (!type->tp_as_number && !type->tp_as_sequence) {
3364 type->tp_flags |= base->tp_flags &
3365 Py_TPFLAGS_HAVE_INPLACEOPS;
3366 }
3367 }
3368 /* Wow */
3369 }
3370 if (!type->tp_as_number && base->tp_as_number) {
3371 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3372 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3373 }
3374
3375 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003376 oldsize = base->tp_basicsize;
3377 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3378 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3379 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003380 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3381 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003382 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003383 if (type->tp_traverse == NULL)
3384 type->tp_traverse = base->tp_traverse;
3385 if (type->tp_clear == NULL)
3386 type->tp_clear = base->tp_clear;
3387 }
3388 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00003389 /* The condition below could use some explanation.
3390 It appears that tp_new is not inherited for static types
3391 whose base class is 'object'; this seems to be a precaution
3392 so that old extension types don't suddenly become
3393 callable (object.__new__ wouldn't insure the invariants
3394 that the extension type's own factory function ensures).
3395 Heap types, of course, are under our control, so they do
3396 inherit tp_new; static extension types that specify some
3397 other built-in type as the default are considered
3398 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003399 if (base != &PyBaseObject_Type ||
3400 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3401 if (type->tp_new == NULL)
3402 type->tp_new = base->tp_new;
3403 }
3404 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003405 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003406
3407 /* Copy other non-function slots */
3408
3409#undef COPYVAL
3410#define COPYVAL(SLOT) \
3411 if (type->SLOT == 0) type->SLOT = base->SLOT
3412
3413 COPYVAL(tp_itemsize);
3414 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3415 COPYVAL(tp_weaklistoffset);
3416 }
3417 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3418 COPYVAL(tp_dictoffset);
3419 }
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003420
3421 /* Setup fast subclass flags */
3422 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3423 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3424 else if (PyType_IsSubtype(base, &PyType_Type))
3425 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3426 else if (PyType_IsSubtype(base, &PyInt_Type))
3427 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3428 else if (PyType_IsSubtype(base, &PyLong_Type))
3429 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3430 else if (PyType_IsSubtype(base, &PyString_Type))
3431 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003432#ifdef Py_USING_UNICODE
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003433 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3434 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003435#endif
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003436 else if (PyType_IsSubtype(base, &PyTuple_Type))
3437 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3438 else if (PyType_IsSubtype(base, &PyList_Type))
3439 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3440 else if (PyType_IsSubtype(base, &PyDict_Type))
3441 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003442}
3443
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003444static char *hash_name_op[] = {
3445 "__eq__",
3446 "__cmp__",
3447 "__hash__",
3448 NULL
Guido van Rossum64c06e32007-11-22 00:55:51 +00003449};
3450
3451static int
3452overrides_hash(PyTypeObject *type)
3453{
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003454 char **p;
Guido van Rossum64c06e32007-11-22 00:55:51 +00003455 PyObject *dict = type->tp_dict;
3456
3457 assert(dict != NULL);
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003458 for (p = hash_name_op; *p; p++) {
3459 if (PyDict_GetItemString(dict, *p) != NULL)
Guido van Rossum64c06e32007-11-22 00:55:51 +00003460 return 1;
3461 }
3462 return 0;
3463}
3464
Guido van Rossum13d52f02001-08-10 21:24:08 +00003465static void
3466inherit_slots(PyTypeObject *type, PyTypeObject *base)
3467{
3468 PyTypeObject *basebase;
3469
3470#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003471#undef COPYSLOT
3472#undef COPYNUM
3473#undef COPYSEQ
3474#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003475#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003476
3477#define SLOTDEFINED(SLOT) \
3478 (base->SLOT != 0 && \
3479 (basebase == NULL || base->SLOT != basebase->SLOT))
3480
Tim Peters6d6c1a32001-08-02 04:15:00 +00003481#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003482 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003483
3484#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3485#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3486#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003487#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003488
Guido van Rossum13d52f02001-08-10 21:24:08 +00003489 /* This won't inherit indirect slots (from tp_as_number etc.)
3490 if type doesn't provide the space. */
3491
3492 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3493 basebase = base->tp_base;
3494 if (basebase->tp_as_number == NULL)
3495 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003496 COPYNUM(nb_add);
3497 COPYNUM(nb_subtract);
3498 COPYNUM(nb_multiply);
3499 COPYNUM(nb_divide);
3500 COPYNUM(nb_remainder);
3501 COPYNUM(nb_divmod);
3502 COPYNUM(nb_power);
3503 COPYNUM(nb_negative);
3504 COPYNUM(nb_positive);
3505 COPYNUM(nb_absolute);
3506 COPYNUM(nb_nonzero);
3507 COPYNUM(nb_invert);
3508 COPYNUM(nb_lshift);
3509 COPYNUM(nb_rshift);
3510 COPYNUM(nb_and);
3511 COPYNUM(nb_xor);
3512 COPYNUM(nb_or);
3513 COPYNUM(nb_coerce);
3514 COPYNUM(nb_int);
3515 COPYNUM(nb_long);
3516 COPYNUM(nb_float);
3517 COPYNUM(nb_oct);
3518 COPYNUM(nb_hex);
3519 COPYNUM(nb_inplace_add);
3520 COPYNUM(nb_inplace_subtract);
3521 COPYNUM(nb_inplace_multiply);
3522 COPYNUM(nb_inplace_divide);
3523 COPYNUM(nb_inplace_remainder);
3524 COPYNUM(nb_inplace_power);
3525 COPYNUM(nb_inplace_lshift);
3526 COPYNUM(nb_inplace_rshift);
3527 COPYNUM(nb_inplace_and);
3528 COPYNUM(nb_inplace_xor);
3529 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003530 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3531 COPYNUM(nb_true_divide);
3532 COPYNUM(nb_floor_divide);
3533 COPYNUM(nb_inplace_true_divide);
3534 COPYNUM(nb_inplace_floor_divide);
3535 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003536 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3537 COPYNUM(nb_index);
3538 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003539 }
3540
Guido van Rossum13d52f02001-08-10 21:24:08 +00003541 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3542 basebase = base->tp_base;
3543 if (basebase->tp_as_sequence == NULL)
3544 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003545 COPYSEQ(sq_length);
3546 COPYSEQ(sq_concat);
3547 COPYSEQ(sq_repeat);
3548 COPYSEQ(sq_item);
3549 COPYSEQ(sq_slice);
3550 COPYSEQ(sq_ass_item);
3551 COPYSEQ(sq_ass_slice);
3552 COPYSEQ(sq_contains);
3553 COPYSEQ(sq_inplace_concat);
3554 COPYSEQ(sq_inplace_repeat);
3555 }
3556
Guido van Rossum13d52f02001-08-10 21:24:08 +00003557 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3558 basebase = base->tp_base;
3559 if (basebase->tp_as_mapping == NULL)
3560 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003561 COPYMAP(mp_length);
3562 COPYMAP(mp_subscript);
3563 COPYMAP(mp_ass_subscript);
3564 }
3565
Tim Petersfc57ccb2001-10-12 02:38:24 +00003566 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3567 basebase = base->tp_base;
3568 if (basebase->tp_as_buffer == NULL)
3569 basebase = NULL;
3570 COPYBUF(bf_getreadbuffer);
3571 COPYBUF(bf_getwritebuffer);
3572 COPYBUF(bf_getsegcount);
3573 COPYBUF(bf_getcharbuffer);
3574 }
3575
Guido van Rossum13d52f02001-08-10 21:24:08 +00003576 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003577
Tim Peters6d6c1a32001-08-02 04:15:00 +00003578 COPYSLOT(tp_dealloc);
3579 COPYSLOT(tp_print);
3580 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3581 type->tp_getattr = base->tp_getattr;
3582 type->tp_getattro = base->tp_getattro;
3583 }
3584 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3585 type->tp_setattr = base->tp_setattr;
3586 type->tp_setattro = base->tp_setattro;
3587 }
3588 /* tp_compare see tp_richcompare */
3589 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003590 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003591 COPYSLOT(tp_call);
3592 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003593 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003594 if (type->tp_compare == NULL &&
3595 type->tp_richcompare == NULL &&
Guido van Rossum64c06e32007-11-22 00:55:51 +00003596 type->tp_hash == NULL &&
3597 !overrides_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003598 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003599 type->tp_compare = base->tp_compare;
3600 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003601 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003602 }
3603 }
3604 else {
3605 COPYSLOT(tp_compare);
3606 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003607 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3608 COPYSLOT(tp_iter);
3609 COPYSLOT(tp_iternext);
3610 }
3611 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3612 COPYSLOT(tp_descr_get);
3613 COPYSLOT(tp_descr_set);
3614 COPYSLOT(tp_dictoffset);
3615 COPYSLOT(tp_init);
3616 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003617 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003618 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3619 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3620 /* They agree about gc. */
3621 COPYSLOT(tp_free);
3622 }
3623 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3624 type->tp_free == NULL &&
3625 base->tp_free == _PyObject_Del) {
3626 /* A bit of magic to plug in the correct default
3627 * tp_free function when a derived class adds gc,
3628 * didn't define tp_free, and the base uses the
3629 * default non-gc tp_free.
3630 */
3631 type->tp_free = PyObject_GC_Del;
3632 }
3633 /* else they didn't agree about gc, and there isn't something
3634 * obvious to be done -- the type is on its own.
3635 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003636 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003637}
3638
Jeremy Hylton938ace62002-07-17 16:30:39 +00003639static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003640
Tim Peters6d6c1a32001-08-02 04:15:00 +00003641int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003642PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003643{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003644 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003645 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003646 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003647
Guido van Rossumcab05802002-06-10 15:29:03 +00003648 if (type->tp_flags & Py_TPFLAGS_READY) {
3649 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003650 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003651 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003652 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003653
3654 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003655
Tim Peters36eb4df2003-03-23 03:33:13 +00003656#ifdef Py_TRACE_REFS
3657 /* PyType_Ready is the closest thing we have to a choke point
3658 * for type objects, so is the best place I can think of to try
3659 * to get type objects into the doubly-linked list of all objects.
3660 * Still, not all type objects go thru PyType_Ready.
3661 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003662 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003663#endif
3664
Tim Peters6d6c1a32001-08-02 04:15:00 +00003665 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3666 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003667 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003668 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003669 Py_INCREF(base);
3670 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003671
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003672 /* Now the only way base can still be NULL is if type is
3673 * &PyBaseObject_Type.
3674 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003675
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003676 /* Initialize the base class */
3677 if (base && base->tp_dict == NULL) {
3678 if (PyType_Ready(base) < 0)
3679 goto error;
3680 }
3681
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003682 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003683 compilable separately on Windows can call PyType_Ready() instead of
3684 initializing the ob_type field of their type objects. */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003685 /* The test for base != NULL is really unnecessary, since base is only
3686 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3687 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3688 know that. */
Christian Heimese93237d2007-12-19 02:37:44 +00003689 if (Py_TYPE(type) == NULL && base != NULL)
3690 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003691
Tim Peters6d6c1a32001-08-02 04:15:00 +00003692 /* Initialize tp_bases */
3693 bases = type->tp_bases;
3694 if (bases == NULL) {
3695 if (base == NULL)
3696 bases = PyTuple_New(0);
3697 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003698 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003699 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003700 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003701 type->tp_bases = bases;
3702 }
3703
Guido van Rossum687ae002001-10-15 22:03:32 +00003704 /* Initialize tp_dict */
3705 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003706 if (dict == NULL) {
3707 dict = PyDict_New();
3708 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003709 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003710 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003711 }
3712
Guido van Rossum687ae002001-10-15 22:03:32 +00003713 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003714 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003715 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003716 if (type->tp_methods != NULL) {
3717 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003718 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003719 }
3720 if (type->tp_members != NULL) {
3721 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003722 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003723 }
3724 if (type->tp_getset != NULL) {
3725 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003726 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003727 }
3728
Tim Peters6d6c1a32001-08-02 04:15:00 +00003729 /* Calculate method resolution order */
3730 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003731 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003732 }
3733
Guido van Rossum13d52f02001-08-10 21:24:08 +00003734 /* Inherit special flags from dominant base */
3735 if (type->tp_base != NULL)
3736 inherit_special(type, type->tp_base);
3737
Tim Peters6d6c1a32001-08-02 04:15:00 +00003738 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003739 bases = type->tp_mro;
3740 assert(bases != NULL);
3741 assert(PyTuple_Check(bases));
3742 n = PyTuple_GET_SIZE(bases);
3743 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003744 PyObject *b = PyTuple_GET_ITEM(bases, i);
3745 if (PyType_Check(b))
3746 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003747 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003748
Tim Peters3cfe7542003-05-21 21:29:48 +00003749 /* Sanity check for tp_free. */
3750 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3751 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003752 /* This base class needs to call tp_free, but doesn't have
3753 * one, or its tp_free is for non-gc'ed objects.
3754 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003755 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3756 "gc and is a base type but has inappropriate "
3757 "tp_free slot",
3758 type->tp_name);
3759 goto error;
3760 }
3761
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003762 /* if the type dictionary doesn't contain a __doc__, set it from
3763 the tp_doc slot.
3764 */
3765 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3766 if (type->tp_doc != NULL) {
3767 PyObject *doc = PyString_FromString(type->tp_doc);
Neal Norwitze1fdb322006-07-21 05:32:28 +00003768 if (doc == NULL)
3769 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003770 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3771 Py_DECREF(doc);
3772 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003773 PyDict_SetItemString(type->tp_dict,
3774 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003775 }
3776 }
3777
Guido van Rossum64c06e32007-11-22 00:55:51 +00003778 /* Hack for tp_hash and __hash__.
3779 If after all that, tp_hash is still NULL, and __hash__ is not in
3780 tp_dict, set tp_dict['__hash__'] equal to None.
3781 This signals that __hash__ is not inherited.
3782 */
3783 if (type->tp_hash == NULL &&
3784 PyDict_GetItemString(type->tp_dict, "__hash__") == NULL &&
3785 PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3786 {
3787 goto error;
3788 }
3789
Guido van Rossum13d52f02001-08-10 21:24:08 +00003790 /* Some more special stuff */
3791 base = type->tp_base;
3792 if (base != NULL) {
3793 if (type->tp_as_number == NULL)
3794 type->tp_as_number = base->tp_as_number;
3795 if (type->tp_as_sequence == NULL)
3796 type->tp_as_sequence = base->tp_as_sequence;
3797 if (type->tp_as_mapping == NULL)
3798 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003799 if (type->tp_as_buffer == NULL)
3800 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003801 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003802
Guido van Rossum1c450732001-10-08 15:18:27 +00003803 /* Link into each base class's list of subclasses */
3804 bases = type->tp_bases;
3805 n = PyTuple_GET_SIZE(bases);
3806 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003807 PyObject *b = PyTuple_GET_ITEM(bases, i);
3808 if (PyType_Check(b) &&
3809 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003810 goto error;
3811 }
3812
Guido van Rossum13d52f02001-08-10 21:24:08 +00003813 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003814 assert(type->tp_dict != NULL);
3815 type->tp_flags =
3816 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003817 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003818
3819 error:
3820 type->tp_flags &= ~Py_TPFLAGS_READYING;
3821 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003822}
3823
Guido van Rossum1c450732001-10-08 15:18:27 +00003824static int
3825add_subclass(PyTypeObject *base, PyTypeObject *type)
3826{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003827 Py_ssize_t i;
3828 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00003829 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003830
3831 list = base->tp_subclasses;
3832 if (list == NULL) {
3833 base->tp_subclasses = list = PyList_New(0);
3834 if (list == NULL)
3835 return -1;
3836 }
3837 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00003838 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003839 i = PyList_GET_SIZE(list);
3840 while (--i >= 0) {
3841 ref = PyList_GET_ITEM(list, i);
3842 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003843 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00003844 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003845 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003846 result = PyList_Append(list, newobj);
3847 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003848 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003849}
3850
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003851static void
3852remove_subclass(PyTypeObject *base, PyTypeObject *type)
3853{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003854 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003855 PyObject *list, *ref;
3856
3857 list = base->tp_subclasses;
3858 if (list == NULL) {
3859 return;
3860 }
3861 assert(PyList_Check(list));
3862 i = PyList_GET_SIZE(list);
3863 while (--i >= 0) {
3864 ref = PyList_GET_ITEM(list, i);
3865 assert(PyWeakref_CheckRef(ref));
3866 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3867 /* this can't fail, right? */
3868 PySequence_DelItem(list, i);
3869 return;
3870 }
3871 }
3872}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003873
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003874static int
3875check_num_args(PyObject *ob, int n)
3876{
3877 if (!PyTuple_CheckExact(ob)) {
3878 PyErr_SetString(PyExc_SystemError,
3879 "PyArg_UnpackTuple() argument list is not a tuple");
3880 return 0;
3881 }
3882 if (n == PyTuple_GET_SIZE(ob))
3883 return 1;
3884 PyErr_Format(
3885 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003886 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003887 return 0;
3888}
3889
Tim Peters6d6c1a32001-08-02 04:15:00 +00003890/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3891
3892/* There's a wrapper *function* for each distinct function typedef used
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003893 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003894 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3895 Most tables have only one entry; the tables for binary operators have two
3896 entries, one regular and one with reversed arguments. */
3897
3898static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003899wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003900{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003901 lenfunc func = (lenfunc)wrapped;
3902 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003903
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003904 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003905 return NULL;
3906 res = (*func)(self);
3907 if (res == -1 && PyErr_Occurred())
3908 return NULL;
3909 return PyInt_FromLong((long)res);
3910}
3911
Tim Peters6d6c1a32001-08-02 04:15:00 +00003912static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003913wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3914{
3915 inquiry func = (inquiry)wrapped;
3916 int res;
3917
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003918 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003919 return NULL;
3920 res = (*func)(self);
3921 if (res == -1 && PyErr_Occurred())
3922 return NULL;
3923 return PyBool_FromLong((long)res);
3924}
3925
3926static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003927wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3928{
3929 binaryfunc func = (binaryfunc)wrapped;
3930 PyObject *other;
3931
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003932 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003933 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003934 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003935 return (*func)(self, other);
3936}
3937
3938static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003939wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3940{
3941 binaryfunc func = (binaryfunc)wrapped;
3942 PyObject *other;
3943
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003944 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003945 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003946 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003947 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003948 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003949 Py_INCREF(Py_NotImplemented);
3950 return Py_NotImplemented;
3951 }
3952 return (*func)(self, other);
3953}
3954
3955static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003956wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3957{
3958 binaryfunc func = (binaryfunc)wrapped;
3959 PyObject *other;
3960
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003961 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003962 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003963 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003964 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003965 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003966 Py_INCREF(Py_NotImplemented);
3967 return Py_NotImplemented;
3968 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003969 return (*func)(other, self);
3970}
3971
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003972static PyObject *
3973wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3974{
3975 coercion func = (coercion)wrapped;
3976 PyObject *other, *res;
3977 int ok;
3978
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003979 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003980 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003981 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003982 ok = func(&self, &other);
3983 if (ok < 0)
3984 return NULL;
3985 if (ok > 0) {
3986 Py_INCREF(Py_NotImplemented);
3987 return Py_NotImplemented;
3988 }
3989 res = PyTuple_New(2);
3990 if (res == NULL) {
3991 Py_DECREF(self);
3992 Py_DECREF(other);
3993 return NULL;
3994 }
3995 PyTuple_SET_ITEM(res, 0, self);
3996 PyTuple_SET_ITEM(res, 1, other);
3997 return res;
3998}
3999
Tim Peters6d6c1a32001-08-02 04:15:00 +00004000static PyObject *
4001wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4002{
4003 ternaryfunc func = (ternaryfunc)wrapped;
4004 PyObject *other;
4005 PyObject *third = Py_None;
4006
4007 /* Note: This wrapper only works for __pow__() */
4008
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004009 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004010 return NULL;
4011 return (*func)(self, other, third);
4012}
4013
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004014static PyObject *
4015wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4016{
4017 ternaryfunc func = (ternaryfunc)wrapped;
4018 PyObject *other;
4019 PyObject *third = Py_None;
4020
4021 /* Note: This wrapper only works for __pow__() */
4022
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004023 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004024 return NULL;
4025 return (*func)(other, self, third);
4026}
4027
Tim Peters6d6c1a32001-08-02 04:15:00 +00004028static PyObject *
4029wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4030{
4031 unaryfunc func = (unaryfunc)wrapped;
4032
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004033 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004034 return NULL;
4035 return (*func)(self);
4036}
4037
Tim Peters6d6c1a32001-08-02 04:15:00 +00004038static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00004039wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004040{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004041 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00004042 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004043 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004044
Armin Rigo314861c2006-03-30 14:04:02 +00004045 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4046 return NULL;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004047 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Armin Rigo314861c2006-03-30 14:04:02 +00004048 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004049 return NULL;
4050 return (*func)(self, i);
4051}
4052
Martin v. Löwis18e16552006-02-15 17:27:45 +00004053static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004054getindex(PyObject *self, PyObject *arg)
4055{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004056 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004057
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004058 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004059 if (i == -1 && PyErr_Occurred())
4060 return -1;
4061 if (i < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00004062 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004063 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00004064 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004065 if (n < 0)
4066 return -1;
4067 i += n;
4068 }
4069 }
4070 return i;
4071}
4072
4073static PyObject *
4074wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4075{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004076 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004077 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004078 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004079
Guido van Rossumf4593e02001-10-03 12:09:30 +00004080 if (PyTuple_GET_SIZE(args) == 1) {
4081 arg = PyTuple_GET_ITEM(args, 0);
4082 i = getindex(self, arg);
4083 if (i == -1 && PyErr_Occurred())
4084 return NULL;
4085 return (*func)(self, i);
4086 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004087 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004088 assert(PyErr_Occurred());
4089 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004090}
4091
Tim Peters6d6c1a32001-08-02 04:15:00 +00004092static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004093wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004094{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004095 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
4096 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004097
Martin v. Löwis18e16552006-02-15 17:27:45 +00004098 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004099 return NULL;
4100 return (*func)(self, i, j);
4101}
4102
Tim Peters6d6c1a32001-08-02 04:15:00 +00004103static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004104wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004105{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004106 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4107 Py_ssize_t i;
4108 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004109 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004110
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004111 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004112 return NULL;
4113 i = getindex(self, arg);
4114 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004115 return NULL;
4116 res = (*func)(self, i, value);
4117 if (res == -1 && PyErr_Occurred())
4118 return NULL;
4119 Py_INCREF(Py_None);
4120 return Py_None;
4121}
4122
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004123static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004124wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004125{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004126 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4127 Py_ssize_t i;
4128 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004129 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004130
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004131 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004132 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004133 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004134 i = getindex(self, arg);
4135 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004136 return NULL;
4137 res = (*func)(self, i, NULL);
4138 if (res == -1 && PyErr_Occurred())
4139 return NULL;
4140 Py_INCREF(Py_None);
4141 return Py_None;
4142}
4143
Tim Peters6d6c1a32001-08-02 04:15:00 +00004144static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004145wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004146{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004147 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4148 Py_ssize_t i, j;
4149 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004150 PyObject *value;
4151
Martin v. Löwis18e16552006-02-15 17:27:45 +00004152 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004153 return NULL;
4154 res = (*func)(self, i, j, value);
4155 if (res == -1 && PyErr_Occurred())
4156 return NULL;
4157 Py_INCREF(Py_None);
4158 return Py_None;
4159}
4160
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004161static PyObject *
4162wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
4163{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004164 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4165 Py_ssize_t i, j;
4166 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004167
Martin v. Löwis18e16552006-02-15 17:27:45 +00004168 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004169 return NULL;
4170 res = (*func)(self, i, j, NULL);
4171 if (res == -1 && PyErr_Occurred())
4172 return NULL;
4173 Py_INCREF(Py_None);
4174 return Py_None;
4175}
4176
Tim Peters6d6c1a32001-08-02 04:15:00 +00004177/* XXX objobjproc is a misnomer; should be objargpred */
4178static PyObject *
4179wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4180{
4181 objobjproc func = (objobjproc)wrapped;
4182 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004183 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004184
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004185 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004186 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004187 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004188 res = (*func)(self, value);
4189 if (res == -1 && PyErr_Occurred())
4190 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004191 else
4192 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004193}
4194
Tim Peters6d6c1a32001-08-02 04:15:00 +00004195static PyObject *
4196wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4197{
4198 objobjargproc func = (objobjargproc)wrapped;
4199 int res;
4200 PyObject *key, *value;
4201
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004202 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004203 return NULL;
4204 res = (*func)(self, key, value);
4205 if (res == -1 && PyErr_Occurred())
4206 return NULL;
4207 Py_INCREF(Py_None);
4208 return Py_None;
4209}
4210
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004211static PyObject *
4212wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4213{
4214 objobjargproc func = (objobjargproc)wrapped;
4215 int res;
4216 PyObject *key;
4217
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004218 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004219 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004220 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004221 res = (*func)(self, key, NULL);
4222 if (res == -1 && PyErr_Occurred())
4223 return NULL;
4224 Py_INCREF(Py_None);
4225 return Py_None;
4226}
4227
Tim Peters6d6c1a32001-08-02 04:15:00 +00004228static PyObject *
4229wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
4230{
4231 cmpfunc func = (cmpfunc)wrapped;
4232 int res;
4233 PyObject *other;
4234
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004235 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004236 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004237 other = PyTuple_GET_ITEM(args, 0);
Christian Heimese93237d2007-12-19 02:37:44 +00004238 if (Py_TYPE(other)->tp_compare != func &&
4239 !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
Guido van Rossumceccae52001-09-18 20:03:57 +00004240 PyErr_Format(
4241 PyExc_TypeError,
4242 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +00004243 Py_TYPE(self)->tp_name,
4244 Py_TYPE(self)->tp_name,
4245 Py_TYPE(other)->tp_name);
Guido van Rossumceccae52001-09-18 20:03:57 +00004246 return NULL;
4247 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004248 res = (*func)(self, other);
4249 if (PyErr_Occurred())
4250 return NULL;
4251 return PyInt_FromLong((long)res);
4252}
4253
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004254/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004255 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004256static int
4257hackcheck(PyObject *self, setattrofunc func, char *what)
4258{
Christian Heimese93237d2007-12-19 02:37:44 +00004259 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004260 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4261 type = type->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004262 /* If type is NULL now, this is a really weird type.
4263 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004264 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004265 PyErr_Format(PyExc_TypeError,
4266 "can't apply this %s to %s object",
4267 what,
4268 type->tp_name);
4269 return 0;
4270 }
4271 return 1;
4272}
4273
Tim Peters6d6c1a32001-08-02 04:15:00 +00004274static PyObject *
4275wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4276{
4277 setattrofunc func = (setattrofunc)wrapped;
4278 int res;
4279 PyObject *name, *value;
4280
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004281 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004282 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004283 if (!hackcheck(self, func, "__setattr__"))
4284 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004285 res = (*func)(self, name, value);
4286 if (res < 0)
4287 return NULL;
4288 Py_INCREF(Py_None);
4289 return Py_None;
4290}
4291
4292static PyObject *
4293wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4294{
4295 setattrofunc func = (setattrofunc)wrapped;
4296 int res;
4297 PyObject *name;
4298
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004299 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004300 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004301 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004302 if (!hackcheck(self, func, "__delattr__"))
4303 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004304 res = (*func)(self, name, NULL);
4305 if (res < 0)
4306 return NULL;
4307 Py_INCREF(Py_None);
4308 return Py_None;
4309}
4310
Tim Peters6d6c1a32001-08-02 04:15:00 +00004311static PyObject *
4312wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4313{
4314 hashfunc func = (hashfunc)wrapped;
4315 long res;
4316
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004317 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004318 return NULL;
4319 res = (*func)(self);
4320 if (res == -1 && PyErr_Occurred())
4321 return NULL;
4322 return PyInt_FromLong(res);
4323}
4324
Tim Peters6d6c1a32001-08-02 04:15:00 +00004325static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004326wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004327{
4328 ternaryfunc func = (ternaryfunc)wrapped;
4329
Guido van Rossumc8e56452001-10-22 00:43:43 +00004330 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004331}
4332
Tim Peters6d6c1a32001-08-02 04:15:00 +00004333static PyObject *
4334wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4335{
4336 richcmpfunc func = (richcmpfunc)wrapped;
4337 PyObject *other;
4338
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004339 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004340 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004341 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004342 return (*func)(self, other, op);
4343}
4344
4345#undef RICHCMP_WRAPPER
4346#define RICHCMP_WRAPPER(NAME, OP) \
4347static PyObject * \
4348richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4349{ \
4350 return wrap_richcmpfunc(self, args, wrapped, OP); \
4351}
4352
Jack Jansen8e938b42001-08-08 15:29:49 +00004353RICHCMP_WRAPPER(lt, Py_LT)
4354RICHCMP_WRAPPER(le, Py_LE)
4355RICHCMP_WRAPPER(eq, Py_EQ)
4356RICHCMP_WRAPPER(ne, Py_NE)
4357RICHCMP_WRAPPER(gt, Py_GT)
4358RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004359
Tim Peters6d6c1a32001-08-02 04:15:00 +00004360static PyObject *
4361wrap_next(PyObject *self, PyObject *args, void *wrapped)
4362{
4363 unaryfunc func = (unaryfunc)wrapped;
4364 PyObject *res;
4365
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004366 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004367 return NULL;
4368 res = (*func)(self);
4369 if (res == NULL && !PyErr_Occurred())
4370 PyErr_SetNone(PyExc_StopIteration);
4371 return res;
4372}
4373
Tim Peters6d6c1a32001-08-02 04:15:00 +00004374static PyObject *
4375wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4376{
4377 descrgetfunc func = (descrgetfunc)wrapped;
4378 PyObject *obj;
4379 PyObject *type = NULL;
4380
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004381 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004382 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004383 if (obj == Py_None)
4384 obj = NULL;
4385 if (type == Py_None)
4386 type = NULL;
4387 if (type == NULL &&obj == NULL) {
4388 PyErr_SetString(PyExc_TypeError,
4389 "__get__(None, None) is invalid");
4390 return NULL;
4391 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004392 return (*func)(self, obj, type);
4393}
4394
Tim Peters6d6c1a32001-08-02 04:15:00 +00004395static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004396wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004397{
4398 descrsetfunc func = (descrsetfunc)wrapped;
4399 PyObject *obj, *value;
4400 int ret;
4401
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004402 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004403 return NULL;
4404 ret = (*func)(self, obj, value);
4405 if (ret < 0)
4406 return NULL;
4407 Py_INCREF(Py_None);
4408 return Py_None;
4409}
Guido van Rossum22b13872002-08-06 21:41:44 +00004410
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004411static PyObject *
4412wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4413{
4414 descrsetfunc func = (descrsetfunc)wrapped;
4415 PyObject *obj;
4416 int ret;
4417
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004418 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004419 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004420 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004421 ret = (*func)(self, obj, NULL);
4422 if (ret < 0)
4423 return NULL;
4424 Py_INCREF(Py_None);
4425 return Py_None;
4426}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004427
Tim Peters6d6c1a32001-08-02 04:15:00 +00004428static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004429wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004430{
4431 initproc func = (initproc)wrapped;
4432
Guido van Rossumc8e56452001-10-22 00:43:43 +00004433 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004434 return NULL;
4435 Py_INCREF(Py_None);
4436 return Py_None;
4437}
4438
Tim Peters6d6c1a32001-08-02 04:15:00 +00004439static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004440tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004441{
Barry Warsaw60f01882001-08-22 19:24:42 +00004442 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004443 PyObject *arg0, *res;
4444
4445 if (self == NULL || !PyType_Check(self))
4446 Py_FatalError("__new__() called with non-type 'self'");
4447 type = (PyTypeObject *)self;
4448 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004449 PyErr_Format(PyExc_TypeError,
4450 "%s.__new__(): not enough arguments",
4451 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004452 return NULL;
4453 }
4454 arg0 = PyTuple_GET_ITEM(args, 0);
4455 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004456 PyErr_Format(PyExc_TypeError,
4457 "%s.__new__(X): X is not a type object (%s)",
4458 type->tp_name,
Christian Heimese93237d2007-12-19 02:37:44 +00004459 Py_TYPE(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004460 return NULL;
4461 }
4462 subtype = (PyTypeObject *)arg0;
4463 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004464 PyErr_Format(PyExc_TypeError,
4465 "%s.__new__(%s): %s is not a subtype of %s",
4466 type->tp_name,
4467 subtype->tp_name,
4468 subtype->tp_name,
4469 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004470 return NULL;
4471 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004472
4473 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004474 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004475 most derived base that's not a heap type is this type. */
4476 staticbase = subtype;
4477 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4478 staticbase = staticbase->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004479 /* If staticbase is NULL now, it is a really weird type.
4480 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004481 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004482 PyErr_Format(PyExc_TypeError,
4483 "%s.__new__(%s) is not safe, use %s.__new__()",
4484 type->tp_name,
4485 subtype->tp_name,
4486 staticbase == NULL ? "?" : staticbase->tp_name);
4487 return NULL;
4488 }
4489
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004490 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4491 if (args == NULL)
4492 return NULL;
4493 res = type->tp_new(subtype, args, kwds);
4494 Py_DECREF(args);
4495 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004496}
4497
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004498static struct PyMethodDef tp_new_methoddef[] = {
Neal Norwitza84dcd72007-05-22 07:16:44 +00004499 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004500 PyDoc_STR("T.__new__(S, ...) -> "
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004501 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004502 {0}
4503};
4504
4505static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004506add_tp_new_wrapper(PyTypeObject *type)
4507{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004508 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004509
Guido van Rossum687ae002001-10-15 22:03:32 +00004510 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004511 return 0;
4512 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004513 if (func == NULL)
4514 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004515 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004516 Py_DECREF(func);
4517 return -1;
4518 }
4519 Py_DECREF(func);
4520 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004521}
4522
Guido van Rossumf040ede2001-08-07 16:40:56 +00004523/* Slot wrappers that call the corresponding __foo__ slot. See comments
4524 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004525
Guido van Rossumdc91b992001-08-08 22:26:22 +00004526#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004527static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004528FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004529{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004530 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004531 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004532}
4533
Guido van Rossumdc91b992001-08-08 22:26:22 +00004534#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004535static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004536FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004537{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004538 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004539 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004540}
4541
Guido van Rossumcd118802003-01-06 22:57:47 +00004542/* Boolean helper for SLOT1BINFULL().
4543 right.__class__ is a nontrivial subclass of left.__class__. */
4544static int
4545method_is_overloaded(PyObject *left, PyObject *right, char *name)
4546{
4547 PyObject *a, *b;
4548 int ok;
4549
Christian Heimese93237d2007-12-19 02:37:44 +00004550 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004551 if (b == NULL) {
4552 PyErr_Clear();
4553 /* If right doesn't have it, it's not overloaded */
4554 return 0;
4555 }
4556
Christian Heimese93237d2007-12-19 02:37:44 +00004557 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004558 if (a == NULL) {
4559 PyErr_Clear();
4560 Py_DECREF(b);
4561 /* If right has it but left doesn't, it's overloaded */
4562 return 1;
4563 }
4564
4565 ok = PyObject_RichCompareBool(a, b, Py_NE);
4566 Py_DECREF(a);
4567 Py_DECREF(b);
4568 if (ok < 0) {
4569 PyErr_Clear();
4570 return 0;
4571 }
4572
4573 return ok;
4574}
4575
Guido van Rossumdc91b992001-08-08 22:26:22 +00004576
4577#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004578static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004579FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004580{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004581 static PyObject *cache_str, *rcache_str; \
Christian Heimese93237d2007-12-19 02:37:44 +00004582 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4583 Py_TYPE(other)->tp_as_number != NULL && \
4584 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4585 if (Py_TYPE(self)->tp_as_number != NULL && \
4586 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004587 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004588 if (do_other && \
Christian Heimese93237d2007-12-19 02:37:44 +00004589 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004590 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004591 r = call_maybe( \
4592 other, ROPSTR, &rcache_str, "(O)", self); \
4593 if (r != Py_NotImplemented) \
4594 return r; \
4595 Py_DECREF(r); \
4596 do_other = 0; \
4597 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004598 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004599 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004600 if (r != Py_NotImplemented || \
Christian Heimese93237d2007-12-19 02:37:44 +00004601 Py_TYPE(other) == Py_TYPE(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004602 return r; \
4603 Py_DECREF(r); \
4604 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004605 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004606 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004607 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004608 } \
4609 Py_INCREF(Py_NotImplemented); \
4610 return Py_NotImplemented; \
4611}
4612
4613#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4614 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4615
4616#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4617static PyObject * \
4618FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4619{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004620 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004621 return call_method(self, OPSTR, &cache_str, \
4622 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004623}
4624
Martin v. Löwis18e16552006-02-15 17:27:45 +00004625static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004626slot_sq_length(PyObject *self)
4627{
Guido van Rossum2730b132001-08-28 18:22:14 +00004628 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004629 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004630 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004631
4632 if (res == NULL)
4633 return -1;
Neal Norwitz1872b1c2006-08-12 18:44:06 +00004634 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004635 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004636 if (len < 0) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00004637 if (!PyErr_Occurred())
4638 PyErr_SetString(PyExc_ValueError,
4639 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004640 return -1;
4641 }
Guido van Rossum26111622001-10-01 16:42:49 +00004642 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004643}
4644
Guido van Rossumf4593e02001-10-03 12:09:30 +00004645/* Super-optimized version of slot_sq_item.
4646 Other slots could do the same... */
4647static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004648slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004649{
4650 static PyObject *getitem_str;
4651 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4652 descrgetfunc f;
4653
4654 if (getitem_str == NULL) {
4655 getitem_str = PyString_InternFromString("__getitem__");
4656 if (getitem_str == NULL)
4657 return NULL;
4658 }
Christian Heimese93237d2007-12-19 02:37:44 +00004659 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004660 if (func != NULL) {
Christian Heimese93237d2007-12-19 02:37:44 +00004661 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004662 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004663 else {
Christian Heimese93237d2007-12-19 02:37:44 +00004664 func = f(func, self, (PyObject *)(Py_TYPE(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004665 if (func == NULL) {
4666 return NULL;
4667 }
4668 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004669 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004670 if (ival != NULL) {
4671 args = PyTuple_New(1);
4672 if (args != NULL) {
4673 PyTuple_SET_ITEM(args, 0, ival);
4674 retval = PyObject_Call(func, args, NULL);
4675 Py_XDECREF(args);
4676 Py_XDECREF(func);
4677 return retval;
4678 }
4679 }
4680 }
4681 else {
4682 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4683 }
4684 Py_XDECREF(args);
4685 Py_XDECREF(ival);
4686 Py_XDECREF(func);
4687 return NULL;
4688}
4689
Martin v. Löwis18e16552006-02-15 17:27:45 +00004690SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004691
4692static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004693slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004694{
4695 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004696 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004697
4698 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004699 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004700 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004701 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004702 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004703 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004704 if (res == NULL)
4705 return -1;
4706 Py_DECREF(res);
4707 return 0;
4708}
4709
4710static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004711slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004712{
4713 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004714 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004715
4716 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004717 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004718 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004719 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004720 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004721 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004722 if (res == NULL)
4723 return -1;
4724 Py_DECREF(res);
4725 return 0;
4726}
4727
4728static int
4729slot_sq_contains(PyObject *self, PyObject *value)
4730{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004731 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004732 int result = -1;
4733
Guido van Rossum60718732001-08-28 17:47:51 +00004734 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004735
Guido van Rossum55f20992001-10-01 17:18:22 +00004736 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004737 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004738 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004739 if (args == NULL)
4740 res = NULL;
4741 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004742 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004743 Py_DECREF(args);
4744 }
4745 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004746 if (res != NULL) {
4747 result = PyObject_IsTrue(res);
4748 Py_DECREF(res);
4749 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004750 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004751 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004752 /* Possible results: -1 and 1 */
4753 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004754 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004755 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004756 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004757}
4758
Tim Peters6d6c1a32001-08-02 04:15:00 +00004759#define slot_mp_length slot_sq_length
4760
Guido van Rossumdc91b992001-08-08 22:26:22 +00004761SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004762
4763static int
4764slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4765{
4766 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004767 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004768
4769 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004770 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004771 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004772 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004773 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004774 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004775 if (res == NULL)
4776 return -1;
4777 Py_DECREF(res);
4778 return 0;
4779}
4780
Guido van Rossumdc91b992001-08-08 22:26:22 +00004781SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4782SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4783SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4784SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4785SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4786SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4787
Jeremy Hylton938ace62002-07-17 16:30:39 +00004788static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004789
4790SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4791 nb_power, "__pow__", "__rpow__")
4792
4793static PyObject *
4794slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4795{
Guido van Rossum2730b132001-08-28 18:22:14 +00004796 static PyObject *pow_str;
4797
Guido van Rossumdc91b992001-08-08 22:26:22 +00004798 if (modulus == Py_None)
4799 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004800 /* Three-arg power doesn't use __rpow__. But ternary_op
4801 can call this when the second argument's type uses
4802 slot_nb_power, so check before calling self.__pow__. */
Christian Heimese93237d2007-12-19 02:37:44 +00004803 if (Py_TYPE(self)->tp_as_number != NULL &&
4804 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00004805 return call_method(self, "__pow__", &pow_str,
4806 "(OO)", other, modulus);
4807 }
4808 Py_INCREF(Py_NotImplemented);
4809 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004810}
4811
4812SLOT0(slot_nb_negative, "__neg__")
4813SLOT0(slot_nb_positive, "__pos__")
4814SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004815
4816static int
4817slot_nb_nonzero(PyObject *self)
4818{
Tim Petersea7f75d2002-12-07 21:39:16 +00004819 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004820 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004821 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004822
Guido van Rossum55f20992001-10-01 17:18:22 +00004823 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004824 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004825 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004826 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004827 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004828 if (func == NULL)
4829 return PyErr_Occurred() ? -1 : 1;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004830 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004831 args = PyTuple_New(0);
4832 if (args != NULL) {
4833 PyObject *temp = PyObject_Call(func, args, NULL);
4834 Py_DECREF(args);
4835 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004836 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004837 result = PyObject_IsTrue(temp);
4838 else {
4839 PyErr_Format(PyExc_TypeError,
4840 "__nonzero__ should return "
4841 "bool or int, returned %s",
4842 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004843 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004844 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004845 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004846 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004847 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004848 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004849 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004850}
4851
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004852
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004853static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004854slot_nb_index(PyObject *self)
4855{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004856 static PyObject *index_str;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004857 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004858}
4859
4860
Guido van Rossumdc91b992001-08-08 22:26:22 +00004861SLOT0(slot_nb_invert, "__invert__")
4862SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4863SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4864SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4865SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4866SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004867
4868static int
4869slot_nb_coerce(PyObject **a, PyObject **b)
4870{
4871 static PyObject *coerce_str;
4872 PyObject *self = *a, *other = *b;
4873
4874 if (self->ob_type->tp_as_number != NULL &&
4875 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4876 PyObject *r;
4877 r = call_maybe(
4878 self, "__coerce__", &coerce_str, "(O)", other);
4879 if (r == NULL)
4880 return -1;
4881 if (r == Py_NotImplemented) {
4882 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004883 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004884 else {
4885 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4886 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004887 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004888 Py_DECREF(r);
4889 return -1;
4890 }
4891 *a = PyTuple_GET_ITEM(r, 0);
4892 Py_INCREF(*a);
4893 *b = PyTuple_GET_ITEM(r, 1);
4894 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004895 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004896 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004897 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004898 }
4899 if (other->ob_type->tp_as_number != NULL &&
4900 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4901 PyObject *r;
4902 r = call_maybe(
4903 other, "__coerce__", &coerce_str, "(O)", self);
4904 if (r == NULL)
4905 return -1;
4906 if (r == Py_NotImplemented) {
4907 Py_DECREF(r);
4908 return 1;
4909 }
4910 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4911 PyErr_SetString(PyExc_TypeError,
4912 "__coerce__ didn't return a 2-tuple");
4913 Py_DECREF(r);
4914 return -1;
4915 }
4916 *a = PyTuple_GET_ITEM(r, 1);
4917 Py_INCREF(*a);
4918 *b = PyTuple_GET_ITEM(r, 0);
4919 Py_INCREF(*b);
4920 Py_DECREF(r);
4921 return 0;
4922 }
4923 return 1;
4924}
4925
Guido van Rossumdc91b992001-08-08 22:26:22 +00004926SLOT0(slot_nb_int, "__int__")
4927SLOT0(slot_nb_long, "__long__")
4928SLOT0(slot_nb_float, "__float__")
4929SLOT0(slot_nb_oct, "__oct__")
4930SLOT0(slot_nb_hex, "__hex__")
4931SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4932SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4933SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4934SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4935SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Martin v. Löwisfd963262007-02-09 12:19:32 +00004936/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4937static PyObject *
4938slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4939{
4940 static PyObject *cache_str;
4941 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4942}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004943SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4944SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4945SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4946SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4947SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4948SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4949 "__floordiv__", "__rfloordiv__")
4950SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4951SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4952SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004953
4954static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004955half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004956{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004957 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004958 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004959 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004960
Guido van Rossum60718732001-08-28 17:47:51 +00004961 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004962 if (func == NULL) {
4963 PyErr_Clear();
4964 }
4965 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004966 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004967 if (args == NULL)
4968 res = NULL;
4969 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004970 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004971 Py_DECREF(args);
4972 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004973 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004974 if (res != Py_NotImplemented) {
4975 if (res == NULL)
4976 return -2;
4977 c = PyInt_AsLong(res);
4978 Py_DECREF(res);
4979 if (c == -1 && PyErr_Occurred())
4980 return -2;
4981 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4982 }
4983 Py_DECREF(res);
4984 }
4985 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004986}
4987
Guido van Rossumab3b0342001-09-18 20:38:53 +00004988/* This slot is published for the benefit of try_3way_compare in object.c */
4989int
4990_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004991{
4992 int c;
4993
Christian Heimese93237d2007-12-19 02:37:44 +00004994 if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004995 c = half_compare(self, other);
4996 if (c <= 1)
4997 return c;
4998 }
Christian Heimese93237d2007-12-19 02:37:44 +00004999 if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005000 c = half_compare(other, self);
5001 if (c < -1)
5002 return -2;
5003 if (c <= 1)
5004 return -c;
5005 }
5006 return (void *)self < (void *)other ? -1 :
5007 (void *)self > (void *)other ? 1 : 0;
5008}
5009
5010static PyObject *
5011slot_tp_repr(PyObject *self)
5012{
5013 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005014 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005015
Guido van Rossum60718732001-08-28 17:47:51 +00005016 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005017 if (func != NULL) {
5018 res = PyEval_CallObject(func, NULL);
5019 Py_DECREF(func);
5020 return res;
5021 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00005022 PyErr_Clear();
5023 return PyString_FromFormat("<%s object at %p>",
Christian Heimese93237d2007-12-19 02:37:44 +00005024 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005025}
5026
5027static PyObject *
5028slot_tp_str(PyObject *self)
5029{
5030 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005031 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005032
Guido van Rossum60718732001-08-28 17:47:51 +00005033 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005034 if (func != NULL) {
5035 res = PyEval_CallObject(func, NULL);
5036 Py_DECREF(func);
5037 return res;
5038 }
5039 else {
5040 PyErr_Clear();
5041 return slot_tp_repr(self);
5042 }
5043}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005044
5045static long
5046slot_tp_hash(PyObject *self)
5047{
Tim Peters61ce0a92002-12-06 23:38:02 +00005048 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00005049 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005050 long h;
5051
Guido van Rossum60718732001-08-28 17:47:51 +00005052 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005053
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005054 if (func != NULL && func != Py_None) {
Tim Peters61ce0a92002-12-06 23:38:02 +00005055 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005056 Py_DECREF(func);
5057 if (res == NULL)
5058 return -1;
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00005059 if (PyLong_Check(res))
Armin Rigo51fc8c42006-08-09 14:55:26 +00005060 h = PyLong_Type.tp_hash(res);
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00005061 else
5062 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00005063 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005064 }
5065 else {
Georg Brandl30b78042007-12-20 21:03:02 +00005066 Py_XDECREF(func); /* may be None */
Guido van Rossumb8f63662001-08-15 23:57:02 +00005067 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005068 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005069 if (func == NULL) {
5070 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005071 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005072 }
5073 if (func != NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00005074 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
5075 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005076 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005077 return -1;
5078 }
5079 PyErr_Clear();
5080 h = _Py_HashPointer((void *)self);
5081 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005082 if (h == -1 && !PyErr_Occurred())
5083 h = -2;
5084 return h;
5085}
5086
5087static PyObject *
5088slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5089{
Guido van Rossum60718732001-08-28 17:47:51 +00005090 static PyObject *call_str;
5091 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005092 PyObject *res;
5093
5094 if (meth == NULL)
5095 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00005096
Tim Peters6d6c1a32001-08-02 04:15:00 +00005097 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00005098
Tim Peters6d6c1a32001-08-02 04:15:00 +00005099 Py_DECREF(meth);
5100 return res;
5101}
5102
Guido van Rossum14a6f832001-10-17 13:59:09 +00005103/* There are two slot dispatch functions for tp_getattro.
5104
5105 - slot_tp_getattro() is used when __getattribute__ is overridden
5106 but no __getattr__ hook is present;
5107
5108 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5109
Guido van Rossumc334df52002-04-04 23:44:47 +00005110 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5111 detects the absence of __getattr__ and then installs the simpler slot if
5112 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005113
Tim Peters6d6c1a32001-08-02 04:15:00 +00005114static PyObject *
5115slot_tp_getattro(PyObject *self, PyObject *name)
5116{
Guido van Rossum14a6f832001-10-17 13:59:09 +00005117 static PyObject *getattribute_str = NULL;
5118 return call_method(self, "__getattribute__", &getattribute_str,
5119 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005120}
5121
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005122static PyObject *
5123slot_tp_getattr_hook(PyObject *self, PyObject *name)
5124{
Christian Heimese93237d2007-12-19 02:37:44 +00005125 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005126 PyObject *getattr, *getattribute, *res;
5127 static PyObject *getattribute_str = NULL;
5128 static PyObject *getattr_str = NULL;
5129
5130 if (getattr_str == NULL) {
5131 getattr_str = PyString_InternFromString("__getattr__");
5132 if (getattr_str == NULL)
5133 return NULL;
5134 }
5135 if (getattribute_str == NULL) {
5136 getattribute_str =
5137 PyString_InternFromString("__getattribute__");
5138 if (getattribute_str == NULL)
5139 return NULL;
5140 }
5141 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005142 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005143 /* No __getattr__ hook: use a simpler dispatcher */
5144 tp->tp_getattro = slot_tp_getattro;
5145 return slot_tp_getattro(self, name);
5146 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005147 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005148 if (getattribute == NULL ||
Christian Heimese93237d2007-12-19 02:37:44 +00005149 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00005150 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5151 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005152 res = PyObject_GenericGetAttr(self, name);
5153 else
Georg Brandl684fd0c2006-05-25 19:15:31 +00005154 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005155 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005156 PyErr_Clear();
Georg Brandl684fd0c2006-05-25 19:15:31 +00005157 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005158 }
5159 return res;
5160}
5161
Tim Peters6d6c1a32001-08-02 04:15:00 +00005162static int
5163slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5164{
5165 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005166 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005167
5168 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00005169 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005170 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005171 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005172 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005173 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005174 if (res == NULL)
5175 return -1;
5176 Py_DECREF(res);
5177 return 0;
5178}
5179
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005180static char *name_op[] = {
5181 "__lt__",
5182 "__le__",
5183 "__eq__",
5184 "__ne__",
5185 "__gt__",
5186 "__ge__",
5187};
5188
Tim Peters6d6c1a32001-08-02 04:15:00 +00005189static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005190half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005191{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005192 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005193 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005194
Guido van Rossum60718732001-08-28 17:47:51 +00005195 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005196 if (func == NULL) {
5197 PyErr_Clear();
5198 Py_INCREF(Py_NotImplemented);
5199 return Py_NotImplemented;
5200 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005201 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005202 if (args == NULL)
5203 res = NULL;
5204 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005205 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005206 Py_DECREF(args);
5207 }
5208 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005209 return res;
5210}
5211
Guido van Rossumb8f63662001-08-15 23:57:02 +00005212static PyObject *
5213slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5214{
5215 PyObject *res;
5216
Christian Heimese93237d2007-12-19 02:37:44 +00005217 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005218 res = half_richcompare(self, other, op);
5219 if (res != Py_NotImplemented)
5220 return res;
5221 Py_DECREF(res);
5222 }
Christian Heimese93237d2007-12-19 02:37:44 +00005223 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00005224 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005225 if (res != Py_NotImplemented) {
5226 return res;
5227 }
5228 Py_DECREF(res);
5229 }
5230 Py_INCREF(Py_NotImplemented);
5231 return Py_NotImplemented;
5232}
5233
5234static PyObject *
5235slot_tp_iter(PyObject *self)
5236{
5237 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005238 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005239
Guido van Rossum60718732001-08-28 17:47:51 +00005240 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005241 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00005242 PyObject *args;
5243 args = res = PyTuple_New(0);
5244 if (args != NULL) {
5245 res = PyObject_Call(func, args, NULL);
5246 Py_DECREF(args);
5247 }
5248 Py_DECREF(func);
5249 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005250 }
5251 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005252 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005253 if (func == NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00005254 PyErr_Format(PyExc_TypeError,
5255 "'%.200s' object is not iterable",
Christian Heimese93237d2007-12-19 02:37:44 +00005256 Py_TYPE(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005257 return NULL;
5258 }
5259 Py_DECREF(func);
5260 return PySeqIter_New(self);
5261}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005262
5263static PyObject *
5264slot_tp_iternext(PyObject *self)
5265{
Guido van Rossum2730b132001-08-28 18:22:14 +00005266 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00005267 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005268}
5269
Guido van Rossum1a493502001-08-17 16:47:50 +00005270static PyObject *
5271slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5272{
Christian Heimese93237d2007-12-19 02:37:44 +00005273 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00005274 PyObject *get;
5275 static PyObject *get_str = NULL;
5276
5277 if (get_str == NULL) {
5278 get_str = PyString_InternFromString("__get__");
5279 if (get_str == NULL)
5280 return NULL;
5281 }
5282 get = _PyType_Lookup(tp, get_str);
5283 if (get == NULL) {
5284 /* Avoid further slowdowns */
5285 if (tp->tp_descr_get == slot_tp_descr_get)
5286 tp->tp_descr_get = NULL;
5287 Py_INCREF(self);
5288 return self;
5289 }
Guido van Rossum2c252392001-08-24 10:13:31 +00005290 if (obj == NULL)
5291 obj = Py_None;
5292 if (type == NULL)
5293 type = Py_None;
Georg Brandl684fd0c2006-05-25 19:15:31 +00005294 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005295}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005296
5297static int
5298slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5299{
Guido van Rossum2c252392001-08-24 10:13:31 +00005300 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005301 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005302
5303 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00005304 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005305 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00005306 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005307 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005308 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005309 if (res == NULL)
5310 return -1;
5311 Py_DECREF(res);
5312 return 0;
5313}
5314
5315static int
5316slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5317{
Guido van Rossum60718732001-08-28 17:47:51 +00005318 static PyObject *init_str;
5319 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005320 PyObject *res;
5321
5322 if (meth == NULL)
5323 return -1;
5324 res = PyObject_Call(meth, args, kwds);
5325 Py_DECREF(meth);
5326 if (res == NULL)
5327 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005328 if (res != Py_None) {
Georg Brandlccff7852006-06-18 22:17:29 +00005329 PyErr_Format(PyExc_TypeError,
5330 "__init__() should return None, not '%.200s'",
Christian Heimese93237d2007-12-19 02:37:44 +00005331 Py_TYPE(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005332 Py_DECREF(res);
5333 return -1;
5334 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005335 Py_DECREF(res);
5336 return 0;
5337}
5338
5339static PyObject *
5340slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5341{
Guido van Rossum7bed2132002-08-08 21:57:53 +00005342 static PyObject *new_str;
5343 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005344 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005345 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005346
Guido van Rossum7bed2132002-08-08 21:57:53 +00005347 if (new_str == NULL) {
5348 new_str = PyString_InternFromString("__new__");
5349 if (new_str == NULL)
5350 return NULL;
5351 }
5352 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005353 if (func == NULL)
5354 return NULL;
5355 assert(PyTuple_Check(args));
5356 n = PyTuple_GET_SIZE(args);
5357 newargs = PyTuple_New(n+1);
5358 if (newargs == NULL)
5359 return NULL;
5360 Py_INCREF(type);
5361 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5362 for (i = 0; i < n; i++) {
5363 x = PyTuple_GET_ITEM(args, i);
5364 Py_INCREF(x);
5365 PyTuple_SET_ITEM(newargs, i+1, x);
5366 }
5367 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005368 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005369 Py_DECREF(func);
5370 return x;
5371}
5372
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005373static void
5374slot_tp_del(PyObject *self)
5375{
5376 static PyObject *del_str = NULL;
5377 PyObject *del, *res;
5378 PyObject *error_type, *error_value, *error_traceback;
5379
5380 /* Temporarily resurrect the object. */
5381 assert(self->ob_refcnt == 0);
5382 self->ob_refcnt = 1;
5383
5384 /* Save the current exception, if any. */
5385 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5386
5387 /* Execute __del__ method, if any. */
5388 del = lookup_maybe(self, "__del__", &del_str);
5389 if (del != NULL) {
5390 res = PyEval_CallObject(del, NULL);
5391 if (res == NULL)
5392 PyErr_WriteUnraisable(del);
5393 else
5394 Py_DECREF(res);
5395 Py_DECREF(del);
5396 }
5397
5398 /* Restore the saved exception. */
5399 PyErr_Restore(error_type, error_value, error_traceback);
5400
5401 /* Undo the temporary resurrection; can't use DECREF here, it would
5402 * cause a recursive call.
5403 */
5404 assert(self->ob_refcnt > 0);
5405 if (--self->ob_refcnt == 0)
5406 return; /* this is the normal path out */
5407
5408 /* __del__ resurrected it! Make it look like the original Py_DECREF
5409 * never happened.
5410 */
5411 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005412 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005413 _Py_NewReference(self);
5414 self->ob_refcnt = refcnt;
5415 }
Christian Heimese93237d2007-12-19 02:37:44 +00005416 assert(!PyType_IS_GC(Py_TYPE(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005417 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005418 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5419 * we need to undo that. */
5420 _Py_DEC_REFTOTAL;
5421 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5422 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005423 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5424 * _Py_NewReference bumped tp_allocs: both of those need to be
5425 * undone.
5426 */
5427#ifdef COUNT_ALLOCS
Christian Heimese93237d2007-12-19 02:37:44 +00005428 --Py_TYPE(self)->tp_frees;
5429 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005430#endif
5431}
5432
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005433
5434/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005435 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005436 structure, which incorporates the additional structures used for numbers,
5437 sequences and mappings.
5438 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005439 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005440 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5441 terminated with an all-zero entry. (This table is further initialized and
5442 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005443
Guido van Rossum6d204072001-10-21 00:44:31 +00005444typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005445
5446#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005447#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005448#undef ETSLOT
5449#undef SQSLOT
5450#undef MPSLOT
5451#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005452#undef UNSLOT
5453#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005454#undef BINSLOT
5455#undef RBINSLOT
5456
Guido van Rossum6d204072001-10-21 00:44:31 +00005457#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005458 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5459 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005460#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5461 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005462 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005463#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005464 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005465 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005466#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5467 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5468#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5469 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5470#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5471 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5472#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5473 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5474 "x." NAME "() <==> " DOC)
5475#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5476 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5477 "x." NAME "(y) <==> x" DOC "y")
5478#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5479 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5480 "x." NAME "(y) <==> x" DOC "y")
5481#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5482 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5483 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005484#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5485 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5486 "x." NAME "(y) <==> " DOC)
5487#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5488 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5489 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005490
5491static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005492 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005493 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005494 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5495 The logic in abstract.c always falls back to nb_add/nb_multiply in
5496 this case. Defining both the nb_* and the sq_* slots to call the
5497 user-defined methods has unexpected side-effects, as shown by
5498 test_descr.notimplemented() */
5499 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005500 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00005501 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005502 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005503 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005504 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005505 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5506 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005507 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005508 "x.__getslice__(i, j) <==> x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005509 \n\
5510 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005511 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005512 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005513 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005514 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005515 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005516 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005517 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005518 \n\
5519 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005520 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005521 "x.__delslice__(i, j) <==> del x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005522 \n\
5523 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005524 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5525 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005526 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005527 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005528 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005529 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005530
Martin v. Löwis18e16552006-02-15 17:27:45 +00005531 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005532 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005533 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005534 wrap_binaryfunc,
5535 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005536 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005537 wrap_objobjargproc,
5538 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005539 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005540 wrap_delitem,
5541 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005542
Guido van Rossum6d204072001-10-21 00:44:31 +00005543 BINSLOT("__add__", nb_add, slot_nb_add,
5544 "+"),
5545 RBINSLOT("__radd__", nb_add, slot_nb_add,
5546 "+"),
5547 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5548 "-"),
5549 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5550 "-"),
5551 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5552 "*"),
5553 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5554 "*"),
5555 BINSLOT("__div__", nb_divide, slot_nb_divide,
5556 "/"),
5557 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5558 "/"),
5559 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5560 "%"),
5561 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5562 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005563 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005564 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005565 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005566 "divmod(y, x)"),
5567 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5568 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5569 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5570 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5571 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5572 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5573 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5574 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005575 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005576 "x != 0"),
5577 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5578 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5579 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5580 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5581 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5582 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5583 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5584 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5585 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5586 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5587 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5588 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5589 "x.__coerce__(y) <==> coerce(x, y)"),
5590 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5591 "int(x)"),
5592 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5593 "long(x)"),
5594 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5595 "float(x)"),
5596 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5597 "oct(x)"),
5598 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5599 "hex(x)"),
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005600 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005601 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005602 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5603 wrap_binaryfunc, "+"),
5604 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5605 wrap_binaryfunc, "-"),
5606 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5607 wrap_binaryfunc, "*"),
5608 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5609 wrap_binaryfunc, "/"),
5610 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5611 wrap_binaryfunc, "%"),
5612 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005613 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005614 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5615 wrap_binaryfunc, "<<"),
5616 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5617 wrap_binaryfunc, ">>"),
5618 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5619 wrap_binaryfunc, "&"),
5620 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5621 wrap_binaryfunc, "^"),
5622 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5623 wrap_binaryfunc, "|"),
5624 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5625 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5626 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5627 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5628 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5629 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5630 IBSLOT("__itruediv__", nb_inplace_true_divide,
5631 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005632
Guido van Rossum6d204072001-10-21 00:44:31 +00005633 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5634 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005635 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005636 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5637 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005638 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005639 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5640 "x.__cmp__(y) <==> cmp(x,y)"),
5641 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5642 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005643 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5644 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005645 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005646 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5647 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5648 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5649 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5650 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5651 "x.__setattr__('name', value) <==> x.name = value"),
5652 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5653 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5654 "x.__delattr__('name') <==> del x.name"),
5655 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5656 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5657 "x.__lt__(y) <==> x<y"),
5658 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5659 "x.__le__(y) <==> x<=y"),
5660 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5661 "x.__eq__(y) <==> x==y"),
5662 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5663 "x.__ne__(y) <==> x!=y"),
5664 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5665 "x.__gt__(y) <==> x>y"),
5666 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5667 "x.__ge__(y) <==> x>=y"),
5668 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5669 "x.__iter__() <==> iter(x)"),
5670 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5671 "x.next() -> the next value, or raise StopIteration"),
5672 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5673 "descr.__get__(obj[, type]) -> value"),
5674 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5675 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005676 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5677 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005678 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005679 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005680 "see x.__class__.__doc__ for signature",
5681 PyWrapperFlag_KEYWORDS),
5682 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005683 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005684 {NULL}
5685};
5686
Guido van Rossumc334df52002-04-04 23:44:47 +00005687/* Given a type pointer and an offset gotten from a slotdef entry, return a
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005688 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005689 the offset to the type pointer, since it takes care to indirect through the
5690 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5691 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005692static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005693slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005694{
5695 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005696 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005697
Guido van Rossume5c691a2003-03-07 15:13:17 +00005698 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005699 assert(offset >= 0);
Skip Montanaro429433b2006-04-18 00:35:43 +00005700 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5701 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005702 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005703 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005704 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005705 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005706 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005707 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005708 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005709 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005710 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005711 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005712 }
5713 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005714 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005715 }
5716 if (ptr != NULL)
5717 ptr += offset;
5718 return (void **)ptr;
5719}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005720
Guido van Rossumc334df52002-04-04 23:44:47 +00005721/* Length of array of slotdef pointers used to store slots with the
5722 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5723 the same __name__, for any __name__. Since that's a static property, it is
5724 appropriate to declare fixed-size arrays for this. */
5725#define MAX_EQUIV 10
5726
5727/* Return a slot pointer for a given name, but ONLY if the attribute has
5728 exactly one slot function. The name must be an interned string. */
5729static void **
5730resolve_slotdups(PyTypeObject *type, PyObject *name)
5731{
5732 /* XXX Maybe this could be optimized more -- but is it worth it? */
5733
5734 /* pname and ptrs act as a little cache */
5735 static PyObject *pname;
5736 static slotdef *ptrs[MAX_EQUIV];
5737 slotdef *p, **pp;
5738 void **res, **ptr;
5739
5740 if (pname != name) {
5741 /* Collect all slotdefs that match name into ptrs. */
5742 pname = name;
5743 pp = ptrs;
5744 for (p = slotdefs; p->name_strobj; p++) {
5745 if (p->name_strobj == name)
5746 *pp++ = p;
5747 }
5748 *pp = NULL;
5749 }
5750
5751 /* Look in all matching slots of the type; if exactly one of these has
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005752 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005753 res = NULL;
5754 for (pp = ptrs; *pp; pp++) {
5755 ptr = slotptr(type, (*pp)->offset);
5756 if (ptr == NULL || *ptr == NULL)
5757 continue;
5758 if (res != NULL)
5759 return NULL;
5760 res = ptr;
5761 }
5762 return res;
5763}
5764
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005765/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005766 does some incredibly complex thinking and then sticks something into the
5767 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5768 interests, and then stores a generic wrapper or a specific function into
5769 the slot.) Return a pointer to the next slotdef with a different offset,
5770 because that's convenient for fixup_slot_dispatchers(). */
5771static slotdef *
5772update_one_slot(PyTypeObject *type, slotdef *p)
5773{
5774 PyObject *descr;
5775 PyWrapperDescrObject *d;
5776 void *generic = NULL, *specific = NULL;
5777 int use_generic = 0;
5778 int offset = p->offset;
5779 void **ptr = slotptr(type, offset);
5780
5781 if (ptr == NULL) {
5782 do {
5783 ++p;
5784 } while (p->offset == offset);
5785 return p;
5786 }
5787 do {
5788 descr = _PyType_Lookup(type, p->name_strobj);
5789 if (descr == NULL)
5790 continue;
Christian Heimese93237d2007-12-19 02:37:44 +00005791 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00005792 void **tptr = resolve_slotdups(type, p->name_strobj);
5793 if (tptr == NULL || tptr == ptr)
5794 generic = p->function;
5795 d = (PyWrapperDescrObject *)descr;
5796 if (d->d_base->wrapper == p->wrapper &&
5797 PyType_IsSubtype(type, d->d_type))
5798 {
5799 if (specific == NULL ||
5800 specific == d->d_wrapped)
5801 specific = d->d_wrapped;
5802 else
5803 use_generic = 1;
5804 }
5805 }
Christian Heimese93237d2007-12-19 02:37:44 +00005806 else if (Py_TYPE(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00005807 PyCFunction_GET_FUNCTION(descr) ==
5808 (PyCFunction)tp_new_wrapper &&
5809 strcmp(p->name, "__new__") == 0)
5810 {
5811 /* The __new__ wrapper is not a wrapper descriptor,
5812 so must be special-cased differently.
5813 If we don't do this, creating an instance will
5814 always use slot_tp_new which will look up
5815 __new__ in the MRO which will call tp_new_wrapper
5816 which will look through the base classes looking
5817 for a static base and call its tp_new (usually
5818 PyType_GenericNew), after performing various
5819 sanity checks and constructing a new argument
5820 list. Cut all that nonsense short -- this speeds
5821 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005822 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005823 /* XXX I'm not 100% sure that there isn't a hole
5824 in this reasoning that requires additional
5825 sanity checks. I'll buy the first person to
5826 point out a bug in this reasoning a beer. */
5827 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005828 else {
5829 use_generic = 1;
5830 generic = p->function;
5831 }
5832 } while ((++p)->offset == offset);
5833 if (specific && !use_generic)
5834 *ptr = specific;
5835 else
5836 *ptr = generic;
5837 return p;
5838}
5839
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005840/* In the type, update the slots whose slotdefs are gathered in the pp array.
5841 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005842static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005843update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005844{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005845 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005846
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005847 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005848 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005849 return 0;
5850}
5851
Guido van Rossumc334df52002-04-04 23:44:47 +00005852/* Comparison function for qsort() to compare slotdefs by their offset, and
5853 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005854static int
5855slotdef_cmp(const void *aa, const void *bb)
5856{
5857 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5858 int c = a->offset - b->offset;
5859 if (c != 0)
5860 return c;
5861 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005862 /* Cannot use a-b, as this gives off_t,
5863 which may lose precision when converted to int. */
5864 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005865}
5866
Guido van Rossumc334df52002-04-04 23:44:47 +00005867/* Initialize the slotdefs table by adding interned string objects for the
5868 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005869static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005870init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005871{
5872 slotdef *p;
5873 static int initialized = 0;
5874
5875 if (initialized)
5876 return;
5877 for (p = slotdefs; p->name; p++) {
5878 p->name_strobj = PyString_InternFromString(p->name);
5879 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005880 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005881 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005882 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5883 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005884 initialized = 1;
5885}
5886
Guido van Rossumc334df52002-04-04 23:44:47 +00005887/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005888static int
5889update_slot(PyTypeObject *type, PyObject *name)
5890{
Guido van Rossumc334df52002-04-04 23:44:47 +00005891 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005892 slotdef *p;
5893 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005894 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005895
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00005896 /* Clear the VALID_VERSION flag of 'type' and all its
5897 subclasses. This could possibly be unified with the
5898 update_subclasses() recursion below, but carefully:
5899 they each have their own conditions on which to stop
5900 recursing into subclasses. */
5901 type_modified(type);
5902
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005903 init_slotdefs();
5904 pp = ptrs;
5905 for (p = slotdefs; p->name; p++) {
5906 /* XXX assume name is interned! */
5907 if (p->name_strobj == name)
5908 *pp++ = p;
5909 }
5910 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005911 for (pp = ptrs; *pp; pp++) {
5912 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005913 offset = p->offset;
5914 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005915 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005916 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005917 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005918 if (ptrs[0] == NULL)
5919 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005920 return update_subclasses(type, name,
5921 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005922}
5923
Guido van Rossumc334df52002-04-04 23:44:47 +00005924/* Store the proper functions in the slot dispatches at class (type)
5925 definition time, based upon which operations the class overrides in its
5926 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005927static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005928fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005929{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005930 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005931
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005932 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005933 for (p = slotdefs; p->name; )
5934 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005935}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005936
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005937static void
5938update_all_slots(PyTypeObject* type)
5939{
5940 slotdef *p;
5941
5942 init_slotdefs();
5943 for (p = slotdefs; p->name; p++) {
5944 /* update_slot returns int but can't actually fail */
5945 update_slot(type, p->name_strobj);
5946 }
5947}
5948
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005949/* recurse_down_subclasses() and update_subclasses() are mutually
5950 recursive functions to call a callback for all subclasses,
5951 but refraining from recursing into subclasses that define 'name'. */
5952
5953static int
5954update_subclasses(PyTypeObject *type, PyObject *name,
5955 update_callback callback, void *data)
5956{
5957 if (callback(type, data) < 0)
5958 return -1;
5959 return recurse_down_subclasses(type, name, callback, data);
5960}
5961
5962static int
5963recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5964 update_callback callback, void *data)
5965{
5966 PyTypeObject *subclass;
5967 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005968 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005969
5970 subclasses = type->tp_subclasses;
5971 if (subclasses == NULL)
5972 return 0;
5973 assert(PyList_Check(subclasses));
5974 n = PyList_GET_SIZE(subclasses);
5975 for (i = 0; i < n; i++) {
5976 ref = PyList_GET_ITEM(subclasses, i);
5977 assert(PyWeakref_CheckRef(ref));
5978 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5979 assert(subclass != NULL);
5980 if ((PyObject *)subclass == Py_None)
5981 continue;
5982 assert(PyType_Check(subclass));
5983 /* Avoid recursing down into unaffected classes */
5984 dict = subclass->tp_dict;
5985 if (dict != NULL && PyDict_Check(dict) &&
5986 PyDict_GetItem(dict, name) != NULL)
5987 continue;
5988 if (update_subclasses(subclass, name, callback, data) < 0)
5989 return -1;
5990 }
5991 return 0;
5992}
5993
Guido van Rossum6d204072001-10-21 00:44:31 +00005994/* This function is called by PyType_Ready() to populate the type's
5995 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005996 function slot (like tp_repr) that's defined in the type, one or more
5997 corresponding descriptors are added in the type's tp_dict dictionary
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005998 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005999 cause more than one descriptor to be added (for example, the nb_add
6000 slot adds both __add__ and __radd__ descriptors) and some function
6001 slots compete for the same descriptor (for example both sq_item and
6002 mp_subscript generate a __getitem__ descriptor).
6003
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006004 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006005 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006006 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006007 between competing slots: the members of PyHeapTypeObject are listed
6008 from most general to least general, so the most general slot is
6009 preferred. In particular, because as_mapping comes before as_sequence,
6010 for a type that defines both mp_subscript and sq_item, mp_subscript
6011 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006012
6013 This only adds new descriptors and doesn't overwrite entries in
6014 tp_dict that were previously defined. The descriptors contain a
6015 reference to the C function they must call, so that it's safe if they
6016 are copied into a subtype's __dict__ and the subtype has a different
6017 C function in its slot -- calling the method defined by the
6018 descriptor will call the C function that was used to create it,
6019 rather than the C function present in the slot when it is called.
6020 (This is important because a subtype may have a C function in the
6021 slot that calls the method from the dictionary, and we want to avoid
6022 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006023
6024static int
6025add_operators(PyTypeObject *type)
6026{
6027 PyObject *dict = type->tp_dict;
6028 slotdef *p;
6029 PyObject *descr;
6030 void **ptr;
6031
6032 init_slotdefs();
6033 for (p = slotdefs; p->name; p++) {
6034 if (p->wrapper == NULL)
6035 continue;
6036 ptr = slotptr(type, p->offset);
6037 if (!ptr || !*ptr)
6038 continue;
6039 if (PyDict_GetItem(dict, p->name_strobj))
6040 continue;
6041 descr = PyDescr_NewWrapper(type, p, *ptr);
6042 if (descr == NULL)
6043 return -1;
6044 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6045 return -1;
6046 Py_DECREF(descr);
6047 }
6048 if (type->tp_new != NULL) {
6049 if (add_tp_new_wrapper(type) < 0)
6050 return -1;
6051 }
6052 return 0;
6053}
6054
Guido van Rossum705f0f52001-08-24 16:47:00 +00006055
6056/* Cooperative 'super' */
6057
6058typedef struct {
6059 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00006060 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006061 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006062 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006063} superobject;
6064
Guido van Rossum6f799372001-09-20 20:46:19 +00006065static PyMemberDef super_members[] = {
6066 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6067 "the class invoking super()"},
6068 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6069 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006070 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00006071 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006072 {0}
6073};
6074
Guido van Rossum705f0f52001-08-24 16:47:00 +00006075static void
6076super_dealloc(PyObject *self)
6077{
6078 superobject *su = (superobject *)self;
6079
Guido van Rossum048eb752001-10-02 21:24:57 +00006080 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006081 Py_XDECREF(su->obj);
6082 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006083 Py_XDECREF(su->obj_type);
Christian Heimese93237d2007-12-19 02:37:44 +00006084 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006085}
6086
6087static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006088super_repr(PyObject *self)
6089{
6090 superobject *su = (superobject *)self;
6091
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006092 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006093 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00006094 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006095 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006096 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006097 else
6098 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00006099 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006100 su->type ? su->type->tp_name : "NULL");
6101}
6102
6103static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006104super_getattro(PyObject *self, PyObject *name)
6105{
6106 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006107 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006108
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006109 if (!skip) {
6110 /* We want __class__ to return the class of the super object
6111 (i.e. super, or a subclass), not the class of su->obj. */
6112 skip = (PyString_Check(name) &&
6113 PyString_GET_SIZE(name) == 9 &&
6114 strcmp(PyString_AS_STRING(name), "__class__") == 0);
6115 }
6116
6117 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00006118 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006119 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006120 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006121 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006122
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006123 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006124 mro = starttype->tp_mro;
6125
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006126 if (mro == NULL)
6127 n = 0;
6128 else {
6129 assert(PyTuple_Check(mro));
6130 n = PyTuple_GET_SIZE(mro);
6131 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006132 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00006133 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00006134 break;
6135 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006136 i++;
6137 res = NULL;
6138 for (; i < n; i++) {
6139 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00006140 if (PyType_Check(tmp))
6141 dict = ((PyTypeObject *)tmp)->tp_dict;
6142 else if (PyClass_Check(tmp))
6143 dict = ((PyClassObject *)tmp)->cl_dict;
6144 else
6145 continue;
6146 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00006147 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00006148 Py_INCREF(res);
Christian Heimese93237d2007-12-19 02:37:44 +00006149 f = Py_TYPE(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006150 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006151 tmp = f(res,
6152 /* Only pass 'obj' param if
6153 this is instance-mode super
6154 (See SF ID #743627)
6155 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00006156 (su->obj == (PyObject *)
6157 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006158 ? (PyObject *)NULL
6159 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00006160 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006161 Py_DECREF(res);
6162 res = tmp;
6163 }
6164 return res;
6165 }
6166 }
6167 }
6168 return PyObject_GenericGetAttr(self, name);
6169}
6170
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006171static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006172supercheck(PyTypeObject *type, PyObject *obj)
6173{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006174 /* Check that a super() call makes sense. Return a type object.
6175
6176 obj can be a new-style class, or an instance of one:
6177
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006178 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006179 used for class methods; the return value is obj.
6180
6181 - If it is an instance, it must be an instance of 'type'. This is
6182 the normal case; the return value is obj.__class__.
6183
6184 But... when obj is an instance, we want to allow for the case where
Christian Heimese93237d2007-12-19 02:37:44 +00006185 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006186 This will allow using super() with a proxy for obj.
6187 */
6188
Guido van Rossum8e80a722003-02-18 19:22:22 +00006189 /* Check for first bullet above (special case) */
6190 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6191 Py_INCREF(obj);
6192 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006193 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006194
6195 /* Normal case */
Christian Heimese93237d2007-12-19 02:37:44 +00006196 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6197 Py_INCREF(Py_TYPE(obj));
6198 return Py_TYPE(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006199 }
6200 else {
6201 /* Try the slow way */
6202 static PyObject *class_str = NULL;
6203 PyObject *class_attr;
6204
6205 if (class_str == NULL) {
6206 class_str = PyString_FromString("__class__");
6207 if (class_str == NULL)
6208 return NULL;
6209 }
6210
6211 class_attr = PyObject_GetAttr(obj, class_str);
6212
6213 if (class_attr != NULL &&
6214 PyType_Check(class_attr) &&
Christian Heimese93237d2007-12-19 02:37:44 +00006215 (PyTypeObject *)class_attr != Py_TYPE(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006216 {
6217 int ok = PyType_IsSubtype(
6218 (PyTypeObject *)class_attr, type);
6219 if (ok)
6220 return (PyTypeObject *)class_attr;
6221 }
6222
6223 if (class_attr == NULL)
6224 PyErr_Clear();
6225 else
6226 Py_DECREF(class_attr);
6227 }
6228
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006229 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006230 "super(type, obj): "
6231 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006232 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006233}
6234
Guido van Rossum705f0f52001-08-24 16:47:00 +00006235static PyObject *
6236super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6237{
6238 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00006239 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006240
6241 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6242 /* Not binding to an object, or already bound */
6243 Py_INCREF(self);
6244 return self;
6245 }
Christian Heimese93237d2007-12-19 02:37:44 +00006246 if (Py_TYPE(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00006247 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006248 call its type */
Christian Heimese93237d2007-12-19 02:37:44 +00006249 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006250 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00006251 else {
6252 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006253 PyTypeObject *obj_type = supercheck(su->type, obj);
6254 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006255 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00006256 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006257 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00006258 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006259 return NULL;
6260 Py_INCREF(su->type);
6261 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00006262 newobj->type = su->type;
6263 newobj->obj = obj;
6264 newobj->obj_type = obj_type;
6265 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006266 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006267}
6268
6269static int
6270super_init(PyObject *self, PyObject *args, PyObject *kwds)
6271{
6272 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00006273 PyTypeObject *type;
6274 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006275 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006276
Georg Brandl5d59c092006-09-30 08:43:30 +00006277 if (!_PyArg_NoKeywords("super", kwds))
6278 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006279 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
6280 return -1;
6281 if (obj == Py_None)
6282 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006283 if (obj != NULL) {
6284 obj_type = supercheck(type, obj);
6285 if (obj_type == NULL)
6286 return -1;
6287 Py_INCREF(obj);
6288 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006289 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006290 su->type = type;
6291 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006292 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006293 return 0;
6294}
6295
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006296PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00006297"super(type) -> unbound super object\n"
6298"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006299"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006300"Typical use to call a cooperative superclass method:\n"
6301"class C(B):\n"
6302" def meth(self, arg):\n"
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006303" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006304
Guido van Rossum048eb752001-10-02 21:24:57 +00006305static int
6306super_traverse(PyObject *self, visitproc visit, void *arg)
6307{
6308 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006309
Thomas Woutersc6e55062006-04-15 21:47:09 +00006310 Py_VISIT(su->obj);
6311 Py_VISIT(su->type);
6312 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006313
6314 return 0;
6315}
6316
Guido van Rossum705f0f52001-08-24 16:47:00 +00006317PyTypeObject PySuper_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00006318 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00006319 "super", /* tp_name */
6320 sizeof(superobject), /* tp_basicsize */
6321 0, /* tp_itemsize */
6322 /* methods */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006323 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006324 0, /* tp_print */
6325 0, /* tp_getattr */
6326 0, /* tp_setattr */
6327 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006328 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006329 0, /* tp_as_number */
6330 0, /* tp_as_sequence */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006331 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006332 0, /* tp_hash */
6333 0, /* tp_call */
6334 0, /* tp_str */
6335 super_getattro, /* tp_getattro */
6336 0, /* tp_setattro */
6337 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006338 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6339 Py_TPFLAGS_BASETYPE, /* tp_flags */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006340 super_doc, /* tp_doc */
6341 super_traverse, /* tp_traverse */
6342 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006343 0, /* tp_richcompare */
6344 0, /* tp_weaklistoffset */
6345 0, /* tp_iter */
6346 0, /* tp_iternext */
6347 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006348 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006349 0, /* tp_getset */
6350 0, /* tp_base */
6351 0, /* tp_dict */
6352 super_descr_get, /* tp_descr_get */
6353 0, /* tp_descr_set */
6354 0, /* tp_dictoffset */
6355 super_init, /* tp_init */
6356 PyType_GenericAlloc, /* tp_alloc */
6357 PyType_GenericNew, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006358 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006359};