blob: 82ced39b30baa7e7ff754de11c3ebfc407252b0e [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
Steven Bethardae42f332008-03-18 17:26:10 +0000596static PyObject*
597type_richcompare(PyObject *v, PyObject *w, int op)
598{
599 PyObject *result;
600 Py_uintptr_t vv, ww;
601 int c;
602
603 /* Make sure both arguments are types. */
604 if (!PyType_Check(v) || !PyType_Check(w)) {
605 result = Py_NotImplemented;
606 goto out;
607 }
608
609 /* Py3K warning if comparison isn't == or != */
610 if (Py_Py3kWarningFlag && op != Py_EQ && op != Py_NE &&
611 PyErr_Warn(PyExc_DeprecationWarning,
612 "type inequality comparisons not supported in 3.x.") < 0) {
613 return NULL;
614 }
615
616 /* Compare addresses */
617 vv = (Py_uintptr_t)v;
618 ww = (Py_uintptr_t)w;
619 switch (op) {
620 case Py_LT: c = vv < ww; break;
621 case Py_LE: c = vv <= ww; break;
622 case Py_EQ: c = vv == ww; break;
623 case Py_NE: c = vv != ww; break;
624 case Py_GT: c = vv > ww; break;
625 case Py_GE: c = vv >= ww; break;
626 default:
627 result = Py_NotImplemented;
628 goto out;
629 }
630 result = c ? Py_True : Py_False;
631
632 /* incref and return */
633 out:
634 Py_INCREF(result);
635 return result;
636}
637
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000638static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000639type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000640{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000641 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000642 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000643
644 mod = type_module(type, NULL);
645 if (mod == NULL)
646 PyErr_Clear();
647 else if (!PyString_Check(mod)) {
648 Py_DECREF(mod);
649 mod = NULL;
650 }
651 name = type_name(type, NULL);
652 if (name == NULL)
653 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000654
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000655 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
656 kind = "class";
657 else
658 kind = "type";
659
Barry Warsaw7ce36942001-08-24 18:34:26 +0000660 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000661 rtn = PyString_FromFormat("<%s '%s.%s'>",
662 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000663 PyString_AS_STRING(mod),
664 PyString_AS_STRING(name));
665 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000666 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000667 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000668
Guido van Rossumc3542212001-08-16 09:18:56 +0000669 Py_XDECREF(mod);
670 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000671 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000672}
673
Tim Peters6d6c1a32001-08-02 04:15:00 +0000674static PyObject *
675type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
676{
677 PyObject *obj;
678
679 if (type->tp_new == NULL) {
680 PyErr_Format(PyExc_TypeError,
681 "cannot create '%.100s' instances",
682 type->tp_name);
683 return NULL;
684 }
685
Tim Peters3f996e72001-09-13 19:18:27 +0000686 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000687 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000688 /* Ugly exception: when the call was type(something),
689 don't call tp_init on the result. */
690 if (type == &PyType_Type &&
691 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
692 (kwds == NULL ||
693 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
694 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000695 /* If the returned object is not an instance of type,
696 it won't be initialized. */
697 if (!PyType_IsSubtype(obj->ob_type, type))
698 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000699 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000700 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
701 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000702 type->tp_init(obj, args, kwds) < 0) {
703 Py_DECREF(obj);
704 obj = NULL;
705 }
706 }
707 return obj;
708}
709
710PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000711PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000712{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000713 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000714 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
715 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000716
717 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000718 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000719 else
Anthony Baxtera6286212006-04-11 07:42:36 +0000720 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000721
Neil Schemenauerc806c882001-08-29 23:54:54 +0000722 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000723 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000724
Neil Schemenauerc806c882001-08-29 23:54:54 +0000725 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000726
Tim Peters6d6c1a32001-08-02 04:15:00 +0000727 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
728 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000729
Tim Peters6d6c1a32001-08-02 04:15:00 +0000730 if (type->tp_itemsize == 0)
731 PyObject_INIT(obj, type);
732 else
733 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000734
Tim Peters6d6c1a32001-08-02 04:15:00 +0000735 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000736 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000737 return obj;
738}
739
740PyObject *
741PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
742{
743 return type->tp_alloc(type, 0);
744}
745
Guido van Rossum9475a232001-10-05 20:51:39 +0000746/* Helpers for subtyping */
747
748static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000749traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
750{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000751 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000752 PyMemberDef *mp;
753
Christian Heimese93237d2007-12-19 02:37:44 +0000754 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000755 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000756 for (i = 0; i < n; i++, mp++) {
757 if (mp->type == T_OBJECT_EX) {
758 char *addr = (char *)self + mp->offset;
759 PyObject *obj = *(PyObject **)addr;
760 if (obj != NULL) {
761 int err = visit(obj, arg);
762 if (err)
763 return err;
764 }
765 }
766 }
767 return 0;
768}
769
770static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000771subtype_traverse(PyObject *self, visitproc visit, void *arg)
772{
773 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000774 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000775
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000776 /* Find the nearest base with a different tp_traverse,
777 and traverse slots while we're at it */
Christian Heimese93237d2007-12-19 02:37:44 +0000778 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000779 base = type;
780 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
Christian Heimese93237d2007-12-19 02:37:44 +0000781 if (Py_SIZE(base)) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000782 int err = traverse_slots(base, self, visit, arg);
783 if (err)
784 return err;
785 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000786 base = base->tp_base;
787 assert(base);
788 }
789
790 if (type->tp_dictoffset != base->tp_dictoffset) {
791 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Woutersc6e55062006-04-15 21:47:09 +0000792 if (dictptr && *dictptr)
793 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000794 }
795
Thomas Woutersc6e55062006-04-15 21:47:09 +0000796 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000797 /* For a heaptype, the instances count as references
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000798 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000799 can find cycles involving this link. */
Thomas Woutersc6e55062006-04-15 21:47:09 +0000800 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000801
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000802 if (basetraverse)
803 return basetraverse(self, visit, arg);
804 return 0;
805}
806
807static void
808clear_slots(PyTypeObject *type, PyObject *self)
809{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000810 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000811 PyMemberDef *mp;
812
Christian Heimese93237d2007-12-19 02:37:44 +0000813 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000814 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000815 for (i = 0; i < n; i++, mp++) {
816 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
817 char *addr = (char *)self + mp->offset;
818 PyObject *obj = *(PyObject **)addr;
819 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000820 *(PyObject **)addr = NULL;
Thomas Woutersedf17d82006-04-15 17:28:34 +0000821 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000822 }
823 }
824 }
825}
826
827static int
828subtype_clear(PyObject *self)
829{
830 PyTypeObject *type, *base;
831 inquiry baseclear;
832
833 /* Find the nearest base with a different tp_clear
834 and clear slots while we're at it */
Christian Heimese93237d2007-12-19 02:37:44 +0000835 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000836 base = type;
837 while ((baseclear = base->tp_clear) == subtype_clear) {
Christian Heimese93237d2007-12-19 02:37:44 +0000838 if (Py_SIZE(base))
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000839 clear_slots(base, self);
840 base = base->tp_base;
841 assert(base);
842 }
843
Guido van Rossuma3862092002-06-10 15:24:42 +0000844 /* There's no need to clear the instance dict (if any);
845 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000846
847 if (baseclear)
848 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000849 return 0;
850}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000851
852static void
853subtype_dealloc(PyObject *self)
854{
Guido van Rossum14227b42001-12-06 02:35:58 +0000855 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000856 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000857
Guido van Rossum22b13872002-08-06 21:41:44 +0000858 /* Extract the type; we expect it to be a heap type */
Christian Heimese93237d2007-12-19 02:37:44 +0000859 type = Py_TYPE(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000860 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000861
Guido van Rossum22b13872002-08-06 21:41:44 +0000862 /* Test whether the type has GC exactly once */
863
864 if (!PyType_IS_GC(type)) {
865 /* It's really rare to find a dynamic type that doesn't have
866 GC; it can only happen when deriving from 'object' and not
867 adding any slots or instance variables. This allows
868 certain simplifications: there's no need to call
869 clear_slots(), or DECREF the dict, or clear weakrefs. */
870
871 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000872 if (type->tp_del) {
873 type->tp_del(self);
874 if (self->ob_refcnt > 0)
875 return;
876 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000877
878 /* Find the nearest base with a different tp_dealloc */
879 base = type;
880 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimese93237d2007-12-19 02:37:44 +0000881 assert(Py_SIZE(base) == 0);
Guido van Rossum22b13872002-08-06 21:41:44 +0000882 base = base->tp_base;
883 assert(base);
884 }
885
886 /* Call the base tp_dealloc() */
887 assert(basedealloc);
888 basedealloc(self);
889
890 /* Can't reference self beyond this point */
891 Py_DECREF(type);
892
893 /* Done */
894 return;
895 }
896
897 /* We get here only if the type has GC */
898
899 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000900 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000901 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000902 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000903 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000904 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000905 /* DO NOT restore GC tracking at this point. weakref callbacks
906 * (if any, and whether directly here or indirectly in something we
907 * call) may trigger GC, and if self is tracked at that point, it
908 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000909 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000910
Guido van Rossum59195fd2003-06-13 20:54:40 +0000911 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000912 base = type;
913 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000914 base = base->tp_base;
915 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000916 }
917
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000918 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000919 the finalizer (__del__), clearing slots, or clearing the instance
920 dict. */
921
Guido van Rossum1987c662003-05-29 14:29:23 +0000922 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
923 PyObject_ClearWeakRefs(self);
924
925 /* Maybe call finalizer; exit early if resurrected */
926 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000927 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000928 type->tp_del(self);
929 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000930 goto endlabel; /* resurrected */
931 else
932 _PyObject_GC_UNTRACK(self);
Brett Cannonf5bee302007-01-23 23:21:22 +0000933 /* New weakrefs could be created during the finalizer call.
934 If this occurs, clear them out without calling their
935 finalizers since they might rely on part of the object
936 being finalized that has already been destroyed. */
937 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
938 /* Modeled after GET_WEAKREFS_LISTPTR() */
939 PyWeakReference **list = (PyWeakReference **) \
940 PyObject_GET_WEAKREFS_LISTPTR(self);
941 while (*list)
942 _PyWeakref_ClearRef(*list);
943 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000944 }
945
Guido van Rossum59195fd2003-06-13 20:54:40 +0000946 /* Clear slots up to the nearest base with a different tp_dealloc */
947 base = type;
948 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimese93237d2007-12-19 02:37:44 +0000949 if (Py_SIZE(base))
Guido van Rossum59195fd2003-06-13 20:54:40 +0000950 clear_slots(base, self);
951 base = base->tp_base;
952 assert(base);
953 }
954
Tim Peters6d6c1a32001-08-02 04:15:00 +0000955 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000956 if (type->tp_dictoffset && !base->tp_dictoffset) {
957 PyObject **dictptr = _PyObject_GetDictPtr(self);
958 if (dictptr != NULL) {
959 PyObject *dict = *dictptr;
960 if (dict != NULL) {
961 Py_DECREF(dict);
962 *dictptr = NULL;
963 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000964 }
965 }
966
Tim Peters0bd743c2003-11-13 22:50:00 +0000967 /* Call the base tp_dealloc(); first retrack self if
968 * basedealloc knows about gc.
969 */
970 if (PyType_IS_GC(base))
971 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000972 assert(basedealloc);
973 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000974
975 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000976 Py_DECREF(type);
977
Guido van Rossum0906e072002-08-07 20:42:09 +0000978 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000979 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000980 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000981 --_PyTrash_delete_nesting;
982
983 /* Explanation of the weirdness around the trashcan macros:
984
985 Q. What do the trashcan macros do?
986
987 A. Read the comment titled "Trashcan mechanism" in object.h.
988 For one, this explains why there must be a call to GC-untrack
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000989 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000990 trashcan code, the answers to the following questions don't make
991 sense.
992
993 Q. Why do we GC-untrack before the trashcan and then immediately
994 GC-track again afterward?
995
996 A. In the case that the base class is GC-aware, the base class
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000997 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000998 UNTRACK macro, this will crash when the object is already
999 untracked. Because we don't know what the base class does, the
1000 only safe thing is to make sure the object is tracked when we
1001 call the base class dealloc. But... The trashcan begin macro
1002 requires that the object is *untracked* before it is called. So
1003 the dance becomes:
1004
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001005 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001006 trashcan begin
1007 GC track
1008
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001009 Q. Why did the last question say "immediately GC-track again"?
1010 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001011
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001012 A. Because the code *used* to re-track immediately. Bad Idea.
1013 self has a refcount of 0, and if gc ever gets its hands on it
1014 (which can happen if any weakref callback gets invoked), it
1015 looks like trash to gc too, and gc also tries to delete self
1016 then. But we're already deleting self. Double dealloction is
1017 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001018
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001019 Q. Why the bizarre (net-zero) manipulation of
1020 _PyTrash_delete_nesting around the trashcan macros?
1021
1022 A. Some base classes (e.g. list) also use the trashcan mechanism.
1023 The following scenario used to be possible:
1024
1025 - suppose the trashcan level is one below the trashcan limit
1026
1027 - subtype_dealloc() is called
1028
1029 - the trashcan limit is not yet reached, so the trashcan level
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001030 is incremented and the code between trashcan begin and end is
1031 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001032
1033 - this destroys much of the object's contents, including its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001034 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001035
1036 - basedealloc() is called; this is really list_dealloc(), or
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001037 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001038
1039 - the trashcan limit is now reached, so the object is put on the
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001040 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001041
1042 - basedealloc() returns
1043
1044 - subtype_dealloc() decrefs the object's type
1045
1046 - subtype_dealloc() returns
1047
1048 - later, the trashcan code starts deleting the objects from its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001049 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001050
1051 - subtype_dealloc() is called *AGAIN* for the same object
1052
1053 - at the very least (if the destroyed slots and __dict__ don't
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001054 cause problems) the object's type gets decref'ed a second
1055 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001056
1057 The remedy is to make sure that if the code between trashcan
1058 begin and end in subtype_dealloc() is called, the code between
1059 trashcan begin and end in basedealloc() will also be called.
1060 This is done by decrementing the level after passing into the
1061 trashcan block, and incrementing it just before leaving the
1062 block.
1063
1064 But now it's possible that a chain of objects consisting solely
1065 of objects whose deallocator is subtype_dealloc() will defeat
1066 the trashcan mechanism completely: the decremented level means
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001067 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001068 *increment* the level *before* entering the trashcan block, and
1069 matchingly decrement it after leaving. This means the trashcan
1070 code will trigger a little early, but that's no big deal.
1071
1072 Q. Are there any live examples of code in need of all this
1073 complexity?
1074
1075 A. Yes. See SF bug 668433 for code that crashed (when Python was
1076 compiled in debug mode) before the trashcan level manipulations
1077 were added. For more discussion, see SF patches 581742, 575073
1078 and bug 574207.
1079 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001080}
1081
Jeremy Hylton938ace62002-07-17 16:30:39 +00001082static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001083
Tim Peters6d6c1a32001-08-02 04:15:00 +00001084/* type test with subclassing support */
1085
1086int
1087PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1088{
1089 PyObject *mro;
1090
Guido van Rossum9478d072001-09-07 18:52:13 +00001091 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1092 return b == a || b == &PyBaseObject_Type;
1093
Tim Peters6d6c1a32001-08-02 04:15:00 +00001094 mro = a->tp_mro;
1095 if (mro != NULL) {
1096 /* Deal with multiple inheritance without recursion
1097 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001098 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001099 assert(PyTuple_Check(mro));
1100 n = PyTuple_GET_SIZE(mro);
1101 for (i = 0; i < n; i++) {
1102 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1103 return 1;
1104 }
1105 return 0;
1106 }
1107 else {
1108 /* a is not completely initilized yet; follow tp_base */
1109 do {
1110 if (a == b)
1111 return 1;
1112 a = a->tp_base;
1113 } while (a != NULL);
1114 return b == &PyBaseObject_Type;
1115 }
1116}
1117
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001118/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001119 without looking in the instance dictionary
1120 (so we can't use PyObject_GetAttr) but still binding
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001121 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001122 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001123 static variable used to cache the interned Python string.
1124
1125 Two variants:
1126
1127 - lookup_maybe() returns NULL without raising an exception
1128 when the _PyType_Lookup() call fails;
1129
1130 - lookup_method() always raises an exception upon errors.
1131*/
Guido van Rossum60718732001-08-28 17:47:51 +00001132
1133static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001134lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001135{
1136 PyObject *res;
1137
1138 if (*attrobj == NULL) {
1139 *attrobj = PyString_InternFromString(attrstr);
1140 if (*attrobj == NULL)
1141 return NULL;
1142 }
Christian Heimese93237d2007-12-19 02:37:44 +00001143 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001144 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +00001145 descrgetfunc f;
Christian Heimese93237d2007-12-19 02:37:44 +00001146 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
Guido van Rossum60718732001-08-28 17:47:51 +00001147 Py_INCREF(res);
1148 else
Christian Heimese93237d2007-12-19 02:37:44 +00001149 res = f(res, self, (PyObject *)(Py_TYPE(self)));
Guido van Rossum60718732001-08-28 17:47:51 +00001150 }
1151 return res;
1152}
1153
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001154static PyObject *
1155lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1156{
1157 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1158 if (res == NULL && !PyErr_Occurred())
1159 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1160 return res;
1161}
1162
Guido van Rossum2730b132001-08-28 18:22:14 +00001163/* A variation of PyObject_CallMethod that uses lookup_method()
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001164 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001165 as lookup_method to cache the interned name string object. */
1166
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001167static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001168call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1169{
1170 va_list va;
1171 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001172 va_start(va, format);
1173
Guido van Rossumda21c012001-10-03 00:50:18 +00001174 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001175 if (func == NULL) {
1176 va_end(va);
1177 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +00001178 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001179 return NULL;
1180 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001181
1182 if (format && *format)
1183 args = Py_VaBuildValue(format, va);
1184 else
1185 args = PyTuple_New(0);
1186
1187 va_end(va);
1188
1189 if (args == NULL)
1190 return NULL;
1191
1192 assert(PyTuple_Check(args));
1193 retval = PyObject_Call(func, args, NULL);
1194
1195 Py_DECREF(args);
1196 Py_DECREF(func);
1197
1198 return retval;
1199}
1200
1201/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1202
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001203static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001204call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1205{
1206 va_list va;
1207 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001208 va_start(va, format);
1209
Guido van Rossumda21c012001-10-03 00:50:18 +00001210 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +00001211 if (func == NULL) {
1212 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001213 if (!PyErr_Occurred()) {
1214 Py_INCREF(Py_NotImplemented);
1215 return Py_NotImplemented;
1216 }
Guido van Rossum717ce002001-09-14 16:58:08 +00001217 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001218 }
1219
1220 if (format && *format)
1221 args = Py_VaBuildValue(format, va);
1222 else
1223 args = PyTuple_New(0);
1224
1225 va_end(va);
1226
Guido van Rossum717ce002001-09-14 16:58:08 +00001227 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00001228 return NULL;
1229
Guido van Rossum717ce002001-09-14 16:58:08 +00001230 assert(PyTuple_Check(args));
1231 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001232
1233 Py_DECREF(args);
1234 Py_DECREF(func);
1235
1236 return retval;
1237}
1238
Tim Petersa91e9642001-11-14 23:32:33 +00001239static int
1240fill_classic_mro(PyObject *mro, PyObject *cls)
1241{
1242 PyObject *bases, *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001243 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001244
1245 assert(PyList_Check(mro));
1246 assert(PyClass_Check(cls));
1247 i = PySequence_Contains(mro, cls);
1248 if (i < 0)
1249 return -1;
1250 if (!i) {
1251 if (PyList_Append(mro, cls) < 0)
1252 return -1;
1253 }
1254 bases = ((PyClassObject *)cls)->cl_bases;
1255 assert(bases && PyTuple_Check(bases));
1256 n = PyTuple_GET_SIZE(bases);
1257 for (i = 0; i < n; i++) {
1258 base = PyTuple_GET_ITEM(bases, i);
1259 if (fill_classic_mro(mro, base) < 0)
1260 return -1;
1261 }
1262 return 0;
1263}
1264
1265static PyObject *
1266classic_mro(PyObject *cls)
1267{
1268 PyObject *mro;
1269
1270 assert(PyClass_Check(cls));
1271 mro = PyList_New(0);
1272 if (mro != NULL) {
1273 if (fill_classic_mro(mro, cls) == 0)
1274 return mro;
1275 Py_DECREF(mro);
1276 }
1277 return NULL;
1278}
1279
Tim Petersea7f75d2002-12-07 21:39:16 +00001280/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001281 Method resolution order algorithm C3 described in
1282 "A Monotonic Superclass Linearization for Dylan",
1283 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001284 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001285 (OOPSLA 1996)
1286
Guido van Rossum98f33732002-11-25 21:36:54 +00001287 Some notes about the rules implied by C3:
1288
Tim Petersea7f75d2002-12-07 21:39:16 +00001289 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001290 It isn't legal to repeat a class in a list of base classes.
1291
1292 The next three properties are the 3 constraints in "C3".
1293
Tim Petersea7f75d2002-12-07 21:39:16 +00001294 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001295 If A precedes B in C's MRO, then A will precede B in the MRO of all
1296 subclasses of C.
1297
1298 Monotonicity.
1299 The MRO of a class must be an extension without reordering of the
1300 MRO of each of its superclasses.
1301
1302 Extended Precedence Graph (EPG).
1303 Linearization is consistent if there is a path in the EPG from
1304 each class to all its successors in the linearization. See
1305 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001306 */
1307
Tim Petersea7f75d2002-12-07 21:39:16 +00001308static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001309tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001310 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001311 size = PyList_GET_SIZE(list);
1312
1313 for (j = whence+1; j < size; j++) {
1314 if (PyList_GET_ITEM(list, j) == o)
1315 return 1;
1316 }
1317 return 0;
1318}
1319
Guido van Rossum98f33732002-11-25 21:36:54 +00001320static PyObject *
1321class_name(PyObject *cls)
1322{
1323 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1324 if (name == NULL) {
1325 PyErr_Clear();
1326 Py_XDECREF(name);
1327 name = PyObject_Repr(cls);
1328 }
1329 if (name == NULL)
1330 return NULL;
1331 if (!PyString_Check(name)) {
1332 Py_DECREF(name);
1333 return NULL;
1334 }
1335 return name;
1336}
1337
1338static int
1339check_duplicates(PyObject *list)
1340{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001341 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001342 /* Let's use a quadratic time algorithm,
1343 assuming that the bases lists is short.
1344 */
1345 n = PyList_GET_SIZE(list);
1346 for (i = 0; i < n; i++) {
1347 PyObject *o = PyList_GET_ITEM(list, i);
1348 for (j = i + 1; j < n; j++) {
1349 if (PyList_GET_ITEM(list, j) == o) {
1350 o = class_name(o);
1351 PyErr_Format(PyExc_TypeError,
1352 "duplicate base class %s",
1353 o ? PyString_AS_STRING(o) : "?");
1354 Py_XDECREF(o);
1355 return -1;
1356 }
1357 }
1358 }
1359 return 0;
1360}
1361
1362/* Raise a TypeError for an MRO order disagreement.
1363
1364 It's hard to produce a good error message. In the absence of better
1365 insight into error reporting, report the classes that were candidates
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001366 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001367 order in which they should be put in the MRO, but it's hard to
1368 diagnose what constraint can't be satisfied.
1369*/
1370
1371static void
1372set_mro_error(PyObject *to_merge, int *remain)
1373{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001374 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001375 char buf[1000];
1376 PyObject *k, *v;
1377 PyObject *set = PyDict_New();
Georg Brandl5c170fd2006-03-17 19:03:25 +00001378 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001379
1380 to_merge_size = PyList_GET_SIZE(to_merge);
1381 for (i = 0; i < to_merge_size; i++) {
1382 PyObject *L = PyList_GET_ITEM(to_merge, i);
1383 if (remain[i] < PyList_GET_SIZE(L)) {
1384 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Georg Brandl5c170fd2006-03-17 19:03:25 +00001385 if (PyDict_SetItem(set, c, Py_None) < 0) {
1386 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001387 return;
Georg Brandl5c170fd2006-03-17 19:03:25 +00001388 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001389 }
1390 }
1391 n = PyDict_Size(set);
1392
Raymond Hettingerf394df42003-04-06 19:13:41 +00001393 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1394consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001395 i = 0;
Skip Montanaro429433b2006-04-18 00:35:43 +00001396 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001397 PyObject *name = class_name(k);
1398 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1399 name ? PyString_AS_STRING(name) : "?");
1400 Py_XDECREF(name);
Skip Montanaro429433b2006-04-18 00:35:43 +00001401 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001402 buf[off++] = ',';
1403 buf[off] = '\0';
1404 }
1405 }
1406 PyErr_SetString(PyExc_TypeError, buf);
1407 Py_DECREF(set);
1408}
1409
Tim Petersea7f75d2002-12-07 21:39:16 +00001410static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001411pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001412 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001413 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001414 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001415
Guido van Rossum1f121312002-11-14 19:49:16 +00001416 to_merge_size = PyList_GET_SIZE(to_merge);
1417
Guido van Rossum98f33732002-11-25 21:36:54 +00001418 /* remain stores an index into each sublist of to_merge.
1419 remain[i] is the index of the next base in to_merge[i]
1420 that is not included in acc.
1421 */
Anthony Baxtera6286212006-04-11 07:42:36 +00001422 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001423 if (remain == NULL)
1424 return -1;
1425 for (i = 0; i < to_merge_size; i++)
1426 remain[i] = 0;
1427
1428 again:
1429 empty_cnt = 0;
1430 for (i = 0; i < to_merge_size; i++) {
1431 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001432
Guido van Rossum1f121312002-11-14 19:49:16 +00001433 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1434
1435 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1436 empty_cnt++;
1437 continue;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001438 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001439
Guido van Rossum98f33732002-11-25 21:36:54 +00001440 /* Choose next candidate for MRO.
1441
1442 The input sequences alone can determine the choice.
1443 If not, choose the class which appears in the MRO
1444 of the earliest direct superclass of the new class.
1445 */
1446
Guido van Rossum1f121312002-11-14 19:49:16 +00001447 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1448 for (j = 0; j < to_merge_size; j++) {
1449 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001450 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001451 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001452 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001453 }
1454 ok = PyList_Append(acc, candidate);
1455 if (ok < 0) {
1456 PyMem_Free(remain);
1457 return -1;
1458 }
1459 for (j = 0; j < to_merge_size; j++) {
1460 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001461 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1462 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001463 remain[j]++;
1464 }
1465 }
1466 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001467 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001468 }
1469
Guido van Rossum98f33732002-11-25 21:36:54 +00001470 if (empty_cnt == to_merge_size) {
1471 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001472 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001473 }
1474 set_mro_error(to_merge, remain);
1475 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001476 return -1;
1477}
1478
Tim Peters6d6c1a32001-08-02 04:15:00 +00001479static PyObject *
1480mro_implementation(PyTypeObject *type)
1481{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001482 Py_ssize_t i, n;
1483 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001484 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001485 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001486
Neal Norwitze7bb9182008-01-27 17:10:14 +00001487 if (type->tp_dict == NULL) {
1488 if (PyType_Ready(type) < 0)
Guido van Rossum63517572002-06-18 16:44:57 +00001489 return NULL;
1490 }
1491
Guido van Rossum98f33732002-11-25 21:36:54 +00001492 /* Find a superclass linearization that honors the constraints
1493 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001494 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001495
1496 to_merge is a list of lists, where each list is a superclass
1497 linearization implied by a base class. The last element of
1498 to_merge is the declared list of bases.
1499 */
1500
Tim Peters6d6c1a32001-08-02 04:15:00 +00001501 bases = type->tp_bases;
1502 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001503
1504 to_merge = PyList_New(n+1);
1505 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001506 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001507
Tim Peters6d6c1a32001-08-02 04:15:00 +00001508 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001509 PyObject *base = PyTuple_GET_ITEM(bases, i);
1510 PyObject *parentMRO;
1511 if (PyType_Check(base))
1512 parentMRO = PySequence_List(
1513 ((PyTypeObject*)base)->tp_mro);
1514 else
1515 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001516 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001517 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001518 return NULL;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001519 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001520
1521 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001522 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001523
1524 bases_aslist = PySequence_List(bases);
1525 if (bases_aslist == NULL) {
1526 Py_DECREF(to_merge);
1527 return NULL;
1528 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001529 /* This is just a basic sanity check. */
1530 if (check_duplicates(bases_aslist) < 0) {
1531 Py_DECREF(to_merge);
1532 Py_DECREF(bases_aslist);
1533 return NULL;
1534 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001535 PyList_SET_ITEM(to_merge, n, bases_aslist);
1536
1537 result = Py_BuildValue("[O]", (PyObject *)type);
1538 if (result == NULL) {
1539 Py_DECREF(to_merge);
1540 return NULL;
1541 }
1542
1543 ok = pmerge(result, to_merge);
1544 Py_DECREF(to_merge);
1545 if (ok < 0) {
1546 Py_DECREF(result);
1547 return NULL;
1548 }
1549
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550 return result;
1551}
1552
1553static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001554mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001555{
1556 PyTypeObject *type = (PyTypeObject *)self;
1557
Tim Peters6d6c1a32001-08-02 04:15:00 +00001558 return mro_implementation(type);
1559}
1560
1561static int
1562mro_internal(PyTypeObject *type)
1563{
1564 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001565 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001566
Christian Heimese93237d2007-12-19 02:37:44 +00001567 if (Py_TYPE(type) == &PyType_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001568 result = mro_implementation(type);
1569 }
1570 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001571 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001572 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001573 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001574 if (mro == NULL)
1575 return -1;
1576 result = PyObject_CallObject(mro, NULL);
1577 Py_DECREF(mro);
1578 }
1579 if (result == NULL)
1580 return -1;
1581 tuple = PySequence_Tuple(result);
1582 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001583 if (tuple == NULL)
1584 return -1;
1585 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001586 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001587 PyObject *cls;
1588 PyTypeObject *solid;
1589
1590 solid = solid_base(type);
1591
1592 len = PyTuple_GET_SIZE(tuple);
1593
1594 for (i = 0; i < len; i++) {
1595 PyTypeObject *t;
1596 cls = PyTuple_GET_ITEM(tuple, i);
1597 if (PyClass_Check(cls))
1598 continue;
1599 else if (!PyType_Check(cls)) {
1600 PyErr_Format(PyExc_TypeError,
1601 "mro() returned a non-class ('%.500s')",
Christian Heimese93237d2007-12-19 02:37:44 +00001602 Py_TYPE(cls)->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001603 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001604 return -1;
1605 }
1606 t = (PyTypeObject*)cls;
1607 if (!PyType_IsSubtype(solid, solid_base(t))) {
1608 PyErr_Format(PyExc_TypeError,
1609 "mro() returned base with unsuitable layout ('%.500s')",
1610 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001611 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001612 return -1;
1613 }
1614 }
1615 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001616 type->tp_mro = tuple;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001617
1618 type_mro_modified(type, type->tp_mro);
1619 /* corner case: the old-style super class might have been hidden
1620 from the custom MRO */
1621 type_mro_modified(type, type->tp_bases);
1622
1623 type_modified(type);
1624
Tim Peters6d6c1a32001-08-02 04:15:00 +00001625 return 0;
1626}
1627
1628
1629/* Calculate the best base amongst multiple base classes.
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001630 This is the first one that's on the path to the "solid base". */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631
1632static PyTypeObject *
1633best_base(PyObject *bases)
1634{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001635 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001636 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001637 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001638
1639 assert(PyTuple_Check(bases));
1640 n = PyTuple_GET_SIZE(bases);
1641 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001642 base = NULL;
1643 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001644 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001645 base_proto = PyTuple_GET_ITEM(bases, i);
1646 if (PyClass_Check(base_proto))
1647 continue;
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001648 if (!PyType_Check(base_proto)) {
1649 PyErr_SetString(
1650 PyExc_TypeError,
1651 "bases must be types");
1652 return NULL;
1653 }
Tim Petersa91e9642001-11-14 23:32:33 +00001654 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001655 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001656 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657 return NULL;
1658 }
1659 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001660 if (winner == NULL) {
1661 winner = candidate;
1662 base = base_i;
1663 }
1664 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001665 ;
1666 else if (PyType_IsSubtype(candidate, winner)) {
1667 winner = candidate;
1668 base = base_i;
1669 }
1670 else {
1671 PyErr_SetString(
1672 PyExc_TypeError,
1673 "multiple bases have "
1674 "instance lay-out conflict");
1675 return NULL;
1676 }
1677 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001678 if (base == NULL)
1679 PyErr_SetString(PyExc_TypeError,
1680 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681 return base;
1682}
1683
1684static int
1685extra_ivars(PyTypeObject *type, PyTypeObject *base)
1686{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001687 size_t t_size = type->tp_basicsize;
1688 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001689
Guido van Rossum9676b222001-08-17 20:32:36 +00001690 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001691 if (type->tp_itemsize || base->tp_itemsize) {
1692 /* If itemsize is involved, stricter rules */
1693 return t_size != b_size ||
1694 type->tp_itemsize != base->tp_itemsize;
1695 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001696 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001697 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1698 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001699 t_size -= sizeof(PyObject *);
1700 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001701 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1702 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001703 t_size -= sizeof(PyObject *);
1704
1705 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001706}
1707
1708static PyTypeObject *
1709solid_base(PyTypeObject *type)
1710{
1711 PyTypeObject *base;
1712
1713 if (type->tp_base)
1714 base = solid_base(type->tp_base);
1715 else
1716 base = &PyBaseObject_Type;
1717 if (extra_ivars(type, base))
1718 return type;
1719 else
1720 return base;
1721}
1722
Jeremy Hylton938ace62002-07-17 16:30:39 +00001723static void object_dealloc(PyObject *);
1724static int object_init(PyObject *, PyObject *, PyObject *);
1725static int update_slot(PyTypeObject *, PyObject *);
1726static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001727
Armin Rigo9790a272007-05-02 19:23:31 +00001728/*
1729 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1730 * inherited from various builtin types. The builtin base usually provides
1731 * its own __dict__ descriptor, so we use that when we can.
1732 */
1733static PyTypeObject *
1734get_builtin_base_with_dict(PyTypeObject *type)
1735{
1736 while (type->tp_base != NULL) {
1737 if (type->tp_dictoffset != 0 &&
1738 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1739 return type;
1740 type = type->tp_base;
1741 }
1742 return NULL;
1743}
1744
1745static PyObject *
1746get_dict_descriptor(PyTypeObject *type)
1747{
1748 static PyObject *dict_str;
1749 PyObject *descr;
1750
1751 if (dict_str == NULL) {
1752 dict_str = PyString_InternFromString("__dict__");
1753 if (dict_str == NULL)
1754 return NULL;
1755 }
1756 descr = _PyType_Lookup(type, dict_str);
1757 if (descr == NULL || !PyDescr_IsData(descr))
1758 return NULL;
1759
1760 return descr;
1761}
1762
1763static void
1764raise_dict_descr_error(PyObject *obj)
1765{
1766 PyErr_Format(PyExc_TypeError,
1767 "this __dict__ descriptor does not support "
1768 "'%.200s' objects", obj->ob_type->tp_name);
1769}
1770
Tim Peters6d6c1a32001-08-02 04:15:00 +00001771static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001772subtype_dict(PyObject *obj, void *context)
1773{
Armin Rigo9790a272007-05-02 19:23:31 +00001774 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001775 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001776 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001777
Armin Rigo9790a272007-05-02 19:23:31 +00001778 base = get_builtin_base_with_dict(obj->ob_type);
1779 if (base != NULL) {
1780 descrgetfunc func;
1781 PyObject *descr = get_dict_descriptor(base);
1782 if (descr == NULL) {
1783 raise_dict_descr_error(obj);
1784 return NULL;
1785 }
1786 func = descr->ob_type->tp_descr_get;
1787 if (func == NULL) {
1788 raise_dict_descr_error(obj);
1789 return NULL;
1790 }
1791 return func(descr, obj, (PyObject *)(obj->ob_type));
1792 }
1793
1794 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001795 if (dictptr == NULL) {
1796 PyErr_SetString(PyExc_AttributeError,
1797 "This object has no __dict__");
1798 return NULL;
1799 }
1800 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001801 if (dict == NULL)
1802 *dictptr = dict = PyDict_New();
1803 Py_XINCREF(dict);
1804 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001805}
1806
Guido van Rossum6661be32001-10-26 04:26:12 +00001807static int
1808subtype_setdict(PyObject *obj, PyObject *value, void *context)
1809{
Armin Rigo9790a272007-05-02 19:23:31 +00001810 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001811 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001812 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001813
Armin Rigo9790a272007-05-02 19:23:31 +00001814 base = get_builtin_base_with_dict(obj->ob_type);
1815 if (base != NULL) {
1816 descrsetfunc func;
1817 PyObject *descr = get_dict_descriptor(base);
1818 if (descr == NULL) {
1819 raise_dict_descr_error(obj);
1820 return -1;
1821 }
1822 func = descr->ob_type->tp_descr_set;
1823 if (func == NULL) {
1824 raise_dict_descr_error(obj);
1825 return -1;
1826 }
1827 return func(descr, obj, value);
1828 }
1829
1830 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001831 if (dictptr == NULL) {
1832 PyErr_SetString(PyExc_AttributeError,
1833 "This object has no __dict__");
1834 return -1;
1835 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001836 if (value != NULL && !PyDict_Check(value)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001837 PyErr_Format(PyExc_TypeError,
1838 "__dict__ must be set to a dictionary, "
Christian Heimese93237d2007-12-19 02:37:44 +00001839 "not a '%.200s'", Py_TYPE(value)->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001840 return -1;
1841 }
1842 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001843 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001844 *dictptr = value;
1845 Py_XDECREF(dict);
1846 return 0;
1847}
1848
Guido van Rossumad47da02002-08-12 19:05:44 +00001849static PyObject *
1850subtype_getweakref(PyObject *obj, void *context)
1851{
1852 PyObject **weaklistptr;
1853 PyObject *result;
1854
Christian Heimese93237d2007-12-19 02:37:44 +00001855 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001856 PyErr_SetString(PyExc_AttributeError,
Fred Drake7a36f5f2006-08-04 05:17:21 +00001857 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001858 return NULL;
1859 }
Christian Heimese93237d2007-12-19 02:37:44 +00001860 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1861 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1862 (size_t)(Py_TYPE(obj)->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001863 weaklistptr = (PyObject **)
Christian Heimese93237d2007-12-19 02:37:44 +00001864 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001865 if (*weaklistptr == NULL)
1866 result = Py_None;
1867 else
1868 result = *weaklistptr;
1869 Py_INCREF(result);
1870 return result;
1871}
1872
Guido van Rossum373c7412003-01-07 13:41:37 +00001873/* Three variants on the subtype_getsets list. */
1874
1875static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001876 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001877 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001878 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001879 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001880 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001881};
1882
Guido van Rossum373c7412003-01-07 13:41:37 +00001883static PyGetSetDef subtype_getsets_dict_only[] = {
1884 {"__dict__", subtype_dict, subtype_setdict,
1885 PyDoc_STR("dictionary for instance variables (if defined)")},
1886 {0}
1887};
1888
1889static PyGetSetDef subtype_getsets_weakref_only[] = {
1890 {"__weakref__", subtype_getweakref, NULL,
1891 PyDoc_STR("list of weak references to the object (if defined)")},
1892 {0}
1893};
1894
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001895static int
1896valid_identifier(PyObject *s)
1897{
Guido van Rossum03013a02002-07-16 14:30:28 +00001898 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001899 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001900
1901 if (!PyString_Check(s)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001902 PyErr_Format(PyExc_TypeError,
1903 "__slots__ items must be strings, not '%.200s'",
Christian Heimese93237d2007-12-19 02:37:44 +00001904 Py_TYPE(s)->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001905 return 0;
1906 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001907 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001908 n = PyString_GET_SIZE(s);
1909 /* We must reject an empty name. As a hack, we bump the
1910 length to 1 so that the loop will balk on the trailing \0. */
1911 if (n == 0)
1912 n = 1;
1913 for (i = 0; i < n; i++, p++) {
1914 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1915 PyErr_SetString(PyExc_TypeError,
1916 "__slots__ must be identifiers");
1917 return 0;
1918 }
1919 }
1920 return 1;
1921}
1922
Martin v. Löwisd919a592002-10-14 21:07:28 +00001923#ifdef Py_USING_UNICODE
1924/* Replace Unicode objects in slots. */
1925
1926static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001927_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001928{
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001929 PyObject *tmp = NULL;
1930 PyObject *slot_name, *new_name;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001931 Py_ssize_t i;
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001932
Martin v. Löwisd919a592002-10-14 21:07:28 +00001933 for (i = 0; i < nslots; i++) {
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001934 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1935 if (tmp == NULL) {
1936 tmp = PySequence_List(slots);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001937 if (tmp == NULL)
1938 return NULL;
1939 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001940 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1941 NULL);
1942 if (new_name == NULL) {
Martin v. Löwisd919a592002-10-14 21:07:28 +00001943 Py_DECREF(tmp);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001944 return NULL;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001945 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001946 Py_INCREF(new_name);
1947 PyList_SET_ITEM(tmp, i, new_name);
1948 Py_DECREF(slot_name);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001949 }
1950 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001951 if (tmp != NULL) {
1952 slots = PyList_AsTuple(tmp);
1953 Py_DECREF(tmp);
1954 }
1955 return slots;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001956}
1957#endif
1958
Guido van Rossumf102e242007-03-23 18:53:03 +00001959/* Forward */
1960static int
1961object_init(PyObject *self, PyObject *args, PyObject *kwds);
1962
1963static int
1964type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1965{
1966 int res;
1967
1968 assert(args != NULL && PyTuple_Check(args));
1969 assert(kwds == NULL || PyDict_Check(kwds));
1970
1971 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1972 PyErr_SetString(PyExc_TypeError,
1973 "type.__init__() takes no keyword arguments");
1974 return -1;
1975 }
1976
1977 if (args != NULL && PyTuple_Check(args) &&
1978 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1979 PyErr_SetString(PyExc_TypeError,
1980 "type.__init__() takes 1 or 3 arguments");
1981 return -1;
1982 }
1983
1984 /* Call object.__init__(self) now. */
1985 /* XXX Could call super(type, cls).__init__() but what's the point? */
1986 args = PyTuple_GetSlice(args, 0, 0);
1987 res = object_init(cls, args, NULL);
1988 Py_DECREF(args);
1989 return res;
1990}
1991
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001992static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001993type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1994{
1995 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001996 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001997 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001998 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001999 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00002000 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002001 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00002002 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002003
Tim Peters3abca122001-10-27 19:37:48 +00002004 assert(args != NULL && PyTuple_Check(args));
2005 assert(kwds == NULL || PyDict_Check(kwds));
2006
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00002007 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00002008 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002009 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2010 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002011
2012 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2013 PyObject *x = PyTuple_GET_ITEM(args, 0);
Christian Heimese93237d2007-12-19 02:37:44 +00002014 Py_INCREF(Py_TYPE(x));
2015 return (PyObject *) Py_TYPE(x);
Tim Peters3abca122001-10-27 19:37:48 +00002016 }
2017
2018 /* SF bug 475327 -- if that didn't trigger, we need 3
2019 arguments. but PyArg_ParseTupleAndKeywords below may give
2020 a msg saying type() needs exactly 3. */
2021 if (nargs + nkwds != 3) {
2022 PyErr_SetString(PyExc_TypeError,
2023 "type() takes 1 or 3 arguments");
2024 return NULL;
2025 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002026 }
2027
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00002028 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002029 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
2030 &name,
2031 &PyTuple_Type, &bases,
2032 &PyDict_Type, &dict))
2033 return NULL;
2034
Armin Rigoc0ba52d2007-04-19 14:44:48 +00002035 /* Determine the proper metatype to deal with this,
2036 and check for metatype conflicts while we're at it.
2037 Note that if some other metatype wins to contract,
2038 it's possible that its instances are not types. */
2039 nbases = PyTuple_GET_SIZE(bases);
2040 winner = metatype;
2041 for (i = 0; i < nbases; i++) {
2042 tmp = PyTuple_GET_ITEM(bases, i);
2043 tmptype = tmp->ob_type;
2044 if (tmptype == &PyClass_Type)
2045 continue; /* Special case classic classes */
2046 if (PyType_IsSubtype(winner, tmptype))
2047 continue;
2048 if (PyType_IsSubtype(tmptype, winner)) {
2049 winner = tmptype;
2050 continue;
Jeremy Hyltonfa955692007-02-27 18:29:45 +00002051 }
Armin Rigoc0ba52d2007-04-19 14:44:48 +00002052 PyErr_SetString(PyExc_TypeError,
2053 "metaclass conflict: "
2054 "the metaclass of a derived class "
2055 "must be a (non-strict) subclass "
2056 "of the metaclasses of all its bases");
2057 return NULL;
2058 }
2059 if (winner != metatype) {
2060 if (winner->tp_new != type_new) /* Pass it to the winner */
2061 return winner->tp_new(winner, args, kwds);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00002062 metatype = winner;
2063 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002064
2065 /* Adjust for empty tuple bases */
2066 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002067 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002068 if (bases == NULL)
2069 return NULL;
2070 nbases = 1;
2071 }
2072 else
2073 Py_INCREF(bases);
2074
2075 /* XXX From here until type is allocated, "return NULL" leaks bases! */
2076
2077 /* Calculate best base, and check that all bases are type objects */
2078 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002079 if (base == NULL) {
2080 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002081 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002082 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002083 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2084 PyErr_Format(PyExc_TypeError,
2085 "type '%.100s' is not an acceptable base type",
2086 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002087 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002088 return NULL;
2089 }
2090
Tim Peters6d6c1a32001-08-02 04:15:00 +00002091 /* Check for a __slots__ sequence variable in dict, and count it */
2092 slots = PyDict_GetItemString(dict, "__slots__");
2093 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00002094 add_dict = 0;
2095 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00002096 may_add_dict = base->tp_dictoffset == 0;
2097 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2098 if (slots == NULL) {
2099 if (may_add_dict) {
2100 add_dict++;
2101 }
2102 if (may_add_weak) {
2103 add_weak++;
2104 }
2105 }
2106 else {
2107 /* Have slots */
2108
Tim Peters6d6c1a32001-08-02 04:15:00 +00002109 /* Make it into a tuple */
Neal Norwitzcbd9ee62007-04-14 05:25:50 +00002110 if (PyString_Check(slots) || PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002111 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002112 else
2113 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002114 if (slots == NULL) {
2115 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002116 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002117 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002118 assert(PyTuple_Check(slots));
2119
2120 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002121 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00002122 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00002123 PyErr_Format(PyExc_TypeError,
2124 "nonempty __slots__ "
2125 "not supported for subtype of '%s'",
2126 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00002127 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002128 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00002129 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00002130 return NULL;
2131 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002132
Martin v. Löwisd919a592002-10-14 21:07:28 +00002133#ifdef Py_USING_UNICODE
2134 tmp = _unicode_to_string(slots, nslots);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00002135 if (tmp == NULL)
2136 goto bad_slots;
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00002137 if (tmp != slots) {
2138 Py_DECREF(slots);
2139 slots = tmp;
2140 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00002141#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00002142 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002143 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00002144 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2145 char *s;
2146 if (!valid_identifier(tmp))
2147 goto bad_slots;
2148 assert(PyString_Check(tmp));
2149 s = PyString_AS_STRING(tmp);
2150 if (strcmp(s, "__dict__") == 0) {
2151 if (!may_add_dict || add_dict) {
2152 PyErr_SetString(PyExc_TypeError,
2153 "__dict__ slot disallowed: "
2154 "we already got one");
2155 goto bad_slots;
2156 }
2157 add_dict++;
2158 }
2159 if (strcmp(s, "__weakref__") == 0) {
2160 if (!may_add_weak || add_weak) {
2161 PyErr_SetString(PyExc_TypeError,
2162 "__weakref__ slot disallowed: "
2163 "either we already got one, "
2164 "or __itemsize__ != 0");
2165 goto bad_slots;
2166 }
2167 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002168 }
2169 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002170
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002171 /* Copy slots into a list, mangle names and sort them.
2172 Sorted names are needed for __class__ assignment.
2173 Convert them back to tuple at the end.
2174 */
2175 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002176 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00002177 goto bad_slots;
2178 for (i = j = 0; i < nslots; i++) {
2179 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002180 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00002181 s = PyString_AS_STRING(tmp);
2182 if ((add_dict && strcmp(s, "__dict__") == 0) ||
2183 (add_weak && strcmp(s, "__weakref__") == 0))
2184 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002185 tmp =_Py_Mangle(name, tmp);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002186 if (!tmp)
2187 goto bad_slots;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002188 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00002189 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002190 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002191 assert(j == nslots - add_dict - add_weak);
2192 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002193 Py_DECREF(slots);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002194 if (PyList_Sort(newslots) == -1) {
2195 Py_DECREF(bases);
2196 Py_DECREF(newslots);
2197 return NULL;
2198 }
2199 slots = PyList_AsTuple(newslots);
2200 Py_DECREF(newslots);
2201 if (slots == NULL) {
2202 Py_DECREF(bases);
2203 return NULL;
2204 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002205
Guido van Rossumad47da02002-08-12 19:05:44 +00002206 /* Secondary bases may provide weakrefs or dict */
2207 if (nbases > 1 &&
2208 ((may_add_dict && !add_dict) ||
2209 (may_add_weak && !add_weak))) {
2210 for (i = 0; i < nbases; i++) {
2211 tmp = PyTuple_GET_ITEM(bases, i);
2212 if (tmp == (PyObject *)base)
2213 continue; /* Skip primary base */
2214 if (PyClass_Check(tmp)) {
2215 /* Classic base class provides both */
2216 if (may_add_dict && !add_dict)
2217 add_dict++;
2218 if (may_add_weak && !add_weak)
2219 add_weak++;
2220 break;
2221 }
2222 assert(PyType_Check(tmp));
2223 tmptype = (PyTypeObject *)tmp;
2224 if (may_add_dict && !add_dict &&
2225 tmptype->tp_dictoffset != 0)
2226 add_dict++;
2227 if (may_add_weak && !add_weak &&
2228 tmptype->tp_weaklistoffset != 0)
2229 add_weak++;
2230 if (may_add_dict && !add_dict)
2231 continue;
2232 if (may_add_weak && !add_weak)
2233 continue;
2234 /* Nothing more to check */
2235 break;
2236 }
2237 }
Guido van Rossum9676b222001-08-17 20:32:36 +00002238 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239
2240 /* XXX From here until type is safely allocated,
2241 "return NULL" may leak slots! */
2242
2243 /* Allocate the type object */
2244 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00002245 if (type == NULL) {
2246 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002247 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002248 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00002249 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002250
2251 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002252 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002253 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002254 et->ht_name = name;
2255 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002256
Guido van Rossumdc91b992001-08-08 22:26:22 +00002257 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002258 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2259 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002260 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2261 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002262
2263 /* It's a new-style number unless it specifically inherits any
2264 old-style numeric behavior */
2265 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
2266 (base->tp_as_number == NULL))
2267 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
2268
2269 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002270 type->tp_as_number = &et->as_number;
2271 type->tp_as_sequence = &et->as_sequence;
2272 type->tp_as_mapping = &et->as_mapping;
2273 type->tp_as_buffer = &et->as_buffer;
2274 type->tp_name = PyString_AS_STRING(name);
2275
2276 /* Set tp_base and tp_bases */
2277 type->tp_bases = bases;
2278 Py_INCREF(base);
2279 type->tp_base = base;
2280
Guido van Rossum687ae002001-10-15 22:03:32 +00002281 /* Initialize tp_dict from passed-in dict */
2282 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002283 if (dict == NULL) {
2284 Py_DECREF(type);
2285 return NULL;
2286 }
2287
Guido van Rossumc3542212001-08-16 09:18:56 +00002288 /* Set __module__ in the dict */
2289 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2290 tmp = PyEval_GetGlobals();
2291 if (tmp != NULL) {
2292 tmp = PyDict_GetItemString(tmp, "__name__");
2293 if (tmp != NULL) {
2294 if (PyDict_SetItemString(dict, "__module__",
2295 tmp) < 0)
2296 return NULL;
2297 }
2298 }
2299 }
2300
Tim Peters2f93e282001-10-04 05:27:00 +00002301 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00002302 and is a string. The __doc__ accessor will first look for tp_doc;
2303 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00002304 */
2305 {
2306 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2307 if (doc != NULL && PyString_Check(doc)) {
2308 const size_t n = (size_t)PyString_GET_SIZE(doc);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002309 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002310 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00002311 Py_DECREF(type);
2312 return NULL;
2313 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002314 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002315 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00002316 }
2317 }
2318
Tim Peters6d6c1a32001-08-02 04:15:00 +00002319 /* Special-case __new__: if it's a plain function,
2320 make it a static function */
2321 tmp = PyDict_GetItemString(dict, "__new__");
2322 if (tmp != NULL && PyFunction_Check(tmp)) {
2323 tmp = PyStaticMethod_New(tmp);
2324 if (tmp == NULL) {
2325 Py_DECREF(type);
2326 return NULL;
2327 }
2328 PyDict_SetItemString(dict, "__new__", tmp);
2329 Py_DECREF(tmp);
2330 }
2331
2332 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002333 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00002334 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002335 if (slots != NULL) {
2336 for (i = 0; i < nslots; i++, mp++) {
2337 mp->name = PyString_AS_STRING(
2338 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00002339 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002340 mp->offset = slotoffset;
Žiga Seilnacht89032082007-03-11 15:54:54 +00002341
2342 /* __dict__ and __weakref__ are already filtered out */
2343 assert(strcmp(mp->name, "__dict__") != 0);
2344 assert(strcmp(mp->name, "__weakref__") != 0);
2345
Tim Peters6d6c1a32001-08-02 04:15:00 +00002346 slotoffset += sizeof(PyObject *);
2347 }
2348 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002349 if (add_dict) {
2350 if (base->tp_itemsize)
2351 type->tp_dictoffset = -(long)sizeof(PyObject *);
2352 else
2353 type->tp_dictoffset = slotoffset;
2354 slotoffset += sizeof(PyObject *);
2355 }
2356 if (add_weak) {
2357 assert(!base->tp_itemsize);
2358 type->tp_weaklistoffset = slotoffset;
2359 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002360 }
2361 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002362 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002363 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002364
2365 if (type->tp_weaklistoffset && type->tp_dictoffset)
2366 type->tp_getset = subtype_getsets_full;
2367 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2368 type->tp_getset = subtype_getsets_weakref_only;
2369 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2370 type->tp_getset = subtype_getsets_dict_only;
2371 else
2372 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002373
2374 /* Special case some slots */
2375 if (type->tp_dictoffset != 0 || nslots > 0) {
2376 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2377 type->tp_getattro = PyObject_GenericGetAttr;
2378 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2379 type->tp_setattro = PyObject_GenericSetAttr;
2380 }
2381 type->tp_dealloc = subtype_dealloc;
2382
Guido van Rossum9475a232001-10-05 20:51:39 +00002383 /* Enable GC unless there are really no instance variables possible */
2384 if (!(type->tp_basicsize == sizeof(PyObject) &&
2385 type->tp_itemsize == 0))
2386 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2387
Tim Peters6d6c1a32001-08-02 04:15:00 +00002388 /* Always override allocation strategy to use regular heap */
2389 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002390 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002391 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002392 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002393 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002394 }
2395 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002396 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002397
2398 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002399 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002400 Py_DECREF(type);
2401 return NULL;
2402 }
2403
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002404 /* Put the proper slots in place */
2405 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002406
Tim Peters6d6c1a32001-08-02 04:15:00 +00002407 return (PyObject *)type;
2408}
2409
2410/* Internal API to look for a name through the MRO.
2411 This returns a borrowed reference, and doesn't set an exception! */
2412PyObject *
2413_PyType_Lookup(PyTypeObject *type, PyObject *name)
2414{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002415 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002416 PyObject *mro, *res, *base, *dict;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002417 unsigned int h;
2418
2419 if (MCACHE_CACHEABLE_NAME(name) &&
Neal Norwitze7bb9182008-01-27 17:10:14 +00002420 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002421 /* fast path */
2422 h = MCACHE_HASH_METHOD(type, name);
2423 if (method_cache[h].version == type->tp_version_tag &&
2424 method_cache[h].name == name)
2425 return method_cache[h].value;
2426 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002427
Guido van Rossum687ae002001-10-15 22:03:32 +00002428 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002429 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002430
2431 /* If mro is NULL, the type is either not yet initialized
2432 by PyType_Ready(), or already cleared by type_clear().
2433 Either way the safest thing to do is to return NULL. */
2434 if (mro == NULL)
2435 return NULL;
2436
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002437 res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002438 assert(PyTuple_Check(mro));
2439 n = PyTuple_GET_SIZE(mro);
2440 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002441 base = PyTuple_GET_ITEM(mro, i);
2442 if (PyClass_Check(base))
2443 dict = ((PyClassObject *)base)->cl_dict;
2444 else {
2445 assert(PyType_Check(base));
2446 dict = ((PyTypeObject *)base)->tp_dict;
2447 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002448 assert(dict && PyDict_Check(dict));
2449 res = PyDict_GetItem(dict, name);
2450 if (res != NULL)
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002451 break;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002452 }
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002453
2454 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2455 h = MCACHE_HASH_METHOD(type, name);
2456 method_cache[h].version = type->tp_version_tag;
2457 method_cache[h].value = res; /* borrowed */
2458 Py_INCREF(name);
2459 Py_DECREF(method_cache[h].name);
2460 method_cache[h].name = name;
2461 }
2462 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002463}
2464
2465/* This is similar to PyObject_GenericGetAttr(),
2466 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2467static PyObject *
2468type_getattro(PyTypeObject *type, PyObject *name)
2469{
Christian Heimese93237d2007-12-19 02:37:44 +00002470 PyTypeObject *metatype = Py_TYPE(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002471 PyObject *meta_attribute, *attribute;
2472 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002473
2474 /* Initialize this type (we'll assume the metatype is initialized) */
2475 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002476 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002477 return NULL;
2478 }
2479
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002480 /* No readable descriptor found yet */
2481 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002482
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002483 /* Look for the attribute in the metatype */
2484 meta_attribute = _PyType_Lookup(metatype, name);
2485
2486 if (meta_attribute != NULL) {
Christian Heimese93237d2007-12-19 02:37:44 +00002487 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002488
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002489 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2490 /* Data descriptors implement tp_descr_set to intercept
2491 * writes. Assume the attribute is not overridden in
2492 * type's tp_dict (and bases): call the descriptor now.
2493 */
2494 return meta_get(meta_attribute, (PyObject *)type,
2495 (PyObject *)metatype);
2496 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002497 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002498 }
2499
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002500 /* No data descriptor found on metatype. Look in tp_dict of this
2501 * type and its bases */
2502 attribute = _PyType_Lookup(type, name);
2503 if (attribute != NULL) {
2504 /* Implement descriptor functionality, if any */
Christian Heimese93237d2007-12-19 02:37:44 +00002505 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002506
2507 Py_XDECREF(meta_attribute);
2508
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002509 if (local_get != NULL) {
2510 /* NULL 2nd argument indicates the descriptor was
2511 * found on the target object itself (or a base) */
2512 return local_get(attribute, (PyObject *)NULL,
2513 (PyObject *)type);
2514 }
Tim Peters34592512002-07-11 06:23:50 +00002515
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002516 Py_INCREF(attribute);
2517 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002518 }
2519
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002520 /* No attribute found in local __dict__ (or bases): use the
2521 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002522 if (meta_get != NULL) {
2523 PyObject *res;
2524 res = meta_get(meta_attribute, (PyObject *)type,
2525 (PyObject *)metatype);
2526 Py_DECREF(meta_attribute);
2527 return res;
2528 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002529
2530 /* If an ordinary attribute was found on the metatype, return it now */
2531 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002532 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002533 }
2534
2535 /* Give up */
2536 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002537 "type object '%.50s' has no attribute '%.400s'",
2538 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002539 return NULL;
2540}
2541
2542static int
2543type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2544{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002545 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2546 PyErr_Format(
2547 PyExc_TypeError,
2548 "can't set attributes of built-in/extension type '%s'",
2549 type->tp_name);
2550 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002551 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002552 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2553 return -1;
2554 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002555}
2556
2557static void
2558type_dealloc(PyTypeObject *type)
2559{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002560 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002561
2562 /* Assert this is a heap-allocated type object */
2563 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002564 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002565 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002566 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002567 Py_XDECREF(type->tp_base);
2568 Py_XDECREF(type->tp_dict);
2569 Py_XDECREF(type->tp_bases);
2570 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002571 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002572 Py_XDECREF(type->tp_subclasses);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002573 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2574 * of most other objects. It's okay to cast it to char *.
2575 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002576 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002577 Py_XDECREF(et->ht_name);
2578 Py_XDECREF(et->ht_slots);
Christian Heimese93237d2007-12-19 02:37:44 +00002579 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002580}
2581
Guido van Rossum1c450732001-10-08 15:18:27 +00002582static PyObject *
2583type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2584{
2585 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002586 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002587
2588 list = PyList_New(0);
2589 if (list == NULL)
2590 return NULL;
2591 raw = type->tp_subclasses;
2592 if (raw == NULL)
2593 return list;
2594 assert(PyList_Check(raw));
2595 n = PyList_GET_SIZE(raw);
2596 for (i = 0; i < n; i++) {
2597 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002598 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002599 ref = PyWeakref_GET_OBJECT(ref);
2600 if (ref != Py_None) {
2601 if (PyList_Append(list, ref) < 0) {
2602 Py_DECREF(list);
2603 return NULL;
2604 }
2605 }
2606 }
2607 return list;
2608}
2609
Tim Peters6d6c1a32001-08-02 04:15:00 +00002610static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002611 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002612 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002613 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002614 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002615 {0}
2616};
2617
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002618PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002619"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002620"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002621
Guido van Rossum048eb752001-10-02 21:24:57 +00002622static int
2623type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2624{
Guido van Rossuma3862092002-06-10 15:24:42 +00002625 /* Because of type_is_gc(), the collector only calls this
2626 for heaptypes. */
2627 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002628
Thomas Woutersc6e55062006-04-15 21:47:09 +00002629 Py_VISIT(type->tp_dict);
2630 Py_VISIT(type->tp_cache);
2631 Py_VISIT(type->tp_mro);
2632 Py_VISIT(type->tp_bases);
2633 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002634
2635 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002636 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002637 in cycles; tp_subclasses is a list of weak references,
2638 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002639
Guido van Rossum048eb752001-10-02 21:24:57 +00002640 return 0;
2641}
2642
2643static int
2644type_clear(PyTypeObject *type)
2645{
Guido van Rossuma3862092002-06-10 15:24:42 +00002646 /* Because of type_is_gc(), the collector only calls this
2647 for heaptypes. */
2648 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002649
Guido van Rossuma3862092002-06-10 15:24:42 +00002650 /* The only field we need to clear is tp_mro, which is part of a
2651 hard cycle (its first element is the class itself) that won't
2652 be broken otherwise (it's a tuple and tuples don't have a
2653 tp_clear handler). None of the other fields need to be
2654 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002655
Guido van Rossuma3862092002-06-10 15:24:42 +00002656 tp_dict:
2657 It is a dict, so the collector will call its tp_clear.
2658
2659 tp_cache:
2660 Not used; if it were, it would be a dict.
2661
2662 tp_bases, tp_base:
2663 If these are involved in a cycle, there must be at least
2664 one other, mutable object in the cycle, e.g. a base
2665 class's dict; the cycle will be broken that way.
2666
2667 tp_subclasses:
2668 A list of weak references can't be part of a cycle; and
2669 lists have their own tp_clear.
2670
Guido van Rossume5c691a2003-03-07 15:13:17 +00002671 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002672 A tuple of strings can't be part of a cycle.
2673 */
2674
Thomas Woutersedf17d82006-04-15 17:28:34 +00002675 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002676
2677 return 0;
2678}
2679
2680static int
2681type_is_gc(PyTypeObject *type)
2682{
2683 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2684}
2685
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002686PyTypeObject PyType_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002687 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002688 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002689 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002690 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002691 (destructor)type_dealloc, /* tp_dealloc */
2692 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002693 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002694 0, /* tp_setattr */
2695 type_compare, /* tp_compare */
2696 (reprfunc)type_repr, /* tp_repr */
2697 0, /* tp_as_number */
2698 0, /* tp_as_sequence */
2699 0, /* tp_as_mapping */
2700 (hashfunc)_Py_HashPointer, /* tp_hash */
2701 (ternaryfunc)type_call, /* tp_call */
2702 0, /* tp_str */
2703 (getattrofunc)type_getattro, /* tp_getattro */
2704 (setattrofunc)type_setattro, /* tp_setattro */
2705 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002706 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002707 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002708 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002709 (traverseproc)type_traverse, /* tp_traverse */
2710 (inquiry)type_clear, /* tp_clear */
Steven Bethardae42f332008-03-18 17:26:10 +00002711 type_richcompare, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002712 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002713 0, /* tp_iter */
2714 0, /* tp_iternext */
2715 type_methods, /* tp_methods */
2716 type_members, /* tp_members */
2717 type_getsets, /* tp_getset */
2718 0, /* tp_base */
2719 0, /* tp_dict */
2720 0, /* tp_descr_get */
2721 0, /* tp_descr_set */
2722 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumf102e242007-03-23 18:53:03 +00002723 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002724 0, /* tp_alloc */
2725 type_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002726 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002727 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002728};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002729
2730
2731/* The base type of all types (eventually)... except itself. */
2732
Guido van Rossum143b5642007-03-23 04:58:42 +00002733/* You may wonder why object.__new__() only complains about arguments
2734 when object.__init__() is not overridden, and vice versa.
2735
2736 Consider the use cases:
2737
2738 1. When neither is overridden, we want to hear complaints about
2739 excess (i.e., any) arguments, since their presence could
2740 indicate there's a bug.
2741
2742 2. When defining an Immutable type, we are likely to override only
2743 __new__(), since __init__() is called too late to initialize an
2744 Immutable object. Since __new__() defines the signature for the
2745 type, it would be a pain to have to override __init__() just to
2746 stop it from complaining about excess arguments.
2747
2748 3. When defining a Mutable type, we are likely to override only
2749 __init__(). So here the converse reasoning applies: we don't
2750 want to have to override __new__() just to stop it from
2751 complaining.
2752
2753 4. When __init__() is overridden, and the subclass __init__() calls
2754 object.__init__(), the latter should complain about excess
2755 arguments; ditto for __new__().
2756
2757 Use cases 2 and 3 make it unattractive to unconditionally check for
2758 excess arguments. The best solution that addresses all four use
2759 cases is as follows: __init__() complains about excess arguments
2760 unless __new__() is overridden and __init__() is not overridden
2761 (IOW, if __init__() is overridden or __new__() is not overridden);
2762 symmetrically, __new__() complains about excess arguments unless
2763 __init__() is overridden and __new__() is not overridden
2764 (IOW, if __new__() is overridden or __init__() is not overridden).
2765
2766 However, for backwards compatibility, this breaks too much code.
2767 Therefore, in 2.6, we'll *warn* about excess arguments when both
2768 methods are overridden; for all other cases we'll use the above
2769 rules.
2770
2771*/
2772
2773/* Forward */
2774static PyObject *
2775object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2776
2777static int
2778excess_args(PyObject *args, PyObject *kwds)
2779{
2780 return PyTuple_GET_SIZE(args) ||
2781 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2782}
2783
Tim Peters6d6c1a32001-08-02 04:15:00 +00002784static int
2785object_init(PyObject *self, PyObject *args, PyObject *kwds)
2786{
Guido van Rossum143b5642007-03-23 04:58:42 +00002787 int err = 0;
2788 if (excess_args(args, kwds)) {
Christian Heimese93237d2007-12-19 02:37:44 +00002789 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum143b5642007-03-23 04:58:42 +00002790 if (type->tp_init != object_init &&
2791 type->tp_new != object_new)
2792 {
2793 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2794 "object.__init__() takes no parameters",
2795 1);
2796 }
2797 else if (type->tp_init != object_init ||
2798 type->tp_new == object_new)
2799 {
2800 PyErr_SetString(PyExc_TypeError,
2801 "object.__init__() takes no parameters");
2802 err = -1;
2803 }
2804 }
2805 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002806}
2807
Guido van Rossum298e4212003-02-13 16:30:16 +00002808static PyObject *
2809object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2810{
Guido van Rossum143b5642007-03-23 04:58:42 +00002811 int err = 0;
2812 if (excess_args(args, kwds)) {
2813 if (type->tp_new != object_new &&
2814 type->tp_init != object_init)
2815 {
2816 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2817 "object.__new__() takes no parameters",
2818 1);
2819 }
2820 else if (type->tp_new != object_new ||
2821 type->tp_init == object_init)
2822 {
2823 PyErr_SetString(PyExc_TypeError,
2824 "object.__new__() takes no parameters");
2825 err = -1;
2826 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002827 }
Guido van Rossum143b5642007-03-23 04:58:42 +00002828 if (err < 0)
2829 return NULL;
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00002830
2831 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2832 static PyObject *comma = NULL;
2833 PyObject *abstract_methods = NULL;
2834 PyObject *builtins;
2835 PyObject *sorted;
2836 PyObject *sorted_methods = NULL;
2837 PyObject *joined = NULL;
2838 const char *joined_str;
2839
2840 /* Compute ", ".join(sorted(type.__abstractmethods__))
2841 into joined. */
2842 abstract_methods = type_abstractmethods(type, NULL);
2843 if (abstract_methods == NULL)
2844 goto error;
2845 builtins = PyEval_GetBuiltins();
2846 if (builtins == NULL)
2847 goto error;
2848 sorted = PyDict_GetItemString(builtins, "sorted");
2849 if (sorted == NULL)
2850 goto error;
2851 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2852 abstract_methods,
2853 NULL);
2854 if (sorted_methods == NULL)
2855 goto error;
2856 if (comma == NULL) {
2857 comma = PyString_InternFromString(", ");
2858 if (comma == NULL)
2859 goto error;
2860 }
2861 joined = PyObject_CallMethod(comma, "join",
2862 "O", sorted_methods);
2863 if (joined == NULL)
2864 goto error;
2865 joined_str = PyString_AsString(joined);
2866 if (joined_str == NULL)
2867 goto error;
2868
2869 PyErr_Format(PyExc_TypeError,
2870 "Can't instantiate abstract class %s "
2871 "with abstract methods %s",
2872 type->tp_name,
2873 joined_str);
2874 error:
2875 Py_XDECREF(joined);
2876 Py_XDECREF(sorted_methods);
2877 Py_XDECREF(abstract_methods);
2878 return NULL;
2879 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002880 return type->tp_alloc(type, 0);
2881}
2882
Tim Peters6d6c1a32001-08-02 04:15:00 +00002883static void
2884object_dealloc(PyObject *self)
2885{
Christian Heimese93237d2007-12-19 02:37:44 +00002886 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002887}
2888
Guido van Rossum8e248182001-08-12 05:17:56 +00002889static PyObject *
2890object_repr(PyObject *self)
2891{
Guido van Rossum76e69632001-08-16 18:52:43 +00002892 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002893 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002894
Christian Heimese93237d2007-12-19 02:37:44 +00002895 type = Py_TYPE(self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002896 mod = type_module(type, NULL);
2897 if (mod == NULL)
2898 PyErr_Clear();
2899 else if (!PyString_Check(mod)) {
2900 Py_DECREF(mod);
2901 mod = NULL;
2902 }
2903 name = type_name(type, NULL);
2904 if (name == NULL)
2905 return NULL;
2906 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002907 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002908 PyString_AS_STRING(mod),
2909 PyString_AS_STRING(name),
2910 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002911 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002912 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002913 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002914 Py_XDECREF(mod);
2915 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002916 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002917}
2918
Guido van Rossumb8f63662001-08-15 23:57:02 +00002919static PyObject *
2920object_str(PyObject *self)
2921{
2922 unaryfunc f;
2923
Christian Heimese93237d2007-12-19 02:37:44 +00002924 f = Py_TYPE(self)->tp_repr;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002925 if (f == NULL)
2926 f = object_repr;
2927 return f(self);
2928}
2929
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002930static PyObject *
2931object_get_class(PyObject *self, void *closure)
2932{
Christian Heimese93237d2007-12-19 02:37:44 +00002933 Py_INCREF(Py_TYPE(self));
2934 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002935}
2936
2937static int
2938equiv_structs(PyTypeObject *a, PyTypeObject *b)
2939{
2940 return a == b ||
2941 (a != NULL &&
2942 b != NULL &&
2943 a->tp_basicsize == b->tp_basicsize &&
2944 a->tp_itemsize == b->tp_itemsize &&
2945 a->tp_dictoffset == b->tp_dictoffset &&
2946 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2947 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2948 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2949}
2950
2951static int
2952same_slots_added(PyTypeObject *a, PyTypeObject *b)
2953{
2954 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002955 Py_ssize_t size;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002956 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002957
2958 if (base != b->tp_base)
2959 return 0;
2960 if (equiv_structs(a, base) && equiv_structs(b, base))
2961 return 1;
2962 size = base->tp_basicsize;
2963 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2964 size += sizeof(PyObject *);
2965 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2966 size += sizeof(PyObject *);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002967
2968 /* Check slots compliance */
2969 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2970 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2971 if (slots_a && slots_b) {
2972 if (PyObject_Compare(slots_a, slots_b) != 0)
2973 return 0;
2974 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2975 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002976 return size == a->tp_basicsize && size == b->tp_basicsize;
2977}
2978
2979static int
Anthony Baxtera6286212006-04-11 07:42:36 +00002980compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002981{
2982 PyTypeObject *newbase, *oldbase;
2983
Anthony Baxtera6286212006-04-11 07:42:36 +00002984 if (newto->tp_dealloc != oldto->tp_dealloc ||
2985 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002986 {
2987 PyErr_Format(PyExc_TypeError,
2988 "%s assignment: "
2989 "'%s' deallocator differs from '%s'",
2990 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002991 newto->tp_name,
2992 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002993 return 0;
2994 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002995 newbase = newto;
2996 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002997 while (equiv_structs(newbase, newbase->tp_base))
2998 newbase = newbase->tp_base;
2999 while (equiv_structs(oldbase, oldbase->tp_base))
3000 oldbase = oldbase->tp_base;
3001 if (newbase != oldbase &&
3002 (newbase->tp_base != oldbase->tp_base ||
3003 !same_slots_added(newbase, oldbase))) {
3004 PyErr_Format(PyExc_TypeError,
3005 "%s assignment: "
3006 "'%s' object layout differs from '%s'",
3007 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00003008 newto->tp_name,
3009 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003010 return 0;
3011 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003012
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003013 return 1;
3014}
3015
3016static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003017object_set_class(PyObject *self, PyObject *value, void *closure)
3018{
Christian Heimese93237d2007-12-19 02:37:44 +00003019 PyTypeObject *oldto = Py_TYPE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00003020 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003021
Guido van Rossumb6b89422002-04-15 01:03:30 +00003022 if (value == NULL) {
3023 PyErr_SetString(PyExc_TypeError,
3024 "can't delete __class__ attribute");
3025 return -1;
3026 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003027 if (!PyType_Check(value)) {
3028 PyErr_Format(PyExc_TypeError,
3029 "__class__ must be set to new-style class, not '%s' object",
Christian Heimese93237d2007-12-19 02:37:44 +00003030 Py_TYPE(value)->tp_name);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003031 return -1;
3032 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003033 newto = (PyTypeObject *)value;
3034 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3035 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00003036 {
3037 PyErr_Format(PyExc_TypeError,
3038 "__class__ assignment: only for heap types");
3039 return -1;
3040 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003041 if (compatible_for_assignment(newto, oldto, "__class__")) {
3042 Py_INCREF(newto);
Christian Heimese93237d2007-12-19 02:37:44 +00003043 Py_TYPE(self) = newto;
Anthony Baxtera6286212006-04-11 07:42:36 +00003044 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003045 return 0;
3046 }
3047 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00003048 return -1;
3049 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003050}
3051
3052static PyGetSetDef object_getsets[] = {
3053 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00003054 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003055 {0}
3056};
3057
Guido van Rossumc53f0092003-02-18 22:05:12 +00003058
Guido van Rossum036f9992003-02-21 22:02:54 +00003059/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
3060 We fall back to helpers in copy_reg for:
3061 - pickle protocols < 2
3062 - calculating the list of slot names (done only once per class)
3063 - the __newobj__ function (which is used as a token but never called)
3064*/
3065
3066static PyObject *
3067import_copy_reg(void)
3068{
3069 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00003070
3071 if (!copy_reg_str) {
3072 copy_reg_str = PyString_InternFromString("copy_reg");
3073 if (copy_reg_str == NULL)
3074 return NULL;
3075 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003076
3077 return PyImport_Import(copy_reg_str);
3078}
3079
3080static PyObject *
3081slotnames(PyObject *cls)
3082{
3083 PyObject *clsdict;
3084 PyObject *copy_reg;
3085 PyObject *slotnames;
3086
3087 if (!PyType_Check(cls)) {
3088 Py_INCREF(Py_None);
3089 return Py_None;
3090 }
3091
3092 clsdict = ((PyTypeObject *)cls)->tp_dict;
3093 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00003094 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00003095 Py_INCREF(slotnames);
3096 return slotnames;
3097 }
3098
3099 copy_reg = import_copy_reg();
3100 if (copy_reg == NULL)
3101 return NULL;
3102
3103 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
3104 Py_DECREF(copy_reg);
3105 if (slotnames != NULL &&
3106 slotnames != Py_None &&
3107 !PyList_Check(slotnames))
3108 {
3109 PyErr_SetString(PyExc_TypeError,
3110 "copy_reg._slotnames didn't return a list or None");
3111 Py_DECREF(slotnames);
3112 slotnames = NULL;
3113 }
3114
3115 return slotnames;
3116}
3117
3118static PyObject *
3119reduce_2(PyObject *obj)
3120{
3121 PyObject *cls, *getnewargs;
3122 PyObject *args = NULL, *args2 = NULL;
3123 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3124 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3125 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003126 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00003127
3128 cls = PyObject_GetAttrString(obj, "__class__");
3129 if (cls == NULL)
3130 return NULL;
3131
3132 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
3133 if (getnewargs != NULL) {
3134 args = PyObject_CallObject(getnewargs, NULL);
3135 Py_DECREF(getnewargs);
3136 if (args != NULL && !PyTuple_Check(args)) {
Georg Brandlccff7852006-06-18 22:17:29 +00003137 PyErr_Format(PyExc_TypeError,
3138 "__getnewargs__ should return a tuple, "
Christian Heimese93237d2007-12-19 02:37:44 +00003139 "not '%.200s'", Py_TYPE(args)->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00003140 goto end;
3141 }
3142 }
3143 else {
3144 PyErr_Clear();
3145 args = PyTuple_New(0);
3146 }
3147 if (args == NULL)
3148 goto end;
3149
3150 getstate = PyObject_GetAttrString(obj, "__getstate__");
3151 if (getstate != NULL) {
3152 state = PyObject_CallObject(getstate, NULL);
3153 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00003154 if (state == NULL)
3155 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003156 }
3157 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00003158 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00003159 state = PyObject_GetAttrString(obj, "__dict__");
3160 if (state == NULL) {
3161 PyErr_Clear();
3162 state = Py_None;
3163 Py_INCREF(state);
3164 }
3165 names = slotnames(cls);
3166 if (names == NULL)
3167 goto end;
3168 if (names != Py_None) {
3169 assert(PyList_Check(names));
3170 slots = PyDict_New();
3171 if (slots == NULL)
3172 goto end;
3173 n = 0;
3174 /* Can't pre-compute the list size; the list
3175 is stored on the class so accessible to other
3176 threads, which may be run by DECREF */
3177 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3178 PyObject *name, *value;
3179 name = PyList_GET_ITEM(names, i);
3180 value = PyObject_GetAttr(obj, name);
3181 if (value == NULL)
3182 PyErr_Clear();
3183 else {
3184 int err = PyDict_SetItem(slots, name,
3185 value);
3186 Py_DECREF(value);
3187 if (err)
3188 goto end;
3189 n++;
3190 }
3191 }
3192 if (n) {
3193 state = Py_BuildValue("(NO)", state, slots);
3194 if (state == NULL)
3195 goto end;
3196 }
3197 }
3198 }
3199
3200 if (!PyList_Check(obj)) {
3201 listitems = Py_None;
3202 Py_INCREF(listitems);
3203 }
3204 else {
3205 listitems = PyObject_GetIter(obj);
3206 if (listitems == NULL)
3207 goto end;
3208 }
3209
3210 if (!PyDict_Check(obj)) {
3211 dictitems = Py_None;
3212 Py_INCREF(dictitems);
3213 }
3214 else {
3215 dictitems = PyObject_CallMethod(obj, "iteritems", "");
3216 if (dictitems == NULL)
3217 goto end;
3218 }
3219
3220 copy_reg = import_copy_reg();
3221 if (copy_reg == NULL)
3222 goto end;
3223 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
3224 if (newobj == NULL)
3225 goto end;
3226
3227 n = PyTuple_GET_SIZE(args);
3228 args2 = PyTuple_New(n+1);
3229 if (args2 == NULL)
3230 goto end;
3231 PyTuple_SET_ITEM(args2, 0, cls);
3232 cls = NULL;
3233 for (i = 0; i < n; i++) {
3234 PyObject *v = PyTuple_GET_ITEM(args, i);
3235 Py_INCREF(v);
3236 PyTuple_SET_ITEM(args2, i+1, v);
3237 }
3238
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003239 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003240
3241 end:
3242 Py_XDECREF(cls);
3243 Py_XDECREF(args);
3244 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00003245 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00003246 Py_XDECREF(state);
3247 Py_XDECREF(names);
3248 Py_XDECREF(listitems);
3249 Py_XDECREF(dictitems);
3250 Py_XDECREF(copy_reg);
3251 Py_XDECREF(newobj);
3252 return res;
3253}
3254
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003255/*
3256 * There were two problems when object.__reduce__ and object.__reduce_ex__
3257 * were implemented in the same function:
3258 * - trying to pickle an object with a custom __reduce__ method that
3259 * fell back to object.__reduce__ in certain circumstances led to
3260 * infinite recursion at Python level and eventual RuntimeError.
3261 * - Pickling objects that lied about their type by overwriting the
3262 * __class__ descriptor could lead to infinite recursion at C level
3263 * and eventual segfault.
3264 *
3265 * Because of backwards compatibility, the two methods still have to
3266 * behave in the same way, even if this is not required by the pickle
3267 * protocol. This common functionality was moved to the _common_reduce
3268 * function.
3269 */
3270static PyObject *
3271_common_reduce(PyObject *self, int proto)
3272{
3273 PyObject *copy_reg, *res;
3274
3275 if (proto >= 2)
3276 return reduce_2(self);
3277
3278 copy_reg = import_copy_reg();
3279 if (!copy_reg)
3280 return NULL;
3281
3282 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
3283 Py_DECREF(copy_reg);
3284
3285 return res;
3286}
3287
3288static PyObject *
3289object_reduce(PyObject *self, PyObject *args)
3290{
3291 int proto = 0;
3292
3293 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3294 return NULL;
3295
3296 return _common_reduce(self, proto);
3297}
3298
Guido van Rossum036f9992003-02-21 22:02:54 +00003299static PyObject *
3300object_reduce_ex(PyObject *self, PyObject *args)
3301{
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003302 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003303 int proto = 0;
3304
3305 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3306 return NULL;
3307
3308 reduce = PyObject_GetAttrString(self, "__reduce__");
3309 if (reduce == NULL)
3310 PyErr_Clear();
3311 else {
3312 PyObject *cls, *clsreduce, *objreduce;
3313 int override;
3314 cls = PyObject_GetAttrString(self, "__class__");
3315 if (cls == NULL) {
3316 Py_DECREF(reduce);
3317 return NULL;
3318 }
3319 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3320 Py_DECREF(cls);
3321 if (clsreduce == NULL) {
3322 Py_DECREF(reduce);
3323 return NULL;
3324 }
3325 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3326 "__reduce__");
3327 override = (clsreduce != objreduce);
3328 Py_DECREF(clsreduce);
3329 if (override) {
3330 res = PyObject_CallObject(reduce, NULL);
3331 Py_DECREF(reduce);
3332 return res;
3333 }
3334 else
3335 Py_DECREF(reduce);
3336 }
3337
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003338 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003339}
3340
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00003341static PyObject *
3342object_subclasshook(PyObject *cls, PyObject *args)
3343{
3344 Py_INCREF(Py_NotImplemented);
3345 return Py_NotImplemented;
3346}
3347
3348PyDoc_STRVAR(object_subclasshook_doc,
3349"Abstract classes can override this to customize issubclass().\n"
3350"\n"
3351"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3352"It should return True, False or NotImplemented. If it returns\n"
3353"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3354"overrides the normal algorithm (and the outcome is cached).\n");
3355
Eric Smitha9f7d622008-02-17 19:46:49 +00003356/*
3357 from PEP 3101, this code implements:
3358
3359 class object:
3360 def __format__(self, format_spec):
3361 if isinstance(format_spec, str):
3362 return format(str(self), format_spec)
3363 elif isinstance(format_spec, unicode):
3364 return format(unicode(self), format_spec)
3365*/
3366static PyObject *
3367object_format(PyObject *self, PyObject *args)
3368{
3369 PyObject *format_spec;
3370 PyObject *self_as_str = NULL;
3371 PyObject *result = NULL;
3372 PyObject *format_meth = NULL;
3373
3374 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3375 return NULL;
3376 if (PyUnicode_Check(format_spec)) {
3377 self_as_str = PyObject_Unicode(self);
3378 } else if (PyString_Check(format_spec)) {
3379 self_as_str = PyObject_Str(self);
3380 } else {
3381 PyErr_SetString(PyExc_TypeError, "argument to __format__ must be unicode or str");
3382 return NULL;
3383 }
3384
3385 if (self_as_str != NULL) {
3386 /* find the format function */
3387 format_meth = PyObject_GetAttrString(self_as_str, "__format__");
3388 if (format_meth != NULL) {
3389 /* and call it */
3390 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
3391 }
3392 }
3393
3394 Py_XDECREF(self_as_str);
3395 Py_XDECREF(format_meth);
3396
3397 return result;
3398}
3399
Guido van Rossum3926a632001-09-25 16:25:58 +00003400static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00003401 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3402 PyDoc_STR("helper for pickle")},
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003403 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003404 PyDoc_STR("helper for pickle")},
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00003405 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3406 object_subclasshook_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00003407 {"__format__", object_format, METH_VARARGS,
3408 PyDoc_STR("default object formatter")},
Guido van Rossum3926a632001-09-25 16:25:58 +00003409 {0}
3410};
3411
Guido van Rossum036f9992003-02-21 22:02:54 +00003412
Tim Peters6d6c1a32001-08-02 04:15:00 +00003413PyTypeObject PyBaseObject_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00003414 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003415 "object", /* tp_name */
3416 sizeof(PyObject), /* tp_basicsize */
3417 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003418 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003419 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003420 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003421 0, /* tp_setattr */
3422 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003423 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003424 0, /* tp_as_number */
3425 0, /* tp_as_sequence */
3426 0, /* tp_as_mapping */
Guido van Rossum64c06e32007-11-22 00:55:51 +00003427 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003428 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003429 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003430 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003431 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003432 0, /* tp_as_buffer */
3433 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003434 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003435 0, /* tp_traverse */
3436 0, /* tp_clear */
3437 0, /* tp_richcompare */
3438 0, /* tp_weaklistoffset */
3439 0, /* tp_iter */
3440 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00003441 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003442 0, /* tp_members */
3443 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003444 0, /* tp_base */
3445 0, /* tp_dict */
3446 0, /* tp_descr_get */
3447 0, /* tp_descr_set */
3448 0, /* tp_dictoffset */
3449 object_init, /* tp_init */
3450 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003451 object_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003452 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003453};
3454
3455
3456/* Initialize the __dict__ in a type object */
3457
3458static int
3459add_methods(PyTypeObject *type, PyMethodDef *meth)
3460{
Guido van Rossum687ae002001-10-15 22:03:32 +00003461 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003462
3463 for (; meth->ml_name != NULL; meth++) {
3464 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003465 if (PyDict_GetItemString(dict, meth->ml_name) &&
3466 !(meth->ml_flags & METH_COEXIST))
3467 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003468 if (meth->ml_flags & METH_CLASS) {
3469 if (meth->ml_flags & METH_STATIC) {
3470 PyErr_SetString(PyExc_ValueError,
3471 "method cannot be both class and static");
3472 return -1;
3473 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003474 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003475 }
3476 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003477 PyObject *cfunc = PyCFunction_New(meth, NULL);
3478 if (cfunc == NULL)
3479 return -1;
3480 descr = PyStaticMethod_New(cfunc);
3481 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003482 }
3483 else {
3484 descr = PyDescr_NewMethod(type, meth);
3485 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003486 if (descr == NULL)
3487 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003488 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003489 return -1;
3490 Py_DECREF(descr);
3491 }
3492 return 0;
3493}
3494
3495static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003496add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003497{
Guido van Rossum687ae002001-10-15 22:03:32 +00003498 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003499
3500 for (; memb->name != NULL; memb++) {
3501 PyObject *descr;
3502 if (PyDict_GetItemString(dict, memb->name))
3503 continue;
3504 descr = PyDescr_NewMember(type, memb);
3505 if (descr == NULL)
3506 return -1;
3507 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3508 return -1;
3509 Py_DECREF(descr);
3510 }
3511 return 0;
3512}
3513
3514static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003515add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003516{
Guido van Rossum687ae002001-10-15 22:03:32 +00003517 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003518
3519 for (; gsp->name != NULL; gsp++) {
3520 PyObject *descr;
3521 if (PyDict_GetItemString(dict, gsp->name))
3522 continue;
3523 descr = PyDescr_NewGetSet(type, gsp);
3524
3525 if (descr == NULL)
3526 return -1;
3527 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3528 return -1;
3529 Py_DECREF(descr);
3530 }
3531 return 0;
3532}
3533
Guido van Rossum13d52f02001-08-10 21:24:08 +00003534static void
3535inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003536{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003537 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003538
Guido van Rossum13d52f02001-08-10 21:24:08 +00003539 /* Special flag magic */
3540 if (!type->tp_as_buffer && base->tp_as_buffer) {
3541 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
3542 type->tp_flags |=
3543 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
3544 }
3545 if (!type->tp_as_sequence && base->tp_as_sequence) {
3546 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3547 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3548 }
3549 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3550 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3551 if ((!type->tp_as_number && base->tp_as_number) ||
3552 (!type->tp_as_sequence && base->tp_as_sequence)) {
3553 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3554 if (!type->tp_as_number && !type->tp_as_sequence) {
3555 type->tp_flags |= base->tp_flags &
3556 Py_TPFLAGS_HAVE_INPLACEOPS;
3557 }
3558 }
3559 /* Wow */
3560 }
3561 if (!type->tp_as_number && base->tp_as_number) {
3562 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3563 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3564 }
3565
3566 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003567 oldsize = base->tp_basicsize;
3568 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3569 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3570 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003571 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3572 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003573 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003574 if (type->tp_traverse == NULL)
3575 type->tp_traverse = base->tp_traverse;
3576 if (type->tp_clear == NULL)
3577 type->tp_clear = base->tp_clear;
3578 }
3579 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00003580 /* The condition below could use some explanation.
3581 It appears that tp_new is not inherited for static types
3582 whose base class is 'object'; this seems to be a precaution
3583 so that old extension types don't suddenly become
3584 callable (object.__new__ wouldn't insure the invariants
3585 that the extension type's own factory function ensures).
3586 Heap types, of course, are under our control, so they do
3587 inherit tp_new; static extension types that specify some
3588 other built-in type as the default are considered
3589 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003590 if (base != &PyBaseObject_Type ||
3591 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3592 if (type->tp_new == NULL)
3593 type->tp_new = base->tp_new;
3594 }
3595 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003596 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003597
3598 /* Copy other non-function slots */
3599
3600#undef COPYVAL
3601#define COPYVAL(SLOT) \
3602 if (type->SLOT == 0) type->SLOT = base->SLOT
3603
3604 COPYVAL(tp_itemsize);
3605 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3606 COPYVAL(tp_weaklistoffset);
3607 }
3608 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3609 COPYVAL(tp_dictoffset);
3610 }
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003611
3612 /* Setup fast subclass flags */
3613 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3614 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3615 else if (PyType_IsSubtype(base, &PyType_Type))
3616 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3617 else if (PyType_IsSubtype(base, &PyInt_Type))
3618 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3619 else if (PyType_IsSubtype(base, &PyLong_Type))
3620 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3621 else if (PyType_IsSubtype(base, &PyString_Type))
3622 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003623#ifdef Py_USING_UNICODE
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003624 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3625 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003626#endif
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003627 else if (PyType_IsSubtype(base, &PyTuple_Type))
3628 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3629 else if (PyType_IsSubtype(base, &PyList_Type))
3630 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3631 else if (PyType_IsSubtype(base, &PyDict_Type))
3632 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003633}
3634
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003635static char *hash_name_op[] = {
3636 "__eq__",
3637 "__cmp__",
3638 "__hash__",
3639 NULL
Guido van Rossum64c06e32007-11-22 00:55:51 +00003640};
3641
3642static int
3643overrides_hash(PyTypeObject *type)
3644{
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003645 char **p;
Guido van Rossum64c06e32007-11-22 00:55:51 +00003646 PyObject *dict = type->tp_dict;
3647
3648 assert(dict != NULL);
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003649 for (p = hash_name_op; *p; p++) {
3650 if (PyDict_GetItemString(dict, *p) != NULL)
Guido van Rossum64c06e32007-11-22 00:55:51 +00003651 return 1;
3652 }
3653 return 0;
3654}
3655
Guido van Rossum13d52f02001-08-10 21:24:08 +00003656static void
3657inherit_slots(PyTypeObject *type, PyTypeObject *base)
3658{
3659 PyTypeObject *basebase;
3660
3661#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003662#undef COPYSLOT
3663#undef COPYNUM
3664#undef COPYSEQ
3665#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003666#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003667
3668#define SLOTDEFINED(SLOT) \
3669 (base->SLOT != 0 && \
3670 (basebase == NULL || base->SLOT != basebase->SLOT))
3671
Tim Peters6d6c1a32001-08-02 04:15:00 +00003672#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003673 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674
3675#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3676#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3677#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003678#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003679
Guido van Rossum13d52f02001-08-10 21:24:08 +00003680 /* This won't inherit indirect slots (from tp_as_number etc.)
3681 if type doesn't provide the space. */
3682
3683 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3684 basebase = base->tp_base;
3685 if (basebase->tp_as_number == NULL)
3686 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003687 COPYNUM(nb_add);
3688 COPYNUM(nb_subtract);
3689 COPYNUM(nb_multiply);
3690 COPYNUM(nb_divide);
3691 COPYNUM(nb_remainder);
3692 COPYNUM(nb_divmod);
3693 COPYNUM(nb_power);
3694 COPYNUM(nb_negative);
3695 COPYNUM(nb_positive);
3696 COPYNUM(nb_absolute);
3697 COPYNUM(nb_nonzero);
3698 COPYNUM(nb_invert);
3699 COPYNUM(nb_lshift);
3700 COPYNUM(nb_rshift);
3701 COPYNUM(nb_and);
3702 COPYNUM(nb_xor);
3703 COPYNUM(nb_or);
3704 COPYNUM(nb_coerce);
3705 COPYNUM(nb_int);
3706 COPYNUM(nb_long);
3707 COPYNUM(nb_float);
3708 COPYNUM(nb_oct);
3709 COPYNUM(nb_hex);
3710 COPYNUM(nb_inplace_add);
3711 COPYNUM(nb_inplace_subtract);
3712 COPYNUM(nb_inplace_multiply);
3713 COPYNUM(nb_inplace_divide);
3714 COPYNUM(nb_inplace_remainder);
3715 COPYNUM(nb_inplace_power);
3716 COPYNUM(nb_inplace_lshift);
3717 COPYNUM(nb_inplace_rshift);
3718 COPYNUM(nb_inplace_and);
3719 COPYNUM(nb_inplace_xor);
3720 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003721 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3722 COPYNUM(nb_true_divide);
3723 COPYNUM(nb_floor_divide);
3724 COPYNUM(nb_inplace_true_divide);
3725 COPYNUM(nb_inplace_floor_divide);
3726 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003727 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3728 COPYNUM(nb_index);
3729 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003730 }
3731
Guido van Rossum13d52f02001-08-10 21:24:08 +00003732 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3733 basebase = base->tp_base;
3734 if (basebase->tp_as_sequence == NULL)
3735 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003736 COPYSEQ(sq_length);
3737 COPYSEQ(sq_concat);
3738 COPYSEQ(sq_repeat);
3739 COPYSEQ(sq_item);
3740 COPYSEQ(sq_slice);
3741 COPYSEQ(sq_ass_item);
3742 COPYSEQ(sq_ass_slice);
3743 COPYSEQ(sq_contains);
3744 COPYSEQ(sq_inplace_concat);
3745 COPYSEQ(sq_inplace_repeat);
3746 }
3747
Guido van Rossum13d52f02001-08-10 21:24:08 +00003748 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3749 basebase = base->tp_base;
3750 if (basebase->tp_as_mapping == NULL)
3751 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003752 COPYMAP(mp_length);
3753 COPYMAP(mp_subscript);
3754 COPYMAP(mp_ass_subscript);
3755 }
3756
Tim Petersfc57ccb2001-10-12 02:38:24 +00003757 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3758 basebase = base->tp_base;
3759 if (basebase->tp_as_buffer == NULL)
3760 basebase = NULL;
3761 COPYBUF(bf_getreadbuffer);
3762 COPYBUF(bf_getwritebuffer);
3763 COPYBUF(bf_getsegcount);
3764 COPYBUF(bf_getcharbuffer);
3765 }
3766
Guido van Rossum13d52f02001-08-10 21:24:08 +00003767 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003768
Tim Peters6d6c1a32001-08-02 04:15:00 +00003769 COPYSLOT(tp_dealloc);
3770 COPYSLOT(tp_print);
3771 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3772 type->tp_getattr = base->tp_getattr;
3773 type->tp_getattro = base->tp_getattro;
3774 }
3775 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3776 type->tp_setattr = base->tp_setattr;
3777 type->tp_setattro = base->tp_setattro;
3778 }
3779 /* tp_compare see tp_richcompare */
3780 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003781 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003782 COPYSLOT(tp_call);
3783 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003784 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003785 if (type->tp_compare == NULL &&
3786 type->tp_richcompare == NULL &&
Guido van Rossum64c06e32007-11-22 00:55:51 +00003787 type->tp_hash == NULL &&
3788 !overrides_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003789 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003790 type->tp_compare = base->tp_compare;
3791 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003792 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003793 }
3794 }
3795 else {
3796 COPYSLOT(tp_compare);
3797 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003798 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3799 COPYSLOT(tp_iter);
3800 COPYSLOT(tp_iternext);
3801 }
3802 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3803 COPYSLOT(tp_descr_get);
3804 COPYSLOT(tp_descr_set);
3805 COPYSLOT(tp_dictoffset);
3806 COPYSLOT(tp_init);
3807 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003808 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003809 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3810 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3811 /* They agree about gc. */
3812 COPYSLOT(tp_free);
3813 }
3814 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3815 type->tp_free == NULL &&
3816 base->tp_free == _PyObject_Del) {
3817 /* A bit of magic to plug in the correct default
3818 * tp_free function when a derived class adds gc,
3819 * didn't define tp_free, and the base uses the
3820 * default non-gc tp_free.
3821 */
3822 type->tp_free = PyObject_GC_Del;
3823 }
3824 /* else they didn't agree about gc, and there isn't something
3825 * obvious to be done -- the type is on its own.
3826 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003827 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003828}
3829
Jeremy Hylton938ace62002-07-17 16:30:39 +00003830static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003831
Tim Peters6d6c1a32001-08-02 04:15:00 +00003832int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003833PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003834{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003835 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003836 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003837 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003838
Guido van Rossumcab05802002-06-10 15:29:03 +00003839 if (type->tp_flags & Py_TPFLAGS_READY) {
3840 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003841 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003842 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003843 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003844
3845 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003846
Tim Peters36eb4df2003-03-23 03:33:13 +00003847#ifdef Py_TRACE_REFS
3848 /* PyType_Ready is the closest thing we have to a choke point
3849 * for type objects, so is the best place I can think of to try
3850 * to get type objects into the doubly-linked list of all objects.
3851 * Still, not all type objects go thru PyType_Ready.
3852 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003853 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003854#endif
3855
Tim Peters6d6c1a32001-08-02 04:15:00 +00003856 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3857 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003858 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003859 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003860 Py_INCREF(base);
3861 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003862
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003863 /* Now the only way base can still be NULL is if type is
3864 * &PyBaseObject_Type.
3865 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003866
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003867 /* Initialize the base class */
3868 if (base && base->tp_dict == NULL) {
3869 if (PyType_Ready(base) < 0)
3870 goto error;
3871 }
3872
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003873 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003874 compilable separately on Windows can call PyType_Ready() instead of
3875 initializing the ob_type field of their type objects. */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003876 /* The test for base != NULL is really unnecessary, since base is only
3877 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3878 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3879 know that. */
Christian Heimese93237d2007-12-19 02:37:44 +00003880 if (Py_TYPE(type) == NULL && base != NULL)
3881 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003882
Tim Peters6d6c1a32001-08-02 04:15:00 +00003883 /* Initialize tp_bases */
3884 bases = type->tp_bases;
3885 if (bases == NULL) {
3886 if (base == NULL)
3887 bases = PyTuple_New(0);
3888 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003889 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003890 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003891 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003892 type->tp_bases = bases;
3893 }
3894
Guido van Rossum687ae002001-10-15 22:03:32 +00003895 /* Initialize tp_dict */
3896 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003897 if (dict == NULL) {
3898 dict = PyDict_New();
3899 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003900 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003901 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003902 }
3903
Guido van Rossum687ae002001-10-15 22:03:32 +00003904 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003905 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003906 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003907 if (type->tp_methods != NULL) {
3908 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003909 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003910 }
3911 if (type->tp_members != NULL) {
3912 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003913 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003914 }
3915 if (type->tp_getset != NULL) {
3916 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003917 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003918 }
3919
Tim Peters6d6c1a32001-08-02 04:15:00 +00003920 /* Calculate method resolution order */
3921 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003922 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003923 }
3924
Guido van Rossum13d52f02001-08-10 21:24:08 +00003925 /* Inherit special flags from dominant base */
3926 if (type->tp_base != NULL)
3927 inherit_special(type, type->tp_base);
3928
Tim Peters6d6c1a32001-08-02 04:15:00 +00003929 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003930 bases = type->tp_mro;
3931 assert(bases != NULL);
3932 assert(PyTuple_Check(bases));
3933 n = PyTuple_GET_SIZE(bases);
3934 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003935 PyObject *b = PyTuple_GET_ITEM(bases, i);
3936 if (PyType_Check(b))
3937 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003938 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003939
Tim Peters3cfe7542003-05-21 21:29:48 +00003940 /* Sanity check for tp_free. */
3941 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3942 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003943 /* This base class needs to call tp_free, but doesn't have
3944 * one, or its tp_free is for non-gc'ed objects.
3945 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003946 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3947 "gc and is a base type but has inappropriate "
3948 "tp_free slot",
3949 type->tp_name);
3950 goto error;
3951 }
3952
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003953 /* if the type dictionary doesn't contain a __doc__, set it from
3954 the tp_doc slot.
3955 */
3956 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3957 if (type->tp_doc != NULL) {
3958 PyObject *doc = PyString_FromString(type->tp_doc);
Neal Norwitze1fdb322006-07-21 05:32:28 +00003959 if (doc == NULL)
3960 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003961 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3962 Py_DECREF(doc);
3963 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003964 PyDict_SetItemString(type->tp_dict,
3965 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003966 }
3967 }
3968
Guido van Rossum64c06e32007-11-22 00:55:51 +00003969 /* Hack for tp_hash and __hash__.
3970 If after all that, tp_hash is still NULL, and __hash__ is not in
3971 tp_dict, set tp_dict['__hash__'] equal to None.
3972 This signals that __hash__ is not inherited.
3973 */
3974 if (type->tp_hash == NULL &&
3975 PyDict_GetItemString(type->tp_dict, "__hash__") == NULL &&
3976 PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3977 {
3978 goto error;
3979 }
3980
Guido van Rossum13d52f02001-08-10 21:24:08 +00003981 /* Some more special stuff */
3982 base = type->tp_base;
3983 if (base != NULL) {
3984 if (type->tp_as_number == NULL)
3985 type->tp_as_number = base->tp_as_number;
3986 if (type->tp_as_sequence == NULL)
3987 type->tp_as_sequence = base->tp_as_sequence;
3988 if (type->tp_as_mapping == NULL)
3989 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003990 if (type->tp_as_buffer == NULL)
3991 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003992 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003993
Guido van Rossum1c450732001-10-08 15:18:27 +00003994 /* Link into each base class's list of subclasses */
3995 bases = type->tp_bases;
3996 n = PyTuple_GET_SIZE(bases);
3997 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003998 PyObject *b = PyTuple_GET_ITEM(bases, i);
3999 if (PyType_Check(b) &&
4000 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00004001 goto error;
4002 }
4003
Guido van Rossum13d52f02001-08-10 21:24:08 +00004004 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00004005 assert(type->tp_dict != NULL);
4006 type->tp_flags =
4007 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004008 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004009
4010 error:
4011 type->tp_flags &= ~Py_TPFLAGS_READYING;
4012 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004013}
4014
Guido van Rossum1c450732001-10-08 15:18:27 +00004015static int
4016add_subclass(PyTypeObject *base, PyTypeObject *type)
4017{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004018 Py_ssize_t i;
4019 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00004020 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004021
4022 list = base->tp_subclasses;
4023 if (list == NULL) {
4024 base->tp_subclasses = list = PyList_New(0);
4025 if (list == NULL)
4026 return -1;
4027 }
4028 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00004029 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00004030 i = PyList_GET_SIZE(list);
4031 while (--i >= 0) {
4032 ref = PyList_GET_ITEM(list, i);
4033 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00004034 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00004035 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00004036 }
Anthony Baxtera6286212006-04-11 07:42:36 +00004037 result = PyList_Append(list, newobj);
4038 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004039 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004040}
4041
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004042static void
4043remove_subclass(PyTypeObject *base, PyTypeObject *type)
4044{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004045 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004046 PyObject *list, *ref;
4047
4048 list = base->tp_subclasses;
4049 if (list == NULL) {
4050 return;
4051 }
4052 assert(PyList_Check(list));
4053 i = PyList_GET_SIZE(list);
4054 while (--i >= 0) {
4055 ref = PyList_GET_ITEM(list, i);
4056 assert(PyWeakref_CheckRef(ref));
4057 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4058 /* this can't fail, right? */
4059 PySequence_DelItem(list, i);
4060 return;
4061 }
4062 }
4063}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004064
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004065static int
4066check_num_args(PyObject *ob, int n)
4067{
4068 if (!PyTuple_CheckExact(ob)) {
4069 PyErr_SetString(PyExc_SystemError,
4070 "PyArg_UnpackTuple() argument list is not a tuple");
4071 return 0;
4072 }
4073 if (n == PyTuple_GET_SIZE(ob))
4074 return 1;
4075 PyErr_Format(
4076 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00004077 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004078 return 0;
4079}
4080
Tim Peters6d6c1a32001-08-02 04:15:00 +00004081/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4082
4083/* There's a wrapper *function* for each distinct function typedef used
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004084 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004085 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4086 Most tables have only one entry; the tables for binary operators have two
4087 entries, one regular and one with reversed arguments. */
4088
4089static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004090wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004091{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004092 lenfunc func = (lenfunc)wrapped;
4093 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004094
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004095 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004096 return NULL;
4097 res = (*func)(self);
4098 if (res == -1 && PyErr_Occurred())
4099 return NULL;
4100 return PyInt_FromLong((long)res);
4101}
4102
Tim Peters6d6c1a32001-08-02 04:15:00 +00004103static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004104wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4105{
4106 inquiry func = (inquiry)wrapped;
4107 int res;
4108
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004109 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004110 return NULL;
4111 res = (*func)(self);
4112 if (res == -1 && PyErr_Occurred())
4113 return NULL;
4114 return PyBool_FromLong((long)res);
4115}
4116
4117static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004118wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4119{
4120 binaryfunc func = (binaryfunc)wrapped;
4121 PyObject *other;
4122
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004123 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004124 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004125 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004126 return (*func)(self, other);
4127}
4128
4129static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004130wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4131{
4132 binaryfunc func = (binaryfunc)wrapped;
4133 PyObject *other;
4134
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004135 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004136 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004137 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004138 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004139 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004140 Py_INCREF(Py_NotImplemented);
4141 return Py_NotImplemented;
4142 }
4143 return (*func)(self, other);
4144}
4145
4146static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004147wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4148{
4149 binaryfunc func = (binaryfunc)wrapped;
4150 PyObject *other;
4151
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004152 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004153 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004154 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004155 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004156 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004157 Py_INCREF(Py_NotImplemented);
4158 return Py_NotImplemented;
4159 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004160 return (*func)(other, self);
4161}
4162
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004163static PyObject *
4164wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
4165{
4166 coercion func = (coercion)wrapped;
4167 PyObject *other, *res;
4168 int ok;
4169
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004170 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004171 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004172 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004173 ok = func(&self, &other);
4174 if (ok < 0)
4175 return NULL;
4176 if (ok > 0) {
4177 Py_INCREF(Py_NotImplemented);
4178 return Py_NotImplemented;
4179 }
4180 res = PyTuple_New(2);
4181 if (res == NULL) {
4182 Py_DECREF(self);
4183 Py_DECREF(other);
4184 return NULL;
4185 }
4186 PyTuple_SET_ITEM(res, 0, self);
4187 PyTuple_SET_ITEM(res, 1, other);
4188 return res;
4189}
4190
Tim Peters6d6c1a32001-08-02 04:15:00 +00004191static PyObject *
4192wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4193{
4194 ternaryfunc func = (ternaryfunc)wrapped;
4195 PyObject *other;
4196 PyObject *third = Py_None;
4197
4198 /* Note: This wrapper only works for __pow__() */
4199
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004200 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004201 return NULL;
4202 return (*func)(self, other, third);
4203}
4204
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004205static PyObject *
4206wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4207{
4208 ternaryfunc func = (ternaryfunc)wrapped;
4209 PyObject *other;
4210 PyObject *third = Py_None;
4211
4212 /* Note: This wrapper only works for __pow__() */
4213
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004214 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004215 return NULL;
4216 return (*func)(other, self, third);
4217}
4218
Tim Peters6d6c1a32001-08-02 04:15:00 +00004219static PyObject *
4220wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4221{
4222 unaryfunc func = (unaryfunc)wrapped;
4223
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004224 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004225 return NULL;
4226 return (*func)(self);
4227}
4228
Tim Peters6d6c1a32001-08-02 04:15:00 +00004229static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00004230wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004231{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004232 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00004233 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004234 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004235
Armin Rigo314861c2006-03-30 14:04:02 +00004236 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4237 return NULL;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004238 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Armin Rigo314861c2006-03-30 14:04:02 +00004239 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004240 return NULL;
4241 return (*func)(self, i);
4242}
4243
Martin v. Löwis18e16552006-02-15 17:27:45 +00004244static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004245getindex(PyObject *self, PyObject *arg)
4246{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004247 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004248
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004249 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004250 if (i == -1 && PyErr_Occurred())
4251 return -1;
4252 if (i < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00004253 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004254 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00004255 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004256 if (n < 0)
4257 return -1;
4258 i += n;
4259 }
4260 }
4261 return i;
4262}
4263
4264static PyObject *
4265wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4266{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004267 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004268 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004269 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004270
Guido van Rossumf4593e02001-10-03 12:09:30 +00004271 if (PyTuple_GET_SIZE(args) == 1) {
4272 arg = PyTuple_GET_ITEM(args, 0);
4273 i = getindex(self, arg);
4274 if (i == -1 && PyErr_Occurred())
4275 return NULL;
4276 return (*func)(self, i);
4277 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004278 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004279 assert(PyErr_Occurred());
4280 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004281}
4282
Tim Peters6d6c1a32001-08-02 04:15:00 +00004283static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004284wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004285{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004286 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
4287 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004288
Martin v. Löwis18e16552006-02-15 17:27:45 +00004289 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004290 return NULL;
4291 return (*func)(self, i, j);
4292}
4293
Tim Peters6d6c1a32001-08-02 04:15:00 +00004294static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004295wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004296{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004297 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4298 Py_ssize_t i;
4299 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004300 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004301
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004302 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004303 return NULL;
4304 i = getindex(self, arg);
4305 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004306 return NULL;
4307 res = (*func)(self, i, value);
4308 if (res == -1 && PyErr_Occurred())
4309 return NULL;
4310 Py_INCREF(Py_None);
4311 return Py_None;
4312}
4313
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004314static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004315wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004316{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004317 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4318 Py_ssize_t i;
4319 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004320 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004321
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004322 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004323 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004324 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004325 i = getindex(self, arg);
4326 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004327 return NULL;
4328 res = (*func)(self, i, NULL);
4329 if (res == -1 && PyErr_Occurred())
4330 return NULL;
4331 Py_INCREF(Py_None);
4332 return Py_None;
4333}
4334
Tim Peters6d6c1a32001-08-02 04:15:00 +00004335static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004336wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004337{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004338 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4339 Py_ssize_t i, j;
4340 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004341 PyObject *value;
4342
Martin v. Löwis18e16552006-02-15 17:27:45 +00004343 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004344 return NULL;
4345 res = (*func)(self, i, j, value);
4346 if (res == -1 && PyErr_Occurred())
4347 return NULL;
4348 Py_INCREF(Py_None);
4349 return Py_None;
4350}
4351
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004352static PyObject *
4353wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
4354{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004355 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4356 Py_ssize_t i, j;
4357 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004358
Martin v. Löwis18e16552006-02-15 17:27:45 +00004359 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004360 return NULL;
4361 res = (*func)(self, i, j, NULL);
4362 if (res == -1 && PyErr_Occurred())
4363 return NULL;
4364 Py_INCREF(Py_None);
4365 return Py_None;
4366}
4367
Tim Peters6d6c1a32001-08-02 04:15:00 +00004368/* XXX objobjproc is a misnomer; should be objargpred */
4369static PyObject *
4370wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4371{
4372 objobjproc func = (objobjproc)wrapped;
4373 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004374 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004375
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004376 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004377 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004378 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004379 res = (*func)(self, value);
4380 if (res == -1 && PyErr_Occurred())
4381 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004382 else
4383 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004384}
4385
Tim Peters6d6c1a32001-08-02 04:15:00 +00004386static PyObject *
4387wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4388{
4389 objobjargproc func = (objobjargproc)wrapped;
4390 int res;
4391 PyObject *key, *value;
4392
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004393 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004394 return NULL;
4395 res = (*func)(self, key, value);
4396 if (res == -1 && PyErr_Occurred())
4397 return NULL;
4398 Py_INCREF(Py_None);
4399 return Py_None;
4400}
4401
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004402static PyObject *
4403wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4404{
4405 objobjargproc func = (objobjargproc)wrapped;
4406 int res;
4407 PyObject *key;
4408
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004409 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004410 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004411 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004412 res = (*func)(self, key, NULL);
4413 if (res == -1 && PyErr_Occurred())
4414 return NULL;
4415 Py_INCREF(Py_None);
4416 return Py_None;
4417}
4418
Tim Peters6d6c1a32001-08-02 04:15:00 +00004419static PyObject *
4420wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
4421{
4422 cmpfunc func = (cmpfunc)wrapped;
4423 int res;
4424 PyObject *other;
4425
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004426 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004427 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004428 other = PyTuple_GET_ITEM(args, 0);
Christian Heimese93237d2007-12-19 02:37:44 +00004429 if (Py_TYPE(other)->tp_compare != func &&
4430 !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
Guido van Rossumceccae52001-09-18 20:03:57 +00004431 PyErr_Format(
4432 PyExc_TypeError,
4433 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +00004434 Py_TYPE(self)->tp_name,
4435 Py_TYPE(self)->tp_name,
4436 Py_TYPE(other)->tp_name);
Guido van Rossumceccae52001-09-18 20:03:57 +00004437 return NULL;
4438 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004439 res = (*func)(self, other);
4440 if (PyErr_Occurred())
4441 return NULL;
4442 return PyInt_FromLong((long)res);
4443}
4444
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004445/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004446 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004447static int
4448hackcheck(PyObject *self, setattrofunc func, char *what)
4449{
Christian Heimese93237d2007-12-19 02:37:44 +00004450 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004451 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4452 type = type->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004453 /* If type is NULL now, this is a really weird type.
4454 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004455 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004456 PyErr_Format(PyExc_TypeError,
4457 "can't apply this %s to %s object",
4458 what,
4459 type->tp_name);
4460 return 0;
4461 }
4462 return 1;
4463}
4464
Tim Peters6d6c1a32001-08-02 04:15:00 +00004465static PyObject *
4466wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4467{
4468 setattrofunc func = (setattrofunc)wrapped;
4469 int res;
4470 PyObject *name, *value;
4471
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004472 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004473 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004474 if (!hackcheck(self, func, "__setattr__"))
4475 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004476 res = (*func)(self, name, value);
4477 if (res < 0)
4478 return NULL;
4479 Py_INCREF(Py_None);
4480 return Py_None;
4481}
4482
4483static PyObject *
4484wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4485{
4486 setattrofunc func = (setattrofunc)wrapped;
4487 int res;
4488 PyObject *name;
4489
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004490 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004491 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004492 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004493 if (!hackcheck(self, func, "__delattr__"))
4494 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004495 res = (*func)(self, name, NULL);
4496 if (res < 0)
4497 return NULL;
4498 Py_INCREF(Py_None);
4499 return Py_None;
4500}
4501
Tim Peters6d6c1a32001-08-02 04:15:00 +00004502static PyObject *
4503wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4504{
4505 hashfunc func = (hashfunc)wrapped;
4506 long res;
4507
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004508 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004509 return NULL;
4510 res = (*func)(self);
4511 if (res == -1 && PyErr_Occurred())
4512 return NULL;
4513 return PyInt_FromLong(res);
4514}
4515
Tim Peters6d6c1a32001-08-02 04:15:00 +00004516static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004517wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004518{
4519 ternaryfunc func = (ternaryfunc)wrapped;
4520
Guido van Rossumc8e56452001-10-22 00:43:43 +00004521 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004522}
4523
Tim Peters6d6c1a32001-08-02 04:15:00 +00004524static PyObject *
4525wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4526{
4527 richcmpfunc func = (richcmpfunc)wrapped;
4528 PyObject *other;
4529
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004530 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004531 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004532 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004533 return (*func)(self, other, op);
4534}
4535
4536#undef RICHCMP_WRAPPER
4537#define RICHCMP_WRAPPER(NAME, OP) \
4538static PyObject * \
4539richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4540{ \
4541 return wrap_richcmpfunc(self, args, wrapped, OP); \
4542}
4543
Jack Jansen8e938b42001-08-08 15:29:49 +00004544RICHCMP_WRAPPER(lt, Py_LT)
4545RICHCMP_WRAPPER(le, Py_LE)
4546RICHCMP_WRAPPER(eq, Py_EQ)
4547RICHCMP_WRAPPER(ne, Py_NE)
4548RICHCMP_WRAPPER(gt, Py_GT)
4549RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004550
Tim Peters6d6c1a32001-08-02 04:15:00 +00004551static PyObject *
4552wrap_next(PyObject *self, PyObject *args, void *wrapped)
4553{
4554 unaryfunc func = (unaryfunc)wrapped;
4555 PyObject *res;
4556
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004557 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004558 return NULL;
4559 res = (*func)(self);
4560 if (res == NULL && !PyErr_Occurred())
4561 PyErr_SetNone(PyExc_StopIteration);
4562 return res;
4563}
4564
Tim Peters6d6c1a32001-08-02 04:15:00 +00004565static PyObject *
4566wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4567{
4568 descrgetfunc func = (descrgetfunc)wrapped;
4569 PyObject *obj;
4570 PyObject *type = NULL;
4571
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004572 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004573 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004574 if (obj == Py_None)
4575 obj = NULL;
4576 if (type == Py_None)
4577 type = NULL;
4578 if (type == NULL &&obj == NULL) {
4579 PyErr_SetString(PyExc_TypeError,
4580 "__get__(None, None) is invalid");
4581 return NULL;
4582 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004583 return (*func)(self, obj, type);
4584}
4585
Tim Peters6d6c1a32001-08-02 04:15:00 +00004586static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004587wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004588{
4589 descrsetfunc func = (descrsetfunc)wrapped;
4590 PyObject *obj, *value;
4591 int ret;
4592
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004593 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004594 return NULL;
4595 ret = (*func)(self, obj, value);
4596 if (ret < 0)
4597 return NULL;
4598 Py_INCREF(Py_None);
4599 return Py_None;
4600}
Guido van Rossum22b13872002-08-06 21:41:44 +00004601
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004602static PyObject *
4603wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4604{
4605 descrsetfunc func = (descrsetfunc)wrapped;
4606 PyObject *obj;
4607 int ret;
4608
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004609 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004610 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004611 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004612 ret = (*func)(self, obj, NULL);
4613 if (ret < 0)
4614 return NULL;
4615 Py_INCREF(Py_None);
4616 return Py_None;
4617}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004618
Tim Peters6d6c1a32001-08-02 04:15:00 +00004619static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004620wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004621{
4622 initproc func = (initproc)wrapped;
4623
Guido van Rossumc8e56452001-10-22 00:43:43 +00004624 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004625 return NULL;
4626 Py_INCREF(Py_None);
4627 return Py_None;
4628}
4629
Tim Peters6d6c1a32001-08-02 04:15:00 +00004630static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004631tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004632{
Barry Warsaw60f01882001-08-22 19:24:42 +00004633 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004634 PyObject *arg0, *res;
4635
4636 if (self == NULL || !PyType_Check(self))
4637 Py_FatalError("__new__() called with non-type 'self'");
4638 type = (PyTypeObject *)self;
4639 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004640 PyErr_Format(PyExc_TypeError,
4641 "%s.__new__(): not enough arguments",
4642 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004643 return NULL;
4644 }
4645 arg0 = PyTuple_GET_ITEM(args, 0);
4646 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004647 PyErr_Format(PyExc_TypeError,
4648 "%s.__new__(X): X is not a type object (%s)",
4649 type->tp_name,
Christian Heimese93237d2007-12-19 02:37:44 +00004650 Py_TYPE(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004651 return NULL;
4652 }
4653 subtype = (PyTypeObject *)arg0;
4654 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004655 PyErr_Format(PyExc_TypeError,
4656 "%s.__new__(%s): %s is not a subtype of %s",
4657 type->tp_name,
4658 subtype->tp_name,
4659 subtype->tp_name,
4660 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004661 return NULL;
4662 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004663
4664 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004665 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004666 most derived base that's not a heap type is this type. */
4667 staticbase = subtype;
4668 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4669 staticbase = staticbase->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004670 /* If staticbase is NULL now, it is a really weird type.
4671 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004672 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004673 PyErr_Format(PyExc_TypeError,
4674 "%s.__new__(%s) is not safe, use %s.__new__()",
4675 type->tp_name,
4676 subtype->tp_name,
4677 staticbase == NULL ? "?" : staticbase->tp_name);
4678 return NULL;
4679 }
4680
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004681 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4682 if (args == NULL)
4683 return NULL;
4684 res = type->tp_new(subtype, args, kwds);
4685 Py_DECREF(args);
4686 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004687}
4688
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004689static struct PyMethodDef tp_new_methoddef[] = {
Neal Norwitza84dcd72007-05-22 07:16:44 +00004690 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004691 PyDoc_STR("T.__new__(S, ...) -> "
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004692 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004693 {0}
4694};
4695
4696static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004697add_tp_new_wrapper(PyTypeObject *type)
4698{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004699 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004700
Guido van Rossum687ae002001-10-15 22:03:32 +00004701 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004702 return 0;
4703 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004704 if (func == NULL)
4705 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004706 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004707 Py_DECREF(func);
4708 return -1;
4709 }
4710 Py_DECREF(func);
4711 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004712}
4713
Guido van Rossumf040ede2001-08-07 16:40:56 +00004714/* Slot wrappers that call the corresponding __foo__ slot. See comments
4715 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004716
Guido van Rossumdc91b992001-08-08 22:26:22 +00004717#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004718static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004719FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004720{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004721 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004722 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004723}
4724
Guido van Rossumdc91b992001-08-08 22:26:22 +00004725#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004726static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004727FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004728{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004729 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004730 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004731}
4732
Guido van Rossumcd118802003-01-06 22:57:47 +00004733/* Boolean helper for SLOT1BINFULL().
4734 right.__class__ is a nontrivial subclass of left.__class__. */
4735static int
4736method_is_overloaded(PyObject *left, PyObject *right, char *name)
4737{
4738 PyObject *a, *b;
4739 int ok;
4740
Christian Heimese93237d2007-12-19 02:37:44 +00004741 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004742 if (b == NULL) {
4743 PyErr_Clear();
4744 /* If right doesn't have it, it's not overloaded */
4745 return 0;
4746 }
4747
Christian Heimese93237d2007-12-19 02:37:44 +00004748 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004749 if (a == NULL) {
4750 PyErr_Clear();
4751 Py_DECREF(b);
4752 /* If right has it but left doesn't, it's overloaded */
4753 return 1;
4754 }
4755
4756 ok = PyObject_RichCompareBool(a, b, Py_NE);
4757 Py_DECREF(a);
4758 Py_DECREF(b);
4759 if (ok < 0) {
4760 PyErr_Clear();
4761 return 0;
4762 }
4763
4764 return ok;
4765}
4766
Guido van Rossumdc91b992001-08-08 22:26:22 +00004767
4768#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004769static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004770FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004771{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004772 static PyObject *cache_str, *rcache_str; \
Christian Heimese93237d2007-12-19 02:37:44 +00004773 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4774 Py_TYPE(other)->tp_as_number != NULL && \
4775 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4776 if (Py_TYPE(self)->tp_as_number != NULL && \
4777 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004778 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004779 if (do_other && \
Christian Heimese93237d2007-12-19 02:37:44 +00004780 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004781 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004782 r = call_maybe( \
4783 other, ROPSTR, &rcache_str, "(O)", self); \
4784 if (r != Py_NotImplemented) \
4785 return r; \
4786 Py_DECREF(r); \
4787 do_other = 0; \
4788 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004789 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004790 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004791 if (r != Py_NotImplemented || \
Christian Heimese93237d2007-12-19 02:37:44 +00004792 Py_TYPE(other) == Py_TYPE(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004793 return r; \
4794 Py_DECREF(r); \
4795 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004796 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004797 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004798 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004799 } \
4800 Py_INCREF(Py_NotImplemented); \
4801 return Py_NotImplemented; \
4802}
4803
4804#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4805 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4806
4807#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4808static PyObject * \
4809FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4810{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004811 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004812 return call_method(self, OPSTR, &cache_str, \
4813 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004814}
4815
Martin v. Löwis18e16552006-02-15 17:27:45 +00004816static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004817slot_sq_length(PyObject *self)
4818{
Guido van Rossum2730b132001-08-28 18:22:14 +00004819 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004820 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004821 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004822
4823 if (res == NULL)
4824 return -1;
Neal Norwitz1872b1c2006-08-12 18:44:06 +00004825 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004826 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004827 if (len < 0) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00004828 if (!PyErr_Occurred())
4829 PyErr_SetString(PyExc_ValueError,
4830 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004831 return -1;
4832 }
Guido van Rossum26111622001-10-01 16:42:49 +00004833 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004834}
4835
Guido van Rossumf4593e02001-10-03 12:09:30 +00004836/* Super-optimized version of slot_sq_item.
4837 Other slots could do the same... */
4838static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004839slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004840{
4841 static PyObject *getitem_str;
4842 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4843 descrgetfunc f;
4844
4845 if (getitem_str == NULL) {
4846 getitem_str = PyString_InternFromString("__getitem__");
4847 if (getitem_str == NULL)
4848 return NULL;
4849 }
Christian Heimese93237d2007-12-19 02:37:44 +00004850 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004851 if (func != NULL) {
Christian Heimese93237d2007-12-19 02:37:44 +00004852 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004853 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004854 else {
Christian Heimese93237d2007-12-19 02:37:44 +00004855 func = f(func, self, (PyObject *)(Py_TYPE(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004856 if (func == NULL) {
4857 return NULL;
4858 }
4859 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004860 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004861 if (ival != NULL) {
4862 args = PyTuple_New(1);
4863 if (args != NULL) {
4864 PyTuple_SET_ITEM(args, 0, ival);
4865 retval = PyObject_Call(func, args, NULL);
4866 Py_XDECREF(args);
4867 Py_XDECREF(func);
4868 return retval;
4869 }
4870 }
4871 }
4872 else {
4873 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4874 }
4875 Py_XDECREF(args);
4876 Py_XDECREF(ival);
4877 Py_XDECREF(func);
4878 return NULL;
4879}
4880
Martin v. Löwis18e16552006-02-15 17:27:45 +00004881SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004882
4883static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004884slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004885{
4886 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004887 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004888
4889 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004890 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004891 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004892 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004893 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004894 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004895 if (res == NULL)
4896 return -1;
4897 Py_DECREF(res);
4898 return 0;
4899}
4900
4901static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004902slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004903{
4904 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004905 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004906
4907 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004908 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004909 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004910 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004911 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004912 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004913 if (res == NULL)
4914 return -1;
4915 Py_DECREF(res);
4916 return 0;
4917}
4918
4919static int
4920slot_sq_contains(PyObject *self, PyObject *value)
4921{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004922 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004923 int result = -1;
4924
Guido van Rossum60718732001-08-28 17:47:51 +00004925 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004926
Guido van Rossum55f20992001-10-01 17:18:22 +00004927 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004928 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004929 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004930 if (args == NULL)
4931 res = NULL;
4932 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004933 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004934 Py_DECREF(args);
4935 }
4936 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004937 if (res != NULL) {
4938 result = PyObject_IsTrue(res);
4939 Py_DECREF(res);
4940 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004941 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004942 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004943 /* Possible results: -1 and 1 */
4944 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004945 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004946 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004947 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004948}
4949
Tim Peters6d6c1a32001-08-02 04:15:00 +00004950#define slot_mp_length slot_sq_length
4951
Guido van Rossumdc91b992001-08-08 22:26:22 +00004952SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004953
4954static int
4955slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4956{
4957 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004958 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004959
4960 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004961 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004962 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004963 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004964 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004965 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004966 if (res == NULL)
4967 return -1;
4968 Py_DECREF(res);
4969 return 0;
4970}
4971
Guido van Rossumdc91b992001-08-08 22:26:22 +00004972SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4973SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4974SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4975SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4976SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4977SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4978
Jeremy Hylton938ace62002-07-17 16:30:39 +00004979static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004980
4981SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4982 nb_power, "__pow__", "__rpow__")
4983
4984static PyObject *
4985slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4986{
Guido van Rossum2730b132001-08-28 18:22:14 +00004987 static PyObject *pow_str;
4988
Guido van Rossumdc91b992001-08-08 22:26:22 +00004989 if (modulus == Py_None)
4990 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004991 /* Three-arg power doesn't use __rpow__. But ternary_op
4992 can call this when the second argument's type uses
4993 slot_nb_power, so check before calling self.__pow__. */
Christian Heimese93237d2007-12-19 02:37:44 +00004994 if (Py_TYPE(self)->tp_as_number != NULL &&
4995 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00004996 return call_method(self, "__pow__", &pow_str,
4997 "(OO)", other, modulus);
4998 }
4999 Py_INCREF(Py_NotImplemented);
5000 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005001}
5002
5003SLOT0(slot_nb_negative, "__neg__")
5004SLOT0(slot_nb_positive, "__pos__")
5005SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005006
5007static int
5008slot_nb_nonzero(PyObject *self)
5009{
Tim Petersea7f75d2002-12-07 21:39:16 +00005010 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00005011 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00005012 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005013
Guido van Rossum55f20992001-10-01 17:18:22 +00005014 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005015 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00005016 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00005017 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00005018 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00005019 if (func == NULL)
5020 return PyErr_Occurred() ? -1 : 1;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005021 }
Tim Petersea7f75d2002-12-07 21:39:16 +00005022 args = PyTuple_New(0);
5023 if (args != NULL) {
5024 PyObject *temp = PyObject_Call(func, args, NULL);
5025 Py_DECREF(args);
5026 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00005027 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00005028 result = PyObject_IsTrue(temp);
5029 else {
5030 PyErr_Format(PyExc_TypeError,
5031 "__nonzero__ should return "
5032 "bool or int, returned %s",
5033 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00005034 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00005035 }
Tim Petersea7f75d2002-12-07 21:39:16 +00005036 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00005037 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005038 }
Guido van Rossum55f20992001-10-01 17:18:22 +00005039 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00005040 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005041}
5042
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005043
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005044static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005045slot_nb_index(PyObject *self)
5046{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005047 static PyObject *index_str;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005048 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005049}
5050
5051
Guido van Rossumdc91b992001-08-08 22:26:22 +00005052SLOT0(slot_nb_invert, "__invert__")
5053SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5054SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5055SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5056SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5057SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005058
5059static int
5060slot_nb_coerce(PyObject **a, PyObject **b)
5061{
5062 static PyObject *coerce_str;
5063 PyObject *self = *a, *other = *b;
5064
5065 if (self->ob_type->tp_as_number != NULL &&
5066 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5067 PyObject *r;
5068 r = call_maybe(
5069 self, "__coerce__", &coerce_str, "(O)", other);
5070 if (r == NULL)
5071 return -1;
5072 if (r == Py_NotImplemented) {
5073 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005074 }
Guido van Rossum55f20992001-10-01 17:18:22 +00005075 else {
5076 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5077 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005078 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00005079 Py_DECREF(r);
5080 return -1;
5081 }
5082 *a = PyTuple_GET_ITEM(r, 0);
5083 Py_INCREF(*a);
5084 *b = PyTuple_GET_ITEM(r, 1);
5085 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005086 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00005087 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005088 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005089 }
5090 if (other->ob_type->tp_as_number != NULL &&
5091 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5092 PyObject *r;
5093 r = call_maybe(
5094 other, "__coerce__", &coerce_str, "(O)", self);
5095 if (r == NULL)
5096 return -1;
5097 if (r == Py_NotImplemented) {
5098 Py_DECREF(r);
5099 return 1;
5100 }
5101 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5102 PyErr_SetString(PyExc_TypeError,
5103 "__coerce__ didn't return a 2-tuple");
5104 Py_DECREF(r);
5105 return -1;
5106 }
5107 *a = PyTuple_GET_ITEM(r, 1);
5108 Py_INCREF(*a);
5109 *b = PyTuple_GET_ITEM(r, 0);
5110 Py_INCREF(*b);
5111 Py_DECREF(r);
5112 return 0;
5113 }
5114 return 1;
5115}
5116
Guido van Rossumdc91b992001-08-08 22:26:22 +00005117SLOT0(slot_nb_int, "__int__")
5118SLOT0(slot_nb_long, "__long__")
5119SLOT0(slot_nb_float, "__float__")
5120SLOT0(slot_nb_oct, "__oct__")
5121SLOT0(slot_nb_hex, "__hex__")
5122SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5123SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5124SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
5125SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
5126SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Martin v. Löwisfd963262007-02-09 12:19:32 +00005127/* Can't use SLOT1 here, because nb_inplace_power is ternary */
5128static PyObject *
5129slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5130{
5131 static PyObject *cache_str;
5132 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
5133}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005134SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5135SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5136SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5137SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5138SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5139SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
5140 "__floordiv__", "__rfloordiv__")
5141SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5142SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5143SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005144
5145static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00005146half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005147{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005148 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005149 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005150 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005151
Guido van Rossum60718732001-08-28 17:47:51 +00005152 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005153 if (func == NULL) {
5154 PyErr_Clear();
5155 }
5156 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005157 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005158 if (args == NULL)
5159 res = NULL;
5160 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005161 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005162 Py_DECREF(args);
5163 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00005164 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005165 if (res != Py_NotImplemented) {
5166 if (res == NULL)
5167 return -2;
5168 c = PyInt_AsLong(res);
5169 Py_DECREF(res);
5170 if (c == -1 && PyErr_Occurred())
5171 return -2;
5172 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
5173 }
5174 Py_DECREF(res);
5175 }
5176 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005177}
5178
Guido van Rossumab3b0342001-09-18 20:38:53 +00005179/* This slot is published for the benefit of try_3way_compare in object.c */
5180int
5181_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00005182{
5183 int c;
5184
Christian Heimese93237d2007-12-19 02:37:44 +00005185 if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005186 c = half_compare(self, other);
5187 if (c <= 1)
5188 return c;
5189 }
Christian Heimese93237d2007-12-19 02:37:44 +00005190 if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005191 c = half_compare(other, self);
5192 if (c < -1)
5193 return -2;
5194 if (c <= 1)
5195 return -c;
5196 }
5197 return (void *)self < (void *)other ? -1 :
5198 (void *)self > (void *)other ? 1 : 0;
5199}
5200
5201static PyObject *
5202slot_tp_repr(PyObject *self)
5203{
5204 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005205 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005206
Guido van Rossum60718732001-08-28 17:47:51 +00005207 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005208 if (func != NULL) {
5209 res = PyEval_CallObject(func, NULL);
5210 Py_DECREF(func);
5211 return res;
5212 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00005213 PyErr_Clear();
5214 return PyString_FromFormat("<%s object at %p>",
Christian Heimese93237d2007-12-19 02:37:44 +00005215 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005216}
5217
5218static PyObject *
5219slot_tp_str(PyObject *self)
5220{
5221 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005222 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005223
Guido van Rossum60718732001-08-28 17:47:51 +00005224 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005225 if (func != NULL) {
5226 res = PyEval_CallObject(func, NULL);
5227 Py_DECREF(func);
5228 return res;
5229 }
5230 else {
5231 PyErr_Clear();
5232 return slot_tp_repr(self);
5233 }
5234}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005235
5236static long
5237slot_tp_hash(PyObject *self)
5238{
Tim Peters61ce0a92002-12-06 23:38:02 +00005239 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00005240 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005241 long h;
5242
Guido van Rossum60718732001-08-28 17:47:51 +00005243 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005244
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005245 if (func != NULL && func != Py_None) {
Tim Peters61ce0a92002-12-06 23:38:02 +00005246 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005247 Py_DECREF(func);
5248 if (res == NULL)
5249 return -1;
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00005250 if (PyLong_Check(res))
Armin Rigo51fc8c42006-08-09 14:55:26 +00005251 h = PyLong_Type.tp_hash(res);
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00005252 else
5253 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00005254 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005255 }
5256 else {
Georg Brandl30b78042007-12-20 21:03:02 +00005257 Py_XDECREF(func); /* may be None */
Guido van Rossumb8f63662001-08-15 23:57:02 +00005258 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005259 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005260 if (func == NULL) {
5261 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005262 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005263 }
5264 if (func != NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00005265 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
5266 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005267 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005268 return -1;
5269 }
5270 PyErr_Clear();
5271 h = _Py_HashPointer((void *)self);
5272 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005273 if (h == -1 && !PyErr_Occurred())
5274 h = -2;
5275 return h;
5276}
5277
5278static PyObject *
5279slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5280{
Guido van Rossum60718732001-08-28 17:47:51 +00005281 static PyObject *call_str;
5282 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005283 PyObject *res;
5284
5285 if (meth == NULL)
5286 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00005287
Tim Peters6d6c1a32001-08-02 04:15:00 +00005288 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00005289
Tim Peters6d6c1a32001-08-02 04:15:00 +00005290 Py_DECREF(meth);
5291 return res;
5292}
5293
Guido van Rossum14a6f832001-10-17 13:59:09 +00005294/* There are two slot dispatch functions for tp_getattro.
5295
5296 - slot_tp_getattro() is used when __getattribute__ is overridden
5297 but no __getattr__ hook is present;
5298
5299 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5300
Guido van Rossumc334df52002-04-04 23:44:47 +00005301 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5302 detects the absence of __getattr__ and then installs the simpler slot if
5303 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005304
Tim Peters6d6c1a32001-08-02 04:15:00 +00005305static PyObject *
5306slot_tp_getattro(PyObject *self, PyObject *name)
5307{
Guido van Rossum14a6f832001-10-17 13:59:09 +00005308 static PyObject *getattribute_str = NULL;
5309 return call_method(self, "__getattribute__", &getattribute_str,
5310 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005311}
5312
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005313static PyObject *
5314slot_tp_getattr_hook(PyObject *self, PyObject *name)
5315{
Christian Heimese93237d2007-12-19 02:37:44 +00005316 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005317 PyObject *getattr, *getattribute, *res;
5318 static PyObject *getattribute_str = NULL;
5319 static PyObject *getattr_str = NULL;
5320
5321 if (getattr_str == NULL) {
5322 getattr_str = PyString_InternFromString("__getattr__");
5323 if (getattr_str == NULL)
5324 return NULL;
5325 }
5326 if (getattribute_str == NULL) {
5327 getattribute_str =
5328 PyString_InternFromString("__getattribute__");
5329 if (getattribute_str == NULL)
5330 return NULL;
5331 }
5332 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005333 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005334 /* No __getattr__ hook: use a simpler dispatcher */
5335 tp->tp_getattro = slot_tp_getattro;
5336 return slot_tp_getattro(self, name);
5337 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005338 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005339 if (getattribute == NULL ||
Christian Heimese93237d2007-12-19 02:37:44 +00005340 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00005341 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5342 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005343 res = PyObject_GenericGetAttr(self, name);
5344 else
Georg Brandl684fd0c2006-05-25 19:15:31 +00005345 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005346 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005347 PyErr_Clear();
Georg Brandl684fd0c2006-05-25 19:15:31 +00005348 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005349 }
5350 return res;
5351}
5352
Tim Peters6d6c1a32001-08-02 04:15:00 +00005353static int
5354slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5355{
5356 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005357 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005358
5359 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00005360 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005361 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005362 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005363 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005364 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005365 if (res == NULL)
5366 return -1;
5367 Py_DECREF(res);
5368 return 0;
5369}
5370
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005371static char *name_op[] = {
5372 "__lt__",
5373 "__le__",
5374 "__eq__",
5375 "__ne__",
5376 "__gt__",
5377 "__ge__",
5378};
5379
Tim Peters6d6c1a32001-08-02 04:15:00 +00005380static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005381half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005382{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005383 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005384 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005385
Guido van Rossum60718732001-08-28 17:47:51 +00005386 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005387 if (func == NULL) {
5388 PyErr_Clear();
5389 Py_INCREF(Py_NotImplemented);
5390 return Py_NotImplemented;
5391 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005392 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005393 if (args == NULL)
5394 res = NULL;
5395 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005396 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005397 Py_DECREF(args);
5398 }
5399 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005400 return res;
5401}
5402
Guido van Rossumb8f63662001-08-15 23:57:02 +00005403static PyObject *
5404slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5405{
5406 PyObject *res;
5407
Christian Heimese93237d2007-12-19 02:37:44 +00005408 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005409 res = half_richcompare(self, other, op);
5410 if (res != Py_NotImplemented)
5411 return res;
5412 Py_DECREF(res);
5413 }
Christian Heimese93237d2007-12-19 02:37:44 +00005414 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00005415 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005416 if (res != Py_NotImplemented) {
5417 return res;
5418 }
5419 Py_DECREF(res);
5420 }
5421 Py_INCREF(Py_NotImplemented);
5422 return Py_NotImplemented;
5423}
5424
5425static PyObject *
5426slot_tp_iter(PyObject *self)
5427{
5428 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005429 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005430
Guido van Rossum60718732001-08-28 17:47:51 +00005431 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005432 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00005433 PyObject *args;
5434 args = res = PyTuple_New(0);
5435 if (args != NULL) {
5436 res = PyObject_Call(func, args, NULL);
5437 Py_DECREF(args);
5438 }
5439 Py_DECREF(func);
5440 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005441 }
5442 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005443 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005444 if (func == NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00005445 PyErr_Format(PyExc_TypeError,
5446 "'%.200s' object is not iterable",
Christian Heimese93237d2007-12-19 02:37:44 +00005447 Py_TYPE(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005448 return NULL;
5449 }
5450 Py_DECREF(func);
5451 return PySeqIter_New(self);
5452}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005453
5454static PyObject *
5455slot_tp_iternext(PyObject *self)
5456{
Guido van Rossum2730b132001-08-28 18:22:14 +00005457 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00005458 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005459}
5460
Guido van Rossum1a493502001-08-17 16:47:50 +00005461static PyObject *
5462slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5463{
Christian Heimese93237d2007-12-19 02:37:44 +00005464 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00005465 PyObject *get;
5466 static PyObject *get_str = NULL;
5467
5468 if (get_str == NULL) {
5469 get_str = PyString_InternFromString("__get__");
5470 if (get_str == NULL)
5471 return NULL;
5472 }
5473 get = _PyType_Lookup(tp, get_str);
5474 if (get == NULL) {
5475 /* Avoid further slowdowns */
5476 if (tp->tp_descr_get == slot_tp_descr_get)
5477 tp->tp_descr_get = NULL;
5478 Py_INCREF(self);
5479 return self;
5480 }
Guido van Rossum2c252392001-08-24 10:13:31 +00005481 if (obj == NULL)
5482 obj = Py_None;
5483 if (type == NULL)
5484 type = Py_None;
Georg Brandl684fd0c2006-05-25 19:15:31 +00005485 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005486}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005487
5488static int
5489slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5490{
Guido van Rossum2c252392001-08-24 10:13:31 +00005491 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005492 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005493
5494 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00005495 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005496 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00005497 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005498 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005499 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005500 if (res == NULL)
5501 return -1;
5502 Py_DECREF(res);
5503 return 0;
5504}
5505
5506static int
5507slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5508{
Guido van Rossum60718732001-08-28 17:47:51 +00005509 static PyObject *init_str;
5510 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005511 PyObject *res;
5512
5513 if (meth == NULL)
5514 return -1;
5515 res = PyObject_Call(meth, args, kwds);
5516 Py_DECREF(meth);
5517 if (res == NULL)
5518 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005519 if (res != Py_None) {
Georg Brandlccff7852006-06-18 22:17:29 +00005520 PyErr_Format(PyExc_TypeError,
5521 "__init__() should return None, not '%.200s'",
Christian Heimese93237d2007-12-19 02:37:44 +00005522 Py_TYPE(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005523 Py_DECREF(res);
5524 return -1;
5525 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005526 Py_DECREF(res);
5527 return 0;
5528}
5529
5530static PyObject *
5531slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5532{
Guido van Rossum7bed2132002-08-08 21:57:53 +00005533 static PyObject *new_str;
5534 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005535 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005536 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005537
Guido van Rossum7bed2132002-08-08 21:57:53 +00005538 if (new_str == NULL) {
5539 new_str = PyString_InternFromString("__new__");
5540 if (new_str == NULL)
5541 return NULL;
5542 }
5543 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005544 if (func == NULL)
5545 return NULL;
5546 assert(PyTuple_Check(args));
5547 n = PyTuple_GET_SIZE(args);
5548 newargs = PyTuple_New(n+1);
5549 if (newargs == NULL)
5550 return NULL;
5551 Py_INCREF(type);
5552 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5553 for (i = 0; i < n; i++) {
5554 x = PyTuple_GET_ITEM(args, i);
5555 Py_INCREF(x);
5556 PyTuple_SET_ITEM(newargs, i+1, x);
5557 }
5558 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005559 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005560 Py_DECREF(func);
5561 return x;
5562}
5563
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005564static void
5565slot_tp_del(PyObject *self)
5566{
5567 static PyObject *del_str = NULL;
5568 PyObject *del, *res;
5569 PyObject *error_type, *error_value, *error_traceback;
5570
5571 /* Temporarily resurrect the object. */
5572 assert(self->ob_refcnt == 0);
5573 self->ob_refcnt = 1;
5574
5575 /* Save the current exception, if any. */
5576 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5577
5578 /* Execute __del__ method, if any. */
5579 del = lookup_maybe(self, "__del__", &del_str);
5580 if (del != NULL) {
5581 res = PyEval_CallObject(del, NULL);
5582 if (res == NULL)
5583 PyErr_WriteUnraisable(del);
5584 else
5585 Py_DECREF(res);
5586 Py_DECREF(del);
5587 }
5588
5589 /* Restore the saved exception. */
5590 PyErr_Restore(error_type, error_value, error_traceback);
5591
5592 /* Undo the temporary resurrection; can't use DECREF here, it would
5593 * cause a recursive call.
5594 */
5595 assert(self->ob_refcnt > 0);
5596 if (--self->ob_refcnt == 0)
5597 return; /* this is the normal path out */
5598
5599 /* __del__ resurrected it! Make it look like the original Py_DECREF
5600 * never happened.
5601 */
5602 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005603 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005604 _Py_NewReference(self);
5605 self->ob_refcnt = refcnt;
5606 }
Christian Heimese93237d2007-12-19 02:37:44 +00005607 assert(!PyType_IS_GC(Py_TYPE(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005608 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005609 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5610 * we need to undo that. */
5611 _Py_DEC_REFTOTAL;
5612 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5613 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005614 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5615 * _Py_NewReference bumped tp_allocs: both of those need to be
5616 * undone.
5617 */
5618#ifdef COUNT_ALLOCS
Christian Heimese93237d2007-12-19 02:37:44 +00005619 --Py_TYPE(self)->tp_frees;
5620 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005621#endif
5622}
5623
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005624
5625/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005626 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005627 structure, which incorporates the additional structures used for numbers,
5628 sequences and mappings.
5629 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005630 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005631 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5632 terminated with an all-zero entry. (This table is further initialized and
5633 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005634
Guido van Rossum6d204072001-10-21 00:44:31 +00005635typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005636
5637#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005638#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005639#undef ETSLOT
5640#undef SQSLOT
5641#undef MPSLOT
5642#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005643#undef UNSLOT
5644#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005645#undef BINSLOT
5646#undef RBINSLOT
5647
Guido van Rossum6d204072001-10-21 00:44:31 +00005648#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005649 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5650 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005651#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5652 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005653 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005654#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005655 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005656 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005657#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5658 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5659#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5660 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5661#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5662 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5663#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5664 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5665 "x." NAME "() <==> " DOC)
5666#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5667 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5668 "x." NAME "(y) <==> x" DOC "y")
5669#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5670 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5671 "x." NAME "(y) <==> x" DOC "y")
5672#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5673 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5674 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005675#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5676 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5677 "x." NAME "(y) <==> " DOC)
5678#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5679 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5680 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005681
5682static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005683 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005684 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005685 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5686 The logic in abstract.c always falls back to nb_add/nb_multiply in
5687 this case. Defining both the nb_* and the sq_* slots to call the
5688 user-defined methods has unexpected side-effects, as shown by
5689 test_descr.notimplemented() */
5690 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005691 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00005692 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005693 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005694 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005695 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005696 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5697 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005698 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005699 "x.__getslice__(i, j) <==> x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005700 \n\
5701 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005702 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005703 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005704 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005705 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005706 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005707 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005708 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005709 \n\
5710 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005711 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005712 "x.__delslice__(i, j) <==> del x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005713 \n\
5714 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005715 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5716 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005717 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005718 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005719 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005720 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005721
Martin v. Löwis18e16552006-02-15 17:27:45 +00005722 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005723 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005724 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005725 wrap_binaryfunc,
5726 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005727 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005728 wrap_objobjargproc,
5729 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005730 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005731 wrap_delitem,
5732 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005733
Guido van Rossum6d204072001-10-21 00:44:31 +00005734 BINSLOT("__add__", nb_add, slot_nb_add,
5735 "+"),
5736 RBINSLOT("__radd__", nb_add, slot_nb_add,
5737 "+"),
5738 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5739 "-"),
5740 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5741 "-"),
5742 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5743 "*"),
5744 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5745 "*"),
5746 BINSLOT("__div__", nb_divide, slot_nb_divide,
5747 "/"),
5748 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5749 "/"),
5750 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5751 "%"),
5752 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5753 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005754 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005755 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005756 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005757 "divmod(y, x)"),
5758 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5759 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5760 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5761 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5762 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5763 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5764 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5765 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005766 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005767 "x != 0"),
5768 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5769 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5770 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5771 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5772 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5773 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5774 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5775 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5776 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5777 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5778 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5779 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5780 "x.__coerce__(y) <==> coerce(x, y)"),
5781 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5782 "int(x)"),
5783 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5784 "long(x)"),
5785 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5786 "float(x)"),
5787 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5788 "oct(x)"),
5789 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5790 "hex(x)"),
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005791 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005792 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005793 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5794 wrap_binaryfunc, "+"),
5795 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5796 wrap_binaryfunc, "-"),
5797 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5798 wrap_binaryfunc, "*"),
5799 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5800 wrap_binaryfunc, "/"),
5801 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5802 wrap_binaryfunc, "%"),
5803 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005804 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005805 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5806 wrap_binaryfunc, "<<"),
5807 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5808 wrap_binaryfunc, ">>"),
5809 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5810 wrap_binaryfunc, "&"),
5811 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5812 wrap_binaryfunc, "^"),
5813 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5814 wrap_binaryfunc, "|"),
5815 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5816 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5817 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5818 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5819 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5820 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5821 IBSLOT("__itruediv__", nb_inplace_true_divide,
5822 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005823
Guido van Rossum6d204072001-10-21 00:44:31 +00005824 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5825 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005826 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005827 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5828 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005829 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005830 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5831 "x.__cmp__(y) <==> cmp(x,y)"),
5832 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5833 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005834 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5835 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005836 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005837 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5838 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5839 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5840 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5841 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5842 "x.__setattr__('name', value) <==> x.name = value"),
5843 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5844 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5845 "x.__delattr__('name') <==> del x.name"),
5846 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5847 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5848 "x.__lt__(y) <==> x<y"),
5849 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5850 "x.__le__(y) <==> x<=y"),
5851 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5852 "x.__eq__(y) <==> x==y"),
5853 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5854 "x.__ne__(y) <==> x!=y"),
5855 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5856 "x.__gt__(y) <==> x>y"),
5857 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5858 "x.__ge__(y) <==> x>=y"),
5859 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5860 "x.__iter__() <==> iter(x)"),
5861 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5862 "x.next() -> the next value, or raise StopIteration"),
5863 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5864 "descr.__get__(obj[, type]) -> value"),
5865 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5866 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005867 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5868 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005869 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005870 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005871 "see x.__class__.__doc__ for signature",
5872 PyWrapperFlag_KEYWORDS),
5873 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005874 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005875 {NULL}
5876};
5877
Guido van Rossumc334df52002-04-04 23:44:47 +00005878/* Given a type pointer and an offset gotten from a slotdef entry, return a
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005879 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005880 the offset to the type pointer, since it takes care to indirect through the
5881 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5882 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005883static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005884slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005885{
5886 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005887 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005888
Guido van Rossume5c691a2003-03-07 15:13:17 +00005889 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005890 assert(offset >= 0);
Skip Montanaro429433b2006-04-18 00:35:43 +00005891 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5892 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005893 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005894 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005895 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005896 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005897 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005898 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005899 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005900 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005901 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005902 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005903 }
5904 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005905 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005906 }
5907 if (ptr != NULL)
5908 ptr += offset;
5909 return (void **)ptr;
5910}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005911
Guido van Rossumc334df52002-04-04 23:44:47 +00005912/* Length of array of slotdef pointers used to store slots with the
5913 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5914 the same __name__, for any __name__. Since that's a static property, it is
5915 appropriate to declare fixed-size arrays for this. */
5916#define MAX_EQUIV 10
5917
5918/* Return a slot pointer for a given name, but ONLY if the attribute has
5919 exactly one slot function. The name must be an interned string. */
5920static void **
5921resolve_slotdups(PyTypeObject *type, PyObject *name)
5922{
5923 /* XXX Maybe this could be optimized more -- but is it worth it? */
5924
5925 /* pname and ptrs act as a little cache */
5926 static PyObject *pname;
5927 static slotdef *ptrs[MAX_EQUIV];
5928 slotdef *p, **pp;
5929 void **res, **ptr;
5930
5931 if (pname != name) {
5932 /* Collect all slotdefs that match name into ptrs. */
5933 pname = name;
5934 pp = ptrs;
5935 for (p = slotdefs; p->name_strobj; p++) {
5936 if (p->name_strobj == name)
5937 *pp++ = p;
5938 }
5939 *pp = NULL;
5940 }
5941
5942 /* Look in all matching slots of the type; if exactly one of these has
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005943 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005944 res = NULL;
5945 for (pp = ptrs; *pp; pp++) {
5946 ptr = slotptr(type, (*pp)->offset);
5947 if (ptr == NULL || *ptr == NULL)
5948 continue;
5949 if (res != NULL)
5950 return NULL;
5951 res = ptr;
5952 }
5953 return res;
5954}
5955
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005956/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005957 does some incredibly complex thinking and then sticks something into the
5958 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5959 interests, and then stores a generic wrapper or a specific function into
5960 the slot.) Return a pointer to the next slotdef with a different offset,
5961 because that's convenient for fixup_slot_dispatchers(). */
5962static slotdef *
5963update_one_slot(PyTypeObject *type, slotdef *p)
5964{
5965 PyObject *descr;
5966 PyWrapperDescrObject *d;
5967 void *generic = NULL, *specific = NULL;
5968 int use_generic = 0;
5969 int offset = p->offset;
5970 void **ptr = slotptr(type, offset);
5971
5972 if (ptr == NULL) {
5973 do {
5974 ++p;
5975 } while (p->offset == offset);
5976 return p;
5977 }
5978 do {
5979 descr = _PyType_Lookup(type, p->name_strobj);
5980 if (descr == NULL)
5981 continue;
Christian Heimese93237d2007-12-19 02:37:44 +00005982 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00005983 void **tptr = resolve_slotdups(type, p->name_strobj);
5984 if (tptr == NULL || tptr == ptr)
5985 generic = p->function;
5986 d = (PyWrapperDescrObject *)descr;
5987 if (d->d_base->wrapper == p->wrapper &&
5988 PyType_IsSubtype(type, d->d_type))
5989 {
5990 if (specific == NULL ||
5991 specific == d->d_wrapped)
5992 specific = d->d_wrapped;
5993 else
5994 use_generic = 1;
5995 }
5996 }
Christian Heimese93237d2007-12-19 02:37:44 +00005997 else if (Py_TYPE(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00005998 PyCFunction_GET_FUNCTION(descr) ==
5999 (PyCFunction)tp_new_wrapper &&
6000 strcmp(p->name, "__new__") == 0)
6001 {
6002 /* The __new__ wrapper is not a wrapper descriptor,
6003 so must be special-cased differently.
6004 If we don't do this, creating an instance will
6005 always use slot_tp_new which will look up
6006 __new__ in the MRO which will call tp_new_wrapper
6007 which will look through the base classes looking
6008 for a static base and call its tp_new (usually
6009 PyType_GenericNew), after performing various
6010 sanity checks and constructing a new argument
6011 list. Cut all that nonsense short -- this speeds
6012 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00006013 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00006014 /* XXX I'm not 100% sure that there isn't a hole
6015 in this reasoning that requires additional
6016 sanity checks. I'll buy the first person to
6017 point out a bug in this reasoning a beer. */
6018 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006019 else {
6020 use_generic = 1;
6021 generic = p->function;
6022 }
6023 } while ((++p)->offset == offset);
6024 if (specific && !use_generic)
6025 *ptr = specific;
6026 else
6027 *ptr = generic;
6028 return p;
6029}
6030
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006031/* In the type, update the slots whose slotdefs are gathered in the pp array.
6032 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006033static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006034update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006035{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006036 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006037
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006038 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00006039 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006040 return 0;
6041}
6042
Guido van Rossumc334df52002-04-04 23:44:47 +00006043/* Comparison function for qsort() to compare slotdefs by their offset, and
6044 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006045static int
6046slotdef_cmp(const void *aa, const void *bb)
6047{
6048 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
6049 int c = a->offset - b->offset;
6050 if (c != 0)
6051 return c;
6052 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00006053 /* Cannot use a-b, as this gives off_t,
6054 which may lose precision when converted to int. */
6055 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006056}
6057
Guido van Rossumc334df52002-04-04 23:44:47 +00006058/* Initialize the slotdefs table by adding interned string objects for the
6059 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006060static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006061init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006062{
6063 slotdef *p;
6064 static int initialized = 0;
6065
6066 if (initialized)
6067 return;
6068 for (p = slotdefs; p->name; p++) {
6069 p->name_strobj = PyString_InternFromString(p->name);
6070 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00006071 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006072 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006073 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
6074 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006075 initialized = 1;
6076}
6077
Guido van Rossumc334df52002-04-04 23:44:47 +00006078/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006079static int
6080update_slot(PyTypeObject *type, PyObject *name)
6081{
Guido van Rossumc334df52002-04-04 23:44:47 +00006082 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006083 slotdef *p;
6084 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006085 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006086
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00006087 /* Clear the VALID_VERSION flag of 'type' and all its
6088 subclasses. This could possibly be unified with the
6089 update_subclasses() recursion below, but carefully:
6090 they each have their own conditions on which to stop
6091 recursing into subclasses. */
6092 type_modified(type);
6093
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006094 init_slotdefs();
6095 pp = ptrs;
6096 for (p = slotdefs; p->name; p++) {
6097 /* XXX assume name is interned! */
6098 if (p->name_strobj == name)
6099 *pp++ = p;
6100 }
6101 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006102 for (pp = ptrs; *pp; pp++) {
6103 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006104 offset = p->offset;
6105 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006106 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006107 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006108 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006109 if (ptrs[0] == NULL)
6110 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006111 return update_subclasses(type, name,
6112 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006113}
6114
Guido van Rossumc334df52002-04-04 23:44:47 +00006115/* Store the proper functions in the slot dispatches at class (type)
6116 definition time, based upon which operations the class overrides in its
6117 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006118static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006119fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006120{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006121 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006122
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006123 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00006124 for (p = slotdefs; p->name; )
6125 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006126}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006127
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006128static void
6129update_all_slots(PyTypeObject* type)
6130{
6131 slotdef *p;
6132
6133 init_slotdefs();
6134 for (p = slotdefs; p->name; p++) {
6135 /* update_slot returns int but can't actually fail */
6136 update_slot(type, p->name_strobj);
6137 }
6138}
6139
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006140/* recurse_down_subclasses() and update_subclasses() are mutually
6141 recursive functions to call a callback for all subclasses,
6142 but refraining from recursing into subclasses that define 'name'. */
6143
6144static int
6145update_subclasses(PyTypeObject *type, PyObject *name,
6146 update_callback callback, void *data)
6147{
6148 if (callback(type, data) < 0)
6149 return -1;
6150 return recurse_down_subclasses(type, name, callback, data);
6151}
6152
6153static int
6154recurse_down_subclasses(PyTypeObject *type, PyObject *name,
6155 update_callback callback, void *data)
6156{
6157 PyTypeObject *subclass;
6158 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006159 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006160
6161 subclasses = type->tp_subclasses;
6162 if (subclasses == NULL)
6163 return 0;
6164 assert(PyList_Check(subclasses));
6165 n = PyList_GET_SIZE(subclasses);
6166 for (i = 0; i < n; i++) {
6167 ref = PyList_GET_ITEM(subclasses, i);
6168 assert(PyWeakref_CheckRef(ref));
6169 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6170 assert(subclass != NULL);
6171 if ((PyObject *)subclass == Py_None)
6172 continue;
6173 assert(PyType_Check(subclass));
6174 /* Avoid recursing down into unaffected classes */
6175 dict = subclass->tp_dict;
6176 if (dict != NULL && PyDict_Check(dict) &&
6177 PyDict_GetItem(dict, name) != NULL)
6178 continue;
6179 if (update_subclasses(subclass, name, callback, data) < 0)
6180 return -1;
6181 }
6182 return 0;
6183}
6184
Guido van Rossum6d204072001-10-21 00:44:31 +00006185/* This function is called by PyType_Ready() to populate the type's
6186 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006187 function slot (like tp_repr) that's defined in the type, one or more
6188 corresponding descriptors are added in the type's tp_dict dictionary
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006189 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006190 cause more than one descriptor to be added (for example, the nb_add
6191 slot adds both __add__ and __radd__ descriptors) and some function
6192 slots compete for the same descriptor (for example both sq_item and
6193 mp_subscript generate a __getitem__ descriptor).
6194
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006195 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006196 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006197 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006198 between competing slots: the members of PyHeapTypeObject are listed
6199 from most general to least general, so the most general slot is
6200 preferred. In particular, because as_mapping comes before as_sequence,
6201 for a type that defines both mp_subscript and sq_item, mp_subscript
6202 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006203
6204 This only adds new descriptors and doesn't overwrite entries in
6205 tp_dict that were previously defined. The descriptors contain a
6206 reference to the C function they must call, so that it's safe if they
6207 are copied into a subtype's __dict__ and the subtype has a different
6208 C function in its slot -- calling the method defined by the
6209 descriptor will call the C function that was used to create it,
6210 rather than the C function present in the slot when it is called.
6211 (This is important because a subtype may have a C function in the
6212 slot that calls the method from the dictionary, and we want to avoid
6213 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006214
6215static int
6216add_operators(PyTypeObject *type)
6217{
6218 PyObject *dict = type->tp_dict;
6219 slotdef *p;
6220 PyObject *descr;
6221 void **ptr;
6222
6223 init_slotdefs();
6224 for (p = slotdefs; p->name; p++) {
6225 if (p->wrapper == NULL)
6226 continue;
6227 ptr = slotptr(type, p->offset);
6228 if (!ptr || !*ptr)
6229 continue;
6230 if (PyDict_GetItem(dict, p->name_strobj))
6231 continue;
6232 descr = PyDescr_NewWrapper(type, p, *ptr);
6233 if (descr == NULL)
6234 return -1;
6235 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6236 return -1;
6237 Py_DECREF(descr);
6238 }
6239 if (type->tp_new != NULL) {
6240 if (add_tp_new_wrapper(type) < 0)
6241 return -1;
6242 }
6243 return 0;
6244}
6245
Guido van Rossum705f0f52001-08-24 16:47:00 +00006246
6247/* Cooperative 'super' */
6248
6249typedef struct {
6250 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00006251 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006252 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006253 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006254} superobject;
6255
Guido van Rossum6f799372001-09-20 20:46:19 +00006256static PyMemberDef super_members[] = {
6257 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6258 "the class invoking super()"},
6259 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6260 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006261 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00006262 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006263 {0}
6264};
6265
Guido van Rossum705f0f52001-08-24 16:47:00 +00006266static void
6267super_dealloc(PyObject *self)
6268{
6269 superobject *su = (superobject *)self;
6270
Guido van Rossum048eb752001-10-02 21:24:57 +00006271 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006272 Py_XDECREF(su->obj);
6273 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006274 Py_XDECREF(su->obj_type);
Christian Heimese93237d2007-12-19 02:37:44 +00006275 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006276}
6277
6278static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006279super_repr(PyObject *self)
6280{
6281 superobject *su = (superobject *)self;
6282
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006283 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006284 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00006285 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006286 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006287 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006288 else
6289 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00006290 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006291 su->type ? su->type->tp_name : "NULL");
6292}
6293
6294static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006295super_getattro(PyObject *self, PyObject *name)
6296{
6297 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006298 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006299
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006300 if (!skip) {
6301 /* We want __class__ to return the class of the super object
6302 (i.e. super, or a subclass), not the class of su->obj. */
6303 skip = (PyString_Check(name) &&
6304 PyString_GET_SIZE(name) == 9 &&
6305 strcmp(PyString_AS_STRING(name), "__class__") == 0);
6306 }
6307
6308 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00006309 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006310 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006311 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006312 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006313
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006314 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006315 mro = starttype->tp_mro;
6316
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006317 if (mro == NULL)
6318 n = 0;
6319 else {
6320 assert(PyTuple_Check(mro));
6321 n = PyTuple_GET_SIZE(mro);
6322 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006323 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00006324 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00006325 break;
6326 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006327 i++;
6328 res = NULL;
6329 for (; i < n; i++) {
6330 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00006331 if (PyType_Check(tmp))
6332 dict = ((PyTypeObject *)tmp)->tp_dict;
6333 else if (PyClass_Check(tmp))
6334 dict = ((PyClassObject *)tmp)->cl_dict;
6335 else
6336 continue;
6337 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00006338 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00006339 Py_INCREF(res);
Christian Heimese93237d2007-12-19 02:37:44 +00006340 f = Py_TYPE(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006341 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006342 tmp = f(res,
6343 /* Only pass 'obj' param if
6344 this is instance-mode super
6345 (See SF ID #743627)
6346 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00006347 (su->obj == (PyObject *)
6348 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006349 ? (PyObject *)NULL
6350 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00006351 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006352 Py_DECREF(res);
6353 res = tmp;
6354 }
6355 return res;
6356 }
6357 }
6358 }
6359 return PyObject_GenericGetAttr(self, name);
6360}
6361
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006362static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006363supercheck(PyTypeObject *type, PyObject *obj)
6364{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006365 /* Check that a super() call makes sense. Return a type object.
6366
6367 obj can be a new-style class, or an instance of one:
6368
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006369 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006370 used for class methods; the return value is obj.
6371
6372 - If it is an instance, it must be an instance of 'type'. This is
6373 the normal case; the return value is obj.__class__.
6374
6375 But... when obj is an instance, we want to allow for the case where
Christian Heimese93237d2007-12-19 02:37:44 +00006376 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006377 This will allow using super() with a proxy for obj.
6378 */
6379
Guido van Rossum8e80a722003-02-18 19:22:22 +00006380 /* Check for first bullet above (special case) */
6381 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6382 Py_INCREF(obj);
6383 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006384 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006385
6386 /* Normal case */
Christian Heimese93237d2007-12-19 02:37:44 +00006387 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6388 Py_INCREF(Py_TYPE(obj));
6389 return Py_TYPE(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006390 }
6391 else {
6392 /* Try the slow way */
6393 static PyObject *class_str = NULL;
6394 PyObject *class_attr;
6395
6396 if (class_str == NULL) {
6397 class_str = PyString_FromString("__class__");
6398 if (class_str == NULL)
6399 return NULL;
6400 }
6401
6402 class_attr = PyObject_GetAttr(obj, class_str);
6403
6404 if (class_attr != NULL &&
6405 PyType_Check(class_attr) &&
Christian Heimese93237d2007-12-19 02:37:44 +00006406 (PyTypeObject *)class_attr != Py_TYPE(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006407 {
6408 int ok = PyType_IsSubtype(
6409 (PyTypeObject *)class_attr, type);
6410 if (ok)
6411 return (PyTypeObject *)class_attr;
6412 }
6413
6414 if (class_attr == NULL)
6415 PyErr_Clear();
6416 else
6417 Py_DECREF(class_attr);
6418 }
6419
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006420 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006421 "super(type, obj): "
6422 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006423 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006424}
6425
Guido van Rossum705f0f52001-08-24 16:47:00 +00006426static PyObject *
6427super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6428{
6429 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00006430 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006431
6432 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6433 /* Not binding to an object, or already bound */
6434 Py_INCREF(self);
6435 return self;
6436 }
Christian Heimese93237d2007-12-19 02:37:44 +00006437 if (Py_TYPE(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00006438 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006439 call its type */
Christian Heimese93237d2007-12-19 02:37:44 +00006440 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006441 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00006442 else {
6443 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006444 PyTypeObject *obj_type = supercheck(su->type, obj);
6445 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006446 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00006447 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006448 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00006449 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006450 return NULL;
6451 Py_INCREF(su->type);
6452 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00006453 newobj->type = su->type;
6454 newobj->obj = obj;
6455 newobj->obj_type = obj_type;
6456 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006457 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006458}
6459
6460static int
6461super_init(PyObject *self, PyObject *args, PyObject *kwds)
6462{
6463 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00006464 PyTypeObject *type;
6465 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006466 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006467
Georg Brandl5d59c092006-09-30 08:43:30 +00006468 if (!_PyArg_NoKeywords("super", kwds))
6469 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006470 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
6471 return -1;
6472 if (obj == Py_None)
6473 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006474 if (obj != NULL) {
6475 obj_type = supercheck(type, obj);
6476 if (obj_type == NULL)
6477 return -1;
6478 Py_INCREF(obj);
6479 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006480 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006481 su->type = type;
6482 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006483 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006484 return 0;
6485}
6486
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006487PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00006488"super(type) -> unbound super object\n"
6489"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006490"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006491"Typical use to call a cooperative superclass method:\n"
6492"class C(B):\n"
6493" def meth(self, arg):\n"
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006494" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006495
Guido van Rossum048eb752001-10-02 21:24:57 +00006496static int
6497super_traverse(PyObject *self, visitproc visit, void *arg)
6498{
6499 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006500
Thomas Woutersc6e55062006-04-15 21:47:09 +00006501 Py_VISIT(su->obj);
6502 Py_VISIT(su->type);
6503 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006504
6505 return 0;
6506}
6507
Guido van Rossum705f0f52001-08-24 16:47:00 +00006508PyTypeObject PySuper_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00006509 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00006510 "super", /* tp_name */
6511 sizeof(superobject), /* tp_basicsize */
6512 0, /* tp_itemsize */
6513 /* methods */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006514 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006515 0, /* tp_print */
6516 0, /* tp_getattr */
6517 0, /* tp_setattr */
6518 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006519 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006520 0, /* tp_as_number */
6521 0, /* tp_as_sequence */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006522 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006523 0, /* tp_hash */
6524 0, /* tp_call */
6525 0, /* tp_str */
6526 super_getattro, /* tp_getattro */
6527 0, /* tp_setattro */
6528 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006529 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6530 Py_TPFLAGS_BASETYPE, /* tp_flags */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006531 super_doc, /* tp_doc */
6532 super_traverse, /* tp_traverse */
6533 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006534 0, /* tp_richcompare */
6535 0, /* tp_weaklistoffset */
6536 0, /* tp_iter */
6537 0, /* tp_iternext */
6538 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006539 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006540 0, /* tp_getset */
6541 0, /* tp_base */
6542 0, /* tp_dict */
6543 super_descr_get, /* tp_descr_get */
6544 0, /* tp_descr_set */
6545 0, /* tp_dictoffset */
6546 super_init, /* tp_init */
6547 PyType_GenericAlloc, /* tp_alloc */
6548 PyType_GenericNew, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006549 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006550};