blob: 7db6dac7ca817c195b5a02aca4afca77845663a0 [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 *
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +0000309type_abstractmethods(PyTypeObject *type, void *context)
310{
311 PyObject *mod = PyDict_GetItemString(type->tp_dict,
312 "__abstractmethods__");
313 if (!mod) {
314 PyErr_Format(PyExc_AttributeError, "__abstractmethods__");
315 return NULL;
316 }
317 Py_XINCREF(mod);
318 return mod;
319}
320
321static int
322type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
323{
324 /* __abstractmethods__ should only be set once on a type, in
325 abc.ABCMeta.__new__, so this function doesn't do anything
326 special to update subclasses.
327 */
328 int res = PyDict_SetItemString(type->tp_dict,
329 "__abstractmethods__", value);
330 if (res == 0) {
331 type_modified(type);
332 if (value && PyObject_IsTrue(value)) {
333 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
334 }
335 else {
336 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
337 }
338 }
339 return res;
340}
341
342static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000343type_get_bases(PyTypeObject *type, void *context)
344{
345 Py_INCREF(type->tp_bases);
346 return type->tp_bases;
347}
348
349static PyTypeObject *best_base(PyObject *);
350static int mro_internal(PyTypeObject *);
351static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
352static int add_subclass(PyTypeObject*, PyTypeObject*);
353static void remove_subclass(PyTypeObject *, PyTypeObject *);
354static void update_all_slots(PyTypeObject *);
355
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000356typedef int (*update_callback)(PyTypeObject *, void *);
357static int update_subclasses(PyTypeObject *type, PyObject *name,
358 update_callback callback, void *data);
359static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
360 update_callback callback, void *data);
361
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000362static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000363mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000364{
365 PyTypeObject *subclass;
366 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000367 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000368
369 subclasses = type->tp_subclasses;
370 if (subclasses == NULL)
371 return 0;
372 assert(PyList_Check(subclasses));
373 n = PyList_GET_SIZE(subclasses);
374 for (i = 0; i < n; i++) {
375 ref = PyList_GET_ITEM(subclasses, i);
376 assert(PyWeakref_CheckRef(ref));
377 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
378 assert(subclass != NULL);
379 if ((PyObject *)subclass == Py_None)
380 continue;
381 assert(PyType_Check(subclass));
382 old_mro = subclass->tp_mro;
383 if (mro_internal(subclass) < 0) {
384 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000385 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000386 }
387 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000388 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000389 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000390 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000391 if (!tuple)
392 return -1;
393 if (PyList_Append(temp, tuple) < 0)
394 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000395 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000396 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000397 if (mro_subclasses(subclass, temp) < 0)
398 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000399 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000400 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000401}
402
403static int
404type_set_bases(PyTypeObject *type, PyObject *value, void *context)
405{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000406 Py_ssize_t i;
407 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000408 PyObject *ob, *temp;
Armin Rigoc0ba52d2007-04-19 14:44:48 +0000409 PyTypeObject *new_base, *old_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000410 PyObject *old_bases, *old_mro;
411
412 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
413 PyErr_Format(PyExc_TypeError,
414 "can't set %s.__bases__", type->tp_name);
415 return -1;
416 }
417 if (!value) {
418 PyErr_Format(PyExc_TypeError,
419 "can't delete %s.__bases__", type->tp_name);
420 return -1;
421 }
422 if (!PyTuple_Check(value)) {
423 PyErr_Format(PyExc_TypeError,
424 "can only assign tuple to %s.__bases__, not %s",
Christian Heimese93237d2007-12-19 02:37:44 +0000425 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000426 return -1;
427 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000428 if (PyTuple_GET_SIZE(value) == 0) {
429 PyErr_Format(PyExc_TypeError,
430 "can only assign non-empty tuple to %s.__bases__, not ()",
431 type->tp_name);
432 return -1;
433 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000434 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
435 ob = PyTuple_GET_ITEM(value, i);
436 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
437 PyErr_Format(
438 PyExc_TypeError,
439 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +0000440 type->tp_name, Py_TYPE(ob)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000441 return -1;
442 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000443 if (PyType_Check(ob)) {
444 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
445 PyErr_SetString(PyExc_TypeError,
446 "a __bases__ item causes an inheritance cycle");
447 return -1;
448 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000449 }
450 }
451
452 new_base = best_base(value);
453
454 if (!new_base) {
455 return -1;
456 }
457
458 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
459 return -1;
460
461 Py_INCREF(new_base);
462 Py_INCREF(value);
463
464 old_bases = type->tp_bases;
465 old_base = type->tp_base;
466 old_mro = type->tp_mro;
467
468 type->tp_bases = value;
469 type->tp_base = new_base;
470
471 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000472 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000473 }
474
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000475 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000476 if (!temp)
477 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000478
479 r = mro_subclasses(type, temp);
480
481 if (r < 0) {
482 for (i = 0; i < PyList_Size(temp); i++) {
483 PyTypeObject* cls;
484 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000485 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
486 "", 2, 2, &cls, &mro);
Armin Rigo796fc992007-04-19 14:56:48 +0000487 Py_INCREF(mro);
488 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000489 cls->tp_mro = mro;
Armin Rigo796fc992007-04-19 14:56:48 +0000490 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000491 }
492 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000493 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000494 }
495
496 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000497
498 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000499 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000500 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000501 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000502
503 /* for now, sod that: just remove from all old_bases,
504 add to all new_bases */
505
506 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
507 ob = PyTuple_GET_ITEM(old_bases, i);
508 if (PyType_Check(ob)) {
509 remove_subclass(
510 (PyTypeObject*)ob, type);
511 }
512 }
513
514 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
515 ob = PyTuple_GET_ITEM(value, i);
516 if (PyType_Check(ob)) {
517 if (add_subclass((PyTypeObject*)ob, type) < 0)
518 r = -1;
519 }
520 }
521
522 update_all_slots(type);
523
524 Py_DECREF(old_bases);
525 Py_DECREF(old_base);
526 Py_DECREF(old_mro);
527
528 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000529
530 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000531 Py_DECREF(type->tp_bases);
532 Py_DECREF(type->tp_base);
533 if (type->tp_mro != old_mro) {
534 Py_DECREF(type->tp_mro);
535 }
536
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000537 type->tp_bases = old_bases;
538 type->tp_base = old_base;
539 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000540
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000541 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000542}
543
544static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000545type_dict(PyTypeObject *type, void *context)
546{
547 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548 Py_INCREF(Py_None);
549 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000550 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000551 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000552}
553
Tim Peters24008312002-03-17 18:56:20 +0000554static PyObject *
555type_get_doc(PyTypeObject *type, void *context)
556{
557 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000558 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000559 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000560 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000561 if (result == NULL) {
562 result = Py_None;
563 Py_INCREF(result);
564 }
Christian Heimese93237d2007-12-19 02:37:44 +0000565 else if (Py_TYPE(result)->tp_descr_get) {
566 result = Py_TYPE(result)->tp_descr_get(result, NULL,
Tim Peters2b858972002-04-18 04:12:28 +0000567 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000568 }
569 else {
570 Py_INCREF(result);
571 }
Tim Peters24008312002-03-17 18:56:20 +0000572 return result;
573}
574
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000575static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000576 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
577 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000578 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +0000579 {"__abstractmethods__", (getter)type_abstractmethods,
580 (setter)type_set_abstractmethods, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000581 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000582 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000583 {0}
584};
585
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000586static int
587type_compare(PyObject *v, PyObject *w)
588{
589 /* This is called with type objects only. So we
590 can just compare the addresses. */
591 Py_uintptr_t vv = (Py_uintptr_t)v;
592 Py_uintptr_t ww = (Py_uintptr_t)w;
593 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
594}
595
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000596static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000597type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000598{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000599 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000600 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000601
602 mod = type_module(type, NULL);
603 if (mod == NULL)
604 PyErr_Clear();
605 else if (!PyString_Check(mod)) {
606 Py_DECREF(mod);
607 mod = NULL;
608 }
609 name = type_name(type, NULL);
610 if (name == NULL)
611 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000612
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000613 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
614 kind = "class";
615 else
616 kind = "type";
617
Barry Warsaw7ce36942001-08-24 18:34:26 +0000618 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000619 rtn = PyString_FromFormat("<%s '%s.%s'>",
620 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000621 PyString_AS_STRING(mod),
622 PyString_AS_STRING(name));
623 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000624 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000625 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000626
Guido van Rossumc3542212001-08-16 09:18:56 +0000627 Py_XDECREF(mod);
628 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000629 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000630}
631
Tim Peters6d6c1a32001-08-02 04:15:00 +0000632static PyObject *
633type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
634{
635 PyObject *obj;
636
637 if (type->tp_new == NULL) {
638 PyErr_Format(PyExc_TypeError,
639 "cannot create '%.100s' instances",
640 type->tp_name);
641 return NULL;
642 }
643
Tim Peters3f996e72001-09-13 19:18:27 +0000644 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000645 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000646 /* Ugly exception: when the call was type(something),
647 don't call tp_init on the result. */
648 if (type == &PyType_Type &&
649 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
650 (kwds == NULL ||
651 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
652 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000653 /* If the returned object is not an instance of type,
654 it won't be initialized. */
655 if (!PyType_IsSubtype(obj->ob_type, type))
656 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000657 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000658 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
659 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000660 type->tp_init(obj, args, kwds) < 0) {
661 Py_DECREF(obj);
662 obj = NULL;
663 }
664 }
665 return obj;
666}
667
668PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000669PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000670{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000671 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000672 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
673 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000674
675 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000676 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000677 else
Anthony Baxtera6286212006-04-11 07:42:36 +0000678 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000679
Neil Schemenauerc806c882001-08-29 23:54:54 +0000680 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000681 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000682
Neil Schemenauerc806c882001-08-29 23:54:54 +0000683 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000684
Tim Peters6d6c1a32001-08-02 04:15:00 +0000685 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
686 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000687
Tim Peters6d6c1a32001-08-02 04:15:00 +0000688 if (type->tp_itemsize == 0)
689 PyObject_INIT(obj, type);
690 else
691 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000692
Tim Peters6d6c1a32001-08-02 04:15:00 +0000693 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000694 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000695 return obj;
696}
697
698PyObject *
699PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
700{
701 return type->tp_alloc(type, 0);
702}
703
Guido van Rossum9475a232001-10-05 20:51:39 +0000704/* Helpers for subtyping */
705
706static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000707traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
708{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000709 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000710 PyMemberDef *mp;
711
Christian Heimese93237d2007-12-19 02:37:44 +0000712 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000713 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000714 for (i = 0; i < n; i++, mp++) {
715 if (mp->type == T_OBJECT_EX) {
716 char *addr = (char *)self + mp->offset;
717 PyObject *obj = *(PyObject **)addr;
718 if (obj != NULL) {
719 int err = visit(obj, arg);
720 if (err)
721 return err;
722 }
723 }
724 }
725 return 0;
726}
727
728static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000729subtype_traverse(PyObject *self, visitproc visit, void *arg)
730{
731 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000732 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000733
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000734 /* Find the nearest base with a different tp_traverse,
735 and traverse slots while we're at it */
Christian Heimese93237d2007-12-19 02:37:44 +0000736 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000737 base = type;
738 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
Christian Heimese93237d2007-12-19 02:37:44 +0000739 if (Py_SIZE(base)) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000740 int err = traverse_slots(base, self, visit, arg);
741 if (err)
742 return err;
743 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000744 base = base->tp_base;
745 assert(base);
746 }
747
748 if (type->tp_dictoffset != base->tp_dictoffset) {
749 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Woutersc6e55062006-04-15 21:47:09 +0000750 if (dictptr && *dictptr)
751 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000752 }
753
Thomas Woutersc6e55062006-04-15 21:47:09 +0000754 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000755 /* For a heaptype, the instances count as references
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000756 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000757 can find cycles involving this link. */
Thomas Woutersc6e55062006-04-15 21:47:09 +0000758 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000759
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000760 if (basetraverse)
761 return basetraverse(self, visit, arg);
762 return 0;
763}
764
765static void
766clear_slots(PyTypeObject *type, PyObject *self)
767{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000768 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000769 PyMemberDef *mp;
770
Christian Heimese93237d2007-12-19 02:37:44 +0000771 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000772 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000773 for (i = 0; i < n; i++, mp++) {
774 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
775 char *addr = (char *)self + mp->offset;
776 PyObject *obj = *(PyObject **)addr;
777 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000778 *(PyObject **)addr = NULL;
Thomas Woutersedf17d82006-04-15 17:28:34 +0000779 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000780 }
781 }
782 }
783}
784
785static int
786subtype_clear(PyObject *self)
787{
788 PyTypeObject *type, *base;
789 inquiry baseclear;
790
791 /* Find the nearest base with a different tp_clear
792 and clear slots while we're at it */
Christian Heimese93237d2007-12-19 02:37:44 +0000793 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000794 base = type;
795 while ((baseclear = base->tp_clear) == subtype_clear) {
Christian Heimese93237d2007-12-19 02:37:44 +0000796 if (Py_SIZE(base))
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000797 clear_slots(base, self);
798 base = base->tp_base;
799 assert(base);
800 }
801
Guido van Rossuma3862092002-06-10 15:24:42 +0000802 /* There's no need to clear the instance dict (if any);
803 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000804
805 if (baseclear)
806 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000807 return 0;
808}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000809
810static void
811subtype_dealloc(PyObject *self)
812{
Guido van Rossum14227b42001-12-06 02:35:58 +0000813 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000814 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000815
Guido van Rossum22b13872002-08-06 21:41:44 +0000816 /* Extract the type; we expect it to be a heap type */
Christian Heimese93237d2007-12-19 02:37:44 +0000817 type = Py_TYPE(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000818 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000819
Guido van Rossum22b13872002-08-06 21:41:44 +0000820 /* Test whether the type has GC exactly once */
821
822 if (!PyType_IS_GC(type)) {
823 /* It's really rare to find a dynamic type that doesn't have
824 GC; it can only happen when deriving from 'object' and not
825 adding any slots or instance variables. This allows
826 certain simplifications: there's no need to call
827 clear_slots(), or DECREF the dict, or clear weakrefs. */
828
829 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000830 if (type->tp_del) {
831 type->tp_del(self);
832 if (self->ob_refcnt > 0)
833 return;
834 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000835
836 /* Find the nearest base with a different tp_dealloc */
837 base = type;
838 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimese93237d2007-12-19 02:37:44 +0000839 assert(Py_SIZE(base) == 0);
Guido van Rossum22b13872002-08-06 21:41:44 +0000840 base = base->tp_base;
841 assert(base);
842 }
843
844 /* Call the base tp_dealloc() */
845 assert(basedealloc);
846 basedealloc(self);
847
848 /* Can't reference self beyond this point */
849 Py_DECREF(type);
850
851 /* Done */
852 return;
853 }
854
855 /* We get here only if the type has GC */
856
857 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000858 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000859 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000860 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000861 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000862 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000863 /* DO NOT restore GC tracking at this point. weakref callbacks
864 * (if any, and whether directly here or indirectly in something we
865 * call) may trigger GC, and if self is tracked at that point, it
866 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000867 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000868
Guido van Rossum59195fd2003-06-13 20:54:40 +0000869 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000870 base = type;
871 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000872 base = base->tp_base;
873 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000874 }
875
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000876 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000877 the finalizer (__del__), clearing slots, or clearing the instance
878 dict. */
879
Guido van Rossum1987c662003-05-29 14:29:23 +0000880 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
881 PyObject_ClearWeakRefs(self);
882
883 /* Maybe call finalizer; exit early if resurrected */
884 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000885 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000886 type->tp_del(self);
887 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000888 goto endlabel; /* resurrected */
889 else
890 _PyObject_GC_UNTRACK(self);
Brett Cannonf5bee302007-01-23 23:21:22 +0000891 /* New weakrefs could be created during the finalizer call.
892 If this occurs, clear them out without calling their
893 finalizers since they might rely on part of the object
894 being finalized that has already been destroyed. */
895 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
896 /* Modeled after GET_WEAKREFS_LISTPTR() */
897 PyWeakReference **list = (PyWeakReference **) \
898 PyObject_GET_WEAKREFS_LISTPTR(self);
899 while (*list)
900 _PyWeakref_ClearRef(*list);
901 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000902 }
903
Guido van Rossum59195fd2003-06-13 20:54:40 +0000904 /* Clear slots up to the nearest base with a different tp_dealloc */
905 base = type;
906 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimese93237d2007-12-19 02:37:44 +0000907 if (Py_SIZE(base))
Guido van Rossum59195fd2003-06-13 20:54:40 +0000908 clear_slots(base, self);
909 base = base->tp_base;
910 assert(base);
911 }
912
Tim Peters6d6c1a32001-08-02 04:15:00 +0000913 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000914 if (type->tp_dictoffset && !base->tp_dictoffset) {
915 PyObject **dictptr = _PyObject_GetDictPtr(self);
916 if (dictptr != NULL) {
917 PyObject *dict = *dictptr;
918 if (dict != NULL) {
919 Py_DECREF(dict);
920 *dictptr = NULL;
921 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000922 }
923 }
924
Tim Peters0bd743c2003-11-13 22:50:00 +0000925 /* Call the base tp_dealloc(); first retrack self if
926 * basedealloc knows about gc.
927 */
928 if (PyType_IS_GC(base))
929 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000930 assert(basedealloc);
931 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000932
933 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000934 Py_DECREF(type);
935
Guido van Rossum0906e072002-08-07 20:42:09 +0000936 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000937 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000938 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000939 --_PyTrash_delete_nesting;
940
941 /* Explanation of the weirdness around the trashcan macros:
942
943 Q. What do the trashcan macros do?
944
945 A. Read the comment titled "Trashcan mechanism" in object.h.
946 For one, this explains why there must be a call to GC-untrack
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000947 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000948 trashcan code, the answers to the following questions don't make
949 sense.
950
951 Q. Why do we GC-untrack before the trashcan and then immediately
952 GC-track again afterward?
953
954 A. In the case that the base class is GC-aware, the base class
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000955 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000956 UNTRACK macro, this will crash when the object is already
957 untracked. Because we don't know what the base class does, the
958 only safe thing is to make sure the object is tracked when we
959 call the base class dealloc. But... The trashcan begin macro
960 requires that the object is *untracked* before it is called. So
961 the dance becomes:
962
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000963 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000964 trashcan begin
965 GC track
966
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000967 Q. Why did the last question say "immediately GC-track again"?
968 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000969
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000970 A. Because the code *used* to re-track immediately. Bad Idea.
971 self has a refcount of 0, and if gc ever gets its hands on it
972 (which can happen if any weakref callback gets invoked), it
973 looks like trash to gc too, and gc also tries to delete self
974 then. But we're already deleting self. Double dealloction is
975 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +0000976
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000977 Q. Why the bizarre (net-zero) manipulation of
978 _PyTrash_delete_nesting around the trashcan macros?
979
980 A. Some base classes (e.g. list) also use the trashcan mechanism.
981 The following scenario used to be possible:
982
983 - suppose the trashcan level is one below the trashcan limit
984
985 - subtype_dealloc() is called
986
987 - the trashcan limit is not yet reached, so the trashcan level
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000988 is incremented and the code between trashcan begin and end is
989 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000990
991 - this destroys much of the object's contents, including its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000992 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000993
994 - basedealloc() is called; this is really list_dealloc(), or
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000995 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000996
997 - the trashcan limit is now reached, so the object is put on the
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000998 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000999
1000 - basedealloc() returns
1001
1002 - subtype_dealloc() decrefs the object's type
1003
1004 - subtype_dealloc() returns
1005
1006 - later, the trashcan code starts deleting the objects from its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001007 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001008
1009 - subtype_dealloc() is called *AGAIN* for the same object
1010
1011 - at the very least (if the destroyed slots and __dict__ don't
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001012 cause problems) the object's type gets decref'ed a second
1013 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001014
1015 The remedy is to make sure that if the code between trashcan
1016 begin and end in subtype_dealloc() is called, the code between
1017 trashcan begin and end in basedealloc() will also be called.
1018 This is done by decrementing the level after passing into the
1019 trashcan block, and incrementing it just before leaving the
1020 block.
1021
1022 But now it's possible that a chain of objects consisting solely
1023 of objects whose deallocator is subtype_dealloc() will defeat
1024 the trashcan mechanism completely: the decremented level means
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001025 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001026 *increment* the level *before* entering the trashcan block, and
1027 matchingly decrement it after leaving. This means the trashcan
1028 code will trigger a little early, but that's no big deal.
1029
1030 Q. Are there any live examples of code in need of all this
1031 complexity?
1032
1033 A. Yes. See SF bug 668433 for code that crashed (when Python was
1034 compiled in debug mode) before the trashcan level manipulations
1035 were added. For more discussion, see SF patches 581742, 575073
1036 and bug 574207.
1037 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001038}
1039
Jeremy Hylton938ace62002-07-17 16:30:39 +00001040static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001041
Tim Peters6d6c1a32001-08-02 04:15:00 +00001042/* type test with subclassing support */
1043
1044int
1045PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1046{
1047 PyObject *mro;
1048
Guido van Rossum9478d072001-09-07 18:52:13 +00001049 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1050 return b == a || b == &PyBaseObject_Type;
1051
Tim Peters6d6c1a32001-08-02 04:15:00 +00001052 mro = a->tp_mro;
1053 if (mro != NULL) {
1054 /* Deal with multiple inheritance without recursion
1055 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001056 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001057 assert(PyTuple_Check(mro));
1058 n = PyTuple_GET_SIZE(mro);
1059 for (i = 0; i < n; i++) {
1060 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1061 return 1;
1062 }
1063 return 0;
1064 }
1065 else {
1066 /* a is not completely initilized yet; follow tp_base */
1067 do {
1068 if (a == b)
1069 return 1;
1070 a = a->tp_base;
1071 } while (a != NULL);
1072 return b == &PyBaseObject_Type;
1073 }
1074}
1075
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001076/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001077 without looking in the instance dictionary
1078 (so we can't use PyObject_GetAttr) but still binding
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001079 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001080 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001081 static variable used to cache the interned Python string.
1082
1083 Two variants:
1084
1085 - lookup_maybe() returns NULL without raising an exception
1086 when the _PyType_Lookup() call fails;
1087
1088 - lookup_method() always raises an exception upon errors.
1089*/
Guido van Rossum60718732001-08-28 17:47:51 +00001090
1091static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001092lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001093{
1094 PyObject *res;
1095
1096 if (*attrobj == NULL) {
1097 *attrobj = PyString_InternFromString(attrstr);
1098 if (*attrobj == NULL)
1099 return NULL;
1100 }
Christian Heimese93237d2007-12-19 02:37:44 +00001101 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001102 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +00001103 descrgetfunc f;
Christian Heimese93237d2007-12-19 02:37:44 +00001104 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
Guido van Rossum60718732001-08-28 17:47:51 +00001105 Py_INCREF(res);
1106 else
Christian Heimese93237d2007-12-19 02:37:44 +00001107 res = f(res, self, (PyObject *)(Py_TYPE(self)));
Guido van Rossum60718732001-08-28 17:47:51 +00001108 }
1109 return res;
1110}
1111
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001112static PyObject *
1113lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1114{
1115 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1116 if (res == NULL && !PyErr_Occurred())
1117 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1118 return res;
1119}
1120
Guido van Rossum2730b132001-08-28 18:22:14 +00001121/* A variation of PyObject_CallMethod that uses lookup_method()
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001122 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001123 as lookup_method to cache the interned name string object. */
1124
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001125static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001126call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1127{
1128 va_list va;
1129 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001130 va_start(va, format);
1131
Guido van Rossumda21c012001-10-03 00:50:18 +00001132 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001133 if (func == NULL) {
1134 va_end(va);
1135 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +00001136 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001137 return NULL;
1138 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001139
1140 if (format && *format)
1141 args = Py_VaBuildValue(format, va);
1142 else
1143 args = PyTuple_New(0);
1144
1145 va_end(va);
1146
1147 if (args == NULL)
1148 return NULL;
1149
1150 assert(PyTuple_Check(args));
1151 retval = PyObject_Call(func, args, NULL);
1152
1153 Py_DECREF(args);
1154 Py_DECREF(func);
1155
1156 return retval;
1157}
1158
1159/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1160
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001161static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001162call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1163{
1164 va_list va;
1165 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001166 va_start(va, format);
1167
Guido van Rossumda21c012001-10-03 00:50:18 +00001168 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +00001169 if (func == NULL) {
1170 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001171 if (!PyErr_Occurred()) {
1172 Py_INCREF(Py_NotImplemented);
1173 return Py_NotImplemented;
1174 }
Guido van Rossum717ce002001-09-14 16:58:08 +00001175 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001176 }
1177
1178 if (format && *format)
1179 args = Py_VaBuildValue(format, va);
1180 else
1181 args = PyTuple_New(0);
1182
1183 va_end(va);
1184
Guido van Rossum717ce002001-09-14 16:58:08 +00001185 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00001186 return NULL;
1187
Guido van Rossum717ce002001-09-14 16:58:08 +00001188 assert(PyTuple_Check(args));
1189 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001190
1191 Py_DECREF(args);
1192 Py_DECREF(func);
1193
1194 return retval;
1195}
1196
Tim Petersa91e9642001-11-14 23:32:33 +00001197static int
1198fill_classic_mro(PyObject *mro, PyObject *cls)
1199{
1200 PyObject *bases, *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001201 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001202
1203 assert(PyList_Check(mro));
1204 assert(PyClass_Check(cls));
1205 i = PySequence_Contains(mro, cls);
1206 if (i < 0)
1207 return -1;
1208 if (!i) {
1209 if (PyList_Append(mro, cls) < 0)
1210 return -1;
1211 }
1212 bases = ((PyClassObject *)cls)->cl_bases;
1213 assert(bases && PyTuple_Check(bases));
1214 n = PyTuple_GET_SIZE(bases);
1215 for (i = 0; i < n; i++) {
1216 base = PyTuple_GET_ITEM(bases, i);
1217 if (fill_classic_mro(mro, base) < 0)
1218 return -1;
1219 }
1220 return 0;
1221}
1222
1223static PyObject *
1224classic_mro(PyObject *cls)
1225{
1226 PyObject *mro;
1227
1228 assert(PyClass_Check(cls));
1229 mro = PyList_New(0);
1230 if (mro != NULL) {
1231 if (fill_classic_mro(mro, cls) == 0)
1232 return mro;
1233 Py_DECREF(mro);
1234 }
1235 return NULL;
1236}
1237
Tim Petersea7f75d2002-12-07 21:39:16 +00001238/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001239 Method resolution order algorithm C3 described in
1240 "A Monotonic Superclass Linearization for Dylan",
1241 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001242 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001243 (OOPSLA 1996)
1244
Guido van Rossum98f33732002-11-25 21:36:54 +00001245 Some notes about the rules implied by C3:
1246
Tim Petersea7f75d2002-12-07 21:39:16 +00001247 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001248 It isn't legal to repeat a class in a list of base classes.
1249
1250 The next three properties are the 3 constraints in "C3".
1251
Tim Petersea7f75d2002-12-07 21:39:16 +00001252 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001253 If A precedes B in C's MRO, then A will precede B in the MRO of all
1254 subclasses of C.
1255
1256 Monotonicity.
1257 The MRO of a class must be an extension without reordering of the
1258 MRO of each of its superclasses.
1259
1260 Extended Precedence Graph (EPG).
1261 Linearization is consistent if there is a path in the EPG from
1262 each class to all its successors in the linearization. See
1263 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001264 */
1265
Tim Petersea7f75d2002-12-07 21:39:16 +00001266static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001267tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001268 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001269 size = PyList_GET_SIZE(list);
1270
1271 for (j = whence+1; j < size; j++) {
1272 if (PyList_GET_ITEM(list, j) == o)
1273 return 1;
1274 }
1275 return 0;
1276}
1277
Guido van Rossum98f33732002-11-25 21:36:54 +00001278static PyObject *
1279class_name(PyObject *cls)
1280{
1281 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1282 if (name == NULL) {
1283 PyErr_Clear();
1284 Py_XDECREF(name);
1285 name = PyObject_Repr(cls);
1286 }
1287 if (name == NULL)
1288 return NULL;
1289 if (!PyString_Check(name)) {
1290 Py_DECREF(name);
1291 return NULL;
1292 }
1293 return name;
1294}
1295
1296static int
1297check_duplicates(PyObject *list)
1298{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001299 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001300 /* Let's use a quadratic time algorithm,
1301 assuming that the bases lists is short.
1302 */
1303 n = PyList_GET_SIZE(list);
1304 for (i = 0; i < n; i++) {
1305 PyObject *o = PyList_GET_ITEM(list, i);
1306 for (j = i + 1; j < n; j++) {
1307 if (PyList_GET_ITEM(list, j) == o) {
1308 o = class_name(o);
1309 PyErr_Format(PyExc_TypeError,
1310 "duplicate base class %s",
1311 o ? PyString_AS_STRING(o) : "?");
1312 Py_XDECREF(o);
1313 return -1;
1314 }
1315 }
1316 }
1317 return 0;
1318}
1319
1320/* Raise a TypeError for an MRO order disagreement.
1321
1322 It's hard to produce a good error message. In the absence of better
1323 insight into error reporting, report the classes that were candidates
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001324 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001325 order in which they should be put in the MRO, but it's hard to
1326 diagnose what constraint can't be satisfied.
1327*/
1328
1329static void
1330set_mro_error(PyObject *to_merge, int *remain)
1331{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001332 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001333 char buf[1000];
1334 PyObject *k, *v;
1335 PyObject *set = PyDict_New();
Georg Brandl5c170fd2006-03-17 19:03:25 +00001336 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001337
1338 to_merge_size = PyList_GET_SIZE(to_merge);
1339 for (i = 0; i < to_merge_size; i++) {
1340 PyObject *L = PyList_GET_ITEM(to_merge, i);
1341 if (remain[i] < PyList_GET_SIZE(L)) {
1342 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Georg Brandl5c170fd2006-03-17 19:03:25 +00001343 if (PyDict_SetItem(set, c, Py_None) < 0) {
1344 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001345 return;
Georg Brandl5c170fd2006-03-17 19:03:25 +00001346 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001347 }
1348 }
1349 n = PyDict_Size(set);
1350
Raymond Hettingerf394df42003-04-06 19:13:41 +00001351 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1352consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001353 i = 0;
Skip Montanaro429433b2006-04-18 00:35:43 +00001354 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001355 PyObject *name = class_name(k);
1356 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1357 name ? PyString_AS_STRING(name) : "?");
1358 Py_XDECREF(name);
Skip Montanaro429433b2006-04-18 00:35:43 +00001359 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001360 buf[off++] = ',';
1361 buf[off] = '\0';
1362 }
1363 }
1364 PyErr_SetString(PyExc_TypeError, buf);
1365 Py_DECREF(set);
1366}
1367
Tim Petersea7f75d2002-12-07 21:39:16 +00001368static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001369pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001370 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001371 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001372 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001373
Guido van Rossum1f121312002-11-14 19:49:16 +00001374 to_merge_size = PyList_GET_SIZE(to_merge);
1375
Guido van Rossum98f33732002-11-25 21:36:54 +00001376 /* remain stores an index into each sublist of to_merge.
1377 remain[i] is the index of the next base in to_merge[i]
1378 that is not included in acc.
1379 */
Anthony Baxtera6286212006-04-11 07:42:36 +00001380 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001381 if (remain == NULL)
1382 return -1;
1383 for (i = 0; i < to_merge_size; i++)
1384 remain[i] = 0;
1385
1386 again:
1387 empty_cnt = 0;
1388 for (i = 0; i < to_merge_size; i++) {
1389 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001390
Guido van Rossum1f121312002-11-14 19:49:16 +00001391 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1392
1393 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1394 empty_cnt++;
1395 continue;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001396 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001397
Guido van Rossum98f33732002-11-25 21:36:54 +00001398 /* Choose next candidate for MRO.
1399
1400 The input sequences alone can determine the choice.
1401 If not, choose the class which appears in the MRO
1402 of the earliest direct superclass of the new class.
1403 */
1404
Guido van Rossum1f121312002-11-14 19:49:16 +00001405 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1406 for (j = 0; j < to_merge_size; j++) {
1407 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001408 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001409 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001410 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001411 }
1412 ok = PyList_Append(acc, candidate);
1413 if (ok < 0) {
1414 PyMem_Free(remain);
1415 return -1;
1416 }
1417 for (j = 0; j < to_merge_size; j++) {
1418 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001419 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1420 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001421 remain[j]++;
1422 }
1423 }
1424 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001425 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001426 }
1427
Guido van Rossum98f33732002-11-25 21:36:54 +00001428 if (empty_cnt == to_merge_size) {
1429 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001430 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001431 }
1432 set_mro_error(to_merge, remain);
1433 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001434 return -1;
1435}
1436
Tim Peters6d6c1a32001-08-02 04:15:00 +00001437static PyObject *
1438mro_implementation(PyTypeObject *type)
1439{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001440 Py_ssize_t i, n;
1441 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001442 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001443 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001444
Neal Norwitze7bb9182008-01-27 17:10:14 +00001445 if (type->tp_dict == NULL) {
1446 if (PyType_Ready(type) < 0)
Guido van Rossum63517572002-06-18 16:44:57 +00001447 return NULL;
1448 }
1449
Guido van Rossum98f33732002-11-25 21:36:54 +00001450 /* Find a superclass linearization that honors the constraints
1451 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001452 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001453
1454 to_merge is a list of lists, where each list is a superclass
1455 linearization implied by a base class. The last element of
1456 to_merge is the declared list of bases.
1457 */
1458
Tim Peters6d6c1a32001-08-02 04:15:00 +00001459 bases = type->tp_bases;
1460 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001461
1462 to_merge = PyList_New(n+1);
1463 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001464 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001465
Tim Peters6d6c1a32001-08-02 04:15:00 +00001466 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001467 PyObject *base = PyTuple_GET_ITEM(bases, i);
1468 PyObject *parentMRO;
1469 if (PyType_Check(base))
1470 parentMRO = PySequence_List(
1471 ((PyTypeObject*)base)->tp_mro);
1472 else
1473 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001474 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001475 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001476 return NULL;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001477 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001478
1479 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001480 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001481
1482 bases_aslist = PySequence_List(bases);
1483 if (bases_aslist == NULL) {
1484 Py_DECREF(to_merge);
1485 return NULL;
1486 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001487 /* This is just a basic sanity check. */
1488 if (check_duplicates(bases_aslist) < 0) {
1489 Py_DECREF(to_merge);
1490 Py_DECREF(bases_aslist);
1491 return NULL;
1492 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001493 PyList_SET_ITEM(to_merge, n, bases_aslist);
1494
1495 result = Py_BuildValue("[O]", (PyObject *)type);
1496 if (result == NULL) {
1497 Py_DECREF(to_merge);
1498 return NULL;
1499 }
1500
1501 ok = pmerge(result, to_merge);
1502 Py_DECREF(to_merge);
1503 if (ok < 0) {
1504 Py_DECREF(result);
1505 return NULL;
1506 }
1507
Tim Peters6d6c1a32001-08-02 04:15:00 +00001508 return result;
1509}
1510
1511static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001512mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001513{
1514 PyTypeObject *type = (PyTypeObject *)self;
1515
Tim Peters6d6c1a32001-08-02 04:15:00 +00001516 return mro_implementation(type);
1517}
1518
1519static int
1520mro_internal(PyTypeObject *type)
1521{
1522 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001523 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001524
Christian Heimese93237d2007-12-19 02:37:44 +00001525 if (Py_TYPE(type) == &PyType_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001526 result = mro_implementation(type);
1527 }
1528 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001529 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001530 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001531 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532 if (mro == NULL)
1533 return -1;
1534 result = PyObject_CallObject(mro, NULL);
1535 Py_DECREF(mro);
1536 }
1537 if (result == NULL)
1538 return -1;
1539 tuple = PySequence_Tuple(result);
1540 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001541 if (tuple == NULL)
1542 return -1;
1543 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001544 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001545 PyObject *cls;
1546 PyTypeObject *solid;
1547
1548 solid = solid_base(type);
1549
1550 len = PyTuple_GET_SIZE(tuple);
1551
1552 for (i = 0; i < len; i++) {
1553 PyTypeObject *t;
1554 cls = PyTuple_GET_ITEM(tuple, i);
1555 if (PyClass_Check(cls))
1556 continue;
1557 else if (!PyType_Check(cls)) {
1558 PyErr_Format(PyExc_TypeError,
1559 "mro() returned a non-class ('%.500s')",
Christian Heimese93237d2007-12-19 02:37:44 +00001560 Py_TYPE(cls)->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001561 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001562 return -1;
1563 }
1564 t = (PyTypeObject*)cls;
1565 if (!PyType_IsSubtype(solid, solid_base(t))) {
1566 PyErr_Format(PyExc_TypeError,
1567 "mro() returned base with unsuitable layout ('%.500s')",
1568 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001569 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001570 return -1;
1571 }
1572 }
1573 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001574 type->tp_mro = tuple;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001575
1576 type_mro_modified(type, type->tp_mro);
1577 /* corner case: the old-style super class might have been hidden
1578 from the custom MRO */
1579 type_mro_modified(type, type->tp_bases);
1580
1581 type_modified(type);
1582
Tim Peters6d6c1a32001-08-02 04:15:00 +00001583 return 0;
1584}
1585
1586
1587/* Calculate the best base amongst multiple base classes.
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001588 This is the first one that's on the path to the "solid base". */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589
1590static PyTypeObject *
1591best_base(PyObject *bases)
1592{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001593 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001594 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001595 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001596
1597 assert(PyTuple_Check(bases));
1598 n = PyTuple_GET_SIZE(bases);
1599 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001600 base = NULL;
1601 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001602 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001603 base_proto = PyTuple_GET_ITEM(bases, i);
1604 if (PyClass_Check(base_proto))
1605 continue;
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001606 if (!PyType_Check(base_proto)) {
1607 PyErr_SetString(
1608 PyExc_TypeError,
1609 "bases must be types");
1610 return NULL;
1611 }
Tim Petersa91e9642001-11-14 23:32:33 +00001612 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001613 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001614 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001615 return NULL;
1616 }
1617 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001618 if (winner == NULL) {
1619 winner = candidate;
1620 base = base_i;
1621 }
1622 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001623 ;
1624 else if (PyType_IsSubtype(candidate, winner)) {
1625 winner = candidate;
1626 base = base_i;
1627 }
1628 else {
1629 PyErr_SetString(
1630 PyExc_TypeError,
1631 "multiple bases have "
1632 "instance lay-out conflict");
1633 return NULL;
1634 }
1635 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001636 if (base == NULL)
1637 PyErr_SetString(PyExc_TypeError,
1638 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001639 return base;
1640}
1641
1642static int
1643extra_ivars(PyTypeObject *type, PyTypeObject *base)
1644{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001645 size_t t_size = type->tp_basicsize;
1646 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001647
Guido van Rossum9676b222001-08-17 20:32:36 +00001648 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001649 if (type->tp_itemsize || base->tp_itemsize) {
1650 /* If itemsize is involved, stricter rules */
1651 return t_size != b_size ||
1652 type->tp_itemsize != base->tp_itemsize;
1653 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001654 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001655 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1656 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001657 t_size -= sizeof(PyObject *);
1658 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001659 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1660 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001661 t_size -= sizeof(PyObject *);
1662
1663 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001664}
1665
1666static PyTypeObject *
1667solid_base(PyTypeObject *type)
1668{
1669 PyTypeObject *base;
1670
1671 if (type->tp_base)
1672 base = solid_base(type->tp_base);
1673 else
1674 base = &PyBaseObject_Type;
1675 if (extra_ivars(type, base))
1676 return type;
1677 else
1678 return base;
1679}
1680
Jeremy Hylton938ace62002-07-17 16:30:39 +00001681static void object_dealloc(PyObject *);
1682static int object_init(PyObject *, PyObject *, PyObject *);
1683static int update_slot(PyTypeObject *, PyObject *);
1684static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001685
Armin Rigo9790a272007-05-02 19:23:31 +00001686/*
1687 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1688 * inherited from various builtin types. The builtin base usually provides
1689 * its own __dict__ descriptor, so we use that when we can.
1690 */
1691static PyTypeObject *
1692get_builtin_base_with_dict(PyTypeObject *type)
1693{
1694 while (type->tp_base != NULL) {
1695 if (type->tp_dictoffset != 0 &&
1696 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1697 return type;
1698 type = type->tp_base;
1699 }
1700 return NULL;
1701}
1702
1703static PyObject *
1704get_dict_descriptor(PyTypeObject *type)
1705{
1706 static PyObject *dict_str;
1707 PyObject *descr;
1708
1709 if (dict_str == NULL) {
1710 dict_str = PyString_InternFromString("__dict__");
1711 if (dict_str == NULL)
1712 return NULL;
1713 }
1714 descr = _PyType_Lookup(type, dict_str);
1715 if (descr == NULL || !PyDescr_IsData(descr))
1716 return NULL;
1717
1718 return descr;
1719}
1720
1721static void
1722raise_dict_descr_error(PyObject *obj)
1723{
1724 PyErr_Format(PyExc_TypeError,
1725 "this __dict__ descriptor does not support "
1726 "'%.200s' objects", obj->ob_type->tp_name);
1727}
1728
Tim Peters6d6c1a32001-08-02 04:15:00 +00001729static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001730subtype_dict(PyObject *obj, void *context)
1731{
Armin Rigo9790a272007-05-02 19:23:31 +00001732 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001733 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001734 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001735
Armin Rigo9790a272007-05-02 19:23:31 +00001736 base = get_builtin_base_with_dict(obj->ob_type);
1737 if (base != NULL) {
1738 descrgetfunc func;
1739 PyObject *descr = get_dict_descriptor(base);
1740 if (descr == NULL) {
1741 raise_dict_descr_error(obj);
1742 return NULL;
1743 }
1744 func = descr->ob_type->tp_descr_get;
1745 if (func == NULL) {
1746 raise_dict_descr_error(obj);
1747 return NULL;
1748 }
1749 return func(descr, obj, (PyObject *)(obj->ob_type));
1750 }
1751
1752 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001753 if (dictptr == NULL) {
1754 PyErr_SetString(PyExc_AttributeError,
1755 "This object has no __dict__");
1756 return NULL;
1757 }
1758 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001759 if (dict == NULL)
1760 *dictptr = dict = PyDict_New();
1761 Py_XINCREF(dict);
1762 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001763}
1764
Guido van Rossum6661be32001-10-26 04:26:12 +00001765static int
1766subtype_setdict(PyObject *obj, PyObject *value, void *context)
1767{
Armin Rigo9790a272007-05-02 19:23:31 +00001768 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001769 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001770 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001771
Armin Rigo9790a272007-05-02 19:23:31 +00001772 base = get_builtin_base_with_dict(obj->ob_type);
1773 if (base != NULL) {
1774 descrsetfunc func;
1775 PyObject *descr = get_dict_descriptor(base);
1776 if (descr == NULL) {
1777 raise_dict_descr_error(obj);
1778 return -1;
1779 }
1780 func = descr->ob_type->tp_descr_set;
1781 if (func == NULL) {
1782 raise_dict_descr_error(obj);
1783 return -1;
1784 }
1785 return func(descr, obj, value);
1786 }
1787
1788 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001789 if (dictptr == NULL) {
1790 PyErr_SetString(PyExc_AttributeError,
1791 "This object has no __dict__");
1792 return -1;
1793 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001794 if (value != NULL && !PyDict_Check(value)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001795 PyErr_Format(PyExc_TypeError,
1796 "__dict__ must be set to a dictionary, "
Christian Heimese93237d2007-12-19 02:37:44 +00001797 "not a '%.200s'", Py_TYPE(value)->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001798 return -1;
1799 }
1800 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001801 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001802 *dictptr = value;
1803 Py_XDECREF(dict);
1804 return 0;
1805}
1806
Guido van Rossumad47da02002-08-12 19:05:44 +00001807static PyObject *
1808subtype_getweakref(PyObject *obj, void *context)
1809{
1810 PyObject **weaklistptr;
1811 PyObject *result;
1812
Christian Heimese93237d2007-12-19 02:37:44 +00001813 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001814 PyErr_SetString(PyExc_AttributeError,
Fred Drake7a36f5f2006-08-04 05:17:21 +00001815 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001816 return NULL;
1817 }
Christian Heimese93237d2007-12-19 02:37:44 +00001818 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1819 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1820 (size_t)(Py_TYPE(obj)->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001821 weaklistptr = (PyObject **)
Christian Heimese93237d2007-12-19 02:37:44 +00001822 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001823 if (*weaklistptr == NULL)
1824 result = Py_None;
1825 else
1826 result = *weaklistptr;
1827 Py_INCREF(result);
1828 return result;
1829}
1830
Guido van Rossum373c7412003-01-07 13:41:37 +00001831/* Three variants on the subtype_getsets list. */
1832
1833static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001834 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001835 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001836 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001837 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001838 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001839};
1840
Guido van Rossum373c7412003-01-07 13:41:37 +00001841static PyGetSetDef subtype_getsets_dict_only[] = {
1842 {"__dict__", subtype_dict, subtype_setdict,
1843 PyDoc_STR("dictionary for instance variables (if defined)")},
1844 {0}
1845};
1846
1847static PyGetSetDef subtype_getsets_weakref_only[] = {
1848 {"__weakref__", subtype_getweakref, NULL,
1849 PyDoc_STR("list of weak references to the object (if defined)")},
1850 {0}
1851};
1852
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001853static int
1854valid_identifier(PyObject *s)
1855{
Guido van Rossum03013a02002-07-16 14:30:28 +00001856 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001857 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001858
1859 if (!PyString_Check(s)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001860 PyErr_Format(PyExc_TypeError,
1861 "__slots__ items must be strings, not '%.200s'",
Christian Heimese93237d2007-12-19 02:37:44 +00001862 Py_TYPE(s)->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001863 return 0;
1864 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001865 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001866 n = PyString_GET_SIZE(s);
1867 /* We must reject an empty name. As a hack, we bump the
1868 length to 1 so that the loop will balk on the trailing \0. */
1869 if (n == 0)
1870 n = 1;
1871 for (i = 0; i < n; i++, p++) {
1872 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1873 PyErr_SetString(PyExc_TypeError,
1874 "__slots__ must be identifiers");
1875 return 0;
1876 }
1877 }
1878 return 1;
1879}
1880
Martin v. Löwisd919a592002-10-14 21:07:28 +00001881#ifdef Py_USING_UNICODE
1882/* Replace Unicode objects in slots. */
1883
1884static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001885_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001886{
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001887 PyObject *tmp = NULL;
1888 PyObject *slot_name, *new_name;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001889 Py_ssize_t i;
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001890
Martin v. Löwisd919a592002-10-14 21:07:28 +00001891 for (i = 0; i < nslots; i++) {
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001892 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1893 if (tmp == NULL) {
1894 tmp = PySequence_List(slots);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001895 if (tmp == NULL)
1896 return NULL;
1897 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001898 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1899 NULL);
1900 if (new_name == NULL) {
Martin v. Löwisd919a592002-10-14 21:07:28 +00001901 Py_DECREF(tmp);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001902 return NULL;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001903 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001904 Py_INCREF(new_name);
1905 PyList_SET_ITEM(tmp, i, new_name);
1906 Py_DECREF(slot_name);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001907 }
1908 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001909 if (tmp != NULL) {
1910 slots = PyList_AsTuple(tmp);
1911 Py_DECREF(tmp);
1912 }
1913 return slots;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001914}
1915#endif
1916
Guido van Rossumf102e242007-03-23 18:53:03 +00001917/* Forward */
1918static int
1919object_init(PyObject *self, PyObject *args, PyObject *kwds);
1920
1921static int
1922type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1923{
1924 int res;
1925
1926 assert(args != NULL && PyTuple_Check(args));
1927 assert(kwds == NULL || PyDict_Check(kwds));
1928
1929 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1930 PyErr_SetString(PyExc_TypeError,
1931 "type.__init__() takes no keyword arguments");
1932 return -1;
1933 }
1934
1935 if (args != NULL && PyTuple_Check(args) &&
1936 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1937 PyErr_SetString(PyExc_TypeError,
1938 "type.__init__() takes 1 or 3 arguments");
1939 return -1;
1940 }
1941
1942 /* Call object.__init__(self) now. */
1943 /* XXX Could call super(type, cls).__init__() but what's the point? */
1944 args = PyTuple_GetSlice(args, 0, 0);
1945 res = object_init(cls, args, NULL);
1946 Py_DECREF(args);
1947 return res;
1948}
1949
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001950static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001951type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1952{
1953 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001954 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001955 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001956 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001957 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001958 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001959 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001960 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001961
Tim Peters3abca122001-10-27 19:37:48 +00001962 assert(args != NULL && PyTuple_Check(args));
1963 assert(kwds == NULL || PyDict_Check(kwds));
1964
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001965 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001966 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001967 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1968 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001969
1970 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1971 PyObject *x = PyTuple_GET_ITEM(args, 0);
Christian Heimese93237d2007-12-19 02:37:44 +00001972 Py_INCREF(Py_TYPE(x));
1973 return (PyObject *) Py_TYPE(x);
Tim Peters3abca122001-10-27 19:37:48 +00001974 }
1975
1976 /* SF bug 475327 -- if that didn't trigger, we need 3
1977 arguments. but PyArg_ParseTupleAndKeywords below may give
1978 a msg saying type() needs exactly 3. */
1979 if (nargs + nkwds != 3) {
1980 PyErr_SetString(PyExc_TypeError,
1981 "type() takes 1 or 3 arguments");
1982 return NULL;
1983 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001984 }
1985
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001986 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1988 &name,
1989 &PyTuple_Type, &bases,
1990 &PyDict_Type, &dict))
1991 return NULL;
1992
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001993 /* Determine the proper metatype to deal with this,
1994 and check for metatype conflicts while we're at it.
1995 Note that if some other metatype wins to contract,
1996 it's possible that its instances are not types. */
1997 nbases = PyTuple_GET_SIZE(bases);
1998 winner = metatype;
1999 for (i = 0; i < nbases; i++) {
2000 tmp = PyTuple_GET_ITEM(bases, i);
2001 tmptype = tmp->ob_type;
2002 if (tmptype == &PyClass_Type)
2003 continue; /* Special case classic classes */
2004 if (PyType_IsSubtype(winner, tmptype))
2005 continue;
2006 if (PyType_IsSubtype(tmptype, winner)) {
2007 winner = tmptype;
2008 continue;
Jeremy Hyltonfa955692007-02-27 18:29:45 +00002009 }
Armin Rigoc0ba52d2007-04-19 14:44:48 +00002010 PyErr_SetString(PyExc_TypeError,
2011 "metaclass conflict: "
2012 "the metaclass of a derived class "
2013 "must be a (non-strict) subclass "
2014 "of the metaclasses of all its bases");
2015 return NULL;
2016 }
2017 if (winner != metatype) {
2018 if (winner->tp_new != type_new) /* Pass it to the winner */
2019 return winner->tp_new(winner, args, kwds);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00002020 metatype = winner;
2021 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002022
2023 /* Adjust for empty tuple bases */
2024 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002025 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002026 if (bases == NULL)
2027 return NULL;
2028 nbases = 1;
2029 }
2030 else
2031 Py_INCREF(bases);
2032
2033 /* XXX From here until type is allocated, "return NULL" leaks bases! */
2034
2035 /* Calculate best base, and check that all bases are type objects */
2036 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002037 if (base == NULL) {
2038 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002039 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002040 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002041 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2042 PyErr_Format(PyExc_TypeError,
2043 "type '%.100s' is not an acceptable base type",
2044 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002045 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002046 return NULL;
2047 }
2048
Tim Peters6d6c1a32001-08-02 04:15:00 +00002049 /* Check for a __slots__ sequence variable in dict, and count it */
2050 slots = PyDict_GetItemString(dict, "__slots__");
2051 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00002052 add_dict = 0;
2053 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00002054 may_add_dict = base->tp_dictoffset == 0;
2055 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2056 if (slots == NULL) {
2057 if (may_add_dict) {
2058 add_dict++;
2059 }
2060 if (may_add_weak) {
2061 add_weak++;
2062 }
2063 }
2064 else {
2065 /* Have slots */
2066
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067 /* Make it into a tuple */
Neal Norwitzcbd9ee62007-04-14 05:25:50 +00002068 if (PyString_Check(slots) || PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002069 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002070 else
2071 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002072 if (slots == NULL) {
2073 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002074 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002075 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002076 assert(PyTuple_Check(slots));
2077
2078 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002079 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00002080 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00002081 PyErr_Format(PyExc_TypeError,
2082 "nonempty __slots__ "
2083 "not supported for subtype of '%s'",
2084 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00002085 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002086 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00002087 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00002088 return NULL;
2089 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002090
Martin v. Löwisd919a592002-10-14 21:07:28 +00002091#ifdef Py_USING_UNICODE
2092 tmp = _unicode_to_string(slots, nslots);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00002093 if (tmp == NULL)
2094 goto bad_slots;
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00002095 if (tmp != slots) {
2096 Py_DECREF(slots);
2097 slots = tmp;
2098 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00002099#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00002100 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002101 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00002102 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2103 char *s;
2104 if (!valid_identifier(tmp))
2105 goto bad_slots;
2106 assert(PyString_Check(tmp));
2107 s = PyString_AS_STRING(tmp);
2108 if (strcmp(s, "__dict__") == 0) {
2109 if (!may_add_dict || add_dict) {
2110 PyErr_SetString(PyExc_TypeError,
2111 "__dict__ slot disallowed: "
2112 "we already got one");
2113 goto bad_slots;
2114 }
2115 add_dict++;
2116 }
2117 if (strcmp(s, "__weakref__") == 0) {
2118 if (!may_add_weak || add_weak) {
2119 PyErr_SetString(PyExc_TypeError,
2120 "__weakref__ slot disallowed: "
2121 "either we already got one, "
2122 "or __itemsize__ != 0");
2123 goto bad_slots;
2124 }
2125 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002126 }
2127 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002128
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002129 /* Copy slots into a list, mangle names and sort them.
2130 Sorted names are needed for __class__ assignment.
2131 Convert them back to tuple at the end.
2132 */
2133 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002134 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00002135 goto bad_slots;
2136 for (i = j = 0; i < nslots; i++) {
2137 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002138 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00002139 s = PyString_AS_STRING(tmp);
2140 if ((add_dict && strcmp(s, "__dict__") == 0) ||
2141 (add_weak && strcmp(s, "__weakref__") == 0))
2142 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002143 tmp =_Py_Mangle(name, tmp);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002144 if (!tmp)
2145 goto bad_slots;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002146 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00002147 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002148 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002149 assert(j == nslots - add_dict - add_weak);
2150 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002151 Py_DECREF(slots);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002152 if (PyList_Sort(newslots) == -1) {
2153 Py_DECREF(bases);
2154 Py_DECREF(newslots);
2155 return NULL;
2156 }
2157 slots = PyList_AsTuple(newslots);
2158 Py_DECREF(newslots);
2159 if (slots == NULL) {
2160 Py_DECREF(bases);
2161 return NULL;
2162 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002163
Guido van Rossumad47da02002-08-12 19:05:44 +00002164 /* Secondary bases may provide weakrefs or dict */
2165 if (nbases > 1 &&
2166 ((may_add_dict && !add_dict) ||
2167 (may_add_weak && !add_weak))) {
2168 for (i = 0; i < nbases; i++) {
2169 tmp = PyTuple_GET_ITEM(bases, i);
2170 if (tmp == (PyObject *)base)
2171 continue; /* Skip primary base */
2172 if (PyClass_Check(tmp)) {
2173 /* Classic base class provides both */
2174 if (may_add_dict && !add_dict)
2175 add_dict++;
2176 if (may_add_weak && !add_weak)
2177 add_weak++;
2178 break;
2179 }
2180 assert(PyType_Check(tmp));
2181 tmptype = (PyTypeObject *)tmp;
2182 if (may_add_dict && !add_dict &&
2183 tmptype->tp_dictoffset != 0)
2184 add_dict++;
2185 if (may_add_weak && !add_weak &&
2186 tmptype->tp_weaklistoffset != 0)
2187 add_weak++;
2188 if (may_add_dict && !add_dict)
2189 continue;
2190 if (may_add_weak && !add_weak)
2191 continue;
2192 /* Nothing more to check */
2193 break;
2194 }
2195 }
Guido van Rossum9676b222001-08-17 20:32:36 +00002196 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002197
2198 /* XXX From here until type is safely allocated,
2199 "return NULL" may leak slots! */
2200
2201 /* Allocate the type object */
2202 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00002203 if (type == NULL) {
2204 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002205 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002206 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00002207 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002208
2209 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002210 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002211 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002212 et->ht_name = name;
2213 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002214
Guido van Rossumdc91b992001-08-08 22:26:22 +00002215 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002216 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2217 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002218 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2219 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002220
2221 /* It's a new-style number unless it specifically inherits any
2222 old-style numeric behavior */
2223 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
2224 (base->tp_as_number == NULL))
2225 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
2226
2227 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002228 type->tp_as_number = &et->as_number;
2229 type->tp_as_sequence = &et->as_sequence;
2230 type->tp_as_mapping = &et->as_mapping;
2231 type->tp_as_buffer = &et->as_buffer;
2232 type->tp_name = PyString_AS_STRING(name);
2233
2234 /* Set tp_base and tp_bases */
2235 type->tp_bases = bases;
2236 Py_INCREF(base);
2237 type->tp_base = base;
2238
Guido van Rossum687ae002001-10-15 22:03:32 +00002239 /* Initialize tp_dict from passed-in dict */
2240 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002241 if (dict == NULL) {
2242 Py_DECREF(type);
2243 return NULL;
2244 }
2245
Guido van Rossumc3542212001-08-16 09:18:56 +00002246 /* Set __module__ in the dict */
2247 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2248 tmp = PyEval_GetGlobals();
2249 if (tmp != NULL) {
2250 tmp = PyDict_GetItemString(tmp, "__name__");
2251 if (tmp != NULL) {
2252 if (PyDict_SetItemString(dict, "__module__",
2253 tmp) < 0)
2254 return NULL;
2255 }
2256 }
2257 }
2258
Tim Peters2f93e282001-10-04 05:27:00 +00002259 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00002260 and is a string. The __doc__ accessor will first look for tp_doc;
2261 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00002262 */
2263 {
2264 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2265 if (doc != NULL && PyString_Check(doc)) {
2266 const size_t n = (size_t)PyString_GET_SIZE(doc);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002267 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002268 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00002269 Py_DECREF(type);
2270 return NULL;
2271 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002272 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002273 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00002274 }
2275 }
2276
Tim Peters6d6c1a32001-08-02 04:15:00 +00002277 /* Special-case __new__: if it's a plain function,
2278 make it a static function */
2279 tmp = PyDict_GetItemString(dict, "__new__");
2280 if (tmp != NULL && PyFunction_Check(tmp)) {
2281 tmp = PyStaticMethod_New(tmp);
2282 if (tmp == NULL) {
2283 Py_DECREF(type);
2284 return NULL;
2285 }
2286 PyDict_SetItemString(dict, "__new__", tmp);
2287 Py_DECREF(tmp);
2288 }
2289
2290 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002291 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00002292 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002293 if (slots != NULL) {
2294 for (i = 0; i < nslots; i++, mp++) {
2295 mp->name = PyString_AS_STRING(
2296 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00002297 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002298 mp->offset = slotoffset;
Žiga Seilnacht89032082007-03-11 15:54:54 +00002299
2300 /* __dict__ and __weakref__ are already filtered out */
2301 assert(strcmp(mp->name, "__dict__") != 0);
2302 assert(strcmp(mp->name, "__weakref__") != 0);
2303
Tim Peters6d6c1a32001-08-02 04:15:00 +00002304 slotoffset += sizeof(PyObject *);
2305 }
2306 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002307 if (add_dict) {
2308 if (base->tp_itemsize)
2309 type->tp_dictoffset = -(long)sizeof(PyObject *);
2310 else
2311 type->tp_dictoffset = slotoffset;
2312 slotoffset += sizeof(PyObject *);
2313 }
2314 if (add_weak) {
2315 assert(!base->tp_itemsize);
2316 type->tp_weaklistoffset = slotoffset;
2317 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002318 }
2319 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002320 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002321 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002322
2323 if (type->tp_weaklistoffset && type->tp_dictoffset)
2324 type->tp_getset = subtype_getsets_full;
2325 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2326 type->tp_getset = subtype_getsets_weakref_only;
2327 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2328 type->tp_getset = subtype_getsets_dict_only;
2329 else
2330 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002331
2332 /* Special case some slots */
2333 if (type->tp_dictoffset != 0 || nslots > 0) {
2334 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2335 type->tp_getattro = PyObject_GenericGetAttr;
2336 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2337 type->tp_setattro = PyObject_GenericSetAttr;
2338 }
2339 type->tp_dealloc = subtype_dealloc;
2340
Guido van Rossum9475a232001-10-05 20:51:39 +00002341 /* Enable GC unless there are really no instance variables possible */
2342 if (!(type->tp_basicsize == sizeof(PyObject) &&
2343 type->tp_itemsize == 0))
2344 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2345
Tim Peters6d6c1a32001-08-02 04:15:00 +00002346 /* Always override allocation strategy to use regular heap */
2347 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002348 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002349 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002350 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002351 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002352 }
2353 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002354 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002355
2356 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002357 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002358 Py_DECREF(type);
2359 return NULL;
2360 }
2361
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002362 /* Put the proper slots in place */
2363 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002364
Tim Peters6d6c1a32001-08-02 04:15:00 +00002365 return (PyObject *)type;
2366}
2367
2368/* Internal API to look for a name through the MRO.
2369 This returns a borrowed reference, and doesn't set an exception! */
2370PyObject *
2371_PyType_Lookup(PyTypeObject *type, PyObject *name)
2372{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002373 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002374 PyObject *mro, *res, *base, *dict;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002375 unsigned int h;
2376
2377 if (MCACHE_CACHEABLE_NAME(name) &&
Neal Norwitze7bb9182008-01-27 17:10:14 +00002378 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002379 /* fast path */
2380 h = MCACHE_HASH_METHOD(type, name);
2381 if (method_cache[h].version == type->tp_version_tag &&
2382 method_cache[h].name == name)
2383 return method_cache[h].value;
2384 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002385
Guido van Rossum687ae002001-10-15 22:03:32 +00002386 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002387 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002388
2389 /* If mro is NULL, the type is either not yet initialized
2390 by PyType_Ready(), or already cleared by type_clear().
2391 Either way the safest thing to do is to return NULL. */
2392 if (mro == NULL)
2393 return NULL;
2394
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002395 res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002396 assert(PyTuple_Check(mro));
2397 n = PyTuple_GET_SIZE(mro);
2398 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002399 base = PyTuple_GET_ITEM(mro, i);
2400 if (PyClass_Check(base))
2401 dict = ((PyClassObject *)base)->cl_dict;
2402 else {
2403 assert(PyType_Check(base));
2404 dict = ((PyTypeObject *)base)->tp_dict;
2405 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002406 assert(dict && PyDict_Check(dict));
2407 res = PyDict_GetItem(dict, name);
2408 if (res != NULL)
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002409 break;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002410 }
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002411
2412 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2413 h = MCACHE_HASH_METHOD(type, name);
2414 method_cache[h].version = type->tp_version_tag;
2415 method_cache[h].value = res; /* borrowed */
2416 Py_INCREF(name);
2417 Py_DECREF(method_cache[h].name);
2418 method_cache[h].name = name;
2419 }
2420 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002421}
2422
2423/* This is similar to PyObject_GenericGetAttr(),
2424 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2425static PyObject *
2426type_getattro(PyTypeObject *type, PyObject *name)
2427{
Christian Heimese93237d2007-12-19 02:37:44 +00002428 PyTypeObject *metatype = Py_TYPE(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002429 PyObject *meta_attribute, *attribute;
2430 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002431
2432 /* Initialize this type (we'll assume the metatype is initialized) */
2433 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002434 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002435 return NULL;
2436 }
2437
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002438 /* No readable descriptor found yet */
2439 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002440
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002441 /* Look for the attribute in the metatype */
2442 meta_attribute = _PyType_Lookup(metatype, name);
2443
2444 if (meta_attribute != NULL) {
Christian Heimese93237d2007-12-19 02:37:44 +00002445 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002446
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002447 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2448 /* Data descriptors implement tp_descr_set to intercept
2449 * writes. Assume the attribute is not overridden in
2450 * type's tp_dict (and bases): call the descriptor now.
2451 */
2452 return meta_get(meta_attribute, (PyObject *)type,
2453 (PyObject *)metatype);
2454 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002455 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002456 }
2457
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002458 /* No data descriptor found on metatype. Look in tp_dict of this
2459 * type and its bases */
2460 attribute = _PyType_Lookup(type, name);
2461 if (attribute != NULL) {
2462 /* Implement descriptor functionality, if any */
Christian Heimese93237d2007-12-19 02:37:44 +00002463 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002464
2465 Py_XDECREF(meta_attribute);
2466
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002467 if (local_get != NULL) {
2468 /* NULL 2nd argument indicates the descriptor was
2469 * found on the target object itself (or a base) */
2470 return local_get(attribute, (PyObject *)NULL,
2471 (PyObject *)type);
2472 }
Tim Peters34592512002-07-11 06:23:50 +00002473
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002474 Py_INCREF(attribute);
2475 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002476 }
2477
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002478 /* No attribute found in local __dict__ (or bases): use the
2479 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002480 if (meta_get != NULL) {
2481 PyObject *res;
2482 res = meta_get(meta_attribute, (PyObject *)type,
2483 (PyObject *)metatype);
2484 Py_DECREF(meta_attribute);
2485 return res;
2486 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002487
2488 /* If an ordinary attribute was found on the metatype, return it now */
2489 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002490 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002491 }
2492
2493 /* Give up */
2494 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002495 "type object '%.50s' has no attribute '%.400s'",
2496 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002497 return NULL;
2498}
2499
2500static int
2501type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2502{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002503 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2504 PyErr_Format(
2505 PyExc_TypeError,
2506 "can't set attributes of built-in/extension type '%s'",
2507 type->tp_name);
2508 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002509 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002510 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2511 return -1;
2512 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002513}
2514
2515static void
2516type_dealloc(PyTypeObject *type)
2517{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002518 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002519
2520 /* Assert this is a heap-allocated type object */
2521 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002522 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002523 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002524 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002525 Py_XDECREF(type->tp_base);
2526 Py_XDECREF(type->tp_dict);
2527 Py_XDECREF(type->tp_bases);
2528 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002529 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002530 Py_XDECREF(type->tp_subclasses);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002531 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2532 * of most other objects. It's okay to cast it to char *.
2533 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002534 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002535 Py_XDECREF(et->ht_name);
2536 Py_XDECREF(et->ht_slots);
Christian Heimese93237d2007-12-19 02:37:44 +00002537 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002538}
2539
Guido van Rossum1c450732001-10-08 15:18:27 +00002540static PyObject *
2541type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2542{
2543 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002544 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002545
2546 list = PyList_New(0);
2547 if (list == NULL)
2548 return NULL;
2549 raw = type->tp_subclasses;
2550 if (raw == NULL)
2551 return list;
2552 assert(PyList_Check(raw));
2553 n = PyList_GET_SIZE(raw);
2554 for (i = 0; i < n; i++) {
2555 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002556 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002557 ref = PyWeakref_GET_OBJECT(ref);
2558 if (ref != Py_None) {
2559 if (PyList_Append(list, ref) < 0) {
2560 Py_DECREF(list);
2561 return NULL;
2562 }
2563 }
2564 }
2565 return list;
2566}
2567
Tim Peters6d6c1a32001-08-02 04:15:00 +00002568static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002569 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002570 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002571 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002572 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002573 {0}
2574};
2575
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002576PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002577"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002578"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002579
Guido van Rossum048eb752001-10-02 21:24:57 +00002580static int
2581type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2582{
Guido van Rossuma3862092002-06-10 15:24:42 +00002583 /* Because of type_is_gc(), the collector only calls this
2584 for heaptypes. */
2585 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002586
Thomas Woutersc6e55062006-04-15 21:47:09 +00002587 Py_VISIT(type->tp_dict);
2588 Py_VISIT(type->tp_cache);
2589 Py_VISIT(type->tp_mro);
2590 Py_VISIT(type->tp_bases);
2591 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002592
2593 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002594 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002595 in cycles; tp_subclasses is a list of weak references,
2596 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002597
Guido van Rossum048eb752001-10-02 21:24:57 +00002598 return 0;
2599}
2600
2601static int
2602type_clear(PyTypeObject *type)
2603{
Guido van Rossuma3862092002-06-10 15:24:42 +00002604 /* Because of type_is_gc(), the collector only calls this
2605 for heaptypes. */
2606 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002607
Guido van Rossuma3862092002-06-10 15:24:42 +00002608 /* The only field we need to clear is tp_mro, which is part of a
2609 hard cycle (its first element is the class itself) that won't
2610 be broken otherwise (it's a tuple and tuples don't have a
2611 tp_clear handler). None of the other fields need to be
2612 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002613
Guido van Rossuma3862092002-06-10 15:24:42 +00002614 tp_dict:
2615 It is a dict, so the collector will call its tp_clear.
2616
2617 tp_cache:
2618 Not used; if it were, it would be a dict.
2619
2620 tp_bases, tp_base:
2621 If these are involved in a cycle, there must be at least
2622 one other, mutable object in the cycle, e.g. a base
2623 class's dict; the cycle will be broken that way.
2624
2625 tp_subclasses:
2626 A list of weak references can't be part of a cycle; and
2627 lists have their own tp_clear.
2628
Guido van Rossume5c691a2003-03-07 15:13:17 +00002629 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002630 A tuple of strings can't be part of a cycle.
2631 */
2632
Thomas Woutersedf17d82006-04-15 17:28:34 +00002633 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002634
2635 return 0;
2636}
2637
2638static int
2639type_is_gc(PyTypeObject *type)
2640{
2641 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2642}
2643
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002644PyTypeObject PyType_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002645 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002646 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002647 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002648 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002649 (destructor)type_dealloc, /* tp_dealloc */
2650 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002651 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002652 0, /* tp_setattr */
2653 type_compare, /* tp_compare */
2654 (reprfunc)type_repr, /* tp_repr */
2655 0, /* tp_as_number */
2656 0, /* tp_as_sequence */
2657 0, /* tp_as_mapping */
2658 (hashfunc)_Py_HashPointer, /* tp_hash */
2659 (ternaryfunc)type_call, /* tp_call */
2660 0, /* tp_str */
2661 (getattrofunc)type_getattro, /* tp_getattro */
2662 (setattrofunc)type_setattro, /* tp_setattro */
2663 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002664 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002665 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002666 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002667 (traverseproc)type_traverse, /* tp_traverse */
2668 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002669 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002670 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002671 0, /* tp_iter */
2672 0, /* tp_iternext */
2673 type_methods, /* tp_methods */
2674 type_members, /* tp_members */
2675 type_getsets, /* tp_getset */
2676 0, /* tp_base */
2677 0, /* tp_dict */
2678 0, /* tp_descr_get */
2679 0, /* tp_descr_set */
2680 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumf102e242007-03-23 18:53:03 +00002681 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002682 0, /* tp_alloc */
2683 type_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002684 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002685 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002686};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002687
2688
2689/* The base type of all types (eventually)... except itself. */
2690
Guido van Rossum143b5642007-03-23 04:58:42 +00002691/* You may wonder why object.__new__() only complains about arguments
2692 when object.__init__() is not overridden, and vice versa.
2693
2694 Consider the use cases:
2695
2696 1. When neither is overridden, we want to hear complaints about
2697 excess (i.e., any) arguments, since their presence could
2698 indicate there's a bug.
2699
2700 2. When defining an Immutable type, we are likely to override only
2701 __new__(), since __init__() is called too late to initialize an
2702 Immutable object. Since __new__() defines the signature for the
2703 type, it would be a pain to have to override __init__() just to
2704 stop it from complaining about excess arguments.
2705
2706 3. When defining a Mutable type, we are likely to override only
2707 __init__(). So here the converse reasoning applies: we don't
2708 want to have to override __new__() just to stop it from
2709 complaining.
2710
2711 4. When __init__() is overridden, and the subclass __init__() calls
2712 object.__init__(), the latter should complain about excess
2713 arguments; ditto for __new__().
2714
2715 Use cases 2 and 3 make it unattractive to unconditionally check for
2716 excess arguments. The best solution that addresses all four use
2717 cases is as follows: __init__() complains about excess arguments
2718 unless __new__() is overridden and __init__() is not overridden
2719 (IOW, if __init__() is overridden or __new__() is not overridden);
2720 symmetrically, __new__() complains about excess arguments unless
2721 __init__() is overridden and __new__() is not overridden
2722 (IOW, if __new__() is overridden or __init__() is not overridden).
2723
2724 However, for backwards compatibility, this breaks too much code.
2725 Therefore, in 2.6, we'll *warn* about excess arguments when both
2726 methods are overridden; for all other cases we'll use the above
2727 rules.
2728
2729*/
2730
2731/* Forward */
2732static PyObject *
2733object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2734
2735static int
2736excess_args(PyObject *args, PyObject *kwds)
2737{
2738 return PyTuple_GET_SIZE(args) ||
2739 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2740}
2741
Tim Peters6d6c1a32001-08-02 04:15:00 +00002742static int
2743object_init(PyObject *self, PyObject *args, PyObject *kwds)
2744{
Guido van Rossum143b5642007-03-23 04:58:42 +00002745 int err = 0;
2746 if (excess_args(args, kwds)) {
Christian Heimese93237d2007-12-19 02:37:44 +00002747 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum143b5642007-03-23 04:58:42 +00002748 if (type->tp_init != object_init &&
2749 type->tp_new != object_new)
2750 {
2751 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2752 "object.__init__() takes no parameters",
2753 1);
2754 }
2755 else if (type->tp_init != object_init ||
2756 type->tp_new == object_new)
2757 {
2758 PyErr_SetString(PyExc_TypeError,
2759 "object.__init__() takes no parameters");
2760 err = -1;
2761 }
2762 }
2763 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002764}
2765
Guido van Rossum298e4212003-02-13 16:30:16 +00002766static PyObject *
2767object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2768{
Guido van Rossum143b5642007-03-23 04:58:42 +00002769 int err = 0;
2770 if (excess_args(args, kwds)) {
2771 if (type->tp_new != object_new &&
2772 type->tp_init != object_init)
2773 {
2774 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2775 "object.__new__() takes no parameters",
2776 1);
2777 }
2778 else if (type->tp_new != object_new ||
2779 type->tp_init == object_init)
2780 {
2781 PyErr_SetString(PyExc_TypeError,
2782 "object.__new__() takes no parameters");
2783 err = -1;
2784 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002785 }
Guido van Rossum143b5642007-03-23 04:58:42 +00002786 if (err < 0)
2787 return NULL;
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00002788
2789 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2790 static PyObject *comma = NULL;
2791 PyObject *abstract_methods = NULL;
2792 PyObject *builtins;
2793 PyObject *sorted;
2794 PyObject *sorted_methods = NULL;
2795 PyObject *joined = NULL;
2796 const char *joined_str;
2797
2798 /* Compute ", ".join(sorted(type.__abstractmethods__))
2799 into joined. */
2800 abstract_methods = type_abstractmethods(type, NULL);
2801 if (abstract_methods == NULL)
2802 goto error;
2803 builtins = PyEval_GetBuiltins();
2804 if (builtins == NULL)
2805 goto error;
2806 sorted = PyDict_GetItemString(builtins, "sorted");
2807 if (sorted == NULL)
2808 goto error;
2809 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2810 abstract_methods,
2811 NULL);
2812 if (sorted_methods == NULL)
2813 goto error;
2814 if (comma == NULL) {
2815 comma = PyString_InternFromString(", ");
2816 if (comma == NULL)
2817 goto error;
2818 }
2819 joined = PyObject_CallMethod(comma, "join",
2820 "O", sorted_methods);
2821 if (joined == NULL)
2822 goto error;
2823 joined_str = PyString_AsString(joined);
2824 if (joined_str == NULL)
2825 goto error;
2826
2827 PyErr_Format(PyExc_TypeError,
2828 "Can't instantiate abstract class %s "
2829 "with abstract methods %s",
2830 type->tp_name,
2831 joined_str);
2832 error:
2833 Py_XDECREF(joined);
2834 Py_XDECREF(sorted_methods);
2835 Py_XDECREF(abstract_methods);
2836 return NULL;
2837 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002838 return type->tp_alloc(type, 0);
2839}
2840
Tim Peters6d6c1a32001-08-02 04:15:00 +00002841static void
2842object_dealloc(PyObject *self)
2843{
Christian Heimese93237d2007-12-19 02:37:44 +00002844 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002845}
2846
Guido van Rossum8e248182001-08-12 05:17:56 +00002847static PyObject *
2848object_repr(PyObject *self)
2849{
Guido van Rossum76e69632001-08-16 18:52:43 +00002850 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002851 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002852
Christian Heimese93237d2007-12-19 02:37:44 +00002853 type = Py_TYPE(self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002854 mod = type_module(type, NULL);
2855 if (mod == NULL)
2856 PyErr_Clear();
2857 else if (!PyString_Check(mod)) {
2858 Py_DECREF(mod);
2859 mod = NULL;
2860 }
2861 name = type_name(type, NULL);
2862 if (name == NULL)
2863 return NULL;
2864 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002865 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002866 PyString_AS_STRING(mod),
2867 PyString_AS_STRING(name),
2868 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002869 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002870 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002871 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002872 Py_XDECREF(mod);
2873 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002874 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002875}
2876
Guido van Rossumb8f63662001-08-15 23:57:02 +00002877static PyObject *
2878object_str(PyObject *self)
2879{
2880 unaryfunc f;
2881
Christian Heimese93237d2007-12-19 02:37:44 +00002882 f = Py_TYPE(self)->tp_repr;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002883 if (f == NULL)
2884 f = object_repr;
2885 return f(self);
2886}
2887
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002888static PyObject *
2889object_get_class(PyObject *self, void *closure)
2890{
Christian Heimese93237d2007-12-19 02:37:44 +00002891 Py_INCREF(Py_TYPE(self));
2892 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002893}
2894
2895static int
2896equiv_structs(PyTypeObject *a, PyTypeObject *b)
2897{
2898 return a == b ||
2899 (a != NULL &&
2900 b != NULL &&
2901 a->tp_basicsize == b->tp_basicsize &&
2902 a->tp_itemsize == b->tp_itemsize &&
2903 a->tp_dictoffset == b->tp_dictoffset &&
2904 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2905 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2906 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2907}
2908
2909static int
2910same_slots_added(PyTypeObject *a, PyTypeObject *b)
2911{
2912 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002913 Py_ssize_t size;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002914 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002915
2916 if (base != b->tp_base)
2917 return 0;
2918 if (equiv_structs(a, base) && equiv_structs(b, base))
2919 return 1;
2920 size = base->tp_basicsize;
2921 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2922 size += sizeof(PyObject *);
2923 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2924 size += sizeof(PyObject *);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002925
2926 /* Check slots compliance */
2927 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2928 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2929 if (slots_a && slots_b) {
2930 if (PyObject_Compare(slots_a, slots_b) != 0)
2931 return 0;
2932 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2933 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002934 return size == a->tp_basicsize && size == b->tp_basicsize;
2935}
2936
2937static int
Anthony Baxtera6286212006-04-11 07:42:36 +00002938compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002939{
2940 PyTypeObject *newbase, *oldbase;
2941
Anthony Baxtera6286212006-04-11 07:42:36 +00002942 if (newto->tp_dealloc != oldto->tp_dealloc ||
2943 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002944 {
2945 PyErr_Format(PyExc_TypeError,
2946 "%s assignment: "
2947 "'%s' deallocator differs from '%s'",
2948 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002949 newto->tp_name,
2950 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002951 return 0;
2952 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002953 newbase = newto;
2954 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002955 while (equiv_structs(newbase, newbase->tp_base))
2956 newbase = newbase->tp_base;
2957 while (equiv_structs(oldbase, oldbase->tp_base))
2958 oldbase = oldbase->tp_base;
2959 if (newbase != oldbase &&
2960 (newbase->tp_base != oldbase->tp_base ||
2961 !same_slots_added(newbase, oldbase))) {
2962 PyErr_Format(PyExc_TypeError,
2963 "%s assignment: "
2964 "'%s' object layout differs from '%s'",
2965 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002966 newto->tp_name,
2967 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002968 return 0;
2969 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002970
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002971 return 1;
2972}
2973
2974static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002975object_set_class(PyObject *self, PyObject *value, void *closure)
2976{
Christian Heimese93237d2007-12-19 02:37:44 +00002977 PyTypeObject *oldto = Py_TYPE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00002978 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002979
Guido van Rossumb6b89422002-04-15 01:03:30 +00002980 if (value == NULL) {
2981 PyErr_SetString(PyExc_TypeError,
2982 "can't delete __class__ attribute");
2983 return -1;
2984 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002985 if (!PyType_Check(value)) {
2986 PyErr_Format(PyExc_TypeError,
2987 "__class__ must be set to new-style class, not '%s' object",
Christian Heimese93237d2007-12-19 02:37:44 +00002988 Py_TYPE(value)->tp_name);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002989 return -1;
2990 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002991 newto = (PyTypeObject *)value;
2992 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2993 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002994 {
2995 PyErr_Format(PyExc_TypeError,
2996 "__class__ assignment: only for heap types");
2997 return -1;
2998 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002999 if (compatible_for_assignment(newto, oldto, "__class__")) {
3000 Py_INCREF(newto);
Christian Heimese93237d2007-12-19 02:37:44 +00003001 Py_TYPE(self) = newto;
Anthony Baxtera6286212006-04-11 07:42:36 +00003002 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003003 return 0;
3004 }
3005 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00003006 return -1;
3007 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003008}
3009
3010static PyGetSetDef object_getsets[] = {
3011 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00003012 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003013 {0}
3014};
3015
Guido van Rossumc53f0092003-02-18 22:05:12 +00003016
Guido van Rossum036f9992003-02-21 22:02:54 +00003017/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
3018 We fall back to helpers in copy_reg for:
3019 - pickle protocols < 2
3020 - calculating the list of slot names (done only once per class)
3021 - the __newobj__ function (which is used as a token but never called)
3022*/
3023
3024static PyObject *
3025import_copy_reg(void)
3026{
3027 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00003028
3029 if (!copy_reg_str) {
3030 copy_reg_str = PyString_InternFromString("copy_reg");
3031 if (copy_reg_str == NULL)
3032 return NULL;
3033 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003034
3035 return PyImport_Import(copy_reg_str);
3036}
3037
3038static PyObject *
3039slotnames(PyObject *cls)
3040{
3041 PyObject *clsdict;
3042 PyObject *copy_reg;
3043 PyObject *slotnames;
3044
3045 if (!PyType_Check(cls)) {
3046 Py_INCREF(Py_None);
3047 return Py_None;
3048 }
3049
3050 clsdict = ((PyTypeObject *)cls)->tp_dict;
3051 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00003052 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00003053 Py_INCREF(slotnames);
3054 return slotnames;
3055 }
3056
3057 copy_reg = import_copy_reg();
3058 if (copy_reg == NULL)
3059 return NULL;
3060
3061 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
3062 Py_DECREF(copy_reg);
3063 if (slotnames != NULL &&
3064 slotnames != Py_None &&
3065 !PyList_Check(slotnames))
3066 {
3067 PyErr_SetString(PyExc_TypeError,
3068 "copy_reg._slotnames didn't return a list or None");
3069 Py_DECREF(slotnames);
3070 slotnames = NULL;
3071 }
3072
3073 return slotnames;
3074}
3075
3076static PyObject *
3077reduce_2(PyObject *obj)
3078{
3079 PyObject *cls, *getnewargs;
3080 PyObject *args = NULL, *args2 = NULL;
3081 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3082 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3083 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003084 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00003085
3086 cls = PyObject_GetAttrString(obj, "__class__");
3087 if (cls == NULL)
3088 return NULL;
3089
3090 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
3091 if (getnewargs != NULL) {
3092 args = PyObject_CallObject(getnewargs, NULL);
3093 Py_DECREF(getnewargs);
3094 if (args != NULL && !PyTuple_Check(args)) {
Georg Brandlccff7852006-06-18 22:17:29 +00003095 PyErr_Format(PyExc_TypeError,
3096 "__getnewargs__ should return a tuple, "
Christian Heimese93237d2007-12-19 02:37:44 +00003097 "not '%.200s'", Py_TYPE(args)->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00003098 goto end;
3099 }
3100 }
3101 else {
3102 PyErr_Clear();
3103 args = PyTuple_New(0);
3104 }
3105 if (args == NULL)
3106 goto end;
3107
3108 getstate = PyObject_GetAttrString(obj, "__getstate__");
3109 if (getstate != NULL) {
3110 state = PyObject_CallObject(getstate, NULL);
3111 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00003112 if (state == NULL)
3113 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003114 }
3115 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00003116 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00003117 state = PyObject_GetAttrString(obj, "__dict__");
3118 if (state == NULL) {
3119 PyErr_Clear();
3120 state = Py_None;
3121 Py_INCREF(state);
3122 }
3123 names = slotnames(cls);
3124 if (names == NULL)
3125 goto end;
3126 if (names != Py_None) {
3127 assert(PyList_Check(names));
3128 slots = PyDict_New();
3129 if (slots == NULL)
3130 goto end;
3131 n = 0;
3132 /* Can't pre-compute the list size; the list
3133 is stored on the class so accessible to other
3134 threads, which may be run by DECREF */
3135 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3136 PyObject *name, *value;
3137 name = PyList_GET_ITEM(names, i);
3138 value = PyObject_GetAttr(obj, name);
3139 if (value == NULL)
3140 PyErr_Clear();
3141 else {
3142 int err = PyDict_SetItem(slots, name,
3143 value);
3144 Py_DECREF(value);
3145 if (err)
3146 goto end;
3147 n++;
3148 }
3149 }
3150 if (n) {
3151 state = Py_BuildValue("(NO)", state, slots);
3152 if (state == NULL)
3153 goto end;
3154 }
3155 }
3156 }
3157
3158 if (!PyList_Check(obj)) {
3159 listitems = Py_None;
3160 Py_INCREF(listitems);
3161 }
3162 else {
3163 listitems = PyObject_GetIter(obj);
3164 if (listitems == NULL)
3165 goto end;
3166 }
3167
3168 if (!PyDict_Check(obj)) {
3169 dictitems = Py_None;
3170 Py_INCREF(dictitems);
3171 }
3172 else {
3173 dictitems = PyObject_CallMethod(obj, "iteritems", "");
3174 if (dictitems == NULL)
3175 goto end;
3176 }
3177
3178 copy_reg = import_copy_reg();
3179 if (copy_reg == NULL)
3180 goto end;
3181 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
3182 if (newobj == NULL)
3183 goto end;
3184
3185 n = PyTuple_GET_SIZE(args);
3186 args2 = PyTuple_New(n+1);
3187 if (args2 == NULL)
3188 goto end;
3189 PyTuple_SET_ITEM(args2, 0, cls);
3190 cls = NULL;
3191 for (i = 0; i < n; i++) {
3192 PyObject *v = PyTuple_GET_ITEM(args, i);
3193 Py_INCREF(v);
3194 PyTuple_SET_ITEM(args2, i+1, v);
3195 }
3196
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003197 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003198
3199 end:
3200 Py_XDECREF(cls);
3201 Py_XDECREF(args);
3202 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00003203 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00003204 Py_XDECREF(state);
3205 Py_XDECREF(names);
3206 Py_XDECREF(listitems);
3207 Py_XDECREF(dictitems);
3208 Py_XDECREF(copy_reg);
3209 Py_XDECREF(newobj);
3210 return res;
3211}
3212
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003213/*
3214 * There were two problems when object.__reduce__ and object.__reduce_ex__
3215 * were implemented in the same function:
3216 * - trying to pickle an object with a custom __reduce__ method that
3217 * fell back to object.__reduce__ in certain circumstances led to
3218 * infinite recursion at Python level and eventual RuntimeError.
3219 * - Pickling objects that lied about their type by overwriting the
3220 * __class__ descriptor could lead to infinite recursion at C level
3221 * and eventual segfault.
3222 *
3223 * Because of backwards compatibility, the two methods still have to
3224 * behave in the same way, even if this is not required by the pickle
3225 * protocol. This common functionality was moved to the _common_reduce
3226 * function.
3227 */
3228static PyObject *
3229_common_reduce(PyObject *self, int proto)
3230{
3231 PyObject *copy_reg, *res;
3232
3233 if (proto >= 2)
3234 return reduce_2(self);
3235
3236 copy_reg = import_copy_reg();
3237 if (!copy_reg)
3238 return NULL;
3239
3240 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
3241 Py_DECREF(copy_reg);
3242
3243 return res;
3244}
3245
3246static PyObject *
3247object_reduce(PyObject *self, PyObject *args)
3248{
3249 int proto = 0;
3250
3251 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3252 return NULL;
3253
3254 return _common_reduce(self, proto);
3255}
3256
Guido van Rossum036f9992003-02-21 22:02:54 +00003257static PyObject *
3258object_reduce_ex(PyObject *self, PyObject *args)
3259{
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003260 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003261 int proto = 0;
3262
3263 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3264 return NULL;
3265
3266 reduce = PyObject_GetAttrString(self, "__reduce__");
3267 if (reduce == NULL)
3268 PyErr_Clear();
3269 else {
3270 PyObject *cls, *clsreduce, *objreduce;
3271 int override;
3272 cls = PyObject_GetAttrString(self, "__class__");
3273 if (cls == NULL) {
3274 Py_DECREF(reduce);
3275 return NULL;
3276 }
3277 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3278 Py_DECREF(cls);
3279 if (clsreduce == NULL) {
3280 Py_DECREF(reduce);
3281 return NULL;
3282 }
3283 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3284 "__reduce__");
3285 override = (clsreduce != objreduce);
3286 Py_DECREF(clsreduce);
3287 if (override) {
3288 res = PyObject_CallObject(reduce, NULL);
3289 Py_DECREF(reduce);
3290 return res;
3291 }
3292 else
3293 Py_DECREF(reduce);
3294 }
3295
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003296 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003297}
3298
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00003299static PyObject *
3300object_subclasshook(PyObject *cls, PyObject *args)
3301{
3302 Py_INCREF(Py_NotImplemented);
3303 return Py_NotImplemented;
3304}
3305
3306PyDoc_STRVAR(object_subclasshook_doc,
3307"Abstract classes can override this to customize issubclass().\n"
3308"\n"
3309"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3310"It should return True, False or NotImplemented. If it returns\n"
3311"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3312"overrides the normal algorithm (and the outcome is cached).\n");
3313
Eric Smitha9f7d622008-02-17 19:46:49 +00003314/*
3315 from PEP 3101, this code implements:
3316
3317 class object:
3318 def __format__(self, format_spec):
3319 if isinstance(format_spec, str):
3320 return format(str(self), format_spec)
3321 elif isinstance(format_spec, unicode):
3322 return format(unicode(self), format_spec)
3323*/
3324static PyObject *
3325object_format(PyObject *self, PyObject *args)
3326{
3327 PyObject *format_spec;
3328 PyObject *self_as_str = NULL;
3329 PyObject *result = NULL;
3330 PyObject *format_meth = NULL;
3331
3332 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3333 return NULL;
3334 if (PyUnicode_Check(format_spec)) {
3335 self_as_str = PyObject_Unicode(self);
3336 } else if (PyString_Check(format_spec)) {
3337 self_as_str = PyObject_Str(self);
3338 } else {
3339 PyErr_SetString(PyExc_TypeError, "argument to __format__ must be unicode or str");
3340 return NULL;
3341 }
3342
3343 if (self_as_str != NULL) {
3344 /* find the format function */
3345 format_meth = PyObject_GetAttrString(self_as_str, "__format__");
3346 if (format_meth != NULL) {
3347 /* and call it */
3348 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
3349 }
3350 }
3351
3352 Py_XDECREF(self_as_str);
3353 Py_XDECREF(format_meth);
3354
3355 return result;
3356}
3357
Guido van Rossum3926a632001-09-25 16:25:58 +00003358static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00003359 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3360 PyDoc_STR("helper for pickle")},
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003361 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003362 PyDoc_STR("helper for pickle")},
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00003363 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3364 object_subclasshook_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00003365 {"__format__", object_format, METH_VARARGS,
3366 PyDoc_STR("default object formatter")},
Guido van Rossum3926a632001-09-25 16:25:58 +00003367 {0}
3368};
3369
Guido van Rossum036f9992003-02-21 22:02:54 +00003370
Tim Peters6d6c1a32001-08-02 04:15:00 +00003371PyTypeObject PyBaseObject_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00003372 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003373 "object", /* tp_name */
3374 sizeof(PyObject), /* tp_basicsize */
3375 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003376 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003377 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003378 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003379 0, /* tp_setattr */
3380 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003381 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003382 0, /* tp_as_number */
3383 0, /* tp_as_sequence */
3384 0, /* tp_as_mapping */
Guido van Rossum64c06e32007-11-22 00:55:51 +00003385 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003386 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003387 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003388 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003389 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003390 0, /* tp_as_buffer */
3391 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003392 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003393 0, /* tp_traverse */
3394 0, /* tp_clear */
3395 0, /* tp_richcompare */
3396 0, /* tp_weaklistoffset */
3397 0, /* tp_iter */
3398 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00003399 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003400 0, /* tp_members */
3401 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003402 0, /* tp_base */
3403 0, /* tp_dict */
3404 0, /* tp_descr_get */
3405 0, /* tp_descr_set */
3406 0, /* tp_dictoffset */
3407 object_init, /* tp_init */
3408 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003409 object_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003410 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003411};
3412
3413
3414/* Initialize the __dict__ in a type object */
3415
3416static int
3417add_methods(PyTypeObject *type, PyMethodDef *meth)
3418{
Guido van Rossum687ae002001-10-15 22:03:32 +00003419 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003420
3421 for (; meth->ml_name != NULL; meth++) {
3422 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003423 if (PyDict_GetItemString(dict, meth->ml_name) &&
3424 !(meth->ml_flags & METH_COEXIST))
3425 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003426 if (meth->ml_flags & METH_CLASS) {
3427 if (meth->ml_flags & METH_STATIC) {
3428 PyErr_SetString(PyExc_ValueError,
3429 "method cannot be both class and static");
3430 return -1;
3431 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003432 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003433 }
3434 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003435 PyObject *cfunc = PyCFunction_New(meth, NULL);
3436 if (cfunc == NULL)
3437 return -1;
3438 descr = PyStaticMethod_New(cfunc);
3439 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003440 }
3441 else {
3442 descr = PyDescr_NewMethod(type, meth);
3443 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003444 if (descr == NULL)
3445 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003446 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003447 return -1;
3448 Py_DECREF(descr);
3449 }
3450 return 0;
3451}
3452
3453static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003454add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003455{
Guido van Rossum687ae002001-10-15 22:03:32 +00003456 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003457
3458 for (; memb->name != NULL; memb++) {
3459 PyObject *descr;
3460 if (PyDict_GetItemString(dict, memb->name))
3461 continue;
3462 descr = PyDescr_NewMember(type, memb);
3463 if (descr == NULL)
3464 return -1;
3465 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3466 return -1;
3467 Py_DECREF(descr);
3468 }
3469 return 0;
3470}
3471
3472static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003473add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003474{
Guido van Rossum687ae002001-10-15 22:03:32 +00003475 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003476
3477 for (; gsp->name != NULL; gsp++) {
3478 PyObject *descr;
3479 if (PyDict_GetItemString(dict, gsp->name))
3480 continue;
3481 descr = PyDescr_NewGetSet(type, gsp);
3482
3483 if (descr == NULL)
3484 return -1;
3485 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3486 return -1;
3487 Py_DECREF(descr);
3488 }
3489 return 0;
3490}
3491
Guido van Rossum13d52f02001-08-10 21:24:08 +00003492static void
3493inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003494{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003495 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003496
Guido van Rossum13d52f02001-08-10 21:24:08 +00003497 /* Special flag magic */
3498 if (!type->tp_as_buffer && base->tp_as_buffer) {
3499 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
3500 type->tp_flags |=
3501 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
3502 }
3503 if (!type->tp_as_sequence && base->tp_as_sequence) {
3504 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3505 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3506 }
3507 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3508 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3509 if ((!type->tp_as_number && base->tp_as_number) ||
3510 (!type->tp_as_sequence && base->tp_as_sequence)) {
3511 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3512 if (!type->tp_as_number && !type->tp_as_sequence) {
3513 type->tp_flags |= base->tp_flags &
3514 Py_TPFLAGS_HAVE_INPLACEOPS;
3515 }
3516 }
3517 /* Wow */
3518 }
3519 if (!type->tp_as_number && base->tp_as_number) {
3520 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3521 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3522 }
3523
3524 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003525 oldsize = base->tp_basicsize;
3526 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3527 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3528 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003529 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3530 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003531 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003532 if (type->tp_traverse == NULL)
3533 type->tp_traverse = base->tp_traverse;
3534 if (type->tp_clear == NULL)
3535 type->tp_clear = base->tp_clear;
3536 }
3537 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00003538 /* The condition below could use some explanation.
3539 It appears that tp_new is not inherited for static types
3540 whose base class is 'object'; this seems to be a precaution
3541 so that old extension types don't suddenly become
3542 callable (object.__new__ wouldn't insure the invariants
3543 that the extension type's own factory function ensures).
3544 Heap types, of course, are under our control, so they do
3545 inherit tp_new; static extension types that specify some
3546 other built-in type as the default are considered
3547 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003548 if (base != &PyBaseObject_Type ||
3549 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3550 if (type->tp_new == NULL)
3551 type->tp_new = base->tp_new;
3552 }
3553 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003554 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003555
3556 /* Copy other non-function slots */
3557
3558#undef COPYVAL
3559#define COPYVAL(SLOT) \
3560 if (type->SLOT == 0) type->SLOT = base->SLOT
3561
3562 COPYVAL(tp_itemsize);
3563 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3564 COPYVAL(tp_weaklistoffset);
3565 }
3566 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3567 COPYVAL(tp_dictoffset);
3568 }
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003569
3570 /* Setup fast subclass flags */
3571 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3572 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3573 else if (PyType_IsSubtype(base, &PyType_Type))
3574 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3575 else if (PyType_IsSubtype(base, &PyInt_Type))
3576 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3577 else if (PyType_IsSubtype(base, &PyLong_Type))
3578 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3579 else if (PyType_IsSubtype(base, &PyString_Type))
3580 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003581#ifdef Py_USING_UNICODE
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003582 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3583 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003584#endif
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003585 else if (PyType_IsSubtype(base, &PyTuple_Type))
3586 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3587 else if (PyType_IsSubtype(base, &PyList_Type))
3588 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3589 else if (PyType_IsSubtype(base, &PyDict_Type))
3590 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003591}
3592
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003593static char *hash_name_op[] = {
3594 "__eq__",
3595 "__cmp__",
3596 "__hash__",
3597 NULL
Guido van Rossum64c06e32007-11-22 00:55:51 +00003598};
3599
3600static int
3601overrides_hash(PyTypeObject *type)
3602{
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003603 char **p;
Guido van Rossum64c06e32007-11-22 00:55:51 +00003604 PyObject *dict = type->tp_dict;
3605
3606 assert(dict != NULL);
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003607 for (p = hash_name_op; *p; p++) {
3608 if (PyDict_GetItemString(dict, *p) != NULL)
Guido van Rossum64c06e32007-11-22 00:55:51 +00003609 return 1;
3610 }
3611 return 0;
3612}
3613
Guido van Rossum13d52f02001-08-10 21:24:08 +00003614static void
3615inherit_slots(PyTypeObject *type, PyTypeObject *base)
3616{
3617 PyTypeObject *basebase;
3618
3619#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003620#undef COPYSLOT
3621#undef COPYNUM
3622#undef COPYSEQ
3623#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003624#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003625
3626#define SLOTDEFINED(SLOT) \
3627 (base->SLOT != 0 && \
3628 (basebase == NULL || base->SLOT != basebase->SLOT))
3629
Tim Peters6d6c1a32001-08-02 04:15:00 +00003630#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003631 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003632
3633#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3634#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3635#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003636#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003637
Guido van Rossum13d52f02001-08-10 21:24:08 +00003638 /* This won't inherit indirect slots (from tp_as_number etc.)
3639 if type doesn't provide the space. */
3640
3641 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3642 basebase = base->tp_base;
3643 if (basebase->tp_as_number == NULL)
3644 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003645 COPYNUM(nb_add);
3646 COPYNUM(nb_subtract);
3647 COPYNUM(nb_multiply);
3648 COPYNUM(nb_divide);
3649 COPYNUM(nb_remainder);
3650 COPYNUM(nb_divmod);
3651 COPYNUM(nb_power);
3652 COPYNUM(nb_negative);
3653 COPYNUM(nb_positive);
3654 COPYNUM(nb_absolute);
3655 COPYNUM(nb_nonzero);
3656 COPYNUM(nb_invert);
3657 COPYNUM(nb_lshift);
3658 COPYNUM(nb_rshift);
3659 COPYNUM(nb_and);
3660 COPYNUM(nb_xor);
3661 COPYNUM(nb_or);
3662 COPYNUM(nb_coerce);
3663 COPYNUM(nb_int);
3664 COPYNUM(nb_long);
3665 COPYNUM(nb_float);
3666 COPYNUM(nb_oct);
3667 COPYNUM(nb_hex);
3668 COPYNUM(nb_inplace_add);
3669 COPYNUM(nb_inplace_subtract);
3670 COPYNUM(nb_inplace_multiply);
3671 COPYNUM(nb_inplace_divide);
3672 COPYNUM(nb_inplace_remainder);
3673 COPYNUM(nb_inplace_power);
3674 COPYNUM(nb_inplace_lshift);
3675 COPYNUM(nb_inplace_rshift);
3676 COPYNUM(nb_inplace_and);
3677 COPYNUM(nb_inplace_xor);
3678 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003679 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3680 COPYNUM(nb_true_divide);
3681 COPYNUM(nb_floor_divide);
3682 COPYNUM(nb_inplace_true_divide);
3683 COPYNUM(nb_inplace_floor_divide);
3684 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003685 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3686 COPYNUM(nb_index);
3687 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003688 }
3689
Guido van Rossum13d52f02001-08-10 21:24:08 +00003690 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3691 basebase = base->tp_base;
3692 if (basebase->tp_as_sequence == NULL)
3693 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003694 COPYSEQ(sq_length);
3695 COPYSEQ(sq_concat);
3696 COPYSEQ(sq_repeat);
3697 COPYSEQ(sq_item);
3698 COPYSEQ(sq_slice);
3699 COPYSEQ(sq_ass_item);
3700 COPYSEQ(sq_ass_slice);
3701 COPYSEQ(sq_contains);
3702 COPYSEQ(sq_inplace_concat);
3703 COPYSEQ(sq_inplace_repeat);
3704 }
3705
Guido van Rossum13d52f02001-08-10 21:24:08 +00003706 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3707 basebase = base->tp_base;
3708 if (basebase->tp_as_mapping == NULL)
3709 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003710 COPYMAP(mp_length);
3711 COPYMAP(mp_subscript);
3712 COPYMAP(mp_ass_subscript);
3713 }
3714
Tim Petersfc57ccb2001-10-12 02:38:24 +00003715 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3716 basebase = base->tp_base;
3717 if (basebase->tp_as_buffer == NULL)
3718 basebase = NULL;
3719 COPYBUF(bf_getreadbuffer);
3720 COPYBUF(bf_getwritebuffer);
3721 COPYBUF(bf_getsegcount);
3722 COPYBUF(bf_getcharbuffer);
3723 }
3724
Guido van Rossum13d52f02001-08-10 21:24:08 +00003725 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003726
Tim Peters6d6c1a32001-08-02 04:15:00 +00003727 COPYSLOT(tp_dealloc);
3728 COPYSLOT(tp_print);
3729 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3730 type->tp_getattr = base->tp_getattr;
3731 type->tp_getattro = base->tp_getattro;
3732 }
3733 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3734 type->tp_setattr = base->tp_setattr;
3735 type->tp_setattro = base->tp_setattro;
3736 }
3737 /* tp_compare see tp_richcompare */
3738 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003739 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003740 COPYSLOT(tp_call);
3741 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003742 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003743 if (type->tp_compare == NULL &&
3744 type->tp_richcompare == NULL &&
Guido van Rossum64c06e32007-11-22 00:55:51 +00003745 type->tp_hash == NULL &&
3746 !overrides_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003747 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003748 type->tp_compare = base->tp_compare;
3749 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003750 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003751 }
3752 }
3753 else {
3754 COPYSLOT(tp_compare);
3755 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003756 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3757 COPYSLOT(tp_iter);
3758 COPYSLOT(tp_iternext);
3759 }
3760 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3761 COPYSLOT(tp_descr_get);
3762 COPYSLOT(tp_descr_set);
3763 COPYSLOT(tp_dictoffset);
3764 COPYSLOT(tp_init);
3765 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003766 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003767 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3768 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3769 /* They agree about gc. */
3770 COPYSLOT(tp_free);
3771 }
3772 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3773 type->tp_free == NULL &&
3774 base->tp_free == _PyObject_Del) {
3775 /* A bit of magic to plug in the correct default
3776 * tp_free function when a derived class adds gc,
3777 * didn't define tp_free, and the base uses the
3778 * default non-gc tp_free.
3779 */
3780 type->tp_free = PyObject_GC_Del;
3781 }
3782 /* else they didn't agree about gc, and there isn't something
3783 * obvious to be done -- the type is on its own.
3784 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003785 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003786}
3787
Jeremy Hylton938ace62002-07-17 16:30:39 +00003788static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003789
Tim Peters6d6c1a32001-08-02 04:15:00 +00003790int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003791PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003792{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003793 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003794 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003795 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003796
Guido van Rossumcab05802002-06-10 15:29:03 +00003797 if (type->tp_flags & Py_TPFLAGS_READY) {
3798 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003799 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003800 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003801 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003802
3803 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003804
Tim Peters36eb4df2003-03-23 03:33:13 +00003805#ifdef Py_TRACE_REFS
3806 /* PyType_Ready is the closest thing we have to a choke point
3807 * for type objects, so is the best place I can think of to try
3808 * to get type objects into the doubly-linked list of all objects.
3809 * Still, not all type objects go thru PyType_Ready.
3810 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003811 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003812#endif
3813
Tim Peters6d6c1a32001-08-02 04:15:00 +00003814 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3815 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003816 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003817 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003818 Py_INCREF(base);
3819 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003820
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003821 /* Now the only way base can still be NULL is if type is
3822 * &PyBaseObject_Type.
3823 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003824
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003825 /* Initialize the base class */
3826 if (base && base->tp_dict == NULL) {
3827 if (PyType_Ready(base) < 0)
3828 goto error;
3829 }
3830
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003831 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003832 compilable separately on Windows can call PyType_Ready() instead of
3833 initializing the ob_type field of their type objects. */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003834 /* The test for base != NULL is really unnecessary, since base is only
3835 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3836 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3837 know that. */
Christian Heimese93237d2007-12-19 02:37:44 +00003838 if (Py_TYPE(type) == NULL && base != NULL)
3839 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003840
Tim Peters6d6c1a32001-08-02 04:15:00 +00003841 /* Initialize tp_bases */
3842 bases = type->tp_bases;
3843 if (bases == NULL) {
3844 if (base == NULL)
3845 bases = PyTuple_New(0);
3846 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003847 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003848 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003849 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003850 type->tp_bases = bases;
3851 }
3852
Guido van Rossum687ae002001-10-15 22:03:32 +00003853 /* Initialize tp_dict */
3854 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003855 if (dict == NULL) {
3856 dict = PyDict_New();
3857 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003858 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003859 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003860 }
3861
Guido van Rossum687ae002001-10-15 22:03:32 +00003862 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003863 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003864 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003865 if (type->tp_methods != NULL) {
3866 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003867 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003868 }
3869 if (type->tp_members != NULL) {
3870 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003871 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003872 }
3873 if (type->tp_getset != NULL) {
3874 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003875 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003876 }
3877
Tim Peters6d6c1a32001-08-02 04:15:00 +00003878 /* Calculate method resolution order */
3879 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003880 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003881 }
3882
Guido van Rossum13d52f02001-08-10 21:24:08 +00003883 /* Inherit special flags from dominant base */
3884 if (type->tp_base != NULL)
3885 inherit_special(type, type->tp_base);
3886
Tim Peters6d6c1a32001-08-02 04:15:00 +00003887 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003888 bases = type->tp_mro;
3889 assert(bases != NULL);
3890 assert(PyTuple_Check(bases));
3891 n = PyTuple_GET_SIZE(bases);
3892 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003893 PyObject *b = PyTuple_GET_ITEM(bases, i);
3894 if (PyType_Check(b))
3895 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003896 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003897
Tim Peters3cfe7542003-05-21 21:29:48 +00003898 /* Sanity check for tp_free. */
3899 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3900 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003901 /* This base class needs to call tp_free, but doesn't have
3902 * one, or its tp_free is for non-gc'ed objects.
3903 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003904 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3905 "gc and is a base type but has inappropriate "
3906 "tp_free slot",
3907 type->tp_name);
3908 goto error;
3909 }
3910
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003911 /* if the type dictionary doesn't contain a __doc__, set it from
3912 the tp_doc slot.
3913 */
3914 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3915 if (type->tp_doc != NULL) {
3916 PyObject *doc = PyString_FromString(type->tp_doc);
Neal Norwitze1fdb322006-07-21 05:32:28 +00003917 if (doc == NULL)
3918 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003919 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3920 Py_DECREF(doc);
3921 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003922 PyDict_SetItemString(type->tp_dict,
3923 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003924 }
3925 }
3926
Guido van Rossum64c06e32007-11-22 00:55:51 +00003927 /* Hack for tp_hash and __hash__.
3928 If after all that, tp_hash is still NULL, and __hash__ is not in
3929 tp_dict, set tp_dict['__hash__'] equal to None.
3930 This signals that __hash__ is not inherited.
3931 */
3932 if (type->tp_hash == NULL &&
3933 PyDict_GetItemString(type->tp_dict, "__hash__") == NULL &&
3934 PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3935 {
3936 goto error;
3937 }
3938
Guido van Rossum13d52f02001-08-10 21:24:08 +00003939 /* Some more special stuff */
3940 base = type->tp_base;
3941 if (base != NULL) {
3942 if (type->tp_as_number == NULL)
3943 type->tp_as_number = base->tp_as_number;
3944 if (type->tp_as_sequence == NULL)
3945 type->tp_as_sequence = base->tp_as_sequence;
3946 if (type->tp_as_mapping == NULL)
3947 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003948 if (type->tp_as_buffer == NULL)
3949 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003950 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003951
Guido van Rossum1c450732001-10-08 15:18:27 +00003952 /* Link into each base class's list of subclasses */
3953 bases = type->tp_bases;
3954 n = PyTuple_GET_SIZE(bases);
3955 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003956 PyObject *b = PyTuple_GET_ITEM(bases, i);
3957 if (PyType_Check(b) &&
3958 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003959 goto error;
3960 }
3961
Guido van Rossum13d52f02001-08-10 21:24:08 +00003962 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003963 assert(type->tp_dict != NULL);
3964 type->tp_flags =
3965 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003966 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003967
3968 error:
3969 type->tp_flags &= ~Py_TPFLAGS_READYING;
3970 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003971}
3972
Guido van Rossum1c450732001-10-08 15:18:27 +00003973static int
3974add_subclass(PyTypeObject *base, PyTypeObject *type)
3975{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003976 Py_ssize_t i;
3977 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00003978 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003979
3980 list = base->tp_subclasses;
3981 if (list == NULL) {
3982 base->tp_subclasses = list = PyList_New(0);
3983 if (list == NULL)
3984 return -1;
3985 }
3986 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00003987 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003988 i = PyList_GET_SIZE(list);
3989 while (--i >= 0) {
3990 ref = PyList_GET_ITEM(list, i);
3991 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003992 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00003993 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003994 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003995 result = PyList_Append(list, newobj);
3996 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003997 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003998}
3999
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004000static void
4001remove_subclass(PyTypeObject *base, PyTypeObject *type)
4002{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004003 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004004 PyObject *list, *ref;
4005
4006 list = base->tp_subclasses;
4007 if (list == NULL) {
4008 return;
4009 }
4010 assert(PyList_Check(list));
4011 i = PyList_GET_SIZE(list);
4012 while (--i >= 0) {
4013 ref = PyList_GET_ITEM(list, i);
4014 assert(PyWeakref_CheckRef(ref));
4015 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4016 /* this can't fail, right? */
4017 PySequence_DelItem(list, i);
4018 return;
4019 }
4020 }
4021}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004022
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004023static int
4024check_num_args(PyObject *ob, int n)
4025{
4026 if (!PyTuple_CheckExact(ob)) {
4027 PyErr_SetString(PyExc_SystemError,
4028 "PyArg_UnpackTuple() argument list is not a tuple");
4029 return 0;
4030 }
4031 if (n == PyTuple_GET_SIZE(ob))
4032 return 1;
4033 PyErr_Format(
4034 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00004035 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004036 return 0;
4037}
4038
Tim Peters6d6c1a32001-08-02 04:15:00 +00004039/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4040
4041/* There's a wrapper *function* for each distinct function typedef used
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004042 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004043 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4044 Most tables have only one entry; the tables for binary operators have two
4045 entries, one regular and one with reversed arguments. */
4046
4047static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004048wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004049{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004050 lenfunc func = (lenfunc)wrapped;
4051 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004052
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004053 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004054 return NULL;
4055 res = (*func)(self);
4056 if (res == -1 && PyErr_Occurred())
4057 return NULL;
4058 return PyInt_FromLong((long)res);
4059}
4060
Tim Peters6d6c1a32001-08-02 04:15:00 +00004061static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004062wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4063{
4064 inquiry func = (inquiry)wrapped;
4065 int res;
4066
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004067 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004068 return NULL;
4069 res = (*func)(self);
4070 if (res == -1 && PyErr_Occurred())
4071 return NULL;
4072 return PyBool_FromLong((long)res);
4073}
4074
4075static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004076wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4077{
4078 binaryfunc func = (binaryfunc)wrapped;
4079 PyObject *other;
4080
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004081 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004082 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004083 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004084 return (*func)(self, other);
4085}
4086
4087static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004088wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4089{
4090 binaryfunc func = (binaryfunc)wrapped;
4091 PyObject *other;
4092
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004093 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004094 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004095 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004096 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004097 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004098 Py_INCREF(Py_NotImplemented);
4099 return Py_NotImplemented;
4100 }
4101 return (*func)(self, other);
4102}
4103
4104static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004105wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4106{
4107 binaryfunc func = (binaryfunc)wrapped;
4108 PyObject *other;
4109
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004110 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004111 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004112 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004113 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004114 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004115 Py_INCREF(Py_NotImplemented);
4116 return Py_NotImplemented;
4117 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004118 return (*func)(other, self);
4119}
4120
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004121static PyObject *
4122wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
4123{
4124 coercion func = (coercion)wrapped;
4125 PyObject *other, *res;
4126 int ok;
4127
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004128 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004129 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004130 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004131 ok = func(&self, &other);
4132 if (ok < 0)
4133 return NULL;
4134 if (ok > 0) {
4135 Py_INCREF(Py_NotImplemented);
4136 return Py_NotImplemented;
4137 }
4138 res = PyTuple_New(2);
4139 if (res == NULL) {
4140 Py_DECREF(self);
4141 Py_DECREF(other);
4142 return NULL;
4143 }
4144 PyTuple_SET_ITEM(res, 0, self);
4145 PyTuple_SET_ITEM(res, 1, other);
4146 return res;
4147}
4148
Tim Peters6d6c1a32001-08-02 04:15:00 +00004149static PyObject *
4150wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4151{
4152 ternaryfunc func = (ternaryfunc)wrapped;
4153 PyObject *other;
4154 PyObject *third = Py_None;
4155
4156 /* Note: This wrapper only works for __pow__() */
4157
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004158 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004159 return NULL;
4160 return (*func)(self, other, third);
4161}
4162
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004163static PyObject *
4164wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4165{
4166 ternaryfunc func = (ternaryfunc)wrapped;
4167 PyObject *other;
4168 PyObject *third = Py_None;
4169
4170 /* Note: This wrapper only works for __pow__() */
4171
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004172 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004173 return NULL;
4174 return (*func)(other, self, third);
4175}
4176
Tim Peters6d6c1a32001-08-02 04:15:00 +00004177static PyObject *
4178wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4179{
4180 unaryfunc func = (unaryfunc)wrapped;
4181
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004182 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004183 return NULL;
4184 return (*func)(self);
4185}
4186
Tim Peters6d6c1a32001-08-02 04:15:00 +00004187static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00004188wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004189{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004190 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00004191 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004192 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004193
Armin Rigo314861c2006-03-30 14:04:02 +00004194 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4195 return NULL;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004196 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Armin Rigo314861c2006-03-30 14:04:02 +00004197 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004198 return NULL;
4199 return (*func)(self, i);
4200}
4201
Martin v. Löwis18e16552006-02-15 17:27:45 +00004202static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004203getindex(PyObject *self, PyObject *arg)
4204{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004205 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004206
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004207 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004208 if (i == -1 && PyErr_Occurred())
4209 return -1;
4210 if (i < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00004211 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004212 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00004213 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004214 if (n < 0)
4215 return -1;
4216 i += n;
4217 }
4218 }
4219 return i;
4220}
4221
4222static PyObject *
4223wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4224{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004225 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004226 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004227 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004228
Guido van Rossumf4593e02001-10-03 12:09:30 +00004229 if (PyTuple_GET_SIZE(args) == 1) {
4230 arg = PyTuple_GET_ITEM(args, 0);
4231 i = getindex(self, arg);
4232 if (i == -1 && PyErr_Occurred())
4233 return NULL;
4234 return (*func)(self, i);
4235 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004236 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004237 assert(PyErr_Occurred());
4238 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004239}
4240
Tim Peters6d6c1a32001-08-02 04:15:00 +00004241static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004242wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004243{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004244 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
4245 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004246
Martin v. Löwis18e16552006-02-15 17:27:45 +00004247 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004248 return NULL;
4249 return (*func)(self, i, j);
4250}
4251
Tim Peters6d6c1a32001-08-02 04:15:00 +00004252static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004253wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004254{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004255 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4256 Py_ssize_t i;
4257 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004258 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004259
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004260 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004261 return NULL;
4262 i = getindex(self, arg);
4263 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004264 return NULL;
4265 res = (*func)(self, i, value);
4266 if (res == -1 && PyErr_Occurred())
4267 return NULL;
4268 Py_INCREF(Py_None);
4269 return Py_None;
4270}
4271
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004272static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004273wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004274{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004275 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4276 Py_ssize_t i;
4277 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004278 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004279
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004280 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004281 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004282 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004283 i = getindex(self, arg);
4284 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004285 return NULL;
4286 res = (*func)(self, i, NULL);
4287 if (res == -1 && PyErr_Occurred())
4288 return NULL;
4289 Py_INCREF(Py_None);
4290 return Py_None;
4291}
4292
Tim Peters6d6c1a32001-08-02 04:15:00 +00004293static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004294wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004295{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004296 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4297 Py_ssize_t i, j;
4298 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004299 PyObject *value;
4300
Martin v. Löwis18e16552006-02-15 17:27:45 +00004301 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004302 return NULL;
4303 res = (*func)(self, i, j, value);
4304 if (res == -1 && PyErr_Occurred())
4305 return NULL;
4306 Py_INCREF(Py_None);
4307 return Py_None;
4308}
4309
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004310static PyObject *
4311wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
4312{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004313 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4314 Py_ssize_t i, j;
4315 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004316
Martin v. Löwis18e16552006-02-15 17:27:45 +00004317 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004318 return NULL;
4319 res = (*func)(self, i, j, NULL);
4320 if (res == -1 && PyErr_Occurred())
4321 return NULL;
4322 Py_INCREF(Py_None);
4323 return Py_None;
4324}
4325
Tim Peters6d6c1a32001-08-02 04:15:00 +00004326/* XXX objobjproc is a misnomer; should be objargpred */
4327static PyObject *
4328wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4329{
4330 objobjproc func = (objobjproc)wrapped;
4331 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004332 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004333
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004334 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004335 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004336 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004337 res = (*func)(self, value);
4338 if (res == -1 && PyErr_Occurred())
4339 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004340 else
4341 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004342}
4343
Tim Peters6d6c1a32001-08-02 04:15:00 +00004344static PyObject *
4345wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4346{
4347 objobjargproc func = (objobjargproc)wrapped;
4348 int res;
4349 PyObject *key, *value;
4350
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004351 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004352 return NULL;
4353 res = (*func)(self, key, value);
4354 if (res == -1 && PyErr_Occurred())
4355 return NULL;
4356 Py_INCREF(Py_None);
4357 return Py_None;
4358}
4359
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004360static PyObject *
4361wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4362{
4363 objobjargproc func = (objobjargproc)wrapped;
4364 int res;
4365 PyObject *key;
4366
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004367 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004368 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004369 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004370 res = (*func)(self, key, NULL);
4371 if (res == -1 && PyErr_Occurred())
4372 return NULL;
4373 Py_INCREF(Py_None);
4374 return Py_None;
4375}
4376
Tim Peters6d6c1a32001-08-02 04:15:00 +00004377static PyObject *
4378wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
4379{
4380 cmpfunc func = (cmpfunc)wrapped;
4381 int res;
4382 PyObject *other;
4383
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004384 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004385 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004386 other = PyTuple_GET_ITEM(args, 0);
Christian Heimese93237d2007-12-19 02:37:44 +00004387 if (Py_TYPE(other)->tp_compare != func &&
4388 !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
Guido van Rossumceccae52001-09-18 20:03:57 +00004389 PyErr_Format(
4390 PyExc_TypeError,
4391 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +00004392 Py_TYPE(self)->tp_name,
4393 Py_TYPE(self)->tp_name,
4394 Py_TYPE(other)->tp_name);
Guido van Rossumceccae52001-09-18 20:03:57 +00004395 return NULL;
4396 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004397 res = (*func)(self, other);
4398 if (PyErr_Occurred())
4399 return NULL;
4400 return PyInt_FromLong((long)res);
4401}
4402
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004403/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004404 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004405static int
4406hackcheck(PyObject *self, setattrofunc func, char *what)
4407{
Christian Heimese93237d2007-12-19 02:37:44 +00004408 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004409 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4410 type = type->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004411 /* If type is NULL now, this is a really weird type.
4412 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004413 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004414 PyErr_Format(PyExc_TypeError,
4415 "can't apply this %s to %s object",
4416 what,
4417 type->tp_name);
4418 return 0;
4419 }
4420 return 1;
4421}
4422
Tim Peters6d6c1a32001-08-02 04:15:00 +00004423static PyObject *
4424wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4425{
4426 setattrofunc func = (setattrofunc)wrapped;
4427 int res;
4428 PyObject *name, *value;
4429
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004430 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004431 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004432 if (!hackcheck(self, func, "__setattr__"))
4433 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004434 res = (*func)(self, name, value);
4435 if (res < 0)
4436 return NULL;
4437 Py_INCREF(Py_None);
4438 return Py_None;
4439}
4440
4441static PyObject *
4442wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4443{
4444 setattrofunc func = (setattrofunc)wrapped;
4445 int res;
4446 PyObject *name;
4447
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004448 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004449 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004450 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004451 if (!hackcheck(self, func, "__delattr__"))
4452 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004453 res = (*func)(self, name, NULL);
4454 if (res < 0)
4455 return NULL;
4456 Py_INCREF(Py_None);
4457 return Py_None;
4458}
4459
Tim Peters6d6c1a32001-08-02 04:15:00 +00004460static PyObject *
4461wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4462{
4463 hashfunc func = (hashfunc)wrapped;
4464 long res;
4465
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004466 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004467 return NULL;
4468 res = (*func)(self);
4469 if (res == -1 && PyErr_Occurred())
4470 return NULL;
4471 return PyInt_FromLong(res);
4472}
4473
Tim Peters6d6c1a32001-08-02 04:15:00 +00004474static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004475wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004476{
4477 ternaryfunc func = (ternaryfunc)wrapped;
4478
Guido van Rossumc8e56452001-10-22 00:43:43 +00004479 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004480}
4481
Tim Peters6d6c1a32001-08-02 04:15:00 +00004482static PyObject *
4483wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4484{
4485 richcmpfunc func = (richcmpfunc)wrapped;
4486 PyObject *other;
4487
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004488 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004489 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004490 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004491 return (*func)(self, other, op);
4492}
4493
4494#undef RICHCMP_WRAPPER
4495#define RICHCMP_WRAPPER(NAME, OP) \
4496static PyObject * \
4497richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4498{ \
4499 return wrap_richcmpfunc(self, args, wrapped, OP); \
4500}
4501
Jack Jansen8e938b42001-08-08 15:29:49 +00004502RICHCMP_WRAPPER(lt, Py_LT)
4503RICHCMP_WRAPPER(le, Py_LE)
4504RICHCMP_WRAPPER(eq, Py_EQ)
4505RICHCMP_WRAPPER(ne, Py_NE)
4506RICHCMP_WRAPPER(gt, Py_GT)
4507RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004508
Tim Peters6d6c1a32001-08-02 04:15:00 +00004509static PyObject *
4510wrap_next(PyObject *self, PyObject *args, void *wrapped)
4511{
4512 unaryfunc func = (unaryfunc)wrapped;
4513 PyObject *res;
4514
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004515 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004516 return NULL;
4517 res = (*func)(self);
4518 if (res == NULL && !PyErr_Occurred())
4519 PyErr_SetNone(PyExc_StopIteration);
4520 return res;
4521}
4522
Tim Peters6d6c1a32001-08-02 04:15:00 +00004523static PyObject *
4524wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4525{
4526 descrgetfunc func = (descrgetfunc)wrapped;
4527 PyObject *obj;
4528 PyObject *type = NULL;
4529
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004530 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004531 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004532 if (obj == Py_None)
4533 obj = NULL;
4534 if (type == Py_None)
4535 type = NULL;
4536 if (type == NULL &&obj == NULL) {
4537 PyErr_SetString(PyExc_TypeError,
4538 "__get__(None, None) is invalid");
4539 return NULL;
4540 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004541 return (*func)(self, obj, type);
4542}
4543
Tim Peters6d6c1a32001-08-02 04:15:00 +00004544static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004545wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004546{
4547 descrsetfunc func = (descrsetfunc)wrapped;
4548 PyObject *obj, *value;
4549 int ret;
4550
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004551 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004552 return NULL;
4553 ret = (*func)(self, obj, value);
4554 if (ret < 0)
4555 return NULL;
4556 Py_INCREF(Py_None);
4557 return Py_None;
4558}
Guido van Rossum22b13872002-08-06 21:41:44 +00004559
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004560static PyObject *
4561wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4562{
4563 descrsetfunc func = (descrsetfunc)wrapped;
4564 PyObject *obj;
4565 int ret;
4566
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004567 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004568 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004569 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004570 ret = (*func)(self, obj, NULL);
4571 if (ret < 0)
4572 return NULL;
4573 Py_INCREF(Py_None);
4574 return Py_None;
4575}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004576
Tim Peters6d6c1a32001-08-02 04:15:00 +00004577static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004578wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004579{
4580 initproc func = (initproc)wrapped;
4581
Guido van Rossumc8e56452001-10-22 00:43:43 +00004582 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004583 return NULL;
4584 Py_INCREF(Py_None);
4585 return Py_None;
4586}
4587
Tim Peters6d6c1a32001-08-02 04:15:00 +00004588static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004589tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004590{
Barry Warsaw60f01882001-08-22 19:24:42 +00004591 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004592 PyObject *arg0, *res;
4593
4594 if (self == NULL || !PyType_Check(self))
4595 Py_FatalError("__new__() called with non-type 'self'");
4596 type = (PyTypeObject *)self;
4597 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004598 PyErr_Format(PyExc_TypeError,
4599 "%s.__new__(): not enough arguments",
4600 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004601 return NULL;
4602 }
4603 arg0 = PyTuple_GET_ITEM(args, 0);
4604 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004605 PyErr_Format(PyExc_TypeError,
4606 "%s.__new__(X): X is not a type object (%s)",
4607 type->tp_name,
Christian Heimese93237d2007-12-19 02:37:44 +00004608 Py_TYPE(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004609 return NULL;
4610 }
4611 subtype = (PyTypeObject *)arg0;
4612 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004613 PyErr_Format(PyExc_TypeError,
4614 "%s.__new__(%s): %s is not a subtype of %s",
4615 type->tp_name,
4616 subtype->tp_name,
4617 subtype->tp_name,
4618 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004619 return NULL;
4620 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004621
4622 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004623 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004624 most derived base that's not a heap type is this type. */
4625 staticbase = subtype;
4626 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4627 staticbase = staticbase->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004628 /* If staticbase is NULL now, it is a really weird type.
4629 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004630 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004631 PyErr_Format(PyExc_TypeError,
4632 "%s.__new__(%s) is not safe, use %s.__new__()",
4633 type->tp_name,
4634 subtype->tp_name,
4635 staticbase == NULL ? "?" : staticbase->tp_name);
4636 return NULL;
4637 }
4638
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004639 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4640 if (args == NULL)
4641 return NULL;
4642 res = type->tp_new(subtype, args, kwds);
4643 Py_DECREF(args);
4644 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004645}
4646
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004647static struct PyMethodDef tp_new_methoddef[] = {
Neal Norwitza84dcd72007-05-22 07:16:44 +00004648 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004649 PyDoc_STR("T.__new__(S, ...) -> "
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004650 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004651 {0}
4652};
4653
4654static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004655add_tp_new_wrapper(PyTypeObject *type)
4656{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004657 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004658
Guido van Rossum687ae002001-10-15 22:03:32 +00004659 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004660 return 0;
4661 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004662 if (func == NULL)
4663 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004664 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004665 Py_DECREF(func);
4666 return -1;
4667 }
4668 Py_DECREF(func);
4669 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004670}
4671
Guido van Rossumf040ede2001-08-07 16:40:56 +00004672/* Slot wrappers that call the corresponding __foo__ slot. See comments
4673 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004674
Guido van Rossumdc91b992001-08-08 22:26:22 +00004675#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004676static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004677FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004678{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004679 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004680 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004681}
4682
Guido van Rossumdc91b992001-08-08 22:26:22 +00004683#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004684static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004685FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004686{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004687 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004688 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004689}
4690
Guido van Rossumcd118802003-01-06 22:57:47 +00004691/* Boolean helper for SLOT1BINFULL().
4692 right.__class__ is a nontrivial subclass of left.__class__. */
4693static int
4694method_is_overloaded(PyObject *left, PyObject *right, char *name)
4695{
4696 PyObject *a, *b;
4697 int ok;
4698
Christian Heimese93237d2007-12-19 02:37:44 +00004699 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004700 if (b == NULL) {
4701 PyErr_Clear();
4702 /* If right doesn't have it, it's not overloaded */
4703 return 0;
4704 }
4705
Christian Heimese93237d2007-12-19 02:37:44 +00004706 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004707 if (a == NULL) {
4708 PyErr_Clear();
4709 Py_DECREF(b);
4710 /* If right has it but left doesn't, it's overloaded */
4711 return 1;
4712 }
4713
4714 ok = PyObject_RichCompareBool(a, b, Py_NE);
4715 Py_DECREF(a);
4716 Py_DECREF(b);
4717 if (ok < 0) {
4718 PyErr_Clear();
4719 return 0;
4720 }
4721
4722 return ok;
4723}
4724
Guido van Rossumdc91b992001-08-08 22:26:22 +00004725
4726#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004727static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004728FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004729{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004730 static PyObject *cache_str, *rcache_str; \
Christian Heimese93237d2007-12-19 02:37:44 +00004731 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4732 Py_TYPE(other)->tp_as_number != NULL && \
4733 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4734 if (Py_TYPE(self)->tp_as_number != NULL && \
4735 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004736 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004737 if (do_other && \
Christian Heimese93237d2007-12-19 02:37:44 +00004738 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004739 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004740 r = call_maybe( \
4741 other, ROPSTR, &rcache_str, "(O)", self); \
4742 if (r != Py_NotImplemented) \
4743 return r; \
4744 Py_DECREF(r); \
4745 do_other = 0; \
4746 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004747 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004748 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004749 if (r != Py_NotImplemented || \
Christian Heimese93237d2007-12-19 02:37:44 +00004750 Py_TYPE(other) == Py_TYPE(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004751 return r; \
4752 Py_DECREF(r); \
4753 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004754 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004755 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004756 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004757 } \
4758 Py_INCREF(Py_NotImplemented); \
4759 return Py_NotImplemented; \
4760}
4761
4762#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4763 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4764
4765#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4766static PyObject * \
4767FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4768{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004769 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004770 return call_method(self, OPSTR, &cache_str, \
4771 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004772}
4773
Martin v. Löwis18e16552006-02-15 17:27:45 +00004774static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004775slot_sq_length(PyObject *self)
4776{
Guido van Rossum2730b132001-08-28 18:22:14 +00004777 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004778 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004779 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004780
4781 if (res == NULL)
4782 return -1;
Neal Norwitz1872b1c2006-08-12 18:44:06 +00004783 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004784 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004785 if (len < 0) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00004786 if (!PyErr_Occurred())
4787 PyErr_SetString(PyExc_ValueError,
4788 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004789 return -1;
4790 }
Guido van Rossum26111622001-10-01 16:42:49 +00004791 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004792}
4793
Guido van Rossumf4593e02001-10-03 12:09:30 +00004794/* Super-optimized version of slot_sq_item.
4795 Other slots could do the same... */
4796static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004797slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004798{
4799 static PyObject *getitem_str;
4800 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4801 descrgetfunc f;
4802
4803 if (getitem_str == NULL) {
4804 getitem_str = PyString_InternFromString("__getitem__");
4805 if (getitem_str == NULL)
4806 return NULL;
4807 }
Christian Heimese93237d2007-12-19 02:37:44 +00004808 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004809 if (func != NULL) {
Christian Heimese93237d2007-12-19 02:37:44 +00004810 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004811 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004812 else {
Christian Heimese93237d2007-12-19 02:37:44 +00004813 func = f(func, self, (PyObject *)(Py_TYPE(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004814 if (func == NULL) {
4815 return NULL;
4816 }
4817 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004818 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004819 if (ival != NULL) {
4820 args = PyTuple_New(1);
4821 if (args != NULL) {
4822 PyTuple_SET_ITEM(args, 0, ival);
4823 retval = PyObject_Call(func, args, NULL);
4824 Py_XDECREF(args);
4825 Py_XDECREF(func);
4826 return retval;
4827 }
4828 }
4829 }
4830 else {
4831 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4832 }
4833 Py_XDECREF(args);
4834 Py_XDECREF(ival);
4835 Py_XDECREF(func);
4836 return NULL;
4837}
4838
Martin v. Löwis18e16552006-02-15 17:27:45 +00004839SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004840
4841static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004842slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004843{
4844 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004845 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004846
4847 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004848 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004849 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004850 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004851 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004852 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004853 if (res == NULL)
4854 return -1;
4855 Py_DECREF(res);
4856 return 0;
4857}
4858
4859static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004860slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004861{
4862 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004863 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004864
4865 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004866 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004867 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004868 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004869 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004870 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004871 if (res == NULL)
4872 return -1;
4873 Py_DECREF(res);
4874 return 0;
4875}
4876
4877static int
4878slot_sq_contains(PyObject *self, PyObject *value)
4879{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004880 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004881 int result = -1;
4882
Guido van Rossum60718732001-08-28 17:47:51 +00004883 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004884
Guido van Rossum55f20992001-10-01 17:18:22 +00004885 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004886 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004887 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004888 if (args == NULL)
4889 res = NULL;
4890 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004891 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004892 Py_DECREF(args);
4893 }
4894 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004895 if (res != NULL) {
4896 result = PyObject_IsTrue(res);
4897 Py_DECREF(res);
4898 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004899 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004900 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004901 /* Possible results: -1 and 1 */
4902 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004903 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004904 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004905 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004906}
4907
Tim Peters6d6c1a32001-08-02 04:15:00 +00004908#define slot_mp_length slot_sq_length
4909
Guido van Rossumdc91b992001-08-08 22:26:22 +00004910SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004911
4912static int
4913slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4914{
4915 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004916 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004917
4918 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004919 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004920 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004921 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004922 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004923 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004924 if (res == NULL)
4925 return -1;
4926 Py_DECREF(res);
4927 return 0;
4928}
4929
Guido van Rossumdc91b992001-08-08 22:26:22 +00004930SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4931SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4932SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4933SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4934SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4935SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4936
Jeremy Hylton938ace62002-07-17 16:30:39 +00004937static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004938
4939SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4940 nb_power, "__pow__", "__rpow__")
4941
4942static PyObject *
4943slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4944{
Guido van Rossum2730b132001-08-28 18:22:14 +00004945 static PyObject *pow_str;
4946
Guido van Rossumdc91b992001-08-08 22:26:22 +00004947 if (modulus == Py_None)
4948 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004949 /* Three-arg power doesn't use __rpow__. But ternary_op
4950 can call this when the second argument's type uses
4951 slot_nb_power, so check before calling self.__pow__. */
Christian Heimese93237d2007-12-19 02:37:44 +00004952 if (Py_TYPE(self)->tp_as_number != NULL &&
4953 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00004954 return call_method(self, "__pow__", &pow_str,
4955 "(OO)", other, modulus);
4956 }
4957 Py_INCREF(Py_NotImplemented);
4958 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004959}
4960
4961SLOT0(slot_nb_negative, "__neg__")
4962SLOT0(slot_nb_positive, "__pos__")
4963SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004964
4965static int
4966slot_nb_nonzero(PyObject *self)
4967{
Tim Petersea7f75d2002-12-07 21:39:16 +00004968 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004969 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004970 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004971
Guido van Rossum55f20992001-10-01 17:18:22 +00004972 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004973 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004974 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004975 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004976 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004977 if (func == NULL)
4978 return PyErr_Occurred() ? -1 : 1;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004979 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004980 args = PyTuple_New(0);
4981 if (args != NULL) {
4982 PyObject *temp = PyObject_Call(func, args, NULL);
4983 Py_DECREF(args);
4984 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004985 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004986 result = PyObject_IsTrue(temp);
4987 else {
4988 PyErr_Format(PyExc_TypeError,
4989 "__nonzero__ should return "
4990 "bool or int, returned %s",
4991 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004992 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004993 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004994 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004995 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004996 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004997 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004998 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004999}
5000
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005001
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005002static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005003slot_nb_index(PyObject *self)
5004{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005005 static PyObject *index_str;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005006 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005007}
5008
5009
Guido van Rossumdc91b992001-08-08 22:26:22 +00005010SLOT0(slot_nb_invert, "__invert__")
5011SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5012SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5013SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5014SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5015SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005016
5017static int
5018slot_nb_coerce(PyObject **a, PyObject **b)
5019{
5020 static PyObject *coerce_str;
5021 PyObject *self = *a, *other = *b;
5022
5023 if (self->ob_type->tp_as_number != NULL &&
5024 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5025 PyObject *r;
5026 r = call_maybe(
5027 self, "__coerce__", &coerce_str, "(O)", other);
5028 if (r == NULL)
5029 return -1;
5030 if (r == Py_NotImplemented) {
5031 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005032 }
Guido van Rossum55f20992001-10-01 17:18:22 +00005033 else {
5034 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5035 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005036 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00005037 Py_DECREF(r);
5038 return -1;
5039 }
5040 *a = PyTuple_GET_ITEM(r, 0);
5041 Py_INCREF(*a);
5042 *b = PyTuple_GET_ITEM(r, 1);
5043 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005044 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00005045 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005046 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005047 }
5048 if (other->ob_type->tp_as_number != NULL &&
5049 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5050 PyObject *r;
5051 r = call_maybe(
5052 other, "__coerce__", &coerce_str, "(O)", self);
5053 if (r == NULL)
5054 return -1;
5055 if (r == Py_NotImplemented) {
5056 Py_DECREF(r);
5057 return 1;
5058 }
5059 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5060 PyErr_SetString(PyExc_TypeError,
5061 "__coerce__ didn't return a 2-tuple");
5062 Py_DECREF(r);
5063 return -1;
5064 }
5065 *a = PyTuple_GET_ITEM(r, 1);
5066 Py_INCREF(*a);
5067 *b = PyTuple_GET_ITEM(r, 0);
5068 Py_INCREF(*b);
5069 Py_DECREF(r);
5070 return 0;
5071 }
5072 return 1;
5073}
5074
Guido van Rossumdc91b992001-08-08 22:26:22 +00005075SLOT0(slot_nb_int, "__int__")
5076SLOT0(slot_nb_long, "__long__")
5077SLOT0(slot_nb_float, "__float__")
5078SLOT0(slot_nb_oct, "__oct__")
5079SLOT0(slot_nb_hex, "__hex__")
5080SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5081SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5082SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
5083SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
5084SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Martin v. Löwisfd963262007-02-09 12:19:32 +00005085/* Can't use SLOT1 here, because nb_inplace_power is ternary */
5086static PyObject *
5087slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5088{
5089 static PyObject *cache_str;
5090 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
5091}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005092SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5093SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5094SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5095SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5096SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5097SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
5098 "__floordiv__", "__rfloordiv__")
5099SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5100SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5101SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005102
5103static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00005104half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005105{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005106 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005107 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005108 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005109
Guido van Rossum60718732001-08-28 17:47:51 +00005110 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005111 if (func == NULL) {
5112 PyErr_Clear();
5113 }
5114 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005115 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005116 if (args == NULL)
5117 res = NULL;
5118 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005119 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005120 Py_DECREF(args);
5121 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00005122 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005123 if (res != Py_NotImplemented) {
5124 if (res == NULL)
5125 return -2;
5126 c = PyInt_AsLong(res);
5127 Py_DECREF(res);
5128 if (c == -1 && PyErr_Occurred())
5129 return -2;
5130 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
5131 }
5132 Py_DECREF(res);
5133 }
5134 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005135}
5136
Guido van Rossumab3b0342001-09-18 20:38:53 +00005137/* This slot is published for the benefit of try_3way_compare in object.c */
5138int
5139_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00005140{
5141 int c;
5142
Christian Heimese93237d2007-12-19 02:37:44 +00005143 if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005144 c = half_compare(self, other);
5145 if (c <= 1)
5146 return c;
5147 }
Christian Heimese93237d2007-12-19 02:37:44 +00005148 if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005149 c = half_compare(other, self);
5150 if (c < -1)
5151 return -2;
5152 if (c <= 1)
5153 return -c;
5154 }
5155 return (void *)self < (void *)other ? -1 :
5156 (void *)self > (void *)other ? 1 : 0;
5157}
5158
5159static PyObject *
5160slot_tp_repr(PyObject *self)
5161{
5162 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005163 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005164
Guido van Rossum60718732001-08-28 17:47:51 +00005165 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005166 if (func != NULL) {
5167 res = PyEval_CallObject(func, NULL);
5168 Py_DECREF(func);
5169 return res;
5170 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00005171 PyErr_Clear();
5172 return PyString_FromFormat("<%s object at %p>",
Christian Heimese93237d2007-12-19 02:37:44 +00005173 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005174}
5175
5176static PyObject *
5177slot_tp_str(PyObject *self)
5178{
5179 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005180 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005181
Guido van Rossum60718732001-08-28 17:47:51 +00005182 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005183 if (func != NULL) {
5184 res = PyEval_CallObject(func, NULL);
5185 Py_DECREF(func);
5186 return res;
5187 }
5188 else {
5189 PyErr_Clear();
5190 return slot_tp_repr(self);
5191 }
5192}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005193
5194static long
5195slot_tp_hash(PyObject *self)
5196{
Tim Peters61ce0a92002-12-06 23:38:02 +00005197 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00005198 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005199 long h;
5200
Guido van Rossum60718732001-08-28 17:47:51 +00005201 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005202
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005203 if (func != NULL && func != Py_None) {
Tim Peters61ce0a92002-12-06 23:38:02 +00005204 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005205 Py_DECREF(func);
5206 if (res == NULL)
5207 return -1;
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00005208 if (PyLong_Check(res))
Armin Rigo51fc8c42006-08-09 14:55:26 +00005209 h = PyLong_Type.tp_hash(res);
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00005210 else
5211 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00005212 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005213 }
5214 else {
Georg Brandl30b78042007-12-20 21:03:02 +00005215 Py_XDECREF(func); /* may be None */
Guido van Rossumb8f63662001-08-15 23:57:02 +00005216 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005217 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005218 if (func == NULL) {
5219 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005220 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005221 }
5222 if (func != NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00005223 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
5224 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005225 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005226 return -1;
5227 }
5228 PyErr_Clear();
5229 h = _Py_HashPointer((void *)self);
5230 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005231 if (h == -1 && !PyErr_Occurred())
5232 h = -2;
5233 return h;
5234}
5235
5236static PyObject *
5237slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5238{
Guido van Rossum60718732001-08-28 17:47:51 +00005239 static PyObject *call_str;
5240 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005241 PyObject *res;
5242
5243 if (meth == NULL)
5244 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00005245
Tim Peters6d6c1a32001-08-02 04:15:00 +00005246 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00005247
Tim Peters6d6c1a32001-08-02 04:15:00 +00005248 Py_DECREF(meth);
5249 return res;
5250}
5251
Guido van Rossum14a6f832001-10-17 13:59:09 +00005252/* There are two slot dispatch functions for tp_getattro.
5253
5254 - slot_tp_getattro() is used when __getattribute__ is overridden
5255 but no __getattr__ hook is present;
5256
5257 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5258
Guido van Rossumc334df52002-04-04 23:44:47 +00005259 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5260 detects the absence of __getattr__ and then installs the simpler slot if
5261 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005262
Tim Peters6d6c1a32001-08-02 04:15:00 +00005263static PyObject *
5264slot_tp_getattro(PyObject *self, PyObject *name)
5265{
Guido van Rossum14a6f832001-10-17 13:59:09 +00005266 static PyObject *getattribute_str = NULL;
5267 return call_method(self, "__getattribute__", &getattribute_str,
5268 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005269}
5270
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005271static PyObject *
5272slot_tp_getattr_hook(PyObject *self, PyObject *name)
5273{
Christian Heimese93237d2007-12-19 02:37:44 +00005274 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005275 PyObject *getattr, *getattribute, *res;
5276 static PyObject *getattribute_str = NULL;
5277 static PyObject *getattr_str = NULL;
5278
5279 if (getattr_str == NULL) {
5280 getattr_str = PyString_InternFromString("__getattr__");
5281 if (getattr_str == NULL)
5282 return NULL;
5283 }
5284 if (getattribute_str == NULL) {
5285 getattribute_str =
5286 PyString_InternFromString("__getattribute__");
5287 if (getattribute_str == NULL)
5288 return NULL;
5289 }
5290 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005291 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005292 /* No __getattr__ hook: use a simpler dispatcher */
5293 tp->tp_getattro = slot_tp_getattro;
5294 return slot_tp_getattro(self, name);
5295 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005296 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005297 if (getattribute == NULL ||
Christian Heimese93237d2007-12-19 02:37:44 +00005298 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00005299 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5300 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005301 res = PyObject_GenericGetAttr(self, name);
5302 else
Georg Brandl684fd0c2006-05-25 19:15:31 +00005303 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005304 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005305 PyErr_Clear();
Georg Brandl684fd0c2006-05-25 19:15:31 +00005306 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005307 }
5308 return res;
5309}
5310
Tim Peters6d6c1a32001-08-02 04:15:00 +00005311static int
5312slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5313{
5314 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005315 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005316
5317 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00005318 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005319 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005320 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005321 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005322 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005323 if (res == NULL)
5324 return -1;
5325 Py_DECREF(res);
5326 return 0;
5327}
5328
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005329static char *name_op[] = {
5330 "__lt__",
5331 "__le__",
5332 "__eq__",
5333 "__ne__",
5334 "__gt__",
5335 "__ge__",
5336};
5337
Tim Peters6d6c1a32001-08-02 04:15:00 +00005338static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005339half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005340{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005341 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005342 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005343
Guido van Rossum60718732001-08-28 17:47:51 +00005344 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005345 if (func == NULL) {
5346 PyErr_Clear();
5347 Py_INCREF(Py_NotImplemented);
5348 return Py_NotImplemented;
5349 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005350 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005351 if (args == NULL)
5352 res = NULL;
5353 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005354 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005355 Py_DECREF(args);
5356 }
5357 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005358 return res;
5359}
5360
Guido van Rossumb8f63662001-08-15 23:57:02 +00005361static PyObject *
5362slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5363{
5364 PyObject *res;
5365
Christian Heimese93237d2007-12-19 02:37:44 +00005366 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005367 res = half_richcompare(self, other, op);
5368 if (res != Py_NotImplemented)
5369 return res;
5370 Py_DECREF(res);
5371 }
Christian Heimese93237d2007-12-19 02:37:44 +00005372 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00005373 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005374 if (res != Py_NotImplemented) {
5375 return res;
5376 }
5377 Py_DECREF(res);
5378 }
5379 Py_INCREF(Py_NotImplemented);
5380 return Py_NotImplemented;
5381}
5382
5383static PyObject *
5384slot_tp_iter(PyObject *self)
5385{
5386 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005387 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005388
Guido van Rossum60718732001-08-28 17:47:51 +00005389 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005390 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00005391 PyObject *args;
5392 args = res = PyTuple_New(0);
5393 if (args != NULL) {
5394 res = PyObject_Call(func, args, NULL);
5395 Py_DECREF(args);
5396 }
5397 Py_DECREF(func);
5398 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005399 }
5400 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005401 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005402 if (func == NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00005403 PyErr_Format(PyExc_TypeError,
5404 "'%.200s' object is not iterable",
Christian Heimese93237d2007-12-19 02:37:44 +00005405 Py_TYPE(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005406 return NULL;
5407 }
5408 Py_DECREF(func);
5409 return PySeqIter_New(self);
5410}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005411
5412static PyObject *
5413slot_tp_iternext(PyObject *self)
5414{
Guido van Rossum2730b132001-08-28 18:22:14 +00005415 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00005416 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005417}
5418
Guido van Rossum1a493502001-08-17 16:47:50 +00005419static PyObject *
5420slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5421{
Christian Heimese93237d2007-12-19 02:37:44 +00005422 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00005423 PyObject *get;
5424 static PyObject *get_str = NULL;
5425
5426 if (get_str == NULL) {
5427 get_str = PyString_InternFromString("__get__");
5428 if (get_str == NULL)
5429 return NULL;
5430 }
5431 get = _PyType_Lookup(tp, get_str);
5432 if (get == NULL) {
5433 /* Avoid further slowdowns */
5434 if (tp->tp_descr_get == slot_tp_descr_get)
5435 tp->tp_descr_get = NULL;
5436 Py_INCREF(self);
5437 return self;
5438 }
Guido van Rossum2c252392001-08-24 10:13:31 +00005439 if (obj == NULL)
5440 obj = Py_None;
5441 if (type == NULL)
5442 type = Py_None;
Georg Brandl684fd0c2006-05-25 19:15:31 +00005443 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005444}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005445
5446static int
5447slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5448{
Guido van Rossum2c252392001-08-24 10:13:31 +00005449 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005450 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005451
5452 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00005453 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005454 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00005455 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005456 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005457 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005458 if (res == NULL)
5459 return -1;
5460 Py_DECREF(res);
5461 return 0;
5462}
5463
5464static int
5465slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5466{
Guido van Rossum60718732001-08-28 17:47:51 +00005467 static PyObject *init_str;
5468 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005469 PyObject *res;
5470
5471 if (meth == NULL)
5472 return -1;
5473 res = PyObject_Call(meth, args, kwds);
5474 Py_DECREF(meth);
5475 if (res == NULL)
5476 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005477 if (res != Py_None) {
Georg Brandlccff7852006-06-18 22:17:29 +00005478 PyErr_Format(PyExc_TypeError,
5479 "__init__() should return None, not '%.200s'",
Christian Heimese93237d2007-12-19 02:37:44 +00005480 Py_TYPE(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005481 Py_DECREF(res);
5482 return -1;
5483 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005484 Py_DECREF(res);
5485 return 0;
5486}
5487
5488static PyObject *
5489slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5490{
Guido van Rossum7bed2132002-08-08 21:57:53 +00005491 static PyObject *new_str;
5492 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005493 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005494 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005495
Guido van Rossum7bed2132002-08-08 21:57:53 +00005496 if (new_str == NULL) {
5497 new_str = PyString_InternFromString("__new__");
5498 if (new_str == NULL)
5499 return NULL;
5500 }
5501 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005502 if (func == NULL)
5503 return NULL;
5504 assert(PyTuple_Check(args));
5505 n = PyTuple_GET_SIZE(args);
5506 newargs = PyTuple_New(n+1);
5507 if (newargs == NULL)
5508 return NULL;
5509 Py_INCREF(type);
5510 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5511 for (i = 0; i < n; i++) {
5512 x = PyTuple_GET_ITEM(args, i);
5513 Py_INCREF(x);
5514 PyTuple_SET_ITEM(newargs, i+1, x);
5515 }
5516 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005517 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005518 Py_DECREF(func);
5519 return x;
5520}
5521
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005522static void
5523slot_tp_del(PyObject *self)
5524{
5525 static PyObject *del_str = NULL;
5526 PyObject *del, *res;
5527 PyObject *error_type, *error_value, *error_traceback;
5528
5529 /* Temporarily resurrect the object. */
5530 assert(self->ob_refcnt == 0);
5531 self->ob_refcnt = 1;
5532
5533 /* Save the current exception, if any. */
5534 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5535
5536 /* Execute __del__ method, if any. */
5537 del = lookup_maybe(self, "__del__", &del_str);
5538 if (del != NULL) {
5539 res = PyEval_CallObject(del, NULL);
5540 if (res == NULL)
5541 PyErr_WriteUnraisable(del);
5542 else
5543 Py_DECREF(res);
5544 Py_DECREF(del);
5545 }
5546
5547 /* Restore the saved exception. */
5548 PyErr_Restore(error_type, error_value, error_traceback);
5549
5550 /* Undo the temporary resurrection; can't use DECREF here, it would
5551 * cause a recursive call.
5552 */
5553 assert(self->ob_refcnt > 0);
5554 if (--self->ob_refcnt == 0)
5555 return; /* this is the normal path out */
5556
5557 /* __del__ resurrected it! Make it look like the original Py_DECREF
5558 * never happened.
5559 */
5560 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005561 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005562 _Py_NewReference(self);
5563 self->ob_refcnt = refcnt;
5564 }
Christian Heimese93237d2007-12-19 02:37:44 +00005565 assert(!PyType_IS_GC(Py_TYPE(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005566 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005567 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5568 * we need to undo that. */
5569 _Py_DEC_REFTOTAL;
5570 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5571 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005572 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5573 * _Py_NewReference bumped tp_allocs: both of those need to be
5574 * undone.
5575 */
5576#ifdef COUNT_ALLOCS
Christian Heimese93237d2007-12-19 02:37:44 +00005577 --Py_TYPE(self)->tp_frees;
5578 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005579#endif
5580}
5581
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005582
5583/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005584 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005585 structure, which incorporates the additional structures used for numbers,
5586 sequences and mappings.
5587 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005588 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005589 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5590 terminated with an all-zero entry. (This table is further initialized and
5591 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005592
Guido van Rossum6d204072001-10-21 00:44:31 +00005593typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005594
5595#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005596#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005597#undef ETSLOT
5598#undef SQSLOT
5599#undef MPSLOT
5600#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005601#undef UNSLOT
5602#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005603#undef BINSLOT
5604#undef RBINSLOT
5605
Guido van Rossum6d204072001-10-21 00:44:31 +00005606#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005607 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5608 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005609#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5610 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005611 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005612#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005613 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005614 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005615#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5616 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5617#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5618 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5619#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5620 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5621#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5622 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5623 "x." NAME "() <==> " DOC)
5624#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5625 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5626 "x." NAME "(y) <==> x" DOC "y")
5627#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5628 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5629 "x." NAME "(y) <==> x" DOC "y")
5630#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5631 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5632 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005633#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5634 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5635 "x." NAME "(y) <==> " DOC)
5636#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5637 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5638 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005639
5640static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005641 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005642 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005643 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5644 The logic in abstract.c always falls back to nb_add/nb_multiply in
5645 this case. Defining both the nb_* and the sq_* slots to call the
5646 user-defined methods has unexpected side-effects, as shown by
5647 test_descr.notimplemented() */
5648 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005649 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00005650 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005651 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005652 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005653 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005654 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5655 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005656 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005657 "x.__getslice__(i, j) <==> x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005658 \n\
5659 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005660 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005661 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005662 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005663 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005664 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005665 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005666 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005667 \n\
5668 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005669 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005670 "x.__delslice__(i, j) <==> del x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005671 \n\
5672 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005673 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5674 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005675 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005676 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005677 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005678 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005679
Martin v. Löwis18e16552006-02-15 17:27:45 +00005680 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005681 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005682 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005683 wrap_binaryfunc,
5684 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005685 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005686 wrap_objobjargproc,
5687 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005688 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005689 wrap_delitem,
5690 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005691
Guido van Rossum6d204072001-10-21 00:44:31 +00005692 BINSLOT("__add__", nb_add, slot_nb_add,
5693 "+"),
5694 RBINSLOT("__radd__", nb_add, slot_nb_add,
5695 "+"),
5696 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5697 "-"),
5698 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5699 "-"),
5700 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5701 "*"),
5702 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5703 "*"),
5704 BINSLOT("__div__", nb_divide, slot_nb_divide,
5705 "/"),
5706 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5707 "/"),
5708 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5709 "%"),
5710 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5711 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005712 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005713 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005714 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005715 "divmod(y, x)"),
5716 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5717 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5718 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5719 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5720 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5721 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5722 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5723 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005724 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005725 "x != 0"),
5726 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5727 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5728 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5729 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5730 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5731 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5732 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5733 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5734 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5735 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5736 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5737 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5738 "x.__coerce__(y) <==> coerce(x, y)"),
5739 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5740 "int(x)"),
5741 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5742 "long(x)"),
5743 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5744 "float(x)"),
5745 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5746 "oct(x)"),
5747 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5748 "hex(x)"),
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005749 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005750 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005751 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5752 wrap_binaryfunc, "+"),
5753 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5754 wrap_binaryfunc, "-"),
5755 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5756 wrap_binaryfunc, "*"),
5757 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5758 wrap_binaryfunc, "/"),
5759 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5760 wrap_binaryfunc, "%"),
5761 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005762 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005763 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5764 wrap_binaryfunc, "<<"),
5765 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5766 wrap_binaryfunc, ">>"),
5767 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5768 wrap_binaryfunc, "&"),
5769 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5770 wrap_binaryfunc, "^"),
5771 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5772 wrap_binaryfunc, "|"),
5773 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5774 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5775 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5776 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5777 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5778 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5779 IBSLOT("__itruediv__", nb_inplace_true_divide,
5780 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005781
Guido van Rossum6d204072001-10-21 00:44:31 +00005782 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5783 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005784 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005785 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5786 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005787 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005788 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5789 "x.__cmp__(y) <==> cmp(x,y)"),
5790 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5791 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005792 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5793 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005794 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005795 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5796 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5797 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5798 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5799 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5800 "x.__setattr__('name', value) <==> x.name = value"),
5801 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5802 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5803 "x.__delattr__('name') <==> del x.name"),
5804 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5805 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5806 "x.__lt__(y) <==> x<y"),
5807 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5808 "x.__le__(y) <==> x<=y"),
5809 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5810 "x.__eq__(y) <==> x==y"),
5811 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5812 "x.__ne__(y) <==> x!=y"),
5813 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5814 "x.__gt__(y) <==> x>y"),
5815 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5816 "x.__ge__(y) <==> x>=y"),
5817 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5818 "x.__iter__() <==> iter(x)"),
5819 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5820 "x.next() -> the next value, or raise StopIteration"),
5821 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5822 "descr.__get__(obj[, type]) -> value"),
5823 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5824 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005825 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5826 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005827 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005828 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005829 "see x.__class__.__doc__ for signature",
5830 PyWrapperFlag_KEYWORDS),
5831 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005832 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005833 {NULL}
5834};
5835
Guido van Rossumc334df52002-04-04 23:44:47 +00005836/* Given a type pointer and an offset gotten from a slotdef entry, return a
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005837 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005838 the offset to the type pointer, since it takes care to indirect through the
5839 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5840 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005841static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005842slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005843{
5844 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005845 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005846
Guido van Rossume5c691a2003-03-07 15:13:17 +00005847 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005848 assert(offset >= 0);
Skip Montanaro429433b2006-04-18 00:35:43 +00005849 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5850 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005851 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005852 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005853 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005854 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005855 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005856 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005857 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005858 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005859 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005860 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005861 }
5862 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005863 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005864 }
5865 if (ptr != NULL)
5866 ptr += offset;
5867 return (void **)ptr;
5868}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005869
Guido van Rossumc334df52002-04-04 23:44:47 +00005870/* Length of array of slotdef pointers used to store slots with the
5871 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5872 the same __name__, for any __name__. Since that's a static property, it is
5873 appropriate to declare fixed-size arrays for this. */
5874#define MAX_EQUIV 10
5875
5876/* Return a slot pointer for a given name, but ONLY if the attribute has
5877 exactly one slot function. The name must be an interned string. */
5878static void **
5879resolve_slotdups(PyTypeObject *type, PyObject *name)
5880{
5881 /* XXX Maybe this could be optimized more -- but is it worth it? */
5882
5883 /* pname and ptrs act as a little cache */
5884 static PyObject *pname;
5885 static slotdef *ptrs[MAX_EQUIV];
5886 slotdef *p, **pp;
5887 void **res, **ptr;
5888
5889 if (pname != name) {
5890 /* Collect all slotdefs that match name into ptrs. */
5891 pname = name;
5892 pp = ptrs;
5893 for (p = slotdefs; p->name_strobj; p++) {
5894 if (p->name_strobj == name)
5895 *pp++ = p;
5896 }
5897 *pp = NULL;
5898 }
5899
5900 /* Look in all matching slots of the type; if exactly one of these has
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005901 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005902 res = NULL;
5903 for (pp = ptrs; *pp; pp++) {
5904 ptr = slotptr(type, (*pp)->offset);
5905 if (ptr == NULL || *ptr == NULL)
5906 continue;
5907 if (res != NULL)
5908 return NULL;
5909 res = ptr;
5910 }
5911 return res;
5912}
5913
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005914/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005915 does some incredibly complex thinking and then sticks something into the
5916 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5917 interests, and then stores a generic wrapper or a specific function into
5918 the slot.) Return a pointer to the next slotdef with a different offset,
5919 because that's convenient for fixup_slot_dispatchers(). */
5920static slotdef *
5921update_one_slot(PyTypeObject *type, slotdef *p)
5922{
5923 PyObject *descr;
5924 PyWrapperDescrObject *d;
5925 void *generic = NULL, *specific = NULL;
5926 int use_generic = 0;
5927 int offset = p->offset;
5928 void **ptr = slotptr(type, offset);
5929
5930 if (ptr == NULL) {
5931 do {
5932 ++p;
5933 } while (p->offset == offset);
5934 return p;
5935 }
5936 do {
5937 descr = _PyType_Lookup(type, p->name_strobj);
5938 if (descr == NULL)
5939 continue;
Christian Heimese93237d2007-12-19 02:37:44 +00005940 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00005941 void **tptr = resolve_slotdups(type, p->name_strobj);
5942 if (tptr == NULL || tptr == ptr)
5943 generic = p->function;
5944 d = (PyWrapperDescrObject *)descr;
5945 if (d->d_base->wrapper == p->wrapper &&
5946 PyType_IsSubtype(type, d->d_type))
5947 {
5948 if (specific == NULL ||
5949 specific == d->d_wrapped)
5950 specific = d->d_wrapped;
5951 else
5952 use_generic = 1;
5953 }
5954 }
Christian Heimese93237d2007-12-19 02:37:44 +00005955 else if (Py_TYPE(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00005956 PyCFunction_GET_FUNCTION(descr) ==
5957 (PyCFunction)tp_new_wrapper &&
5958 strcmp(p->name, "__new__") == 0)
5959 {
5960 /* The __new__ wrapper is not a wrapper descriptor,
5961 so must be special-cased differently.
5962 If we don't do this, creating an instance will
5963 always use slot_tp_new which will look up
5964 __new__ in the MRO which will call tp_new_wrapper
5965 which will look through the base classes looking
5966 for a static base and call its tp_new (usually
5967 PyType_GenericNew), after performing various
5968 sanity checks and constructing a new argument
5969 list. Cut all that nonsense short -- this speeds
5970 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005971 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005972 /* XXX I'm not 100% sure that there isn't a hole
5973 in this reasoning that requires additional
5974 sanity checks. I'll buy the first person to
5975 point out a bug in this reasoning a beer. */
5976 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005977 else {
5978 use_generic = 1;
5979 generic = p->function;
5980 }
5981 } while ((++p)->offset == offset);
5982 if (specific && !use_generic)
5983 *ptr = specific;
5984 else
5985 *ptr = generic;
5986 return p;
5987}
5988
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005989/* In the type, update the slots whose slotdefs are gathered in the pp array.
5990 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005991static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005992update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005993{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005994 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005995
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005996 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005997 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005998 return 0;
5999}
6000
Guido van Rossumc334df52002-04-04 23:44:47 +00006001/* Comparison function for qsort() to compare slotdefs by their offset, and
6002 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006003static int
6004slotdef_cmp(const void *aa, const void *bb)
6005{
6006 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
6007 int c = a->offset - b->offset;
6008 if (c != 0)
6009 return c;
6010 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00006011 /* Cannot use a-b, as this gives off_t,
6012 which may lose precision when converted to int. */
6013 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006014}
6015
Guido van Rossumc334df52002-04-04 23:44:47 +00006016/* Initialize the slotdefs table by adding interned string objects for the
6017 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006018static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006019init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006020{
6021 slotdef *p;
6022 static int initialized = 0;
6023
6024 if (initialized)
6025 return;
6026 for (p = slotdefs; p->name; p++) {
6027 p->name_strobj = PyString_InternFromString(p->name);
6028 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00006029 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006030 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006031 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
6032 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006033 initialized = 1;
6034}
6035
Guido van Rossumc334df52002-04-04 23:44:47 +00006036/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006037static int
6038update_slot(PyTypeObject *type, PyObject *name)
6039{
Guido van Rossumc334df52002-04-04 23:44:47 +00006040 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006041 slotdef *p;
6042 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006043 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006044
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00006045 /* Clear the VALID_VERSION flag of 'type' and all its
6046 subclasses. This could possibly be unified with the
6047 update_subclasses() recursion below, but carefully:
6048 they each have their own conditions on which to stop
6049 recursing into subclasses. */
6050 type_modified(type);
6051
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006052 init_slotdefs();
6053 pp = ptrs;
6054 for (p = slotdefs; p->name; p++) {
6055 /* XXX assume name is interned! */
6056 if (p->name_strobj == name)
6057 *pp++ = p;
6058 }
6059 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006060 for (pp = ptrs; *pp; pp++) {
6061 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006062 offset = p->offset;
6063 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006064 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006065 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006066 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006067 if (ptrs[0] == NULL)
6068 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006069 return update_subclasses(type, name,
6070 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006071}
6072
Guido van Rossumc334df52002-04-04 23:44:47 +00006073/* Store the proper functions in the slot dispatches at class (type)
6074 definition time, based upon which operations the class overrides in its
6075 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006076static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006077fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006078{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006079 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006080
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006081 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00006082 for (p = slotdefs; p->name; )
6083 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006084}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006085
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006086static void
6087update_all_slots(PyTypeObject* type)
6088{
6089 slotdef *p;
6090
6091 init_slotdefs();
6092 for (p = slotdefs; p->name; p++) {
6093 /* update_slot returns int but can't actually fail */
6094 update_slot(type, p->name_strobj);
6095 }
6096}
6097
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006098/* recurse_down_subclasses() and update_subclasses() are mutually
6099 recursive functions to call a callback for all subclasses,
6100 but refraining from recursing into subclasses that define 'name'. */
6101
6102static int
6103update_subclasses(PyTypeObject *type, PyObject *name,
6104 update_callback callback, void *data)
6105{
6106 if (callback(type, data) < 0)
6107 return -1;
6108 return recurse_down_subclasses(type, name, callback, data);
6109}
6110
6111static int
6112recurse_down_subclasses(PyTypeObject *type, PyObject *name,
6113 update_callback callback, void *data)
6114{
6115 PyTypeObject *subclass;
6116 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006117 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006118
6119 subclasses = type->tp_subclasses;
6120 if (subclasses == NULL)
6121 return 0;
6122 assert(PyList_Check(subclasses));
6123 n = PyList_GET_SIZE(subclasses);
6124 for (i = 0; i < n; i++) {
6125 ref = PyList_GET_ITEM(subclasses, i);
6126 assert(PyWeakref_CheckRef(ref));
6127 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6128 assert(subclass != NULL);
6129 if ((PyObject *)subclass == Py_None)
6130 continue;
6131 assert(PyType_Check(subclass));
6132 /* Avoid recursing down into unaffected classes */
6133 dict = subclass->tp_dict;
6134 if (dict != NULL && PyDict_Check(dict) &&
6135 PyDict_GetItem(dict, name) != NULL)
6136 continue;
6137 if (update_subclasses(subclass, name, callback, data) < 0)
6138 return -1;
6139 }
6140 return 0;
6141}
6142
Guido van Rossum6d204072001-10-21 00:44:31 +00006143/* This function is called by PyType_Ready() to populate the type's
6144 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006145 function slot (like tp_repr) that's defined in the type, one or more
6146 corresponding descriptors are added in the type's tp_dict dictionary
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006147 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006148 cause more than one descriptor to be added (for example, the nb_add
6149 slot adds both __add__ and __radd__ descriptors) and some function
6150 slots compete for the same descriptor (for example both sq_item and
6151 mp_subscript generate a __getitem__ descriptor).
6152
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006153 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006154 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006155 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006156 between competing slots: the members of PyHeapTypeObject are listed
6157 from most general to least general, so the most general slot is
6158 preferred. In particular, because as_mapping comes before as_sequence,
6159 for a type that defines both mp_subscript and sq_item, mp_subscript
6160 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006161
6162 This only adds new descriptors and doesn't overwrite entries in
6163 tp_dict that were previously defined. The descriptors contain a
6164 reference to the C function they must call, so that it's safe if they
6165 are copied into a subtype's __dict__ and the subtype has a different
6166 C function in its slot -- calling the method defined by the
6167 descriptor will call the C function that was used to create it,
6168 rather than the C function present in the slot when it is called.
6169 (This is important because a subtype may have a C function in the
6170 slot that calls the method from the dictionary, and we want to avoid
6171 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006172
6173static int
6174add_operators(PyTypeObject *type)
6175{
6176 PyObject *dict = type->tp_dict;
6177 slotdef *p;
6178 PyObject *descr;
6179 void **ptr;
6180
6181 init_slotdefs();
6182 for (p = slotdefs; p->name; p++) {
6183 if (p->wrapper == NULL)
6184 continue;
6185 ptr = slotptr(type, p->offset);
6186 if (!ptr || !*ptr)
6187 continue;
6188 if (PyDict_GetItem(dict, p->name_strobj))
6189 continue;
6190 descr = PyDescr_NewWrapper(type, p, *ptr);
6191 if (descr == NULL)
6192 return -1;
6193 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6194 return -1;
6195 Py_DECREF(descr);
6196 }
6197 if (type->tp_new != NULL) {
6198 if (add_tp_new_wrapper(type) < 0)
6199 return -1;
6200 }
6201 return 0;
6202}
6203
Guido van Rossum705f0f52001-08-24 16:47:00 +00006204
6205/* Cooperative 'super' */
6206
6207typedef struct {
6208 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00006209 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006210 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006211 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006212} superobject;
6213
Guido van Rossum6f799372001-09-20 20:46:19 +00006214static PyMemberDef super_members[] = {
6215 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6216 "the class invoking super()"},
6217 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6218 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006219 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00006220 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006221 {0}
6222};
6223
Guido van Rossum705f0f52001-08-24 16:47:00 +00006224static void
6225super_dealloc(PyObject *self)
6226{
6227 superobject *su = (superobject *)self;
6228
Guido van Rossum048eb752001-10-02 21:24:57 +00006229 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006230 Py_XDECREF(su->obj);
6231 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006232 Py_XDECREF(su->obj_type);
Christian Heimese93237d2007-12-19 02:37:44 +00006233 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006234}
6235
6236static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006237super_repr(PyObject *self)
6238{
6239 superobject *su = (superobject *)self;
6240
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006241 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006242 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00006243 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006244 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006245 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006246 else
6247 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00006248 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006249 su->type ? su->type->tp_name : "NULL");
6250}
6251
6252static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006253super_getattro(PyObject *self, PyObject *name)
6254{
6255 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006256 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006257
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006258 if (!skip) {
6259 /* We want __class__ to return the class of the super object
6260 (i.e. super, or a subclass), not the class of su->obj. */
6261 skip = (PyString_Check(name) &&
6262 PyString_GET_SIZE(name) == 9 &&
6263 strcmp(PyString_AS_STRING(name), "__class__") == 0);
6264 }
6265
6266 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00006267 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006268 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006269 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006270 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006271
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006272 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006273 mro = starttype->tp_mro;
6274
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006275 if (mro == NULL)
6276 n = 0;
6277 else {
6278 assert(PyTuple_Check(mro));
6279 n = PyTuple_GET_SIZE(mro);
6280 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006281 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00006282 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00006283 break;
6284 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006285 i++;
6286 res = NULL;
6287 for (; i < n; i++) {
6288 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00006289 if (PyType_Check(tmp))
6290 dict = ((PyTypeObject *)tmp)->tp_dict;
6291 else if (PyClass_Check(tmp))
6292 dict = ((PyClassObject *)tmp)->cl_dict;
6293 else
6294 continue;
6295 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00006296 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00006297 Py_INCREF(res);
Christian Heimese93237d2007-12-19 02:37:44 +00006298 f = Py_TYPE(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006299 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006300 tmp = f(res,
6301 /* Only pass 'obj' param if
6302 this is instance-mode super
6303 (See SF ID #743627)
6304 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00006305 (su->obj == (PyObject *)
6306 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006307 ? (PyObject *)NULL
6308 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00006309 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006310 Py_DECREF(res);
6311 res = tmp;
6312 }
6313 return res;
6314 }
6315 }
6316 }
6317 return PyObject_GenericGetAttr(self, name);
6318}
6319
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006320static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006321supercheck(PyTypeObject *type, PyObject *obj)
6322{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006323 /* Check that a super() call makes sense. Return a type object.
6324
6325 obj can be a new-style class, or an instance of one:
6326
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006327 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006328 used for class methods; the return value is obj.
6329
6330 - If it is an instance, it must be an instance of 'type'. This is
6331 the normal case; the return value is obj.__class__.
6332
6333 But... when obj is an instance, we want to allow for the case where
Christian Heimese93237d2007-12-19 02:37:44 +00006334 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006335 This will allow using super() with a proxy for obj.
6336 */
6337
Guido van Rossum8e80a722003-02-18 19:22:22 +00006338 /* Check for first bullet above (special case) */
6339 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6340 Py_INCREF(obj);
6341 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006342 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006343
6344 /* Normal case */
Christian Heimese93237d2007-12-19 02:37:44 +00006345 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6346 Py_INCREF(Py_TYPE(obj));
6347 return Py_TYPE(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006348 }
6349 else {
6350 /* Try the slow way */
6351 static PyObject *class_str = NULL;
6352 PyObject *class_attr;
6353
6354 if (class_str == NULL) {
6355 class_str = PyString_FromString("__class__");
6356 if (class_str == NULL)
6357 return NULL;
6358 }
6359
6360 class_attr = PyObject_GetAttr(obj, class_str);
6361
6362 if (class_attr != NULL &&
6363 PyType_Check(class_attr) &&
Christian Heimese93237d2007-12-19 02:37:44 +00006364 (PyTypeObject *)class_attr != Py_TYPE(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006365 {
6366 int ok = PyType_IsSubtype(
6367 (PyTypeObject *)class_attr, type);
6368 if (ok)
6369 return (PyTypeObject *)class_attr;
6370 }
6371
6372 if (class_attr == NULL)
6373 PyErr_Clear();
6374 else
6375 Py_DECREF(class_attr);
6376 }
6377
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006378 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006379 "super(type, obj): "
6380 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006381 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006382}
6383
Guido van Rossum705f0f52001-08-24 16:47:00 +00006384static PyObject *
6385super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6386{
6387 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00006388 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006389
6390 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6391 /* Not binding to an object, or already bound */
6392 Py_INCREF(self);
6393 return self;
6394 }
Christian Heimese93237d2007-12-19 02:37:44 +00006395 if (Py_TYPE(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00006396 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006397 call its type */
Christian Heimese93237d2007-12-19 02:37:44 +00006398 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006399 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00006400 else {
6401 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006402 PyTypeObject *obj_type = supercheck(su->type, obj);
6403 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006404 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00006405 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006406 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00006407 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006408 return NULL;
6409 Py_INCREF(su->type);
6410 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00006411 newobj->type = su->type;
6412 newobj->obj = obj;
6413 newobj->obj_type = obj_type;
6414 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006415 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006416}
6417
6418static int
6419super_init(PyObject *self, PyObject *args, PyObject *kwds)
6420{
6421 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00006422 PyTypeObject *type;
6423 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006424 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006425
Georg Brandl5d59c092006-09-30 08:43:30 +00006426 if (!_PyArg_NoKeywords("super", kwds))
6427 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006428 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
6429 return -1;
6430 if (obj == Py_None)
6431 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006432 if (obj != NULL) {
6433 obj_type = supercheck(type, obj);
6434 if (obj_type == NULL)
6435 return -1;
6436 Py_INCREF(obj);
6437 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006438 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006439 su->type = type;
6440 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006441 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006442 return 0;
6443}
6444
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006445PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00006446"super(type) -> unbound super object\n"
6447"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006448"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006449"Typical use to call a cooperative superclass method:\n"
6450"class C(B):\n"
6451" def meth(self, arg):\n"
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006452" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006453
Guido van Rossum048eb752001-10-02 21:24:57 +00006454static int
6455super_traverse(PyObject *self, visitproc visit, void *arg)
6456{
6457 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006458
Thomas Woutersc6e55062006-04-15 21:47:09 +00006459 Py_VISIT(su->obj);
6460 Py_VISIT(su->type);
6461 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006462
6463 return 0;
6464}
6465
Guido van Rossum705f0f52001-08-24 16:47:00 +00006466PyTypeObject PySuper_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00006467 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00006468 "super", /* tp_name */
6469 sizeof(superobject), /* tp_basicsize */
6470 0, /* tp_itemsize */
6471 /* methods */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006472 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006473 0, /* tp_print */
6474 0, /* tp_getattr */
6475 0, /* tp_setattr */
6476 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006477 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006478 0, /* tp_as_number */
6479 0, /* tp_as_sequence */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006480 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006481 0, /* tp_hash */
6482 0, /* tp_call */
6483 0, /* tp_str */
6484 super_getattro, /* tp_getattro */
6485 0, /* tp_setattro */
6486 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006487 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6488 Py_TPFLAGS_BASETYPE, /* tp_flags */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006489 super_doc, /* tp_doc */
6490 super_traverse, /* tp_traverse */
6491 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006492 0, /* tp_richcompare */
6493 0, /* tp_weaklistoffset */
6494 0, /* tp_iter */
6495 0, /* tp_iternext */
6496 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006497 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006498 0, /* tp_getset */
6499 0, /* tp_base */
6500 0, /* tp_dict */
6501 super_descr_get, /* tp_descr_get */
6502 0, /* tp_descr_set */
6503 0, /* tp_dictoffset */
6504 super_init, /* tp_init */
6505 PyType_GenericAlloc, /* tp_alloc */
6506 PyType_GenericNew, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006507 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006508};