blob: 07ab61f87a823595cb702d2e18c691ce2513b8fc [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00008
9/* Support type attribute cache */
10
11/* The cache can keep references to the names alive for longer than
12 they normally would. This is why the maximum size is limited to
13 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
14 strings are used as attribute names. */
15#define MCACHE_MAX_ATTR_SIZE 100
16#define MCACHE_SIZE_EXP 10
17#define MCACHE_HASH(version, name_hash) \
18 (((unsigned int)(version) * (unsigned int)(name_hash)) \
19 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
20#define MCACHE_HASH_METHOD(type, name) \
21 MCACHE_HASH((type)->tp_version_tag, \
22 ((PyStringObject *)(name))->ob_shash)
23#define MCACHE_CACHEABLE_NAME(name) \
24 PyString_CheckExact(name) && \
25 PyString_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
26
27struct method_cache_entry {
28 unsigned int version;
29 PyObject *name; /* reference to exactly a str or None */
30 PyObject *value; /* borrowed */
31};
32
33static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
34static unsigned int next_version_tag = 0;
Christian Heimes908caac2008-01-27 23:34:59 +000035static void type_modified(PyTypeObject *);
36
37unsigned int
38PyType_ClearCache(void)
39{
40 Py_ssize_t i;
41 unsigned int cur_version_tag = next_version_tag - 1;
42
43 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
44 method_cache[i].version = 0;
45 Py_CLEAR(method_cache[i].name);
46 method_cache[i].value = NULL;
47 }
48 next_version_tag = 0;
49 /* mark all version tags as invalid */
50 type_modified(&PyBaseObject_Type);
51 return cur_version_tag;
52}
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000053
54static void
55type_modified(PyTypeObject *type)
56{
57 /* Invalidate any cached data for the specified type and all
58 subclasses. This function is called after the base
59 classes, mro, or attributes of the type are altered.
60
61 Invariants:
62
63 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
64 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
65 objects coming from non-recompiled extension modules)
66
67 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
68 it must first be set on all super types.
69
70 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
71 type (so it must first clear it on all subclasses). The
72 tp_version_tag value is meaningless unless this flag is set.
73 We don't assign new version tags eagerly, but only as
74 needed.
75 */
76 PyObject *raw, *ref;
77 Py_ssize_t i, n;
78
Neal Norwitze7bb9182008-01-27 17:10:14 +000079 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000080 return;
81
82 raw = type->tp_subclasses;
83 if (raw != NULL) {
84 n = PyList_GET_SIZE(raw);
85 for (i = 0; i < n; i++) {
86 ref = PyList_GET_ITEM(raw, i);
87 ref = PyWeakref_GET_OBJECT(ref);
88 if (ref != Py_None) {
89 type_modified((PyTypeObject *)ref);
90 }
91 }
92 }
93 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
94}
95
96static void
97type_mro_modified(PyTypeObject *type, PyObject *bases) {
98 /*
99 Check that all base classes or elements of the mro of type are
100 able to be cached. This function is called after the base
101 classes or mro of the type are altered.
102
103 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
104 inherits from an old-style class, either directly or if it
105 appears in the MRO of a new-style class. No support either for
106 custom MROs that include types that are not officially super
107 types.
108
109 Called from mro_internal, which will subsequently be called on
110 each subclass when their mro is recursively updated.
111 */
112 Py_ssize_t i, n;
113 int clear = 0;
114
Neal Norwitze7bb9182008-01-27 17:10:14 +0000115 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000116 return;
117
118 n = PyTuple_GET_SIZE(bases);
119 for (i = 0; i < n; i++) {
120 PyObject *b = PyTuple_GET_ITEM(bases, i);
121 PyTypeObject *cls;
122
123 if (!PyType_Check(b) ) {
124 clear = 1;
125 break;
126 }
127
128 cls = (PyTypeObject *)b;
129
130 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
131 !PyType_IsSubtype(type, cls)) {
132 clear = 1;
133 break;
134 }
135 }
136
137 if (clear)
138 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
139 Py_TPFLAGS_VALID_VERSION_TAG);
140}
141
142static int
143assign_version_tag(PyTypeObject *type)
144{
145 /* Ensure that the tp_version_tag is valid and set
146 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
147 must first be done on all super classes. Return 0 if this
148 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
149 */
150 Py_ssize_t i, n;
151 PyObject *bases;
152
153 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
154 return 1;
155 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
156 return 0;
157 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
158 return 0;
159
160 type->tp_version_tag = next_version_tag++;
161 /* for stress-testing: next_version_tag &= 0xFF; */
162
163 if (type->tp_version_tag == 0) {
164 /* wrap-around or just starting Python - clear the whole
165 cache by filling names with references to Py_None.
166 Values are also set to NULL for added protection, as they
167 are borrowed reference */
168 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
169 method_cache[i].value = NULL;
170 Py_XDECREF(method_cache[i].name);
171 method_cache[i].name = Py_None;
172 Py_INCREF(Py_None);
173 }
174 /* mark all version tags as invalid */
175 type_modified(&PyBaseObject_Type);
176 return 1;
177 }
178 bases = type->tp_bases;
179 n = PyTuple_GET_SIZE(bases);
180 for (i = 0; i < n; i++) {
181 PyObject *b = PyTuple_GET_ITEM(bases, i);
182 assert(PyType_Check(b));
183 if (!assign_version_tag((PyTypeObject *)b))
184 return 0;
185 }
186 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
187 return 1;
188}
189
190
Guido van Rossum6f799372001-09-20 20:46:19 +0000191static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000192 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
193 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
194 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +0000195 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000196 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
197 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
198 {"__dictoffset__", T_LONG,
199 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000200 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
201 {0}
202};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000204static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000205type_name(PyTypeObject *type, void *context)
206{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000207 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000208
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000209 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +0000210 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000211
Georg Brandlc255c7b2006-02-20 22:27:28 +0000212 Py_INCREF(et->ht_name);
213 return et->ht_name;
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000214 }
215 else {
216 s = strrchr(type->tp_name, '.');
217 if (s == NULL)
218 s = type->tp_name;
219 else
220 s++;
221 return PyString_FromString(s);
222 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000223}
224
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000225static int
226type_set_name(PyTypeObject *type, PyObject *value, void *context)
227{
Guido van Rossume5c691a2003-03-07 15:13:17 +0000228 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000229
230 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
231 PyErr_Format(PyExc_TypeError,
232 "can't set %s.__name__", type->tp_name);
233 return -1;
234 }
235 if (!value) {
236 PyErr_Format(PyExc_TypeError,
237 "can't delete %s.__name__", type->tp_name);
238 return -1;
239 }
240 if (!PyString_Check(value)) {
241 PyErr_Format(PyExc_TypeError,
242 "can only assign string to %s.__name__, not '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +0000243 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000244 return -1;
245 }
Tim Petersea7f75d2002-12-07 21:39:16 +0000246 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000247 != (size_t)PyString_GET_SIZE(value)) {
248 PyErr_Format(PyExc_ValueError,
249 "__name__ must not contain null bytes");
250 return -1;
251 }
252
Guido van Rossume5c691a2003-03-07 15:13:17 +0000253 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000254
255 Py_INCREF(value);
256
Georg Brandlc255c7b2006-02-20 22:27:28 +0000257 Py_DECREF(et->ht_name);
258 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000259
260 type->tp_name = PyString_AS_STRING(value);
261
262 return 0;
263}
264
Guido van Rossumc3542212001-08-16 09:18:56 +0000265static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000266type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000267{
Guido van Rossumc3542212001-08-16 09:18:56 +0000268 PyObject *mod;
269 char *s;
270
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000271 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
272 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +0000273 if (!mod) {
274 PyErr_Format(PyExc_AttributeError, "__module__");
275 return 0;
276 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000277 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +0000278 return mod;
279 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000280 else {
281 s = strrchr(type->tp_name, '.');
282 if (s != NULL)
283 return PyString_FromStringAndSize(
Armin Rigo7ccbca92006-10-04 12:17:45 +0000284 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000285 return PyString_FromString("__builtin__");
286 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000287}
288
Guido van Rossum3926a632001-09-25 16:25:58 +0000289static int
290type_set_module(PyTypeObject *type, PyObject *value, void *context)
291{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000292 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000293 PyErr_Format(PyExc_TypeError,
294 "can't set %s.__module__", type->tp_name);
295 return -1;
296 }
297 if (!value) {
298 PyErr_Format(PyExc_TypeError,
299 "can't delete %s.__module__", type->tp_name);
300 return -1;
301 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000302
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000303 type_modified(type);
304
Guido van Rossum3926a632001-09-25 16:25:58 +0000305 return PyDict_SetItemString(type->tp_dict, "__module__", value);
306}
307
Tim Peters6d6c1a32001-08-02 04:15:00 +0000308static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000309type_get_bases(PyTypeObject *type, void *context)
310{
311 Py_INCREF(type->tp_bases);
312 return type->tp_bases;
313}
314
315static PyTypeObject *best_base(PyObject *);
316static int mro_internal(PyTypeObject *);
317static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
318static int add_subclass(PyTypeObject*, PyTypeObject*);
319static void remove_subclass(PyTypeObject *, PyTypeObject *);
320static void update_all_slots(PyTypeObject *);
321
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000322typedef int (*update_callback)(PyTypeObject *, void *);
323static int update_subclasses(PyTypeObject *type, PyObject *name,
324 update_callback callback, void *data);
325static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
326 update_callback callback, void *data);
327
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000328static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000329mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000330{
331 PyTypeObject *subclass;
332 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000333 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000334
335 subclasses = type->tp_subclasses;
336 if (subclasses == NULL)
337 return 0;
338 assert(PyList_Check(subclasses));
339 n = PyList_GET_SIZE(subclasses);
340 for (i = 0; i < n; i++) {
341 ref = PyList_GET_ITEM(subclasses, i);
342 assert(PyWeakref_CheckRef(ref));
343 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
344 assert(subclass != NULL);
345 if ((PyObject *)subclass == Py_None)
346 continue;
347 assert(PyType_Check(subclass));
348 old_mro = subclass->tp_mro;
349 if (mro_internal(subclass) < 0) {
350 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000351 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000352 }
353 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000354 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000355 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000356 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000357 if (!tuple)
358 return -1;
359 if (PyList_Append(temp, tuple) < 0)
360 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000361 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000362 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000363 if (mro_subclasses(subclass, temp) < 0)
364 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000365 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000366 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000367}
368
369static int
370type_set_bases(PyTypeObject *type, PyObject *value, void *context)
371{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000372 Py_ssize_t i;
373 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000374 PyObject *ob, *temp;
Armin Rigoc0ba52d2007-04-19 14:44:48 +0000375 PyTypeObject *new_base, *old_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000376 PyObject *old_bases, *old_mro;
377
378 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
379 PyErr_Format(PyExc_TypeError,
380 "can't set %s.__bases__", type->tp_name);
381 return -1;
382 }
383 if (!value) {
384 PyErr_Format(PyExc_TypeError,
385 "can't delete %s.__bases__", type->tp_name);
386 return -1;
387 }
388 if (!PyTuple_Check(value)) {
389 PyErr_Format(PyExc_TypeError,
390 "can only assign tuple to %s.__bases__, not %s",
Christian Heimese93237d2007-12-19 02:37:44 +0000391 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000392 return -1;
393 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000394 if (PyTuple_GET_SIZE(value) == 0) {
395 PyErr_Format(PyExc_TypeError,
396 "can only assign non-empty tuple to %s.__bases__, not ()",
397 type->tp_name);
398 return -1;
399 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000400 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
401 ob = PyTuple_GET_ITEM(value, i);
402 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
403 PyErr_Format(
404 PyExc_TypeError,
405 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +0000406 type->tp_name, Py_TYPE(ob)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000407 return -1;
408 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000409 if (PyType_Check(ob)) {
410 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
411 PyErr_SetString(PyExc_TypeError,
412 "a __bases__ item causes an inheritance cycle");
413 return -1;
414 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000415 }
416 }
417
418 new_base = best_base(value);
419
420 if (!new_base) {
421 return -1;
422 }
423
424 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
425 return -1;
426
427 Py_INCREF(new_base);
428 Py_INCREF(value);
429
430 old_bases = type->tp_bases;
431 old_base = type->tp_base;
432 old_mro = type->tp_mro;
433
434 type->tp_bases = value;
435 type->tp_base = new_base;
436
437 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000438 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000439 }
440
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000441 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000442 if (!temp)
443 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000444
445 r = mro_subclasses(type, temp);
446
447 if (r < 0) {
448 for (i = 0; i < PyList_Size(temp); i++) {
449 PyTypeObject* cls;
450 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000451 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
452 "", 2, 2, &cls, &mro);
Armin Rigo796fc992007-04-19 14:56:48 +0000453 Py_INCREF(mro);
454 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000455 cls->tp_mro = mro;
Armin Rigo796fc992007-04-19 14:56:48 +0000456 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000457 }
458 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000459 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000460 }
461
462 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000463
464 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000465 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000466 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000467 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000468
469 /* for now, sod that: just remove from all old_bases,
470 add to all new_bases */
471
472 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
473 ob = PyTuple_GET_ITEM(old_bases, i);
474 if (PyType_Check(ob)) {
475 remove_subclass(
476 (PyTypeObject*)ob, type);
477 }
478 }
479
480 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
481 ob = PyTuple_GET_ITEM(value, i);
482 if (PyType_Check(ob)) {
483 if (add_subclass((PyTypeObject*)ob, type) < 0)
484 r = -1;
485 }
486 }
487
488 update_all_slots(type);
489
490 Py_DECREF(old_bases);
491 Py_DECREF(old_base);
492 Py_DECREF(old_mro);
493
494 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000495
496 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000497 Py_DECREF(type->tp_bases);
498 Py_DECREF(type->tp_base);
499 if (type->tp_mro != old_mro) {
500 Py_DECREF(type->tp_mro);
501 }
502
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000503 type->tp_bases = old_bases;
504 type->tp_base = old_base;
505 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000506
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000507 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000508}
509
510static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000511type_dict(PyTypeObject *type, void *context)
512{
513 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000514 Py_INCREF(Py_None);
515 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000516 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000517 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000518}
519
Tim Peters24008312002-03-17 18:56:20 +0000520static PyObject *
521type_get_doc(PyTypeObject *type, void *context)
522{
523 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000524 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000525 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000526 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000527 if (result == NULL) {
528 result = Py_None;
529 Py_INCREF(result);
530 }
Christian Heimese93237d2007-12-19 02:37:44 +0000531 else if (Py_TYPE(result)->tp_descr_get) {
532 result = Py_TYPE(result)->tp_descr_get(result, NULL,
Tim Peters2b858972002-04-18 04:12:28 +0000533 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000534 }
535 else {
536 Py_INCREF(result);
537 }
Tim Peters24008312002-03-17 18:56:20 +0000538 return result;
539}
540
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000541static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000542 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
543 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000544 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000545 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000546 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000547 {0}
548};
549
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000550static int
551type_compare(PyObject *v, PyObject *w)
552{
553 /* This is called with type objects only. So we
554 can just compare the addresses. */
555 Py_uintptr_t vv = (Py_uintptr_t)v;
556 Py_uintptr_t ww = (Py_uintptr_t)w;
557 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
558}
559
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000560static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000561type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000563 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000564 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000565
566 mod = type_module(type, NULL);
567 if (mod == NULL)
568 PyErr_Clear();
569 else if (!PyString_Check(mod)) {
570 Py_DECREF(mod);
571 mod = NULL;
572 }
573 name = type_name(type, NULL);
574 if (name == NULL)
575 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000576
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000577 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
578 kind = "class";
579 else
580 kind = "type";
581
Barry Warsaw7ce36942001-08-24 18:34:26 +0000582 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000583 rtn = PyString_FromFormat("<%s '%s.%s'>",
584 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000585 PyString_AS_STRING(mod),
586 PyString_AS_STRING(name));
587 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000588 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000589 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000590
Guido van Rossumc3542212001-08-16 09:18:56 +0000591 Py_XDECREF(mod);
592 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000593 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000594}
595
Tim Peters6d6c1a32001-08-02 04:15:00 +0000596static PyObject *
597type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
598{
599 PyObject *obj;
600
601 if (type->tp_new == NULL) {
602 PyErr_Format(PyExc_TypeError,
603 "cannot create '%.100s' instances",
604 type->tp_name);
605 return NULL;
606 }
607
Tim Peters3f996e72001-09-13 19:18:27 +0000608 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000609 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000610 /* Ugly exception: when the call was type(something),
611 don't call tp_init on the result. */
612 if (type == &PyType_Type &&
613 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
614 (kwds == NULL ||
615 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
616 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000617 /* If the returned object is not an instance of type,
618 it won't be initialized. */
619 if (!PyType_IsSubtype(obj->ob_type, type))
620 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000621 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000622 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
623 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000624 type->tp_init(obj, args, kwds) < 0) {
625 Py_DECREF(obj);
626 obj = NULL;
627 }
628 }
629 return obj;
630}
631
632PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000633PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000634{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000635 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000636 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
637 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000638
639 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000640 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000641 else
Anthony Baxtera6286212006-04-11 07:42:36 +0000642 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000643
Neil Schemenauerc806c882001-08-29 23:54:54 +0000644 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000645 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000646
Neil Schemenauerc806c882001-08-29 23:54:54 +0000647 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000648
Tim Peters6d6c1a32001-08-02 04:15:00 +0000649 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
650 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000651
Tim Peters6d6c1a32001-08-02 04:15:00 +0000652 if (type->tp_itemsize == 0)
653 PyObject_INIT(obj, type);
654 else
655 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000656
Tim Peters6d6c1a32001-08-02 04:15:00 +0000657 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000658 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000659 return obj;
660}
661
662PyObject *
663PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
664{
665 return type->tp_alloc(type, 0);
666}
667
Guido van Rossum9475a232001-10-05 20:51:39 +0000668/* Helpers for subtyping */
669
670static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000671traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
672{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000673 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000674 PyMemberDef *mp;
675
Christian Heimese93237d2007-12-19 02:37:44 +0000676 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000677 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000678 for (i = 0; i < n; i++, mp++) {
679 if (mp->type == T_OBJECT_EX) {
680 char *addr = (char *)self + mp->offset;
681 PyObject *obj = *(PyObject **)addr;
682 if (obj != NULL) {
683 int err = visit(obj, arg);
684 if (err)
685 return err;
686 }
687 }
688 }
689 return 0;
690}
691
692static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000693subtype_traverse(PyObject *self, visitproc visit, void *arg)
694{
695 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000696 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000697
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000698 /* Find the nearest base with a different tp_traverse,
699 and traverse slots while we're at it */
Christian Heimese93237d2007-12-19 02:37:44 +0000700 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000701 base = type;
702 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
Christian Heimese93237d2007-12-19 02:37:44 +0000703 if (Py_SIZE(base)) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000704 int err = traverse_slots(base, self, visit, arg);
705 if (err)
706 return err;
707 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000708 base = base->tp_base;
709 assert(base);
710 }
711
712 if (type->tp_dictoffset != base->tp_dictoffset) {
713 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Woutersc6e55062006-04-15 21:47:09 +0000714 if (dictptr && *dictptr)
715 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000716 }
717
Thomas Woutersc6e55062006-04-15 21:47:09 +0000718 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000719 /* For a heaptype, the instances count as references
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000720 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000721 can find cycles involving this link. */
Thomas Woutersc6e55062006-04-15 21:47:09 +0000722 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000723
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000724 if (basetraverse)
725 return basetraverse(self, visit, arg);
726 return 0;
727}
728
729static void
730clear_slots(PyTypeObject *type, PyObject *self)
731{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000732 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000733 PyMemberDef *mp;
734
Christian Heimese93237d2007-12-19 02:37:44 +0000735 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000736 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000737 for (i = 0; i < n; i++, mp++) {
738 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
739 char *addr = (char *)self + mp->offset;
740 PyObject *obj = *(PyObject **)addr;
741 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000742 *(PyObject **)addr = NULL;
Thomas Woutersedf17d82006-04-15 17:28:34 +0000743 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000744 }
745 }
746 }
747}
748
749static int
750subtype_clear(PyObject *self)
751{
752 PyTypeObject *type, *base;
753 inquiry baseclear;
754
755 /* Find the nearest base with a different tp_clear
756 and clear slots while we're at it */
Christian Heimese93237d2007-12-19 02:37:44 +0000757 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000758 base = type;
759 while ((baseclear = base->tp_clear) == subtype_clear) {
Christian Heimese93237d2007-12-19 02:37:44 +0000760 if (Py_SIZE(base))
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000761 clear_slots(base, self);
762 base = base->tp_base;
763 assert(base);
764 }
765
Guido van Rossuma3862092002-06-10 15:24:42 +0000766 /* There's no need to clear the instance dict (if any);
767 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000768
769 if (baseclear)
770 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000771 return 0;
772}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000773
774static void
775subtype_dealloc(PyObject *self)
776{
Guido van Rossum14227b42001-12-06 02:35:58 +0000777 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000778 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000779
Guido van Rossum22b13872002-08-06 21:41:44 +0000780 /* Extract the type; we expect it to be a heap type */
Christian Heimese93237d2007-12-19 02:37:44 +0000781 type = Py_TYPE(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000782 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000783
Guido van Rossum22b13872002-08-06 21:41:44 +0000784 /* Test whether the type has GC exactly once */
785
786 if (!PyType_IS_GC(type)) {
787 /* It's really rare to find a dynamic type that doesn't have
788 GC; it can only happen when deriving from 'object' and not
789 adding any slots or instance variables. This allows
790 certain simplifications: there's no need to call
791 clear_slots(), or DECREF the dict, or clear weakrefs. */
792
793 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000794 if (type->tp_del) {
795 type->tp_del(self);
796 if (self->ob_refcnt > 0)
797 return;
798 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000799
800 /* Find the nearest base with a different tp_dealloc */
801 base = type;
802 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimese93237d2007-12-19 02:37:44 +0000803 assert(Py_SIZE(base) == 0);
Guido van Rossum22b13872002-08-06 21:41:44 +0000804 base = base->tp_base;
805 assert(base);
806 }
807
808 /* Call the base tp_dealloc() */
809 assert(basedealloc);
810 basedealloc(self);
811
812 /* Can't reference self beyond this point */
813 Py_DECREF(type);
814
815 /* Done */
816 return;
817 }
818
819 /* We get here only if the type has GC */
820
821 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000822 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000823 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000824 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000825 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000826 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000827 /* DO NOT restore GC tracking at this point. weakref callbacks
828 * (if any, and whether directly here or indirectly in something we
829 * call) may trigger GC, and if self is tracked at that point, it
830 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000831 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000832
Guido van Rossum59195fd2003-06-13 20:54:40 +0000833 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000834 base = type;
835 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000836 base = base->tp_base;
837 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000838 }
839
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000840 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000841 the finalizer (__del__), clearing slots, or clearing the instance
842 dict. */
843
Guido van Rossum1987c662003-05-29 14:29:23 +0000844 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
845 PyObject_ClearWeakRefs(self);
846
847 /* Maybe call finalizer; exit early if resurrected */
848 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000849 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000850 type->tp_del(self);
851 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000852 goto endlabel; /* resurrected */
853 else
854 _PyObject_GC_UNTRACK(self);
Brett Cannonf5bee302007-01-23 23:21:22 +0000855 /* New weakrefs could be created during the finalizer call.
856 If this occurs, clear them out without calling their
857 finalizers since they might rely on part of the object
858 being finalized that has already been destroyed. */
859 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
860 /* Modeled after GET_WEAKREFS_LISTPTR() */
861 PyWeakReference **list = (PyWeakReference **) \
862 PyObject_GET_WEAKREFS_LISTPTR(self);
863 while (*list)
864 _PyWeakref_ClearRef(*list);
865 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000866 }
867
Guido van Rossum59195fd2003-06-13 20:54:40 +0000868 /* Clear slots up to the nearest base with a different tp_dealloc */
869 base = type;
870 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimese93237d2007-12-19 02:37:44 +0000871 if (Py_SIZE(base))
Guido van Rossum59195fd2003-06-13 20:54:40 +0000872 clear_slots(base, self);
873 base = base->tp_base;
874 assert(base);
875 }
876
Tim Peters6d6c1a32001-08-02 04:15:00 +0000877 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000878 if (type->tp_dictoffset && !base->tp_dictoffset) {
879 PyObject **dictptr = _PyObject_GetDictPtr(self);
880 if (dictptr != NULL) {
881 PyObject *dict = *dictptr;
882 if (dict != NULL) {
883 Py_DECREF(dict);
884 *dictptr = NULL;
885 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000886 }
887 }
888
Tim Peters0bd743c2003-11-13 22:50:00 +0000889 /* Call the base tp_dealloc(); first retrack self if
890 * basedealloc knows about gc.
891 */
892 if (PyType_IS_GC(base))
893 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000894 assert(basedealloc);
895 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000896
897 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000898 Py_DECREF(type);
899
Guido van Rossum0906e072002-08-07 20:42:09 +0000900 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000901 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000902 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000903 --_PyTrash_delete_nesting;
904
905 /* Explanation of the weirdness around the trashcan macros:
906
907 Q. What do the trashcan macros do?
908
909 A. Read the comment titled "Trashcan mechanism" in object.h.
910 For one, this explains why there must be a call to GC-untrack
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000911 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000912 trashcan code, the answers to the following questions don't make
913 sense.
914
915 Q. Why do we GC-untrack before the trashcan and then immediately
916 GC-track again afterward?
917
918 A. In the case that the base class is GC-aware, the base class
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000919 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000920 UNTRACK macro, this will crash when the object is already
921 untracked. Because we don't know what the base class does, the
922 only safe thing is to make sure the object is tracked when we
923 call the base class dealloc. But... The trashcan begin macro
924 requires that the object is *untracked* before it is called. So
925 the dance becomes:
926
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000927 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000928 trashcan begin
929 GC track
930
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000931 Q. Why did the last question say "immediately GC-track again"?
932 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000933
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000934 A. Because the code *used* to re-track immediately. Bad Idea.
935 self has a refcount of 0, and if gc ever gets its hands on it
936 (which can happen if any weakref callback gets invoked), it
937 looks like trash to gc too, and gc also tries to delete self
938 then. But we're already deleting self. Double dealloction is
939 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +0000940
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000941 Q. Why the bizarre (net-zero) manipulation of
942 _PyTrash_delete_nesting around the trashcan macros?
943
944 A. Some base classes (e.g. list) also use the trashcan mechanism.
945 The following scenario used to be possible:
946
947 - suppose the trashcan level is one below the trashcan limit
948
949 - subtype_dealloc() is called
950
951 - the trashcan limit is not yet reached, so the trashcan level
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000952 is incremented and the code between trashcan begin and end is
953 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000954
955 - this destroys much of the object's contents, including its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000956 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000957
958 - basedealloc() is called; this is really list_dealloc(), or
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000959 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000960
961 - the trashcan limit is now reached, so the object is put on the
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000962 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000963
964 - basedealloc() returns
965
966 - subtype_dealloc() decrefs the object's type
967
968 - subtype_dealloc() returns
969
970 - later, the trashcan code starts deleting the objects from its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000971 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000972
973 - subtype_dealloc() is called *AGAIN* for the same object
974
975 - at the very least (if the destroyed slots and __dict__ don't
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000976 cause problems) the object's type gets decref'ed a second
977 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000978
979 The remedy is to make sure that if the code between trashcan
980 begin and end in subtype_dealloc() is called, the code between
981 trashcan begin and end in basedealloc() will also be called.
982 This is done by decrementing the level after passing into the
983 trashcan block, and incrementing it just before leaving the
984 block.
985
986 But now it's possible that a chain of objects consisting solely
987 of objects whose deallocator is subtype_dealloc() will defeat
988 the trashcan mechanism completely: the decremented level means
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000989 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000990 *increment* the level *before* entering the trashcan block, and
991 matchingly decrement it after leaving. This means the trashcan
992 code will trigger a little early, but that's no big deal.
993
994 Q. Are there any live examples of code in need of all this
995 complexity?
996
997 A. Yes. See SF bug 668433 for code that crashed (when Python was
998 compiled in debug mode) before the trashcan level manipulations
999 were added. For more discussion, see SF patches 581742, 575073
1000 and bug 574207.
1001 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001002}
1003
Jeremy Hylton938ace62002-07-17 16:30:39 +00001004static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001005
Tim Peters6d6c1a32001-08-02 04:15:00 +00001006/* type test with subclassing support */
1007
1008int
1009PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1010{
1011 PyObject *mro;
1012
Guido van Rossum9478d072001-09-07 18:52:13 +00001013 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1014 return b == a || b == &PyBaseObject_Type;
1015
Tim Peters6d6c1a32001-08-02 04:15:00 +00001016 mro = a->tp_mro;
1017 if (mro != NULL) {
1018 /* Deal with multiple inheritance without recursion
1019 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001020 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001021 assert(PyTuple_Check(mro));
1022 n = PyTuple_GET_SIZE(mro);
1023 for (i = 0; i < n; i++) {
1024 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1025 return 1;
1026 }
1027 return 0;
1028 }
1029 else {
1030 /* a is not completely initilized yet; follow tp_base */
1031 do {
1032 if (a == b)
1033 return 1;
1034 a = a->tp_base;
1035 } while (a != NULL);
1036 return b == &PyBaseObject_Type;
1037 }
1038}
1039
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001040/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001041 without looking in the instance dictionary
1042 (so we can't use PyObject_GetAttr) but still binding
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001043 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001044 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001045 static variable used to cache the interned Python string.
1046
1047 Two variants:
1048
1049 - lookup_maybe() returns NULL without raising an exception
1050 when the _PyType_Lookup() call fails;
1051
1052 - lookup_method() always raises an exception upon errors.
1053*/
Guido van Rossum60718732001-08-28 17:47:51 +00001054
1055static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001056lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001057{
1058 PyObject *res;
1059
1060 if (*attrobj == NULL) {
1061 *attrobj = PyString_InternFromString(attrstr);
1062 if (*attrobj == NULL)
1063 return NULL;
1064 }
Christian Heimese93237d2007-12-19 02:37:44 +00001065 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001066 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +00001067 descrgetfunc f;
Christian Heimese93237d2007-12-19 02:37:44 +00001068 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
Guido van Rossum60718732001-08-28 17:47:51 +00001069 Py_INCREF(res);
1070 else
Christian Heimese93237d2007-12-19 02:37:44 +00001071 res = f(res, self, (PyObject *)(Py_TYPE(self)));
Guido van Rossum60718732001-08-28 17:47:51 +00001072 }
1073 return res;
1074}
1075
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001076static PyObject *
1077lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1078{
1079 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1080 if (res == NULL && !PyErr_Occurred())
1081 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1082 return res;
1083}
1084
Guido van Rossum2730b132001-08-28 18:22:14 +00001085/* A variation of PyObject_CallMethod that uses lookup_method()
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001086 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001087 as lookup_method to cache the interned name string object. */
1088
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001089static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001090call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1091{
1092 va_list va;
1093 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001094 va_start(va, format);
1095
Guido van Rossumda21c012001-10-03 00:50:18 +00001096 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001097 if (func == NULL) {
1098 va_end(va);
1099 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +00001100 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001101 return NULL;
1102 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001103
1104 if (format && *format)
1105 args = Py_VaBuildValue(format, va);
1106 else
1107 args = PyTuple_New(0);
1108
1109 va_end(va);
1110
1111 if (args == NULL)
1112 return NULL;
1113
1114 assert(PyTuple_Check(args));
1115 retval = PyObject_Call(func, args, NULL);
1116
1117 Py_DECREF(args);
1118 Py_DECREF(func);
1119
1120 return retval;
1121}
1122
1123/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1124
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001125static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001126call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1127{
1128 va_list va;
1129 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001130 va_start(va, format);
1131
Guido van Rossumda21c012001-10-03 00:50:18 +00001132 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +00001133 if (func == NULL) {
1134 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001135 if (!PyErr_Occurred()) {
1136 Py_INCREF(Py_NotImplemented);
1137 return Py_NotImplemented;
1138 }
Guido van Rossum717ce002001-09-14 16:58:08 +00001139 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001140 }
1141
1142 if (format && *format)
1143 args = Py_VaBuildValue(format, va);
1144 else
1145 args = PyTuple_New(0);
1146
1147 va_end(va);
1148
Guido van Rossum717ce002001-09-14 16:58:08 +00001149 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00001150 return NULL;
1151
Guido van Rossum717ce002001-09-14 16:58:08 +00001152 assert(PyTuple_Check(args));
1153 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001154
1155 Py_DECREF(args);
1156 Py_DECREF(func);
1157
1158 return retval;
1159}
1160
Tim Petersa91e9642001-11-14 23:32:33 +00001161static int
1162fill_classic_mro(PyObject *mro, PyObject *cls)
1163{
1164 PyObject *bases, *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001165 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001166
1167 assert(PyList_Check(mro));
1168 assert(PyClass_Check(cls));
1169 i = PySequence_Contains(mro, cls);
1170 if (i < 0)
1171 return -1;
1172 if (!i) {
1173 if (PyList_Append(mro, cls) < 0)
1174 return -1;
1175 }
1176 bases = ((PyClassObject *)cls)->cl_bases;
1177 assert(bases && PyTuple_Check(bases));
1178 n = PyTuple_GET_SIZE(bases);
1179 for (i = 0; i < n; i++) {
1180 base = PyTuple_GET_ITEM(bases, i);
1181 if (fill_classic_mro(mro, base) < 0)
1182 return -1;
1183 }
1184 return 0;
1185}
1186
1187static PyObject *
1188classic_mro(PyObject *cls)
1189{
1190 PyObject *mro;
1191
1192 assert(PyClass_Check(cls));
1193 mro = PyList_New(0);
1194 if (mro != NULL) {
1195 if (fill_classic_mro(mro, cls) == 0)
1196 return mro;
1197 Py_DECREF(mro);
1198 }
1199 return NULL;
1200}
1201
Tim Petersea7f75d2002-12-07 21:39:16 +00001202/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001203 Method resolution order algorithm C3 described in
1204 "A Monotonic Superclass Linearization for Dylan",
1205 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001206 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001207 (OOPSLA 1996)
1208
Guido van Rossum98f33732002-11-25 21:36:54 +00001209 Some notes about the rules implied by C3:
1210
Tim Petersea7f75d2002-12-07 21:39:16 +00001211 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001212 It isn't legal to repeat a class in a list of base classes.
1213
1214 The next three properties are the 3 constraints in "C3".
1215
Tim Petersea7f75d2002-12-07 21:39:16 +00001216 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001217 If A precedes B in C's MRO, then A will precede B in the MRO of all
1218 subclasses of C.
1219
1220 Monotonicity.
1221 The MRO of a class must be an extension without reordering of the
1222 MRO of each of its superclasses.
1223
1224 Extended Precedence Graph (EPG).
1225 Linearization is consistent if there is a path in the EPG from
1226 each class to all its successors in the linearization. See
1227 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001228 */
1229
Tim Petersea7f75d2002-12-07 21:39:16 +00001230static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001231tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001232 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001233 size = PyList_GET_SIZE(list);
1234
1235 for (j = whence+1; j < size; j++) {
1236 if (PyList_GET_ITEM(list, j) == o)
1237 return 1;
1238 }
1239 return 0;
1240}
1241
Guido van Rossum98f33732002-11-25 21:36:54 +00001242static PyObject *
1243class_name(PyObject *cls)
1244{
1245 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1246 if (name == NULL) {
1247 PyErr_Clear();
1248 Py_XDECREF(name);
1249 name = PyObject_Repr(cls);
1250 }
1251 if (name == NULL)
1252 return NULL;
1253 if (!PyString_Check(name)) {
1254 Py_DECREF(name);
1255 return NULL;
1256 }
1257 return name;
1258}
1259
1260static int
1261check_duplicates(PyObject *list)
1262{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001263 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001264 /* Let's use a quadratic time algorithm,
1265 assuming that the bases lists is short.
1266 */
1267 n = PyList_GET_SIZE(list);
1268 for (i = 0; i < n; i++) {
1269 PyObject *o = PyList_GET_ITEM(list, i);
1270 for (j = i + 1; j < n; j++) {
1271 if (PyList_GET_ITEM(list, j) == o) {
1272 o = class_name(o);
1273 PyErr_Format(PyExc_TypeError,
1274 "duplicate base class %s",
1275 o ? PyString_AS_STRING(o) : "?");
1276 Py_XDECREF(o);
1277 return -1;
1278 }
1279 }
1280 }
1281 return 0;
1282}
1283
1284/* Raise a TypeError for an MRO order disagreement.
1285
1286 It's hard to produce a good error message. In the absence of better
1287 insight into error reporting, report the classes that were candidates
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001288 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001289 order in which they should be put in the MRO, but it's hard to
1290 diagnose what constraint can't be satisfied.
1291*/
1292
1293static void
1294set_mro_error(PyObject *to_merge, int *remain)
1295{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001296 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001297 char buf[1000];
1298 PyObject *k, *v;
1299 PyObject *set = PyDict_New();
Georg Brandl5c170fd2006-03-17 19:03:25 +00001300 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001301
1302 to_merge_size = PyList_GET_SIZE(to_merge);
1303 for (i = 0; i < to_merge_size; i++) {
1304 PyObject *L = PyList_GET_ITEM(to_merge, i);
1305 if (remain[i] < PyList_GET_SIZE(L)) {
1306 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Georg Brandl5c170fd2006-03-17 19:03:25 +00001307 if (PyDict_SetItem(set, c, Py_None) < 0) {
1308 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001309 return;
Georg Brandl5c170fd2006-03-17 19:03:25 +00001310 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001311 }
1312 }
1313 n = PyDict_Size(set);
1314
Raymond Hettingerf394df42003-04-06 19:13:41 +00001315 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1316consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001317 i = 0;
Skip Montanaro429433b2006-04-18 00:35:43 +00001318 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001319 PyObject *name = class_name(k);
1320 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1321 name ? PyString_AS_STRING(name) : "?");
1322 Py_XDECREF(name);
Skip Montanaro429433b2006-04-18 00:35:43 +00001323 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001324 buf[off++] = ',';
1325 buf[off] = '\0';
1326 }
1327 }
1328 PyErr_SetString(PyExc_TypeError, buf);
1329 Py_DECREF(set);
1330}
1331
Tim Petersea7f75d2002-12-07 21:39:16 +00001332static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001333pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001334 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001335 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001336 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001337
Guido van Rossum1f121312002-11-14 19:49:16 +00001338 to_merge_size = PyList_GET_SIZE(to_merge);
1339
Guido van Rossum98f33732002-11-25 21:36:54 +00001340 /* remain stores an index into each sublist of to_merge.
1341 remain[i] is the index of the next base in to_merge[i]
1342 that is not included in acc.
1343 */
Anthony Baxtera6286212006-04-11 07:42:36 +00001344 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001345 if (remain == NULL)
1346 return -1;
1347 for (i = 0; i < to_merge_size; i++)
1348 remain[i] = 0;
1349
1350 again:
1351 empty_cnt = 0;
1352 for (i = 0; i < to_merge_size; i++) {
1353 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001354
Guido van Rossum1f121312002-11-14 19:49:16 +00001355 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1356
1357 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1358 empty_cnt++;
1359 continue;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001360 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001361
Guido van Rossum98f33732002-11-25 21:36:54 +00001362 /* Choose next candidate for MRO.
1363
1364 The input sequences alone can determine the choice.
1365 If not, choose the class which appears in the MRO
1366 of the earliest direct superclass of the new class.
1367 */
1368
Guido van Rossum1f121312002-11-14 19:49:16 +00001369 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1370 for (j = 0; j < to_merge_size; j++) {
1371 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001372 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001373 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001374 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001375 }
1376 ok = PyList_Append(acc, candidate);
1377 if (ok < 0) {
1378 PyMem_Free(remain);
1379 return -1;
1380 }
1381 for (j = 0; j < to_merge_size; j++) {
1382 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001383 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1384 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001385 remain[j]++;
1386 }
1387 }
1388 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001389 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001390 }
1391
Guido van Rossum98f33732002-11-25 21:36:54 +00001392 if (empty_cnt == to_merge_size) {
1393 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001394 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001395 }
1396 set_mro_error(to_merge, remain);
1397 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001398 return -1;
1399}
1400
Tim Peters6d6c1a32001-08-02 04:15:00 +00001401static PyObject *
1402mro_implementation(PyTypeObject *type)
1403{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001404 Py_ssize_t i, n;
1405 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001406 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001407 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001408
Neal Norwitze7bb9182008-01-27 17:10:14 +00001409 if (type->tp_dict == NULL) {
1410 if (PyType_Ready(type) < 0)
Guido van Rossum63517572002-06-18 16:44:57 +00001411 return NULL;
1412 }
1413
Guido van Rossum98f33732002-11-25 21:36:54 +00001414 /* Find a superclass linearization that honors the constraints
1415 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001416 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001417
1418 to_merge is a list of lists, where each list is a superclass
1419 linearization implied by a base class. The last element of
1420 to_merge is the declared list of bases.
1421 */
1422
Tim Peters6d6c1a32001-08-02 04:15:00 +00001423 bases = type->tp_bases;
1424 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001425
1426 to_merge = PyList_New(n+1);
1427 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001428 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001429
Tim Peters6d6c1a32001-08-02 04:15:00 +00001430 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001431 PyObject *base = PyTuple_GET_ITEM(bases, i);
1432 PyObject *parentMRO;
1433 if (PyType_Check(base))
1434 parentMRO = PySequence_List(
1435 ((PyTypeObject*)base)->tp_mro);
1436 else
1437 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001438 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001439 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001440 return NULL;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001441 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001442
1443 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001444 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001445
1446 bases_aslist = PySequence_List(bases);
1447 if (bases_aslist == NULL) {
1448 Py_DECREF(to_merge);
1449 return NULL;
1450 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001451 /* This is just a basic sanity check. */
1452 if (check_duplicates(bases_aslist) < 0) {
1453 Py_DECREF(to_merge);
1454 Py_DECREF(bases_aslist);
1455 return NULL;
1456 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001457 PyList_SET_ITEM(to_merge, n, bases_aslist);
1458
1459 result = Py_BuildValue("[O]", (PyObject *)type);
1460 if (result == NULL) {
1461 Py_DECREF(to_merge);
1462 return NULL;
1463 }
1464
1465 ok = pmerge(result, to_merge);
1466 Py_DECREF(to_merge);
1467 if (ok < 0) {
1468 Py_DECREF(result);
1469 return NULL;
1470 }
1471
Tim Peters6d6c1a32001-08-02 04:15:00 +00001472 return result;
1473}
1474
1475static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001476mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001477{
1478 PyTypeObject *type = (PyTypeObject *)self;
1479
Tim Peters6d6c1a32001-08-02 04:15:00 +00001480 return mro_implementation(type);
1481}
1482
1483static int
1484mro_internal(PyTypeObject *type)
1485{
1486 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001487 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001488
Christian Heimese93237d2007-12-19 02:37:44 +00001489 if (Py_TYPE(type) == &PyType_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001490 result = mro_implementation(type);
1491 }
1492 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001493 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001494 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001495 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001496 if (mro == NULL)
1497 return -1;
1498 result = PyObject_CallObject(mro, NULL);
1499 Py_DECREF(mro);
1500 }
1501 if (result == NULL)
1502 return -1;
1503 tuple = PySequence_Tuple(result);
1504 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001505 if (tuple == NULL)
1506 return -1;
1507 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001508 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001509 PyObject *cls;
1510 PyTypeObject *solid;
1511
1512 solid = solid_base(type);
1513
1514 len = PyTuple_GET_SIZE(tuple);
1515
1516 for (i = 0; i < len; i++) {
1517 PyTypeObject *t;
1518 cls = PyTuple_GET_ITEM(tuple, i);
1519 if (PyClass_Check(cls))
1520 continue;
1521 else if (!PyType_Check(cls)) {
1522 PyErr_Format(PyExc_TypeError,
1523 "mro() returned a non-class ('%.500s')",
Christian Heimese93237d2007-12-19 02:37:44 +00001524 Py_TYPE(cls)->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001525 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001526 return -1;
1527 }
1528 t = (PyTypeObject*)cls;
1529 if (!PyType_IsSubtype(solid, solid_base(t))) {
1530 PyErr_Format(PyExc_TypeError,
1531 "mro() returned base with unsuitable layout ('%.500s')",
1532 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001533 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001534 return -1;
1535 }
1536 }
1537 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001538 type->tp_mro = tuple;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001539
1540 type_mro_modified(type, type->tp_mro);
1541 /* corner case: the old-style super class might have been hidden
1542 from the custom MRO */
1543 type_mro_modified(type, type->tp_bases);
1544
1545 type_modified(type);
1546
Tim Peters6d6c1a32001-08-02 04:15:00 +00001547 return 0;
1548}
1549
1550
1551/* Calculate the best base amongst multiple base classes.
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001552 This is the first one that's on the path to the "solid base". */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001553
1554static PyTypeObject *
1555best_base(PyObject *bases)
1556{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001557 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001558 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001559 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001560
1561 assert(PyTuple_Check(bases));
1562 n = PyTuple_GET_SIZE(bases);
1563 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001564 base = NULL;
1565 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001566 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001567 base_proto = PyTuple_GET_ITEM(bases, i);
1568 if (PyClass_Check(base_proto))
1569 continue;
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001570 if (!PyType_Check(base_proto)) {
1571 PyErr_SetString(
1572 PyExc_TypeError,
1573 "bases must be types");
1574 return NULL;
1575 }
Tim Petersa91e9642001-11-14 23:32:33 +00001576 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001577 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001578 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001579 return NULL;
1580 }
1581 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001582 if (winner == NULL) {
1583 winner = candidate;
1584 base = base_i;
1585 }
1586 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001587 ;
1588 else if (PyType_IsSubtype(candidate, winner)) {
1589 winner = candidate;
1590 base = base_i;
1591 }
1592 else {
1593 PyErr_SetString(
1594 PyExc_TypeError,
1595 "multiple bases have "
1596 "instance lay-out conflict");
1597 return NULL;
1598 }
1599 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001600 if (base == NULL)
1601 PyErr_SetString(PyExc_TypeError,
1602 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001603 return base;
1604}
1605
1606static int
1607extra_ivars(PyTypeObject *type, PyTypeObject *base)
1608{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001609 size_t t_size = type->tp_basicsize;
1610 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001611
Guido van Rossum9676b222001-08-17 20:32:36 +00001612 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001613 if (type->tp_itemsize || base->tp_itemsize) {
1614 /* If itemsize is involved, stricter rules */
1615 return t_size != b_size ||
1616 type->tp_itemsize != base->tp_itemsize;
1617 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001618 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001619 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1620 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001621 t_size -= sizeof(PyObject *);
1622 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001623 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1624 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001625 t_size -= sizeof(PyObject *);
1626
1627 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001628}
1629
1630static PyTypeObject *
1631solid_base(PyTypeObject *type)
1632{
1633 PyTypeObject *base;
1634
1635 if (type->tp_base)
1636 base = solid_base(type->tp_base);
1637 else
1638 base = &PyBaseObject_Type;
1639 if (extra_ivars(type, base))
1640 return type;
1641 else
1642 return base;
1643}
1644
Jeremy Hylton938ace62002-07-17 16:30:39 +00001645static void object_dealloc(PyObject *);
1646static int object_init(PyObject *, PyObject *, PyObject *);
1647static int update_slot(PyTypeObject *, PyObject *);
1648static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001649
Armin Rigo9790a272007-05-02 19:23:31 +00001650/*
1651 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1652 * inherited from various builtin types. The builtin base usually provides
1653 * its own __dict__ descriptor, so we use that when we can.
1654 */
1655static PyTypeObject *
1656get_builtin_base_with_dict(PyTypeObject *type)
1657{
1658 while (type->tp_base != NULL) {
1659 if (type->tp_dictoffset != 0 &&
1660 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1661 return type;
1662 type = type->tp_base;
1663 }
1664 return NULL;
1665}
1666
1667static PyObject *
1668get_dict_descriptor(PyTypeObject *type)
1669{
1670 static PyObject *dict_str;
1671 PyObject *descr;
1672
1673 if (dict_str == NULL) {
1674 dict_str = PyString_InternFromString("__dict__");
1675 if (dict_str == NULL)
1676 return NULL;
1677 }
1678 descr = _PyType_Lookup(type, dict_str);
1679 if (descr == NULL || !PyDescr_IsData(descr))
1680 return NULL;
1681
1682 return descr;
1683}
1684
1685static void
1686raise_dict_descr_error(PyObject *obj)
1687{
1688 PyErr_Format(PyExc_TypeError,
1689 "this __dict__ descriptor does not support "
1690 "'%.200s' objects", obj->ob_type->tp_name);
1691}
1692
Tim Peters6d6c1a32001-08-02 04:15:00 +00001693static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001694subtype_dict(PyObject *obj, void *context)
1695{
Armin Rigo9790a272007-05-02 19:23:31 +00001696 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001697 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001698 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001699
Armin Rigo9790a272007-05-02 19:23:31 +00001700 base = get_builtin_base_with_dict(obj->ob_type);
1701 if (base != NULL) {
1702 descrgetfunc func;
1703 PyObject *descr = get_dict_descriptor(base);
1704 if (descr == NULL) {
1705 raise_dict_descr_error(obj);
1706 return NULL;
1707 }
1708 func = descr->ob_type->tp_descr_get;
1709 if (func == NULL) {
1710 raise_dict_descr_error(obj);
1711 return NULL;
1712 }
1713 return func(descr, obj, (PyObject *)(obj->ob_type));
1714 }
1715
1716 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001717 if (dictptr == NULL) {
1718 PyErr_SetString(PyExc_AttributeError,
1719 "This object has no __dict__");
1720 return NULL;
1721 }
1722 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001723 if (dict == NULL)
1724 *dictptr = dict = PyDict_New();
1725 Py_XINCREF(dict);
1726 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001727}
1728
Guido van Rossum6661be32001-10-26 04:26:12 +00001729static int
1730subtype_setdict(PyObject *obj, PyObject *value, void *context)
1731{
Armin Rigo9790a272007-05-02 19:23:31 +00001732 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001733 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001734 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001735
Armin Rigo9790a272007-05-02 19:23:31 +00001736 base = get_builtin_base_with_dict(obj->ob_type);
1737 if (base != NULL) {
1738 descrsetfunc func;
1739 PyObject *descr = get_dict_descriptor(base);
1740 if (descr == NULL) {
1741 raise_dict_descr_error(obj);
1742 return -1;
1743 }
1744 func = descr->ob_type->tp_descr_set;
1745 if (func == NULL) {
1746 raise_dict_descr_error(obj);
1747 return -1;
1748 }
1749 return func(descr, obj, value);
1750 }
1751
1752 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001753 if (dictptr == NULL) {
1754 PyErr_SetString(PyExc_AttributeError,
1755 "This object has no __dict__");
1756 return -1;
1757 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001758 if (value != NULL && !PyDict_Check(value)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001759 PyErr_Format(PyExc_TypeError,
1760 "__dict__ must be set to a dictionary, "
Christian Heimese93237d2007-12-19 02:37:44 +00001761 "not a '%.200s'", Py_TYPE(value)->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001762 return -1;
1763 }
1764 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001765 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001766 *dictptr = value;
1767 Py_XDECREF(dict);
1768 return 0;
1769}
1770
Guido van Rossumad47da02002-08-12 19:05:44 +00001771static PyObject *
1772subtype_getweakref(PyObject *obj, void *context)
1773{
1774 PyObject **weaklistptr;
1775 PyObject *result;
1776
Christian Heimese93237d2007-12-19 02:37:44 +00001777 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001778 PyErr_SetString(PyExc_AttributeError,
Fred Drake7a36f5f2006-08-04 05:17:21 +00001779 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001780 return NULL;
1781 }
Christian Heimese93237d2007-12-19 02:37:44 +00001782 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1783 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1784 (size_t)(Py_TYPE(obj)->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001785 weaklistptr = (PyObject **)
Christian Heimese93237d2007-12-19 02:37:44 +00001786 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001787 if (*weaklistptr == NULL)
1788 result = Py_None;
1789 else
1790 result = *weaklistptr;
1791 Py_INCREF(result);
1792 return result;
1793}
1794
Guido van Rossum373c7412003-01-07 13:41:37 +00001795/* Three variants on the subtype_getsets list. */
1796
1797static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001798 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001799 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001800 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001801 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001802 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001803};
1804
Guido van Rossum373c7412003-01-07 13:41:37 +00001805static PyGetSetDef subtype_getsets_dict_only[] = {
1806 {"__dict__", subtype_dict, subtype_setdict,
1807 PyDoc_STR("dictionary for instance variables (if defined)")},
1808 {0}
1809};
1810
1811static PyGetSetDef subtype_getsets_weakref_only[] = {
1812 {"__weakref__", subtype_getweakref, NULL,
1813 PyDoc_STR("list of weak references to the object (if defined)")},
1814 {0}
1815};
1816
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001817static int
1818valid_identifier(PyObject *s)
1819{
Guido van Rossum03013a02002-07-16 14:30:28 +00001820 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001821 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001822
1823 if (!PyString_Check(s)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001824 PyErr_Format(PyExc_TypeError,
1825 "__slots__ items must be strings, not '%.200s'",
Christian Heimese93237d2007-12-19 02:37:44 +00001826 Py_TYPE(s)->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001827 return 0;
1828 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001829 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001830 n = PyString_GET_SIZE(s);
1831 /* We must reject an empty name. As a hack, we bump the
1832 length to 1 so that the loop will balk on the trailing \0. */
1833 if (n == 0)
1834 n = 1;
1835 for (i = 0; i < n; i++, p++) {
1836 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1837 PyErr_SetString(PyExc_TypeError,
1838 "__slots__ must be identifiers");
1839 return 0;
1840 }
1841 }
1842 return 1;
1843}
1844
Martin v. Löwisd919a592002-10-14 21:07:28 +00001845#ifdef Py_USING_UNICODE
1846/* Replace Unicode objects in slots. */
1847
1848static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001849_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001850{
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001851 PyObject *tmp = NULL;
1852 PyObject *slot_name, *new_name;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001853 Py_ssize_t i;
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001854
Martin v. Löwisd919a592002-10-14 21:07:28 +00001855 for (i = 0; i < nslots; i++) {
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001856 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1857 if (tmp == NULL) {
1858 tmp = PySequence_List(slots);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001859 if (tmp == NULL)
1860 return NULL;
1861 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001862 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1863 NULL);
1864 if (new_name == NULL) {
Martin v. Löwisd919a592002-10-14 21:07:28 +00001865 Py_DECREF(tmp);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001866 return NULL;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001867 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001868 Py_INCREF(new_name);
1869 PyList_SET_ITEM(tmp, i, new_name);
1870 Py_DECREF(slot_name);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001871 }
1872 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001873 if (tmp != NULL) {
1874 slots = PyList_AsTuple(tmp);
1875 Py_DECREF(tmp);
1876 }
1877 return slots;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001878}
1879#endif
1880
Guido van Rossumf102e242007-03-23 18:53:03 +00001881/* Forward */
1882static int
1883object_init(PyObject *self, PyObject *args, PyObject *kwds);
1884
1885static int
1886type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1887{
1888 int res;
1889
1890 assert(args != NULL && PyTuple_Check(args));
1891 assert(kwds == NULL || PyDict_Check(kwds));
1892
1893 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1894 PyErr_SetString(PyExc_TypeError,
1895 "type.__init__() takes no keyword arguments");
1896 return -1;
1897 }
1898
1899 if (args != NULL && PyTuple_Check(args) &&
1900 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1901 PyErr_SetString(PyExc_TypeError,
1902 "type.__init__() takes 1 or 3 arguments");
1903 return -1;
1904 }
1905
1906 /* Call object.__init__(self) now. */
1907 /* XXX Could call super(type, cls).__init__() but what's the point? */
1908 args = PyTuple_GetSlice(args, 0, 0);
1909 res = object_init(cls, args, NULL);
1910 Py_DECREF(args);
1911 return res;
1912}
1913
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001914static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001915type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1916{
1917 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001918 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001919 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001920 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001921 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001922 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001923 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001924 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001925
Tim Peters3abca122001-10-27 19:37:48 +00001926 assert(args != NULL && PyTuple_Check(args));
1927 assert(kwds == NULL || PyDict_Check(kwds));
1928
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001929 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001930 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001931 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1932 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001933
1934 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1935 PyObject *x = PyTuple_GET_ITEM(args, 0);
Christian Heimese93237d2007-12-19 02:37:44 +00001936 Py_INCREF(Py_TYPE(x));
1937 return (PyObject *) Py_TYPE(x);
Tim Peters3abca122001-10-27 19:37:48 +00001938 }
1939
1940 /* SF bug 475327 -- if that didn't trigger, we need 3
1941 arguments. but PyArg_ParseTupleAndKeywords below may give
1942 a msg saying type() needs exactly 3. */
1943 if (nargs + nkwds != 3) {
1944 PyErr_SetString(PyExc_TypeError,
1945 "type() takes 1 or 3 arguments");
1946 return NULL;
1947 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001948 }
1949
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001950 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001951 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1952 &name,
1953 &PyTuple_Type, &bases,
1954 &PyDict_Type, &dict))
1955 return NULL;
1956
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001957 /* Determine the proper metatype to deal with this,
1958 and check for metatype conflicts while we're at it.
1959 Note that if some other metatype wins to contract,
1960 it's possible that its instances are not types. */
1961 nbases = PyTuple_GET_SIZE(bases);
1962 winner = metatype;
1963 for (i = 0; i < nbases; i++) {
1964 tmp = PyTuple_GET_ITEM(bases, i);
1965 tmptype = tmp->ob_type;
1966 if (tmptype == &PyClass_Type)
1967 continue; /* Special case classic classes */
1968 if (PyType_IsSubtype(winner, tmptype))
1969 continue;
1970 if (PyType_IsSubtype(tmptype, winner)) {
1971 winner = tmptype;
1972 continue;
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001973 }
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001974 PyErr_SetString(PyExc_TypeError,
1975 "metaclass conflict: "
1976 "the metaclass of a derived class "
1977 "must be a (non-strict) subclass "
1978 "of the metaclasses of all its bases");
1979 return NULL;
1980 }
1981 if (winner != metatype) {
1982 if (winner->tp_new != type_new) /* Pass it to the winner */
1983 return winner->tp_new(winner, args, kwds);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001984 metatype = winner;
1985 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001986
1987 /* Adjust for empty tuple bases */
1988 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001989 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001990 if (bases == NULL)
1991 return NULL;
1992 nbases = 1;
1993 }
1994 else
1995 Py_INCREF(bases);
1996
1997 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1998
1999 /* Calculate best base, and check that all bases are type objects */
2000 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002001 if (base == NULL) {
2002 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002003 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002004 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002005 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2006 PyErr_Format(PyExc_TypeError,
2007 "type '%.100s' is not an acceptable base type",
2008 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002009 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002010 return NULL;
2011 }
2012
Tim Peters6d6c1a32001-08-02 04:15:00 +00002013 /* Check for a __slots__ sequence variable in dict, and count it */
2014 slots = PyDict_GetItemString(dict, "__slots__");
2015 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00002016 add_dict = 0;
2017 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00002018 may_add_dict = base->tp_dictoffset == 0;
2019 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2020 if (slots == NULL) {
2021 if (may_add_dict) {
2022 add_dict++;
2023 }
2024 if (may_add_weak) {
2025 add_weak++;
2026 }
2027 }
2028 else {
2029 /* Have slots */
2030
Tim Peters6d6c1a32001-08-02 04:15:00 +00002031 /* Make it into a tuple */
Neal Norwitzcbd9ee62007-04-14 05:25:50 +00002032 if (PyString_Check(slots) || PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002033 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002034 else
2035 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002036 if (slots == NULL) {
2037 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002039 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002040 assert(PyTuple_Check(slots));
2041
2042 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00002044 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00002045 PyErr_Format(PyExc_TypeError,
2046 "nonempty __slots__ "
2047 "not supported for subtype of '%s'",
2048 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00002049 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002050 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00002051 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00002052 return NULL;
2053 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002054
Martin v. Löwisd919a592002-10-14 21:07:28 +00002055#ifdef Py_USING_UNICODE
2056 tmp = _unicode_to_string(slots, nslots);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00002057 if (tmp == NULL)
2058 goto bad_slots;
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00002059 if (tmp != slots) {
2060 Py_DECREF(slots);
2061 slots = tmp;
2062 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00002063#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00002064 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002065 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00002066 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2067 char *s;
2068 if (!valid_identifier(tmp))
2069 goto bad_slots;
2070 assert(PyString_Check(tmp));
2071 s = PyString_AS_STRING(tmp);
2072 if (strcmp(s, "__dict__") == 0) {
2073 if (!may_add_dict || add_dict) {
2074 PyErr_SetString(PyExc_TypeError,
2075 "__dict__ slot disallowed: "
2076 "we already got one");
2077 goto bad_slots;
2078 }
2079 add_dict++;
2080 }
2081 if (strcmp(s, "__weakref__") == 0) {
2082 if (!may_add_weak || add_weak) {
2083 PyErr_SetString(PyExc_TypeError,
2084 "__weakref__ slot disallowed: "
2085 "either we already got one, "
2086 "or __itemsize__ != 0");
2087 goto bad_slots;
2088 }
2089 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002090 }
2091 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002092
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002093 /* Copy slots into a list, mangle names and sort them.
2094 Sorted names are needed for __class__ assignment.
2095 Convert them back to tuple at the end.
2096 */
2097 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002098 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00002099 goto bad_slots;
2100 for (i = j = 0; i < nslots; i++) {
2101 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002102 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00002103 s = PyString_AS_STRING(tmp);
2104 if ((add_dict && strcmp(s, "__dict__") == 0) ||
2105 (add_weak && strcmp(s, "__weakref__") == 0))
2106 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107 tmp =_Py_Mangle(name, tmp);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002108 if (!tmp)
2109 goto bad_slots;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002110 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00002111 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002112 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002113 assert(j == nslots - add_dict - add_weak);
2114 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002115 Py_DECREF(slots);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002116 if (PyList_Sort(newslots) == -1) {
2117 Py_DECREF(bases);
2118 Py_DECREF(newslots);
2119 return NULL;
2120 }
2121 slots = PyList_AsTuple(newslots);
2122 Py_DECREF(newslots);
2123 if (slots == NULL) {
2124 Py_DECREF(bases);
2125 return NULL;
2126 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002127
Guido van Rossumad47da02002-08-12 19:05:44 +00002128 /* Secondary bases may provide weakrefs or dict */
2129 if (nbases > 1 &&
2130 ((may_add_dict && !add_dict) ||
2131 (may_add_weak && !add_weak))) {
2132 for (i = 0; i < nbases; i++) {
2133 tmp = PyTuple_GET_ITEM(bases, i);
2134 if (tmp == (PyObject *)base)
2135 continue; /* Skip primary base */
2136 if (PyClass_Check(tmp)) {
2137 /* Classic base class provides both */
2138 if (may_add_dict && !add_dict)
2139 add_dict++;
2140 if (may_add_weak && !add_weak)
2141 add_weak++;
2142 break;
2143 }
2144 assert(PyType_Check(tmp));
2145 tmptype = (PyTypeObject *)tmp;
2146 if (may_add_dict && !add_dict &&
2147 tmptype->tp_dictoffset != 0)
2148 add_dict++;
2149 if (may_add_weak && !add_weak &&
2150 tmptype->tp_weaklistoffset != 0)
2151 add_weak++;
2152 if (may_add_dict && !add_dict)
2153 continue;
2154 if (may_add_weak && !add_weak)
2155 continue;
2156 /* Nothing more to check */
2157 break;
2158 }
2159 }
Guido van Rossum9676b222001-08-17 20:32:36 +00002160 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002161
2162 /* XXX From here until type is safely allocated,
2163 "return NULL" may leak slots! */
2164
2165 /* Allocate the type object */
2166 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00002167 if (type == NULL) {
2168 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002169 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002170 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00002171 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002172
2173 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002174 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002175 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002176 et->ht_name = name;
2177 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002178
Guido van Rossumdc91b992001-08-08 22:26:22 +00002179 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002180 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2181 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002182 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2183 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002184
2185 /* It's a new-style number unless it specifically inherits any
2186 old-style numeric behavior */
2187 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
2188 (base->tp_as_number == NULL))
2189 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
2190
2191 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002192 type->tp_as_number = &et->as_number;
2193 type->tp_as_sequence = &et->as_sequence;
2194 type->tp_as_mapping = &et->as_mapping;
2195 type->tp_as_buffer = &et->as_buffer;
2196 type->tp_name = PyString_AS_STRING(name);
2197
2198 /* Set tp_base and tp_bases */
2199 type->tp_bases = bases;
2200 Py_INCREF(base);
2201 type->tp_base = base;
2202
Guido van Rossum687ae002001-10-15 22:03:32 +00002203 /* Initialize tp_dict from passed-in dict */
2204 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002205 if (dict == NULL) {
2206 Py_DECREF(type);
2207 return NULL;
2208 }
2209
Guido van Rossumc3542212001-08-16 09:18:56 +00002210 /* Set __module__ in the dict */
2211 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2212 tmp = PyEval_GetGlobals();
2213 if (tmp != NULL) {
2214 tmp = PyDict_GetItemString(tmp, "__name__");
2215 if (tmp != NULL) {
2216 if (PyDict_SetItemString(dict, "__module__",
2217 tmp) < 0)
2218 return NULL;
2219 }
2220 }
2221 }
2222
Tim Peters2f93e282001-10-04 05:27:00 +00002223 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00002224 and is a string. The __doc__ accessor will first look for tp_doc;
2225 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00002226 */
2227 {
2228 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2229 if (doc != NULL && PyString_Check(doc)) {
2230 const size_t n = (size_t)PyString_GET_SIZE(doc);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002231 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002232 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00002233 Py_DECREF(type);
2234 return NULL;
2235 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002236 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002237 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00002238 }
2239 }
2240
Tim Peters6d6c1a32001-08-02 04:15:00 +00002241 /* Special-case __new__: if it's a plain function,
2242 make it a static function */
2243 tmp = PyDict_GetItemString(dict, "__new__");
2244 if (tmp != NULL && PyFunction_Check(tmp)) {
2245 tmp = PyStaticMethod_New(tmp);
2246 if (tmp == NULL) {
2247 Py_DECREF(type);
2248 return NULL;
2249 }
2250 PyDict_SetItemString(dict, "__new__", tmp);
2251 Py_DECREF(tmp);
2252 }
2253
2254 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002255 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00002256 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002257 if (slots != NULL) {
2258 for (i = 0; i < nslots; i++, mp++) {
2259 mp->name = PyString_AS_STRING(
2260 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00002261 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002262 mp->offset = slotoffset;
Žiga Seilnacht89032082007-03-11 15:54:54 +00002263
2264 /* __dict__ and __weakref__ are already filtered out */
2265 assert(strcmp(mp->name, "__dict__") != 0);
2266 assert(strcmp(mp->name, "__weakref__") != 0);
2267
Tim Peters6d6c1a32001-08-02 04:15:00 +00002268 slotoffset += sizeof(PyObject *);
2269 }
2270 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002271 if (add_dict) {
2272 if (base->tp_itemsize)
2273 type->tp_dictoffset = -(long)sizeof(PyObject *);
2274 else
2275 type->tp_dictoffset = slotoffset;
2276 slotoffset += sizeof(PyObject *);
2277 }
2278 if (add_weak) {
2279 assert(!base->tp_itemsize);
2280 type->tp_weaklistoffset = slotoffset;
2281 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002282 }
2283 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002284 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002285 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002286
2287 if (type->tp_weaklistoffset && type->tp_dictoffset)
2288 type->tp_getset = subtype_getsets_full;
2289 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2290 type->tp_getset = subtype_getsets_weakref_only;
2291 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2292 type->tp_getset = subtype_getsets_dict_only;
2293 else
2294 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002295
2296 /* Special case some slots */
2297 if (type->tp_dictoffset != 0 || nslots > 0) {
2298 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2299 type->tp_getattro = PyObject_GenericGetAttr;
2300 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2301 type->tp_setattro = PyObject_GenericSetAttr;
2302 }
2303 type->tp_dealloc = subtype_dealloc;
2304
Guido van Rossum9475a232001-10-05 20:51:39 +00002305 /* Enable GC unless there are really no instance variables possible */
2306 if (!(type->tp_basicsize == sizeof(PyObject) &&
2307 type->tp_itemsize == 0))
2308 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2309
Tim Peters6d6c1a32001-08-02 04:15:00 +00002310 /* Always override allocation strategy to use regular heap */
2311 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002312 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002313 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002314 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002315 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002316 }
2317 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002318 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002319
2320 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002321 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002322 Py_DECREF(type);
2323 return NULL;
2324 }
2325
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002326 /* Put the proper slots in place */
2327 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002328
Tim Peters6d6c1a32001-08-02 04:15:00 +00002329 return (PyObject *)type;
2330}
2331
2332/* Internal API to look for a name through the MRO.
2333 This returns a borrowed reference, and doesn't set an exception! */
2334PyObject *
2335_PyType_Lookup(PyTypeObject *type, PyObject *name)
2336{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002337 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002338 PyObject *mro, *res, *base, *dict;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002339 unsigned int h;
2340
2341 if (MCACHE_CACHEABLE_NAME(name) &&
Neal Norwitze7bb9182008-01-27 17:10:14 +00002342 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002343 /* fast path */
2344 h = MCACHE_HASH_METHOD(type, name);
2345 if (method_cache[h].version == type->tp_version_tag &&
2346 method_cache[h].name == name)
2347 return method_cache[h].value;
2348 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002349
Guido van Rossum687ae002001-10-15 22:03:32 +00002350 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002351 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002352
2353 /* If mro is NULL, the type is either not yet initialized
2354 by PyType_Ready(), or already cleared by type_clear().
2355 Either way the safest thing to do is to return NULL. */
2356 if (mro == NULL)
2357 return NULL;
2358
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002359 res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002360 assert(PyTuple_Check(mro));
2361 n = PyTuple_GET_SIZE(mro);
2362 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002363 base = PyTuple_GET_ITEM(mro, i);
2364 if (PyClass_Check(base))
2365 dict = ((PyClassObject *)base)->cl_dict;
2366 else {
2367 assert(PyType_Check(base));
2368 dict = ((PyTypeObject *)base)->tp_dict;
2369 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002370 assert(dict && PyDict_Check(dict));
2371 res = PyDict_GetItem(dict, name);
2372 if (res != NULL)
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002373 break;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002374 }
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002375
2376 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2377 h = MCACHE_HASH_METHOD(type, name);
2378 method_cache[h].version = type->tp_version_tag;
2379 method_cache[h].value = res; /* borrowed */
2380 Py_INCREF(name);
2381 Py_DECREF(method_cache[h].name);
2382 method_cache[h].name = name;
2383 }
2384 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002385}
2386
2387/* This is similar to PyObject_GenericGetAttr(),
2388 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2389static PyObject *
2390type_getattro(PyTypeObject *type, PyObject *name)
2391{
Christian Heimese93237d2007-12-19 02:37:44 +00002392 PyTypeObject *metatype = Py_TYPE(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002393 PyObject *meta_attribute, *attribute;
2394 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002395
2396 /* Initialize this type (we'll assume the metatype is initialized) */
2397 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002398 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002399 return NULL;
2400 }
2401
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002402 /* No readable descriptor found yet */
2403 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002404
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002405 /* Look for the attribute in the metatype */
2406 meta_attribute = _PyType_Lookup(metatype, name);
2407
2408 if (meta_attribute != NULL) {
Christian Heimese93237d2007-12-19 02:37:44 +00002409 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002410
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002411 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2412 /* Data descriptors implement tp_descr_set to intercept
2413 * writes. Assume the attribute is not overridden in
2414 * type's tp_dict (and bases): call the descriptor now.
2415 */
2416 return meta_get(meta_attribute, (PyObject *)type,
2417 (PyObject *)metatype);
2418 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002419 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002420 }
2421
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002422 /* No data descriptor found on metatype. Look in tp_dict of this
2423 * type and its bases */
2424 attribute = _PyType_Lookup(type, name);
2425 if (attribute != NULL) {
2426 /* Implement descriptor functionality, if any */
Christian Heimese93237d2007-12-19 02:37:44 +00002427 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002428
2429 Py_XDECREF(meta_attribute);
2430
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002431 if (local_get != NULL) {
2432 /* NULL 2nd argument indicates the descriptor was
2433 * found on the target object itself (or a base) */
2434 return local_get(attribute, (PyObject *)NULL,
2435 (PyObject *)type);
2436 }
Tim Peters34592512002-07-11 06:23:50 +00002437
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002438 Py_INCREF(attribute);
2439 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002440 }
2441
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002442 /* No attribute found in local __dict__ (or bases): use the
2443 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002444 if (meta_get != NULL) {
2445 PyObject *res;
2446 res = meta_get(meta_attribute, (PyObject *)type,
2447 (PyObject *)metatype);
2448 Py_DECREF(meta_attribute);
2449 return res;
2450 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002451
2452 /* If an ordinary attribute was found on the metatype, return it now */
2453 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002454 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002455 }
2456
2457 /* Give up */
2458 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002459 "type object '%.50s' has no attribute '%.400s'",
2460 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002461 return NULL;
2462}
2463
2464static int
2465type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2466{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002467 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2468 PyErr_Format(
2469 PyExc_TypeError,
2470 "can't set attributes of built-in/extension type '%s'",
2471 type->tp_name);
2472 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002473 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002474 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2475 return -1;
2476 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002477}
2478
2479static void
2480type_dealloc(PyTypeObject *type)
2481{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002482 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002483
2484 /* Assert this is a heap-allocated type object */
2485 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002486 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002487 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002488 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002489 Py_XDECREF(type->tp_base);
2490 Py_XDECREF(type->tp_dict);
2491 Py_XDECREF(type->tp_bases);
2492 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002493 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002494 Py_XDECREF(type->tp_subclasses);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002495 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2496 * of most other objects. It's okay to cast it to char *.
2497 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002498 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002499 Py_XDECREF(et->ht_name);
2500 Py_XDECREF(et->ht_slots);
Christian Heimese93237d2007-12-19 02:37:44 +00002501 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002502}
2503
Guido van Rossum1c450732001-10-08 15:18:27 +00002504static PyObject *
2505type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2506{
2507 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002508 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002509
2510 list = PyList_New(0);
2511 if (list == NULL)
2512 return NULL;
2513 raw = type->tp_subclasses;
2514 if (raw == NULL)
2515 return list;
2516 assert(PyList_Check(raw));
2517 n = PyList_GET_SIZE(raw);
2518 for (i = 0; i < n; i++) {
2519 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002520 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002521 ref = PyWeakref_GET_OBJECT(ref);
2522 if (ref != Py_None) {
2523 if (PyList_Append(list, ref) < 0) {
2524 Py_DECREF(list);
2525 return NULL;
2526 }
2527 }
2528 }
2529 return list;
2530}
2531
Tim Peters6d6c1a32001-08-02 04:15:00 +00002532static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002533 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002534 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002535 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002536 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002537 {0}
2538};
2539
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002540PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002541"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002542"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002543
Guido van Rossum048eb752001-10-02 21:24:57 +00002544static int
2545type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2546{
Guido van Rossuma3862092002-06-10 15:24:42 +00002547 /* Because of type_is_gc(), the collector only calls this
2548 for heaptypes. */
2549 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002550
Thomas Woutersc6e55062006-04-15 21:47:09 +00002551 Py_VISIT(type->tp_dict);
2552 Py_VISIT(type->tp_cache);
2553 Py_VISIT(type->tp_mro);
2554 Py_VISIT(type->tp_bases);
2555 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002556
2557 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002558 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002559 in cycles; tp_subclasses is a list of weak references,
2560 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002561
Guido van Rossum048eb752001-10-02 21:24:57 +00002562 return 0;
2563}
2564
2565static int
2566type_clear(PyTypeObject *type)
2567{
Guido van Rossuma3862092002-06-10 15:24:42 +00002568 /* Because of type_is_gc(), the collector only calls this
2569 for heaptypes. */
2570 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002571
Guido van Rossuma3862092002-06-10 15:24:42 +00002572 /* The only field we need to clear is tp_mro, which is part of a
2573 hard cycle (its first element is the class itself) that won't
2574 be broken otherwise (it's a tuple and tuples don't have a
2575 tp_clear handler). None of the other fields need to be
2576 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002577
Guido van Rossuma3862092002-06-10 15:24:42 +00002578 tp_dict:
2579 It is a dict, so the collector will call its tp_clear.
2580
2581 tp_cache:
2582 Not used; if it were, it would be a dict.
2583
2584 tp_bases, tp_base:
2585 If these are involved in a cycle, there must be at least
2586 one other, mutable object in the cycle, e.g. a base
2587 class's dict; the cycle will be broken that way.
2588
2589 tp_subclasses:
2590 A list of weak references can't be part of a cycle; and
2591 lists have their own tp_clear.
2592
Guido van Rossume5c691a2003-03-07 15:13:17 +00002593 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002594 A tuple of strings can't be part of a cycle.
2595 */
2596
Thomas Woutersedf17d82006-04-15 17:28:34 +00002597 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002598
2599 return 0;
2600}
2601
2602static int
2603type_is_gc(PyTypeObject *type)
2604{
2605 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2606}
2607
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002608PyTypeObject PyType_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002609 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002610 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002611 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002612 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002613 (destructor)type_dealloc, /* tp_dealloc */
2614 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002615 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002616 0, /* tp_setattr */
2617 type_compare, /* tp_compare */
2618 (reprfunc)type_repr, /* tp_repr */
2619 0, /* tp_as_number */
2620 0, /* tp_as_sequence */
2621 0, /* tp_as_mapping */
2622 (hashfunc)_Py_HashPointer, /* tp_hash */
2623 (ternaryfunc)type_call, /* tp_call */
2624 0, /* tp_str */
2625 (getattrofunc)type_getattro, /* tp_getattro */
2626 (setattrofunc)type_setattro, /* tp_setattro */
2627 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002628 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002629 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002630 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002631 (traverseproc)type_traverse, /* tp_traverse */
2632 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002633 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002634 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002635 0, /* tp_iter */
2636 0, /* tp_iternext */
2637 type_methods, /* tp_methods */
2638 type_members, /* tp_members */
2639 type_getsets, /* tp_getset */
2640 0, /* tp_base */
2641 0, /* tp_dict */
2642 0, /* tp_descr_get */
2643 0, /* tp_descr_set */
2644 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumf102e242007-03-23 18:53:03 +00002645 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002646 0, /* tp_alloc */
2647 type_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002648 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002649 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002650};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002651
2652
2653/* The base type of all types (eventually)... except itself. */
2654
Guido van Rossum143b5642007-03-23 04:58:42 +00002655/* You may wonder why object.__new__() only complains about arguments
2656 when object.__init__() is not overridden, and vice versa.
2657
2658 Consider the use cases:
2659
2660 1. When neither is overridden, we want to hear complaints about
2661 excess (i.e., any) arguments, since their presence could
2662 indicate there's a bug.
2663
2664 2. When defining an Immutable type, we are likely to override only
2665 __new__(), since __init__() is called too late to initialize an
2666 Immutable object. Since __new__() defines the signature for the
2667 type, it would be a pain to have to override __init__() just to
2668 stop it from complaining about excess arguments.
2669
2670 3. When defining a Mutable type, we are likely to override only
2671 __init__(). So here the converse reasoning applies: we don't
2672 want to have to override __new__() just to stop it from
2673 complaining.
2674
2675 4. When __init__() is overridden, and the subclass __init__() calls
2676 object.__init__(), the latter should complain about excess
2677 arguments; ditto for __new__().
2678
2679 Use cases 2 and 3 make it unattractive to unconditionally check for
2680 excess arguments. The best solution that addresses all four use
2681 cases is as follows: __init__() complains about excess arguments
2682 unless __new__() is overridden and __init__() is not overridden
2683 (IOW, if __init__() is overridden or __new__() is not overridden);
2684 symmetrically, __new__() complains about excess arguments unless
2685 __init__() is overridden and __new__() is not overridden
2686 (IOW, if __new__() is overridden or __init__() is not overridden).
2687
2688 However, for backwards compatibility, this breaks too much code.
2689 Therefore, in 2.6, we'll *warn* about excess arguments when both
2690 methods are overridden; for all other cases we'll use the above
2691 rules.
2692
2693*/
2694
2695/* Forward */
2696static PyObject *
2697object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2698
2699static int
2700excess_args(PyObject *args, PyObject *kwds)
2701{
2702 return PyTuple_GET_SIZE(args) ||
2703 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2704}
2705
Tim Peters6d6c1a32001-08-02 04:15:00 +00002706static int
2707object_init(PyObject *self, PyObject *args, PyObject *kwds)
2708{
Guido van Rossum143b5642007-03-23 04:58:42 +00002709 int err = 0;
2710 if (excess_args(args, kwds)) {
Christian Heimese93237d2007-12-19 02:37:44 +00002711 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum143b5642007-03-23 04:58:42 +00002712 if (type->tp_init != object_init &&
2713 type->tp_new != object_new)
2714 {
2715 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2716 "object.__init__() takes no parameters",
2717 1);
2718 }
2719 else if (type->tp_init != object_init ||
2720 type->tp_new == object_new)
2721 {
2722 PyErr_SetString(PyExc_TypeError,
2723 "object.__init__() takes no parameters");
2724 err = -1;
2725 }
2726 }
2727 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002728}
2729
Guido van Rossum298e4212003-02-13 16:30:16 +00002730static PyObject *
2731object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2732{
Guido van Rossum143b5642007-03-23 04:58:42 +00002733 int err = 0;
2734 if (excess_args(args, kwds)) {
2735 if (type->tp_new != object_new &&
2736 type->tp_init != object_init)
2737 {
2738 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2739 "object.__new__() takes no parameters",
2740 1);
2741 }
2742 else if (type->tp_new != object_new ||
2743 type->tp_init == object_init)
2744 {
2745 PyErr_SetString(PyExc_TypeError,
2746 "object.__new__() takes no parameters");
2747 err = -1;
2748 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002749 }
Guido van Rossum143b5642007-03-23 04:58:42 +00002750 if (err < 0)
2751 return NULL;
Guido van Rossum298e4212003-02-13 16:30:16 +00002752 return type->tp_alloc(type, 0);
2753}
2754
Tim Peters6d6c1a32001-08-02 04:15:00 +00002755static void
2756object_dealloc(PyObject *self)
2757{
Christian Heimese93237d2007-12-19 02:37:44 +00002758 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002759}
2760
Guido van Rossum8e248182001-08-12 05:17:56 +00002761static PyObject *
2762object_repr(PyObject *self)
2763{
Guido van Rossum76e69632001-08-16 18:52:43 +00002764 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002765 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002766
Christian Heimese93237d2007-12-19 02:37:44 +00002767 type = Py_TYPE(self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002768 mod = type_module(type, NULL);
2769 if (mod == NULL)
2770 PyErr_Clear();
2771 else if (!PyString_Check(mod)) {
2772 Py_DECREF(mod);
2773 mod = NULL;
2774 }
2775 name = type_name(type, NULL);
2776 if (name == NULL)
2777 return NULL;
2778 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002779 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002780 PyString_AS_STRING(mod),
2781 PyString_AS_STRING(name),
2782 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002783 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002784 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002785 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002786 Py_XDECREF(mod);
2787 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002788 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002789}
2790
Guido van Rossumb8f63662001-08-15 23:57:02 +00002791static PyObject *
2792object_str(PyObject *self)
2793{
2794 unaryfunc f;
2795
Christian Heimese93237d2007-12-19 02:37:44 +00002796 f = Py_TYPE(self)->tp_repr;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002797 if (f == NULL)
2798 f = object_repr;
2799 return f(self);
2800}
2801
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002802static PyObject *
2803object_get_class(PyObject *self, void *closure)
2804{
Christian Heimese93237d2007-12-19 02:37:44 +00002805 Py_INCREF(Py_TYPE(self));
2806 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002807}
2808
2809static int
2810equiv_structs(PyTypeObject *a, PyTypeObject *b)
2811{
2812 return a == b ||
2813 (a != NULL &&
2814 b != NULL &&
2815 a->tp_basicsize == b->tp_basicsize &&
2816 a->tp_itemsize == b->tp_itemsize &&
2817 a->tp_dictoffset == b->tp_dictoffset &&
2818 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2819 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2820 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2821}
2822
2823static int
2824same_slots_added(PyTypeObject *a, PyTypeObject *b)
2825{
2826 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002827 Py_ssize_t size;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002828 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002829
2830 if (base != b->tp_base)
2831 return 0;
2832 if (equiv_structs(a, base) && equiv_structs(b, base))
2833 return 1;
2834 size = base->tp_basicsize;
2835 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2836 size += sizeof(PyObject *);
2837 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2838 size += sizeof(PyObject *);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002839
2840 /* Check slots compliance */
2841 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2842 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2843 if (slots_a && slots_b) {
2844 if (PyObject_Compare(slots_a, slots_b) != 0)
2845 return 0;
2846 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2847 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002848 return size == a->tp_basicsize && size == b->tp_basicsize;
2849}
2850
2851static int
Anthony Baxtera6286212006-04-11 07:42:36 +00002852compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002853{
2854 PyTypeObject *newbase, *oldbase;
2855
Anthony Baxtera6286212006-04-11 07:42:36 +00002856 if (newto->tp_dealloc != oldto->tp_dealloc ||
2857 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002858 {
2859 PyErr_Format(PyExc_TypeError,
2860 "%s assignment: "
2861 "'%s' deallocator differs from '%s'",
2862 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002863 newto->tp_name,
2864 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002865 return 0;
2866 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002867 newbase = newto;
2868 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002869 while (equiv_structs(newbase, newbase->tp_base))
2870 newbase = newbase->tp_base;
2871 while (equiv_structs(oldbase, oldbase->tp_base))
2872 oldbase = oldbase->tp_base;
2873 if (newbase != oldbase &&
2874 (newbase->tp_base != oldbase->tp_base ||
2875 !same_slots_added(newbase, oldbase))) {
2876 PyErr_Format(PyExc_TypeError,
2877 "%s assignment: "
2878 "'%s' object layout differs from '%s'",
2879 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002880 newto->tp_name,
2881 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002882 return 0;
2883 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002884
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002885 return 1;
2886}
2887
2888static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002889object_set_class(PyObject *self, PyObject *value, void *closure)
2890{
Christian Heimese93237d2007-12-19 02:37:44 +00002891 PyTypeObject *oldto = Py_TYPE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00002892 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002893
Guido van Rossumb6b89422002-04-15 01:03:30 +00002894 if (value == NULL) {
2895 PyErr_SetString(PyExc_TypeError,
2896 "can't delete __class__ attribute");
2897 return -1;
2898 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002899 if (!PyType_Check(value)) {
2900 PyErr_Format(PyExc_TypeError,
2901 "__class__ must be set to new-style class, not '%s' object",
Christian Heimese93237d2007-12-19 02:37:44 +00002902 Py_TYPE(value)->tp_name);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002903 return -1;
2904 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002905 newto = (PyTypeObject *)value;
2906 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2907 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002908 {
2909 PyErr_Format(PyExc_TypeError,
2910 "__class__ assignment: only for heap types");
2911 return -1;
2912 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002913 if (compatible_for_assignment(newto, oldto, "__class__")) {
2914 Py_INCREF(newto);
Christian Heimese93237d2007-12-19 02:37:44 +00002915 Py_TYPE(self) = newto;
Anthony Baxtera6286212006-04-11 07:42:36 +00002916 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002917 return 0;
2918 }
2919 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002920 return -1;
2921 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002922}
2923
2924static PyGetSetDef object_getsets[] = {
2925 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002926 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002927 {0}
2928};
2929
Guido van Rossumc53f0092003-02-18 22:05:12 +00002930
Guido van Rossum036f9992003-02-21 22:02:54 +00002931/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2932 We fall back to helpers in copy_reg for:
2933 - pickle protocols < 2
2934 - calculating the list of slot names (done only once per class)
2935 - the __newobj__ function (which is used as a token but never called)
2936*/
2937
2938static PyObject *
2939import_copy_reg(void)
2940{
2941 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002942
2943 if (!copy_reg_str) {
2944 copy_reg_str = PyString_InternFromString("copy_reg");
2945 if (copy_reg_str == NULL)
2946 return NULL;
2947 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002948
2949 return PyImport_Import(copy_reg_str);
2950}
2951
2952static PyObject *
2953slotnames(PyObject *cls)
2954{
2955 PyObject *clsdict;
2956 PyObject *copy_reg;
2957 PyObject *slotnames;
2958
2959 if (!PyType_Check(cls)) {
2960 Py_INCREF(Py_None);
2961 return Py_None;
2962 }
2963
2964 clsdict = ((PyTypeObject *)cls)->tp_dict;
2965 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002966 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002967 Py_INCREF(slotnames);
2968 return slotnames;
2969 }
2970
2971 copy_reg = import_copy_reg();
2972 if (copy_reg == NULL)
2973 return NULL;
2974
2975 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2976 Py_DECREF(copy_reg);
2977 if (slotnames != NULL &&
2978 slotnames != Py_None &&
2979 !PyList_Check(slotnames))
2980 {
2981 PyErr_SetString(PyExc_TypeError,
2982 "copy_reg._slotnames didn't return a list or None");
2983 Py_DECREF(slotnames);
2984 slotnames = NULL;
2985 }
2986
2987 return slotnames;
2988}
2989
2990static PyObject *
2991reduce_2(PyObject *obj)
2992{
2993 PyObject *cls, *getnewargs;
2994 PyObject *args = NULL, *args2 = NULL;
2995 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2996 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2997 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002998 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002999
3000 cls = PyObject_GetAttrString(obj, "__class__");
3001 if (cls == NULL)
3002 return NULL;
3003
3004 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
3005 if (getnewargs != NULL) {
3006 args = PyObject_CallObject(getnewargs, NULL);
3007 Py_DECREF(getnewargs);
3008 if (args != NULL && !PyTuple_Check(args)) {
Georg Brandlccff7852006-06-18 22:17:29 +00003009 PyErr_Format(PyExc_TypeError,
3010 "__getnewargs__ should return a tuple, "
Christian Heimese93237d2007-12-19 02:37:44 +00003011 "not '%.200s'", Py_TYPE(args)->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00003012 goto end;
3013 }
3014 }
3015 else {
3016 PyErr_Clear();
3017 args = PyTuple_New(0);
3018 }
3019 if (args == NULL)
3020 goto end;
3021
3022 getstate = PyObject_GetAttrString(obj, "__getstate__");
3023 if (getstate != NULL) {
3024 state = PyObject_CallObject(getstate, NULL);
3025 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00003026 if (state == NULL)
3027 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003028 }
3029 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00003030 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00003031 state = PyObject_GetAttrString(obj, "__dict__");
3032 if (state == NULL) {
3033 PyErr_Clear();
3034 state = Py_None;
3035 Py_INCREF(state);
3036 }
3037 names = slotnames(cls);
3038 if (names == NULL)
3039 goto end;
3040 if (names != Py_None) {
3041 assert(PyList_Check(names));
3042 slots = PyDict_New();
3043 if (slots == NULL)
3044 goto end;
3045 n = 0;
3046 /* Can't pre-compute the list size; the list
3047 is stored on the class so accessible to other
3048 threads, which may be run by DECREF */
3049 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3050 PyObject *name, *value;
3051 name = PyList_GET_ITEM(names, i);
3052 value = PyObject_GetAttr(obj, name);
3053 if (value == NULL)
3054 PyErr_Clear();
3055 else {
3056 int err = PyDict_SetItem(slots, name,
3057 value);
3058 Py_DECREF(value);
3059 if (err)
3060 goto end;
3061 n++;
3062 }
3063 }
3064 if (n) {
3065 state = Py_BuildValue("(NO)", state, slots);
3066 if (state == NULL)
3067 goto end;
3068 }
3069 }
3070 }
3071
3072 if (!PyList_Check(obj)) {
3073 listitems = Py_None;
3074 Py_INCREF(listitems);
3075 }
3076 else {
3077 listitems = PyObject_GetIter(obj);
3078 if (listitems == NULL)
3079 goto end;
3080 }
3081
3082 if (!PyDict_Check(obj)) {
3083 dictitems = Py_None;
3084 Py_INCREF(dictitems);
3085 }
3086 else {
3087 dictitems = PyObject_CallMethod(obj, "iteritems", "");
3088 if (dictitems == NULL)
3089 goto end;
3090 }
3091
3092 copy_reg = import_copy_reg();
3093 if (copy_reg == NULL)
3094 goto end;
3095 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
3096 if (newobj == NULL)
3097 goto end;
3098
3099 n = PyTuple_GET_SIZE(args);
3100 args2 = PyTuple_New(n+1);
3101 if (args2 == NULL)
3102 goto end;
3103 PyTuple_SET_ITEM(args2, 0, cls);
3104 cls = NULL;
3105 for (i = 0; i < n; i++) {
3106 PyObject *v = PyTuple_GET_ITEM(args, i);
3107 Py_INCREF(v);
3108 PyTuple_SET_ITEM(args2, i+1, v);
3109 }
3110
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003111 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003112
3113 end:
3114 Py_XDECREF(cls);
3115 Py_XDECREF(args);
3116 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00003117 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00003118 Py_XDECREF(state);
3119 Py_XDECREF(names);
3120 Py_XDECREF(listitems);
3121 Py_XDECREF(dictitems);
3122 Py_XDECREF(copy_reg);
3123 Py_XDECREF(newobj);
3124 return res;
3125}
3126
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003127/*
3128 * There were two problems when object.__reduce__ and object.__reduce_ex__
3129 * were implemented in the same function:
3130 * - trying to pickle an object with a custom __reduce__ method that
3131 * fell back to object.__reduce__ in certain circumstances led to
3132 * infinite recursion at Python level and eventual RuntimeError.
3133 * - Pickling objects that lied about their type by overwriting the
3134 * __class__ descriptor could lead to infinite recursion at C level
3135 * and eventual segfault.
3136 *
3137 * Because of backwards compatibility, the two methods still have to
3138 * behave in the same way, even if this is not required by the pickle
3139 * protocol. This common functionality was moved to the _common_reduce
3140 * function.
3141 */
3142static PyObject *
3143_common_reduce(PyObject *self, int proto)
3144{
3145 PyObject *copy_reg, *res;
3146
3147 if (proto >= 2)
3148 return reduce_2(self);
3149
3150 copy_reg = import_copy_reg();
3151 if (!copy_reg)
3152 return NULL;
3153
3154 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
3155 Py_DECREF(copy_reg);
3156
3157 return res;
3158}
3159
3160static PyObject *
3161object_reduce(PyObject *self, PyObject *args)
3162{
3163 int proto = 0;
3164
3165 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3166 return NULL;
3167
3168 return _common_reduce(self, proto);
3169}
3170
Guido van Rossum036f9992003-02-21 22:02:54 +00003171static PyObject *
3172object_reduce_ex(PyObject *self, PyObject *args)
3173{
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003174 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003175 int proto = 0;
3176
3177 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3178 return NULL;
3179
3180 reduce = PyObject_GetAttrString(self, "__reduce__");
3181 if (reduce == NULL)
3182 PyErr_Clear();
3183 else {
3184 PyObject *cls, *clsreduce, *objreduce;
3185 int override;
3186 cls = PyObject_GetAttrString(self, "__class__");
3187 if (cls == NULL) {
3188 Py_DECREF(reduce);
3189 return NULL;
3190 }
3191 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3192 Py_DECREF(cls);
3193 if (clsreduce == NULL) {
3194 Py_DECREF(reduce);
3195 return NULL;
3196 }
3197 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3198 "__reduce__");
3199 override = (clsreduce != objreduce);
3200 Py_DECREF(clsreduce);
3201 if (override) {
3202 res = PyObject_CallObject(reduce, NULL);
3203 Py_DECREF(reduce);
3204 return res;
3205 }
3206 else
3207 Py_DECREF(reduce);
3208 }
3209
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003210 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003211}
3212
Eric Smitha9f7d622008-02-17 19:46:49 +00003213/*
3214 from PEP 3101, this code implements:
3215
3216 class object:
3217 def __format__(self, format_spec):
3218 if isinstance(format_spec, str):
3219 return format(str(self), format_spec)
3220 elif isinstance(format_spec, unicode):
3221 return format(unicode(self), format_spec)
3222*/
3223static PyObject *
3224object_format(PyObject *self, PyObject *args)
3225{
3226 PyObject *format_spec;
3227 PyObject *self_as_str = NULL;
3228 PyObject *result = NULL;
3229 PyObject *format_meth = NULL;
3230
3231 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3232 return NULL;
3233 if (PyUnicode_Check(format_spec)) {
3234 self_as_str = PyObject_Unicode(self);
3235 } else if (PyString_Check(format_spec)) {
3236 self_as_str = PyObject_Str(self);
3237 } else {
3238 PyErr_SetString(PyExc_TypeError, "argument to __format__ must be unicode or str");
3239 return NULL;
3240 }
3241
3242 if (self_as_str != NULL) {
3243 /* find the format function */
3244 format_meth = PyObject_GetAttrString(self_as_str, "__format__");
3245 if (format_meth != NULL) {
3246 /* and call it */
3247 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
3248 }
3249 }
3250
3251 Py_XDECREF(self_as_str);
3252 Py_XDECREF(format_meth);
3253
3254 return result;
3255}
3256
Guido van Rossum3926a632001-09-25 16:25:58 +00003257static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00003258 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3259 PyDoc_STR("helper for pickle")},
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003260 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003261 PyDoc_STR("helper for pickle")},
Eric Smitha9f7d622008-02-17 19:46:49 +00003262 {"__format__", object_format, METH_VARARGS,
3263 PyDoc_STR("default object formatter")},
Guido van Rossum3926a632001-09-25 16:25:58 +00003264 {0}
3265};
3266
Guido van Rossum036f9992003-02-21 22:02:54 +00003267
Tim Peters6d6c1a32001-08-02 04:15:00 +00003268PyTypeObject PyBaseObject_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00003269 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003270 "object", /* tp_name */
3271 sizeof(PyObject), /* tp_basicsize */
3272 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003273 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003274 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003275 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003276 0, /* tp_setattr */
3277 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003278 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003279 0, /* tp_as_number */
3280 0, /* tp_as_sequence */
3281 0, /* tp_as_mapping */
Guido van Rossum64c06e32007-11-22 00:55:51 +00003282 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003283 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003284 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003285 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003286 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003287 0, /* tp_as_buffer */
3288 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003289 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003290 0, /* tp_traverse */
3291 0, /* tp_clear */
3292 0, /* tp_richcompare */
3293 0, /* tp_weaklistoffset */
3294 0, /* tp_iter */
3295 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00003296 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003297 0, /* tp_members */
3298 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003299 0, /* tp_base */
3300 0, /* tp_dict */
3301 0, /* tp_descr_get */
3302 0, /* tp_descr_set */
3303 0, /* tp_dictoffset */
3304 object_init, /* tp_init */
3305 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003306 object_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003307 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003308};
3309
3310
3311/* Initialize the __dict__ in a type object */
3312
3313static int
3314add_methods(PyTypeObject *type, PyMethodDef *meth)
3315{
Guido van Rossum687ae002001-10-15 22:03:32 +00003316 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003317
3318 for (; meth->ml_name != NULL; meth++) {
3319 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003320 if (PyDict_GetItemString(dict, meth->ml_name) &&
3321 !(meth->ml_flags & METH_COEXIST))
3322 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003323 if (meth->ml_flags & METH_CLASS) {
3324 if (meth->ml_flags & METH_STATIC) {
3325 PyErr_SetString(PyExc_ValueError,
3326 "method cannot be both class and static");
3327 return -1;
3328 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003329 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003330 }
3331 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003332 PyObject *cfunc = PyCFunction_New(meth, NULL);
3333 if (cfunc == NULL)
3334 return -1;
3335 descr = PyStaticMethod_New(cfunc);
3336 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003337 }
3338 else {
3339 descr = PyDescr_NewMethod(type, meth);
3340 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003341 if (descr == NULL)
3342 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003343 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003344 return -1;
3345 Py_DECREF(descr);
3346 }
3347 return 0;
3348}
3349
3350static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003351add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003352{
Guido van Rossum687ae002001-10-15 22:03:32 +00003353 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003354
3355 for (; memb->name != NULL; memb++) {
3356 PyObject *descr;
3357 if (PyDict_GetItemString(dict, memb->name))
3358 continue;
3359 descr = PyDescr_NewMember(type, memb);
3360 if (descr == NULL)
3361 return -1;
3362 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3363 return -1;
3364 Py_DECREF(descr);
3365 }
3366 return 0;
3367}
3368
3369static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003370add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003371{
Guido van Rossum687ae002001-10-15 22:03:32 +00003372 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003373
3374 for (; gsp->name != NULL; gsp++) {
3375 PyObject *descr;
3376 if (PyDict_GetItemString(dict, gsp->name))
3377 continue;
3378 descr = PyDescr_NewGetSet(type, gsp);
3379
3380 if (descr == NULL)
3381 return -1;
3382 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3383 return -1;
3384 Py_DECREF(descr);
3385 }
3386 return 0;
3387}
3388
Guido van Rossum13d52f02001-08-10 21:24:08 +00003389static void
3390inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003391{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003392 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003393
Guido van Rossum13d52f02001-08-10 21:24:08 +00003394 /* Special flag magic */
3395 if (!type->tp_as_buffer && base->tp_as_buffer) {
3396 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
3397 type->tp_flags |=
3398 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
3399 }
3400 if (!type->tp_as_sequence && base->tp_as_sequence) {
3401 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3402 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3403 }
3404 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3405 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3406 if ((!type->tp_as_number && base->tp_as_number) ||
3407 (!type->tp_as_sequence && base->tp_as_sequence)) {
3408 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3409 if (!type->tp_as_number && !type->tp_as_sequence) {
3410 type->tp_flags |= base->tp_flags &
3411 Py_TPFLAGS_HAVE_INPLACEOPS;
3412 }
3413 }
3414 /* Wow */
3415 }
3416 if (!type->tp_as_number && base->tp_as_number) {
3417 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3418 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3419 }
3420
3421 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003422 oldsize = base->tp_basicsize;
3423 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3424 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3425 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003426 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3427 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003428 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003429 if (type->tp_traverse == NULL)
3430 type->tp_traverse = base->tp_traverse;
3431 if (type->tp_clear == NULL)
3432 type->tp_clear = base->tp_clear;
3433 }
3434 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00003435 /* The condition below could use some explanation.
3436 It appears that tp_new is not inherited for static types
3437 whose base class is 'object'; this seems to be a precaution
3438 so that old extension types don't suddenly become
3439 callable (object.__new__ wouldn't insure the invariants
3440 that the extension type's own factory function ensures).
3441 Heap types, of course, are under our control, so they do
3442 inherit tp_new; static extension types that specify some
3443 other built-in type as the default are considered
3444 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003445 if (base != &PyBaseObject_Type ||
3446 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3447 if (type->tp_new == NULL)
3448 type->tp_new = base->tp_new;
3449 }
3450 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003451 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003452
3453 /* Copy other non-function slots */
3454
3455#undef COPYVAL
3456#define COPYVAL(SLOT) \
3457 if (type->SLOT == 0) type->SLOT = base->SLOT
3458
3459 COPYVAL(tp_itemsize);
3460 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3461 COPYVAL(tp_weaklistoffset);
3462 }
3463 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3464 COPYVAL(tp_dictoffset);
3465 }
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003466
3467 /* Setup fast subclass flags */
3468 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3469 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3470 else if (PyType_IsSubtype(base, &PyType_Type))
3471 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3472 else if (PyType_IsSubtype(base, &PyInt_Type))
3473 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3474 else if (PyType_IsSubtype(base, &PyLong_Type))
3475 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3476 else if (PyType_IsSubtype(base, &PyString_Type))
3477 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003478#ifdef Py_USING_UNICODE
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003479 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3480 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003481#endif
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003482 else if (PyType_IsSubtype(base, &PyTuple_Type))
3483 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3484 else if (PyType_IsSubtype(base, &PyList_Type))
3485 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3486 else if (PyType_IsSubtype(base, &PyDict_Type))
3487 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003488}
3489
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003490static char *hash_name_op[] = {
3491 "__eq__",
3492 "__cmp__",
3493 "__hash__",
3494 NULL
Guido van Rossum64c06e32007-11-22 00:55:51 +00003495};
3496
3497static int
3498overrides_hash(PyTypeObject *type)
3499{
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003500 char **p;
Guido van Rossum64c06e32007-11-22 00:55:51 +00003501 PyObject *dict = type->tp_dict;
3502
3503 assert(dict != NULL);
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003504 for (p = hash_name_op; *p; p++) {
3505 if (PyDict_GetItemString(dict, *p) != NULL)
Guido van Rossum64c06e32007-11-22 00:55:51 +00003506 return 1;
3507 }
3508 return 0;
3509}
3510
Guido van Rossum13d52f02001-08-10 21:24:08 +00003511static void
3512inherit_slots(PyTypeObject *type, PyTypeObject *base)
3513{
3514 PyTypeObject *basebase;
3515
3516#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003517#undef COPYSLOT
3518#undef COPYNUM
3519#undef COPYSEQ
3520#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003521#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003522
3523#define SLOTDEFINED(SLOT) \
3524 (base->SLOT != 0 && \
3525 (basebase == NULL || base->SLOT != basebase->SLOT))
3526
Tim Peters6d6c1a32001-08-02 04:15:00 +00003527#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003528 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003529
3530#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3531#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3532#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003533#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003534
Guido van Rossum13d52f02001-08-10 21:24:08 +00003535 /* This won't inherit indirect slots (from tp_as_number etc.)
3536 if type doesn't provide the space. */
3537
3538 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3539 basebase = base->tp_base;
3540 if (basebase->tp_as_number == NULL)
3541 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003542 COPYNUM(nb_add);
3543 COPYNUM(nb_subtract);
3544 COPYNUM(nb_multiply);
3545 COPYNUM(nb_divide);
3546 COPYNUM(nb_remainder);
3547 COPYNUM(nb_divmod);
3548 COPYNUM(nb_power);
3549 COPYNUM(nb_negative);
3550 COPYNUM(nb_positive);
3551 COPYNUM(nb_absolute);
3552 COPYNUM(nb_nonzero);
3553 COPYNUM(nb_invert);
3554 COPYNUM(nb_lshift);
3555 COPYNUM(nb_rshift);
3556 COPYNUM(nb_and);
3557 COPYNUM(nb_xor);
3558 COPYNUM(nb_or);
3559 COPYNUM(nb_coerce);
3560 COPYNUM(nb_int);
3561 COPYNUM(nb_long);
3562 COPYNUM(nb_float);
3563 COPYNUM(nb_oct);
3564 COPYNUM(nb_hex);
3565 COPYNUM(nb_inplace_add);
3566 COPYNUM(nb_inplace_subtract);
3567 COPYNUM(nb_inplace_multiply);
3568 COPYNUM(nb_inplace_divide);
3569 COPYNUM(nb_inplace_remainder);
3570 COPYNUM(nb_inplace_power);
3571 COPYNUM(nb_inplace_lshift);
3572 COPYNUM(nb_inplace_rshift);
3573 COPYNUM(nb_inplace_and);
3574 COPYNUM(nb_inplace_xor);
3575 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003576 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3577 COPYNUM(nb_true_divide);
3578 COPYNUM(nb_floor_divide);
3579 COPYNUM(nb_inplace_true_divide);
3580 COPYNUM(nb_inplace_floor_divide);
3581 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003582 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3583 COPYNUM(nb_index);
3584 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003585 }
3586
Guido van Rossum13d52f02001-08-10 21:24:08 +00003587 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3588 basebase = base->tp_base;
3589 if (basebase->tp_as_sequence == NULL)
3590 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003591 COPYSEQ(sq_length);
3592 COPYSEQ(sq_concat);
3593 COPYSEQ(sq_repeat);
3594 COPYSEQ(sq_item);
3595 COPYSEQ(sq_slice);
3596 COPYSEQ(sq_ass_item);
3597 COPYSEQ(sq_ass_slice);
3598 COPYSEQ(sq_contains);
3599 COPYSEQ(sq_inplace_concat);
3600 COPYSEQ(sq_inplace_repeat);
3601 }
3602
Guido van Rossum13d52f02001-08-10 21:24:08 +00003603 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3604 basebase = base->tp_base;
3605 if (basebase->tp_as_mapping == NULL)
3606 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003607 COPYMAP(mp_length);
3608 COPYMAP(mp_subscript);
3609 COPYMAP(mp_ass_subscript);
3610 }
3611
Tim Petersfc57ccb2001-10-12 02:38:24 +00003612 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3613 basebase = base->tp_base;
3614 if (basebase->tp_as_buffer == NULL)
3615 basebase = NULL;
3616 COPYBUF(bf_getreadbuffer);
3617 COPYBUF(bf_getwritebuffer);
3618 COPYBUF(bf_getsegcount);
3619 COPYBUF(bf_getcharbuffer);
3620 }
3621
Guido van Rossum13d52f02001-08-10 21:24:08 +00003622 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003623
Tim Peters6d6c1a32001-08-02 04:15:00 +00003624 COPYSLOT(tp_dealloc);
3625 COPYSLOT(tp_print);
3626 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3627 type->tp_getattr = base->tp_getattr;
3628 type->tp_getattro = base->tp_getattro;
3629 }
3630 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3631 type->tp_setattr = base->tp_setattr;
3632 type->tp_setattro = base->tp_setattro;
3633 }
3634 /* tp_compare see tp_richcompare */
3635 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003636 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003637 COPYSLOT(tp_call);
3638 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003639 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003640 if (type->tp_compare == NULL &&
3641 type->tp_richcompare == NULL &&
Guido van Rossum64c06e32007-11-22 00:55:51 +00003642 type->tp_hash == NULL &&
3643 !overrides_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003644 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003645 type->tp_compare = base->tp_compare;
3646 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003647 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003648 }
3649 }
3650 else {
3651 COPYSLOT(tp_compare);
3652 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003653 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3654 COPYSLOT(tp_iter);
3655 COPYSLOT(tp_iternext);
3656 }
3657 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3658 COPYSLOT(tp_descr_get);
3659 COPYSLOT(tp_descr_set);
3660 COPYSLOT(tp_dictoffset);
3661 COPYSLOT(tp_init);
3662 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003663 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003664 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3665 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3666 /* They agree about gc. */
3667 COPYSLOT(tp_free);
3668 }
3669 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3670 type->tp_free == NULL &&
3671 base->tp_free == _PyObject_Del) {
3672 /* A bit of magic to plug in the correct default
3673 * tp_free function when a derived class adds gc,
3674 * didn't define tp_free, and the base uses the
3675 * default non-gc tp_free.
3676 */
3677 type->tp_free = PyObject_GC_Del;
3678 }
3679 /* else they didn't agree about gc, and there isn't something
3680 * obvious to be done -- the type is on its own.
3681 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003682 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003683}
3684
Jeremy Hylton938ace62002-07-17 16:30:39 +00003685static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003686
Tim Peters6d6c1a32001-08-02 04:15:00 +00003687int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003688PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003689{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003690 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003691 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003692 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693
Guido van Rossumcab05802002-06-10 15:29:03 +00003694 if (type->tp_flags & Py_TPFLAGS_READY) {
3695 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003696 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003697 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003698 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003699
3700 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003701
Tim Peters36eb4df2003-03-23 03:33:13 +00003702#ifdef Py_TRACE_REFS
3703 /* PyType_Ready is the closest thing we have to a choke point
3704 * for type objects, so is the best place I can think of to try
3705 * to get type objects into the doubly-linked list of all objects.
3706 * Still, not all type objects go thru PyType_Ready.
3707 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003708 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003709#endif
3710
Tim Peters6d6c1a32001-08-02 04:15:00 +00003711 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3712 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003713 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003714 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003715 Py_INCREF(base);
3716 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003717
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003718 /* Now the only way base can still be NULL is if type is
3719 * &PyBaseObject_Type.
3720 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003721
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003722 /* Initialize the base class */
3723 if (base && base->tp_dict == NULL) {
3724 if (PyType_Ready(base) < 0)
3725 goto error;
3726 }
3727
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003728 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003729 compilable separately on Windows can call PyType_Ready() instead of
3730 initializing the ob_type field of their type objects. */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003731 /* The test for base != NULL is really unnecessary, since base is only
3732 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3733 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3734 know that. */
Christian Heimese93237d2007-12-19 02:37:44 +00003735 if (Py_TYPE(type) == NULL && base != NULL)
3736 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003737
Tim Peters6d6c1a32001-08-02 04:15:00 +00003738 /* Initialize tp_bases */
3739 bases = type->tp_bases;
3740 if (bases == NULL) {
3741 if (base == NULL)
3742 bases = PyTuple_New(0);
3743 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003744 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003745 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003746 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003747 type->tp_bases = bases;
3748 }
3749
Guido van Rossum687ae002001-10-15 22:03:32 +00003750 /* Initialize tp_dict */
3751 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003752 if (dict == NULL) {
3753 dict = PyDict_New();
3754 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003755 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003756 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003757 }
3758
Guido van Rossum687ae002001-10-15 22:03:32 +00003759 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003760 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003761 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003762 if (type->tp_methods != NULL) {
3763 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003764 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003765 }
3766 if (type->tp_members != NULL) {
3767 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003768 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003769 }
3770 if (type->tp_getset != NULL) {
3771 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003772 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003773 }
3774
Tim Peters6d6c1a32001-08-02 04:15:00 +00003775 /* Calculate method resolution order */
3776 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003777 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003778 }
3779
Guido van Rossum13d52f02001-08-10 21:24:08 +00003780 /* Inherit special flags from dominant base */
3781 if (type->tp_base != NULL)
3782 inherit_special(type, type->tp_base);
3783
Tim Peters6d6c1a32001-08-02 04:15:00 +00003784 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003785 bases = type->tp_mro;
3786 assert(bases != NULL);
3787 assert(PyTuple_Check(bases));
3788 n = PyTuple_GET_SIZE(bases);
3789 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003790 PyObject *b = PyTuple_GET_ITEM(bases, i);
3791 if (PyType_Check(b))
3792 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003793 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003794
Tim Peters3cfe7542003-05-21 21:29:48 +00003795 /* Sanity check for tp_free. */
3796 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3797 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003798 /* This base class needs to call tp_free, but doesn't have
3799 * one, or its tp_free is for non-gc'ed objects.
3800 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003801 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3802 "gc and is a base type but has inappropriate "
3803 "tp_free slot",
3804 type->tp_name);
3805 goto error;
3806 }
3807
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003808 /* if the type dictionary doesn't contain a __doc__, set it from
3809 the tp_doc slot.
3810 */
3811 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3812 if (type->tp_doc != NULL) {
3813 PyObject *doc = PyString_FromString(type->tp_doc);
Neal Norwitze1fdb322006-07-21 05:32:28 +00003814 if (doc == NULL)
3815 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003816 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3817 Py_DECREF(doc);
3818 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003819 PyDict_SetItemString(type->tp_dict,
3820 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003821 }
3822 }
3823
Guido van Rossum64c06e32007-11-22 00:55:51 +00003824 /* Hack for tp_hash and __hash__.
3825 If after all that, tp_hash is still NULL, and __hash__ is not in
3826 tp_dict, set tp_dict['__hash__'] equal to None.
3827 This signals that __hash__ is not inherited.
3828 */
3829 if (type->tp_hash == NULL &&
3830 PyDict_GetItemString(type->tp_dict, "__hash__") == NULL &&
3831 PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3832 {
3833 goto error;
3834 }
3835
Guido van Rossum13d52f02001-08-10 21:24:08 +00003836 /* Some more special stuff */
3837 base = type->tp_base;
3838 if (base != NULL) {
3839 if (type->tp_as_number == NULL)
3840 type->tp_as_number = base->tp_as_number;
3841 if (type->tp_as_sequence == NULL)
3842 type->tp_as_sequence = base->tp_as_sequence;
3843 if (type->tp_as_mapping == NULL)
3844 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003845 if (type->tp_as_buffer == NULL)
3846 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003847 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003848
Guido van Rossum1c450732001-10-08 15:18:27 +00003849 /* Link into each base class's list of subclasses */
3850 bases = type->tp_bases;
3851 n = PyTuple_GET_SIZE(bases);
3852 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003853 PyObject *b = PyTuple_GET_ITEM(bases, i);
3854 if (PyType_Check(b) &&
3855 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003856 goto error;
3857 }
3858
Guido van Rossum13d52f02001-08-10 21:24:08 +00003859 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003860 assert(type->tp_dict != NULL);
3861 type->tp_flags =
3862 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003863 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003864
3865 error:
3866 type->tp_flags &= ~Py_TPFLAGS_READYING;
3867 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003868}
3869
Guido van Rossum1c450732001-10-08 15:18:27 +00003870static int
3871add_subclass(PyTypeObject *base, PyTypeObject *type)
3872{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003873 Py_ssize_t i;
3874 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00003875 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003876
3877 list = base->tp_subclasses;
3878 if (list == NULL) {
3879 base->tp_subclasses = list = PyList_New(0);
3880 if (list == NULL)
3881 return -1;
3882 }
3883 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00003884 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003885 i = PyList_GET_SIZE(list);
3886 while (--i >= 0) {
3887 ref = PyList_GET_ITEM(list, i);
3888 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003889 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00003890 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003891 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003892 result = PyList_Append(list, newobj);
3893 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003894 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003895}
3896
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003897static void
3898remove_subclass(PyTypeObject *base, PyTypeObject *type)
3899{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003900 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003901 PyObject *list, *ref;
3902
3903 list = base->tp_subclasses;
3904 if (list == NULL) {
3905 return;
3906 }
3907 assert(PyList_Check(list));
3908 i = PyList_GET_SIZE(list);
3909 while (--i >= 0) {
3910 ref = PyList_GET_ITEM(list, i);
3911 assert(PyWeakref_CheckRef(ref));
3912 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3913 /* this can't fail, right? */
3914 PySequence_DelItem(list, i);
3915 return;
3916 }
3917 }
3918}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003919
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003920static int
3921check_num_args(PyObject *ob, int n)
3922{
3923 if (!PyTuple_CheckExact(ob)) {
3924 PyErr_SetString(PyExc_SystemError,
3925 "PyArg_UnpackTuple() argument list is not a tuple");
3926 return 0;
3927 }
3928 if (n == PyTuple_GET_SIZE(ob))
3929 return 1;
3930 PyErr_Format(
3931 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003932 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003933 return 0;
3934}
3935
Tim Peters6d6c1a32001-08-02 04:15:00 +00003936/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3937
3938/* There's a wrapper *function* for each distinct function typedef used
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003939 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003940 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3941 Most tables have only one entry; the tables for binary operators have two
3942 entries, one regular and one with reversed arguments. */
3943
3944static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003945wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003946{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003947 lenfunc func = (lenfunc)wrapped;
3948 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003949
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003950 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003951 return NULL;
3952 res = (*func)(self);
3953 if (res == -1 && PyErr_Occurred())
3954 return NULL;
3955 return PyInt_FromLong((long)res);
3956}
3957
Tim Peters6d6c1a32001-08-02 04:15:00 +00003958static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003959wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3960{
3961 inquiry func = (inquiry)wrapped;
3962 int res;
3963
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003964 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003965 return NULL;
3966 res = (*func)(self);
3967 if (res == -1 && PyErr_Occurred())
3968 return NULL;
3969 return PyBool_FromLong((long)res);
3970}
3971
3972static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003973wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3974{
3975 binaryfunc func = (binaryfunc)wrapped;
3976 PyObject *other;
3977
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003978 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003979 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003980 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003981 return (*func)(self, other);
3982}
3983
3984static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003985wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3986{
3987 binaryfunc func = (binaryfunc)wrapped;
3988 PyObject *other;
3989
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003990 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003991 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003992 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003993 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003994 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003995 Py_INCREF(Py_NotImplemented);
3996 return Py_NotImplemented;
3997 }
3998 return (*func)(self, other);
3999}
4000
4001static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004002wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4003{
4004 binaryfunc func = (binaryfunc)wrapped;
4005 PyObject *other;
4006
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004007 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004008 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004009 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004010 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004011 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004012 Py_INCREF(Py_NotImplemented);
4013 return Py_NotImplemented;
4014 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004015 return (*func)(other, self);
4016}
4017
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004018static PyObject *
4019wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
4020{
4021 coercion func = (coercion)wrapped;
4022 PyObject *other, *res;
4023 int ok;
4024
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004025 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004026 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004027 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004028 ok = func(&self, &other);
4029 if (ok < 0)
4030 return NULL;
4031 if (ok > 0) {
4032 Py_INCREF(Py_NotImplemented);
4033 return Py_NotImplemented;
4034 }
4035 res = PyTuple_New(2);
4036 if (res == NULL) {
4037 Py_DECREF(self);
4038 Py_DECREF(other);
4039 return NULL;
4040 }
4041 PyTuple_SET_ITEM(res, 0, self);
4042 PyTuple_SET_ITEM(res, 1, other);
4043 return res;
4044}
4045
Tim Peters6d6c1a32001-08-02 04:15:00 +00004046static PyObject *
4047wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4048{
4049 ternaryfunc func = (ternaryfunc)wrapped;
4050 PyObject *other;
4051 PyObject *third = Py_None;
4052
4053 /* Note: This wrapper only works for __pow__() */
4054
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004055 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004056 return NULL;
4057 return (*func)(self, other, third);
4058}
4059
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004060static PyObject *
4061wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4062{
4063 ternaryfunc func = (ternaryfunc)wrapped;
4064 PyObject *other;
4065 PyObject *third = Py_None;
4066
4067 /* Note: This wrapper only works for __pow__() */
4068
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004069 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004070 return NULL;
4071 return (*func)(other, self, third);
4072}
4073
Tim Peters6d6c1a32001-08-02 04:15:00 +00004074static PyObject *
4075wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4076{
4077 unaryfunc func = (unaryfunc)wrapped;
4078
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004079 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004080 return NULL;
4081 return (*func)(self);
4082}
4083
Tim Peters6d6c1a32001-08-02 04:15:00 +00004084static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00004085wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004086{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004087 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00004088 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004089 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004090
Armin Rigo314861c2006-03-30 14:04:02 +00004091 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4092 return NULL;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004093 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Armin Rigo314861c2006-03-30 14:04:02 +00004094 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004095 return NULL;
4096 return (*func)(self, i);
4097}
4098
Martin v. Löwis18e16552006-02-15 17:27:45 +00004099static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004100getindex(PyObject *self, PyObject *arg)
4101{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004102 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004103
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004104 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004105 if (i == -1 && PyErr_Occurred())
4106 return -1;
4107 if (i < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00004108 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004109 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00004110 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004111 if (n < 0)
4112 return -1;
4113 i += n;
4114 }
4115 }
4116 return i;
4117}
4118
4119static PyObject *
4120wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4121{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004122 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004123 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004124 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004125
Guido van Rossumf4593e02001-10-03 12:09:30 +00004126 if (PyTuple_GET_SIZE(args) == 1) {
4127 arg = PyTuple_GET_ITEM(args, 0);
4128 i = getindex(self, arg);
4129 if (i == -1 && PyErr_Occurred())
4130 return NULL;
4131 return (*func)(self, i);
4132 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004133 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004134 assert(PyErr_Occurred());
4135 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004136}
4137
Tim Peters6d6c1a32001-08-02 04:15:00 +00004138static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004139wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004140{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004141 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
4142 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004143
Martin v. Löwis18e16552006-02-15 17:27:45 +00004144 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004145 return NULL;
4146 return (*func)(self, i, j);
4147}
4148
Tim Peters6d6c1a32001-08-02 04:15:00 +00004149static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004150wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004151{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004152 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4153 Py_ssize_t i;
4154 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004155 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004156
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004157 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004158 return NULL;
4159 i = getindex(self, arg);
4160 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004161 return NULL;
4162 res = (*func)(self, i, value);
4163 if (res == -1 && PyErr_Occurred())
4164 return NULL;
4165 Py_INCREF(Py_None);
4166 return Py_None;
4167}
4168
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004169static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004170wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004171{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004172 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4173 Py_ssize_t i;
4174 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004175 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004176
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004177 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004178 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004179 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004180 i = getindex(self, arg);
4181 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004182 return NULL;
4183 res = (*func)(self, i, NULL);
4184 if (res == -1 && PyErr_Occurred())
4185 return NULL;
4186 Py_INCREF(Py_None);
4187 return Py_None;
4188}
4189
Tim Peters6d6c1a32001-08-02 04:15:00 +00004190static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004191wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004192{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004193 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4194 Py_ssize_t i, j;
4195 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004196 PyObject *value;
4197
Martin v. Löwis18e16552006-02-15 17:27:45 +00004198 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004199 return NULL;
4200 res = (*func)(self, i, j, value);
4201 if (res == -1 && PyErr_Occurred())
4202 return NULL;
4203 Py_INCREF(Py_None);
4204 return Py_None;
4205}
4206
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004207static PyObject *
4208wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
4209{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004210 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4211 Py_ssize_t i, j;
4212 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004213
Martin v. Löwis18e16552006-02-15 17:27:45 +00004214 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004215 return NULL;
4216 res = (*func)(self, i, j, NULL);
4217 if (res == -1 && PyErr_Occurred())
4218 return NULL;
4219 Py_INCREF(Py_None);
4220 return Py_None;
4221}
4222
Tim Peters6d6c1a32001-08-02 04:15:00 +00004223/* XXX objobjproc is a misnomer; should be objargpred */
4224static PyObject *
4225wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4226{
4227 objobjproc func = (objobjproc)wrapped;
4228 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004229 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004230
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004231 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004232 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004233 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004234 res = (*func)(self, value);
4235 if (res == -1 && PyErr_Occurred())
4236 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004237 else
4238 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004239}
4240
Tim Peters6d6c1a32001-08-02 04:15:00 +00004241static PyObject *
4242wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4243{
4244 objobjargproc func = (objobjargproc)wrapped;
4245 int res;
4246 PyObject *key, *value;
4247
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004248 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004249 return NULL;
4250 res = (*func)(self, key, value);
4251 if (res == -1 && PyErr_Occurred())
4252 return NULL;
4253 Py_INCREF(Py_None);
4254 return Py_None;
4255}
4256
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004257static PyObject *
4258wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4259{
4260 objobjargproc func = (objobjargproc)wrapped;
4261 int res;
4262 PyObject *key;
4263
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004264 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004265 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004266 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004267 res = (*func)(self, key, NULL);
4268 if (res == -1 && PyErr_Occurred())
4269 return NULL;
4270 Py_INCREF(Py_None);
4271 return Py_None;
4272}
4273
Tim Peters6d6c1a32001-08-02 04:15:00 +00004274static PyObject *
4275wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
4276{
4277 cmpfunc func = (cmpfunc)wrapped;
4278 int res;
4279 PyObject *other;
4280
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004281 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004282 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004283 other = PyTuple_GET_ITEM(args, 0);
Christian Heimese93237d2007-12-19 02:37:44 +00004284 if (Py_TYPE(other)->tp_compare != func &&
4285 !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
Guido van Rossumceccae52001-09-18 20:03:57 +00004286 PyErr_Format(
4287 PyExc_TypeError,
4288 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +00004289 Py_TYPE(self)->tp_name,
4290 Py_TYPE(self)->tp_name,
4291 Py_TYPE(other)->tp_name);
Guido van Rossumceccae52001-09-18 20:03:57 +00004292 return NULL;
4293 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004294 res = (*func)(self, other);
4295 if (PyErr_Occurred())
4296 return NULL;
4297 return PyInt_FromLong((long)res);
4298}
4299
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004300/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004301 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004302static int
4303hackcheck(PyObject *self, setattrofunc func, char *what)
4304{
Christian Heimese93237d2007-12-19 02:37:44 +00004305 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004306 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4307 type = type->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004308 /* If type is NULL now, this is a really weird type.
4309 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004310 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004311 PyErr_Format(PyExc_TypeError,
4312 "can't apply this %s to %s object",
4313 what,
4314 type->tp_name);
4315 return 0;
4316 }
4317 return 1;
4318}
4319
Tim Peters6d6c1a32001-08-02 04:15:00 +00004320static PyObject *
4321wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4322{
4323 setattrofunc func = (setattrofunc)wrapped;
4324 int res;
4325 PyObject *name, *value;
4326
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004327 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004328 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004329 if (!hackcheck(self, func, "__setattr__"))
4330 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004331 res = (*func)(self, name, value);
4332 if (res < 0)
4333 return NULL;
4334 Py_INCREF(Py_None);
4335 return Py_None;
4336}
4337
4338static PyObject *
4339wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4340{
4341 setattrofunc func = (setattrofunc)wrapped;
4342 int res;
4343 PyObject *name;
4344
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004345 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004346 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004347 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004348 if (!hackcheck(self, func, "__delattr__"))
4349 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004350 res = (*func)(self, name, NULL);
4351 if (res < 0)
4352 return NULL;
4353 Py_INCREF(Py_None);
4354 return Py_None;
4355}
4356
Tim Peters6d6c1a32001-08-02 04:15:00 +00004357static PyObject *
4358wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4359{
4360 hashfunc func = (hashfunc)wrapped;
4361 long res;
4362
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004363 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004364 return NULL;
4365 res = (*func)(self);
4366 if (res == -1 && PyErr_Occurred())
4367 return NULL;
4368 return PyInt_FromLong(res);
4369}
4370
Tim Peters6d6c1a32001-08-02 04:15:00 +00004371static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004372wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004373{
4374 ternaryfunc func = (ternaryfunc)wrapped;
4375
Guido van Rossumc8e56452001-10-22 00:43:43 +00004376 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004377}
4378
Tim Peters6d6c1a32001-08-02 04:15:00 +00004379static PyObject *
4380wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4381{
4382 richcmpfunc func = (richcmpfunc)wrapped;
4383 PyObject *other;
4384
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004385 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004386 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004387 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004388 return (*func)(self, other, op);
4389}
4390
4391#undef RICHCMP_WRAPPER
4392#define RICHCMP_WRAPPER(NAME, OP) \
4393static PyObject * \
4394richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4395{ \
4396 return wrap_richcmpfunc(self, args, wrapped, OP); \
4397}
4398
Jack Jansen8e938b42001-08-08 15:29:49 +00004399RICHCMP_WRAPPER(lt, Py_LT)
4400RICHCMP_WRAPPER(le, Py_LE)
4401RICHCMP_WRAPPER(eq, Py_EQ)
4402RICHCMP_WRAPPER(ne, Py_NE)
4403RICHCMP_WRAPPER(gt, Py_GT)
4404RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004405
Tim Peters6d6c1a32001-08-02 04:15:00 +00004406static PyObject *
4407wrap_next(PyObject *self, PyObject *args, void *wrapped)
4408{
4409 unaryfunc func = (unaryfunc)wrapped;
4410 PyObject *res;
4411
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004412 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004413 return NULL;
4414 res = (*func)(self);
4415 if (res == NULL && !PyErr_Occurred())
4416 PyErr_SetNone(PyExc_StopIteration);
4417 return res;
4418}
4419
Tim Peters6d6c1a32001-08-02 04:15:00 +00004420static PyObject *
4421wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4422{
4423 descrgetfunc func = (descrgetfunc)wrapped;
4424 PyObject *obj;
4425 PyObject *type = NULL;
4426
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004427 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004428 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004429 if (obj == Py_None)
4430 obj = NULL;
4431 if (type == Py_None)
4432 type = NULL;
4433 if (type == NULL &&obj == NULL) {
4434 PyErr_SetString(PyExc_TypeError,
4435 "__get__(None, None) is invalid");
4436 return NULL;
4437 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004438 return (*func)(self, obj, type);
4439}
4440
Tim Peters6d6c1a32001-08-02 04:15:00 +00004441static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004442wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004443{
4444 descrsetfunc func = (descrsetfunc)wrapped;
4445 PyObject *obj, *value;
4446 int ret;
4447
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004448 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004449 return NULL;
4450 ret = (*func)(self, obj, value);
4451 if (ret < 0)
4452 return NULL;
4453 Py_INCREF(Py_None);
4454 return Py_None;
4455}
Guido van Rossum22b13872002-08-06 21:41:44 +00004456
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004457static PyObject *
4458wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4459{
4460 descrsetfunc func = (descrsetfunc)wrapped;
4461 PyObject *obj;
4462 int ret;
4463
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004464 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004465 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004466 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004467 ret = (*func)(self, obj, NULL);
4468 if (ret < 0)
4469 return NULL;
4470 Py_INCREF(Py_None);
4471 return Py_None;
4472}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004473
Tim Peters6d6c1a32001-08-02 04:15:00 +00004474static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004475wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004476{
4477 initproc func = (initproc)wrapped;
4478
Guido van Rossumc8e56452001-10-22 00:43:43 +00004479 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004480 return NULL;
4481 Py_INCREF(Py_None);
4482 return Py_None;
4483}
4484
Tim Peters6d6c1a32001-08-02 04:15:00 +00004485static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004486tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004487{
Barry Warsaw60f01882001-08-22 19:24:42 +00004488 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004489 PyObject *arg0, *res;
4490
4491 if (self == NULL || !PyType_Check(self))
4492 Py_FatalError("__new__() called with non-type 'self'");
4493 type = (PyTypeObject *)self;
4494 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004495 PyErr_Format(PyExc_TypeError,
4496 "%s.__new__(): not enough arguments",
4497 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004498 return NULL;
4499 }
4500 arg0 = PyTuple_GET_ITEM(args, 0);
4501 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004502 PyErr_Format(PyExc_TypeError,
4503 "%s.__new__(X): X is not a type object (%s)",
4504 type->tp_name,
Christian Heimese93237d2007-12-19 02:37:44 +00004505 Py_TYPE(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004506 return NULL;
4507 }
4508 subtype = (PyTypeObject *)arg0;
4509 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004510 PyErr_Format(PyExc_TypeError,
4511 "%s.__new__(%s): %s is not a subtype of %s",
4512 type->tp_name,
4513 subtype->tp_name,
4514 subtype->tp_name,
4515 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004516 return NULL;
4517 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004518
4519 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004520 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004521 most derived base that's not a heap type is this type. */
4522 staticbase = subtype;
4523 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4524 staticbase = staticbase->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004525 /* If staticbase is NULL now, it is a really weird type.
4526 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004527 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004528 PyErr_Format(PyExc_TypeError,
4529 "%s.__new__(%s) is not safe, use %s.__new__()",
4530 type->tp_name,
4531 subtype->tp_name,
4532 staticbase == NULL ? "?" : staticbase->tp_name);
4533 return NULL;
4534 }
4535
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004536 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4537 if (args == NULL)
4538 return NULL;
4539 res = type->tp_new(subtype, args, kwds);
4540 Py_DECREF(args);
4541 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004542}
4543
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004544static struct PyMethodDef tp_new_methoddef[] = {
Neal Norwitza84dcd72007-05-22 07:16:44 +00004545 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004546 PyDoc_STR("T.__new__(S, ...) -> "
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004547 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004548 {0}
4549};
4550
4551static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004552add_tp_new_wrapper(PyTypeObject *type)
4553{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004554 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004555
Guido van Rossum687ae002001-10-15 22:03:32 +00004556 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004557 return 0;
4558 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004559 if (func == NULL)
4560 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004561 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004562 Py_DECREF(func);
4563 return -1;
4564 }
4565 Py_DECREF(func);
4566 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004567}
4568
Guido van Rossumf040ede2001-08-07 16:40:56 +00004569/* Slot wrappers that call the corresponding __foo__ slot. See comments
4570 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004571
Guido van Rossumdc91b992001-08-08 22:26:22 +00004572#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004573static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004574FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004575{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004576 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004577 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004578}
4579
Guido van Rossumdc91b992001-08-08 22:26:22 +00004580#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004581static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004582FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004583{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004584 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004585 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004586}
4587
Guido van Rossumcd118802003-01-06 22:57:47 +00004588/* Boolean helper for SLOT1BINFULL().
4589 right.__class__ is a nontrivial subclass of left.__class__. */
4590static int
4591method_is_overloaded(PyObject *left, PyObject *right, char *name)
4592{
4593 PyObject *a, *b;
4594 int ok;
4595
Christian Heimese93237d2007-12-19 02:37:44 +00004596 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004597 if (b == NULL) {
4598 PyErr_Clear();
4599 /* If right doesn't have it, it's not overloaded */
4600 return 0;
4601 }
4602
Christian Heimese93237d2007-12-19 02:37:44 +00004603 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004604 if (a == NULL) {
4605 PyErr_Clear();
4606 Py_DECREF(b);
4607 /* If right has it but left doesn't, it's overloaded */
4608 return 1;
4609 }
4610
4611 ok = PyObject_RichCompareBool(a, b, Py_NE);
4612 Py_DECREF(a);
4613 Py_DECREF(b);
4614 if (ok < 0) {
4615 PyErr_Clear();
4616 return 0;
4617 }
4618
4619 return ok;
4620}
4621
Guido van Rossumdc91b992001-08-08 22:26:22 +00004622
4623#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004624static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004625FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004626{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004627 static PyObject *cache_str, *rcache_str; \
Christian Heimese93237d2007-12-19 02:37:44 +00004628 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4629 Py_TYPE(other)->tp_as_number != NULL && \
4630 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4631 if (Py_TYPE(self)->tp_as_number != NULL && \
4632 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004633 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004634 if (do_other && \
Christian Heimese93237d2007-12-19 02:37:44 +00004635 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004636 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004637 r = call_maybe( \
4638 other, ROPSTR, &rcache_str, "(O)", self); \
4639 if (r != Py_NotImplemented) \
4640 return r; \
4641 Py_DECREF(r); \
4642 do_other = 0; \
4643 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004644 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004645 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004646 if (r != Py_NotImplemented || \
Christian Heimese93237d2007-12-19 02:37:44 +00004647 Py_TYPE(other) == Py_TYPE(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004648 return r; \
4649 Py_DECREF(r); \
4650 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004651 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004652 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004653 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004654 } \
4655 Py_INCREF(Py_NotImplemented); \
4656 return Py_NotImplemented; \
4657}
4658
4659#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4660 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4661
4662#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4663static PyObject * \
4664FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4665{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004666 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004667 return call_method(self, OPSTR, &cache_str, \
4668 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004669}
4670
Martin v. Löwis18e16552006-02-15 17:27:45 +00004671static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004672slot_sq_length(PyObject *self)
4673{
Guido van Rossum2730b132001-08-28 18:22:14 +00004674 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004675 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004676 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004677
4678 if (res == NULL)
4679 return -1;
Neal Norwitz1872b1c2006-08-12 18:44:06 +00004680 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004681 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004682 if (len < 0) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00004683 if (!PyErr_Occurred())
4684 PyErr_SetString(PyExc_ValueError,
4685 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004686 return -1;
4687 }
Guido van Rossum26111622001-10-01 16:42:49 +00004688 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004689}
4690
Guido van Rossumf4593e02001-10-03 12:09:30 +00004691/* Super-optimized version of slot_sq_item.
4692 Other slots could do the same... */
4693static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004694slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004695{
4696 static PyObject *getitem_str;
4697 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4698 descrgetfunc f;
4699
4700 if (getitem_str == NULL) {
4701 getitem_str = PyString_InternFromString("__getitem__");
4702 if (getitem_str == NULL)
4703 return NULL;
4704 }
Christian Heimese93237d2007-12-19 02:37:44 +00004705 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004706 if (func != NULL) {
Christian Heimese93237d2007-12-19 02:37:44 +00004707 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004708 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004709 else {
Christian Heimese93237d2007-12-19 02:37:44 +00004710 func = f(func, self, (PyObject *)(Py_TYPE(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004711 if (func == NULL) {
4712 return NULL;
4713 }
4714 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004715 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004716 if (ival != NULL) {
4717 args = PyTuple_New(1);
4718 if (args != NULL) {
4719 PyTuple_SET_ITEM(args, 0, ival);
4720 retval = PyObject_Call(func, args, NULL);
4721 Py_XDECREF(args);
4722 Py_XDECREF(func);
4723 return retval;
4724 }
4725 }
4726 }
4727 else {
4728 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4729 }
4730 Py_XDECREF(args);
4731 Py_XDECREF(ival);
4732 Py_XDECREF(func);
4733 return NULL;
4734}
4735
Martin v. Löwis18e16552006-02-15 17:27:45 +00004736SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004737
4738static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004739slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004740{
4741 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004742 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004743
4744 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004745 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004746 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004747 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004748 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004749 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004750 if (res == NULL)
4751 return -1;
4752 Py_DECREF(res);
4753 return 0;
4754}
4755
4756static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004757slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004758{
4759 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004760 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004761
4762 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004763 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004764 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004765 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004766 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004767 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004768 if (res == NULL)
4769 return -1;
4770 Py_DECREF(res);
4771 return 0;
4772}
4773
4774static int
4775slot_sq_contains(PyObject *self, PyObject *value)
4776{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004777 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004778 int result = -1;
4779
Guido van Rossum60718732001-08-28 17:47:51 +00004780 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004781
Guido van Rossum55f20992001-10-01 17:18:22 +00004782 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004783 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004784 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004785 if (args == NULL)
4786 res = NULL;
4787 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004788 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004789 Py_DECREF(args);
4790 }
4791 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004792 if (res != NULL) {
4793 result = PyObject_IsTrue(res);
4794 Py_DECREF(res);
4795 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004796 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004797 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004798 /* Possible results: -1 and 1 */
4799 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004800 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004801 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004802 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004803}
4804
Tim Peters6d6c1a32001-08-02 04:15:00 +00004805#define slot_mp_length slot_sq_length
4806
Guido van Rossumdc91b992001-08-08 22:26:22 +00004807SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004808
4809static int
4810slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4811{
4812 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004813 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004814
4815 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004816 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004817 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004818 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004819 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004820 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004821 if (res == NULL)
4822 return -1;
4823 Py_DECREF(res);
4824 return 0;
4825}
4826
Guido van Rossumdc91b992001-08-08 22:26:22 +00004827SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4828SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4829SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4830SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4831SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4832SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4833
Jeremy Hylton938ace62002-07-17 16:30:39 +00004834static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004835
4836SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4837 nb_power, "__pow__", "__rpow__")
4838
4839static PyObject *
4840slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4841{
Guido van Rossum2730b132001-08-28 18:22:14 +00004842 static PyObject *pow_str;
4843
Guido van Rossumdc91b992001-08-08 22:26:22 +00004844 if (modulus == Py_None)
4845 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004846 /* Three-arg power doesn't use __rpow__. But ternary_op
4847 can call this when the second argument's type uses
4848 slot_nb_power, so check before calling self.__pow__. */
Christian Heimese93237d2007-12-19 02:37:44 +00004849 if (Py_TYPE(self)->tp_as_number != NULL &&
4850 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00004851 return call_method(self, "__pow__", &pow_str,
4852 "(OO)", other, modulus);
4853 }
4854 Py_INCREF(Py_NotImplemented);
4855 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004856}
4857
4858SLOT0(slot_nb_negative, "__neg__")
4859SLOT0(slot_nb_positive, "__pos__")
4860SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004861
4862static int
4863slot_nb_nonzero(PyObject *self)
4864{
Tim Petersea7f75d2002-12-07 21:39:16 +00004865 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004866 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004867 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004868
Guido van Rossum55f20992001-10-01 17:18:22 +00004869 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004870 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004871 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004872 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004873 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004874 if (func == NULL)
4875 return PyErr_Occurred() ? -1 : 1;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004876 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004877 args = PyTuple_New(0);
4878 if (args != NULL) {
4879 PyObject *temp = PyObject_Call(func, args, NULL);
4880 Py_DECREF(args);
4881 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004882 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004883 result = PyObject_IsTrue(temp);
4884 else {
4885 PyErr_Format(PyExc_TypeError,
4886 "__nonzero__ should return "
4887 "bool or int, returned %s",
4888 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004889 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004890 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004891 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004892 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004893 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004894 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004895 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004896}
4897
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004898
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004899static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004900slot_nb_index(PyObject *self)
4901{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004902 static PyObject *index_str;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004903 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004904}
4905
4906
Guido van Rossumdc91b992001-08-08 22:26:22 +00004907SLOT0(slot_nb_invert, "__invert__")
4908SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4909SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4910SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4911SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4912SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004913
4914static int
4915slot_nb_coerce(PyObject **a, PyObject **b)
4916{
4917 static PyObject *coerce_str;
4918 PyObject *self = *a, *other = *b;
4919
4920 if (self->ob_type->tp_as_number != NULL &&
4921 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4922 PyObject *r;
4923 r = call_maybe(
4924 self, "__coerce__", &coerce_str, "(O)", other);
4925 if (r == NULL)
4926 return -1;
4927 if (r == Py_NotImplemented) {
4928 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004929 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004930 else {
4931 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4932 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004933 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004934 Py_DECREF(r);
4935 return -1;
4936 }
4937 *a = PyTuple_GET_ITEM(r, 0);
4938 Py_INCREF(*a);
4939 *b = PyTuple_GET_ITEM(r, 1);
4940 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004941 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004942 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004943 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004944 }
4945 if (other->ob_type->tp_as_number != NULL &&
4946 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4947 PyObject *r;
4948 r = call_maybe(
4949 other, "__coerce__", &coerce_str, "(O)", self);
4950 if (r == NULL)
4951 return -1;
4952 if (r == Py_NotImplemented) {
4953 Py_DECREF(r);
4954 return 1;
4955 }
4956 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4957 PyErr_SetString(PyExc_TypeError,
4958 "__coerce__ didn't return a 2-tuple");
4959 Py_DECREF(r);
4960 return -1;
4961 }
4962 *a = PyTuple_GET_ITEM(r, 1);
4963 Py_INCREF(*a);
4964 *b = PyTuple_GET_ITEM(r, 0);
4965 Py_INCREF(*b);
4966 Py_DECREF(r);
4967 return 0;
4968 }
4969 return 1;
4970}
4971
Guido van Rossumdc91b992001-08-08 22:26:22 +00004972SLOT0(slot_nb_int, "__int__")
4973SLOT0(slot_nb_long, "__long__")
4974SLOT0(slot_nb_float, "__float__")
4975SLOT0(slot_nb_oct, "__oct__")
4976SLOT0(slot_nb_hex, "__hex__")
4977SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4978SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4979SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4980SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4981SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Martin v. Löwisfd963262007-02-09 12:19:32 +00004982/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4983static PyObject *
4984slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4985{
4986 static PyObject *cache_str;
4987 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4988}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004989SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4990SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4991SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4992SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4993SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4994SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4995 "__floordiv__", "__rfloordiv__")
4996SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4997SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4998SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004999
5000static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00005001half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005002{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005003 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005004 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005005 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005006
Guido van Rossum60718732001-08-28 17:47:51 +00005007 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005008 if (func == NULL) {
5009 PyErr_Clear();
5010 }
5011 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005012 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005013 if (args == NULL)
5014 res = NULL;
5015 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005016 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005017 Py_DECREF(args);
5018 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00005019 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005020 if (res != Py_NotImplemented) {
5021 if (res == NULL)
5022 return -2;
5023 c = PyInt_AsLong(res);
5024 Py_DECREF(res);
5025 if (c == -1 && PyErr_Occurred())
5026 return -2;
5027 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
5028 }
5029 Py_DECREF(res);
5030 }
5031 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005032}
5033
Guido van Rossumab3b0342001-09-18 20:38:53 +00005034/* This slot is published for the benefit of try_3way_compare in object.c */
5035int
5036_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00005037{
5038 int c;
5039
Christian Heimese93237d2007-12-19 02:37:44 +00005040 if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005041 c = half_compare(self, other);
5042 if (c <= 1)
5043 return c;
5044 }
Christian Heimese93237d2007-12-19 02:37:44 +00005045 if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005046 c = half_compare(other, self);
5047 if (c < -1)
5048 return -2;
5049 if (c <= 1)
5050 return -c;
5051 }
5052 return (void *)self < (void *)other ? -1 :
5053 (void *)self > (void *)other ? 1 : 0;
5054}
5055
5056static PyObject *
5057slot_tp_repr(PyObject *self)
5058{
5059 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005060 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005061
Guido van Rossum60718732001-08-28 17:47:51 +00005062 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005063 if (func != NULL) {
5064 res = PyEval_CallObject(func, NULL);
5065 Py_DECREF(func);
5066 return res;
5067 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00005068 PyErr_Clear();
5069 return PyString_FromFormat("<%s object at %p>",
Christian Heimese93237d2007-12-19 02:37:44 +00005070 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005071}
5072
5073static PyObject *
5074slot_tp_str(PyObject *self)
5075{
5076 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005077 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005078
Guido van Rossum60718732001-08-28 17:47:51 +00005079 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005080 if (func != NULL) {
5081 res = PyEval_CallObject(func, NULL);
5082 Py_DECREF(func);
5083 return res;
5084 }
5085 else {
5086 PyErr_Clear();
5087 return slot_tp_repr(self);
5088 }
5089}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005090
5091static long
5092slot_tp_hash(PyObject *self)
5093{
Tim Peters61ce0a92002-12-06 23:38:02 +00005094 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00005095 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005096 long h;
5097
Guido van Rossum60718732001-08-28 17:47:51 +00005098 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005099
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005100 if (func != NULL && func != Py_None) {
Tim Peters61ce0a92002-12-06 23:38:02 +00005101 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005102 Py_DECREF(func);
5103 if (res == NULL)
5104 return -1;
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00005105 if (PyLong_Check(res))
Armin Rigo51fc8c42006-08-09 14:55:26 +00005106 h = PyLong_Type.tp_hash(res);
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00005107 else
5108 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00005109 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005110 }
5111 else {
Georg Brandl30b78042007-12-20 21:03:02 +00005112 Py_XDECREF(func); /* may be None */
Guido van Rossumb8f63662001-08-15 23:57:02 +00005113 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005114 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005115 if (func == NULL) {
5116 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005117 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005118 }
5119 if (func != NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00005120 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
5121 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005122 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005123 return -1;
5124 }
5125 PyErr_Clear();
5126 h = _Py_HashPointer((void *)self);
5127 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005128 if (h == -1 && !PyErr_Occurred())
5129 h = -2;
5130 return h;
5131}
5132
5133static PyObject *
5134slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5135{
Guido van Rossum60718732001-08-28 17:47:51 +00005136 static PyObject *call_str;
5137 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005138 PyObject *res;
5139
5140 if (meth == NULL)
5141 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00005142
Tim Peters6d6c1a32001-08-02 04:15:00 +00005143 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00005144
Tim Peters6d6c1a32001-08-02 04:15:00 +00005145 Py_DECREF(meth);
5146 return res;
5147}
5148
Guido van Rossum14a6f832001-10-17 13:59:09 +00005149/* There are two slot dispatch functions for tp_getattro.
5150
5151 - slot_tp_getattro() is used when __getattribute__ is overridden
5152 but no __getattr__ hook is present;
5153
5154 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5155
Guido van Rossumc334df52002-04-04 23:44:47 +00005156 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5157 detects the absence of __getattr__ and then installs the simpler slot if
5158 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005159
Tim Peters6d6c1a32001-08-02 04:15:00 +00005160static PyObject *
5161slot_tp_getattro(PyObject *self, PyObject *name)
5162{
Guido van Rossum14a6f832001-10-17 13:59:09 +00005163 static PyObject *getattribute_str = NULL;
5164 return call_method(self, "__getattribute__", &getattribute_str,
5165 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005166}
5167
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005168static PyObject *
5169slot_tp_getattr_hook(PyObject *self, PyObject *name)
5170{
Christian Heimese93237d2007-12-19 02:37:44 +00005171 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005172 PyObject *getattr, *getattribute, *res;
5173 static PyObject *getattribute_str = NULL;
5174 static PyObject *getattr_str = NULL;
5175
5176 if (getattr_str == NULL) {
5177 getattr_str = PyString_InternFromString("__getattr__");
5178 if (getattr_str == NULL)
5179 return NULL;
5180 }
5181 if (getattribute_str == NULL) {
5182 getattribute_str =
5183 PyString_InternFromString("__getattribute__");
5184 if (getattribute_str == NULL)
5185 return NULL;
5186 }
5187 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005188 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005189 /* No __getattr__ hook: use a simpler dispatcher */
5190 tp->tp_getattro = slot_tp_getattro;
5191 return slot_tp_getattro(self, name);
5192 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005193 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005194 if (getattribute == NULL ||
Christian Heimese93237d2007-12-19 02:37:44 +00005195 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00005196 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5197 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005198 res = PyObject_GenericGetAttr(self, name);
5199 else
Georg Brandl684fd0c2006-05-25 19:15:31 +00005200 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005201 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005202 PyErr_Clear();
Georg Brandl684fd0c2006-05-25 19:15:31 +00005203 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005204 }
5205 return res;
5206}
5207
Tim Peters6d6c1a32001-08-02 04:15:00 +00005208static int
5209slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5210{
5211 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005212 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005213
5214 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00005215 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005216 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005217 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005218 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005219 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005220 if (res == NULL)
5221 return -1;
5222 Py_DECREF(res);
5223 return 0;
5224}
5225
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005226static char *name_op[] = {
5227 "__lt__",
5228 "__le__",
5229 "__eq__",
5230 "__ne__",
5231 "__gt__",
5232 "__ge__",
5233};
5234
Tim Peters6d6c1a32001-08-02 04:15:00 +00005235static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005236half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005237{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005238 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005239 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005240
Guido van Rossum60718732001-08-28 17:47:51 +00005241 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005242 if (func == NULL) {
5243 PyErr_Clear();
5244 Py_INCREF(Py_NotImplemented);
5245 return Py_NotImplemented;
5246 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005247 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005248 if (args == NULL)
5249 res = NULL;
5250 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005251 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005252 Py_DECREF(args);
5253 }
5254 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005255 return res;
5256}
5257
Guido van Rossumb8f63662001-08-15 23:57:02 +00005258static PyObject *
5259slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5260{
5261 PyObject *res;
5262
Christian Heimese93237d2007-12-19 02:37:44 +00005263 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005264 res = half_richcompare(self, other, op);
5265 if (res != Py_NotImplemented)
5266 return res;
5267 Py_DECREF(res);
5268 }
Christian Heimese93237d2007-12-19 02:37:44 +00005269 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00005270 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005271 if (res != Py_NotImplemented) {
5272 return res;
5273 }
5274 Py_DECREF(res);
5275 }
5276 Py_INCREF(Py_NotImplemented);
5277 return Py_NotImplemented;
5278}
5279
5280static PyObject *
5281slot_tp_iter(PyObject *self)
5282{
5283 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005284 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005285
Guido van Rossum60718732001-08-28 17:47:51 +00005286 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005287 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00005288 PyObject *args;
5289 args = res = PyTuple_New(0);
5290 if (args != NULL) {
5291 res = PyObject_Call(func, args, NULL);
5292 Py_DECREF(args);
5293 }
5294 Py_DECREF(func);
5295 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005296 }
5297 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005298 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005299 if (func == NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00005300 PyErr_Format(PyExc_TypeError,
5301 "'%.200s' object is not iterable",
Christian Heimese93237d2007-12-19 02:37:44 +00005302 Py_TYPE(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005303 return NULL;
5304 }
5305 Py_DECREF(func);
5306 return PySeqIter_New(self);
5307}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005308
5309static PyObject *
5310slot_tp_iternext(PyObject *self)
5311{
Guido van Rossum2730b132001-08-28 18:22:14 +00005312 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00005313 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005314}
5315
Guido van Rossum1a493502001-08-17 16:47:50 +00005316static PyObject *
5317slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5318{
Christian Heimese93237d2007-12-19 02:37:44 +00005319 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00005320 PyObject *get;
5321 static PyObject *get_str = NULL;
5322
5323 if (get_str == NULL) {
5324 get_str = PyString_InternFromString("__get__");
5325 if (get_str == NULL)
5326 return NULL;
5327 }
5328 get = _PyType_Lookup(tp, get_str);
5329 if (get == NULL) {
5330 /* Avoid further slowdowns */
5331 if (tp->tp_descr_get == slot_tp_descr_get)
5332 tp->tp_descr_get = NULL;
5333 Py_INCREF(self);
5334 return self;
5335 }
Guido van Rossum2c252392001-08-24 10:13:31 +00005336 if (obj == NULL)
5337 obj = Py_None;
5338 if (type == NULL)
5339 type = Py_None;
Georg Brandl684fd0c2006-05-25 19:15:31 +00005340 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005341}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005342
5343static int
5344slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5345{
Guido van Rossum2c252392001-08-24 10:13:31 +00005346 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005347 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005348
5349 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00005350 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005351 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00005352 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005353 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005354 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005355 if (res == NULL)
5356 return -1;
5357 Py_DECREF(res);
5358 return 0;
5359}
5360
5361static int
5362slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5363{
Guido van Rossum60718732001-08-28 17:47:51 +00005364 static PyObject *init_str;
5365 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005366 PyObject *res;
5367
5368 if (meth == NULL)
5369 return -1;
5370 res = PyObject_Call(meth, args, kwds);
5371 Py_DECREF(meth);
5372 if (res == NULL)
5373 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005374 if (res != Py_None) {
Georg Brandlccff7852006-06-18 22:17:29 +00005375 PyErr_Format(PyExc_TypeError,
5376 "__init__() should return None, not '%.200s'",
Christian Heimese93237d2007-12-19 02:37:44 +00005377 Py_TYPE(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005378 Py_DECREF(res);
5379 return -1;
5380 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005381 Py_DECREF(res);
5382 return 0;
5383}
5384
5385static PyObject *
5386slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5387{
Guido van Rossum7bed2132002-08-08 21:57:53 +00005388 static PyObject *new_str;
5389 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005390 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005391 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005392
Guido van Rossum7bed2132002-08-08 21:57:53 +00005393 if (new_str == NULL) {
5394 new_str = PyString_InternFromString("__new__");
5395 if (new_str == NULL)
5396 return NULL;
5397 }
5398 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005399 if (func == NULL)
5400 return NULL;
5401 assert(PyTuple_Check(args));
5402 n = PyTuple_GET_SIZE(args);
5403 newargs = PyTuple_New(n+1);
5404 if (newargs == NULL)
5405 return NULL;
5406 Py_INCREF(type);
5407 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5408 for (i = 0; i < n; i++) {
5409 x = PyTuple_GET_ITEM(args, i);
5410 Py_INCREF(x);
5411 PyTuple_SET_ITEM(newargs, i+1, x);
5412 }
5413 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005414 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005415 Py_DECREF(func);
5416 return x;
5417}
5418
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005419static void
5420slot_tp_del(PyObject *self)
5421{
5422 static PyObject *del_str = NULL;
5423 PyObject *del, *res;
5424 PyObject *error_type, *error_value, *error_traceback;
5425
5426 /* Temporarily resurrect the object. */
5427 assert(self->ob_refcnt == 0);
5428 self->ob_refcnt = 1;
5429
5430 /* Save the current exception, if any. */
5431 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5432
5433 /* Execute __del__ method, if any. */
5434 del = lookup_maybe(self, "__del__", &del_str);
5435 if (del != NULL) {
5436 res = PyEval_CallObject(del, NULL);
5437 if (res == NULL)
5438 PyErr_WriteUnraisable(del);
5439 else
5440 Py_DECREF(res);
5441 Py_DECREF(del);
5442 }
5443
5444 /* Restore the saved exception. */
5445 PyErr_Restore(error_type, error_value, error_traceback);
5446
5447 /* Undo the temporary resurrection; can't use DECREF here, it would
5448 * cause a recursive call.
5449 */
5450 assert(self->ob_refcnt > 0);
5451 if (--self->ob_refcnt == 0)
5452 return; /* this is the normal path out */
5453
5454 /* __del__ resurrected it! Make it look like the original Py_DECREF
5455 * never happened.
5456 */
5457 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005458 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005459 _Py_NewReference(self);
5460 self->ob_refcnt = refcnt;
5461 }
Christian Heimese93237d2007-12-19 02:37:44 +00005462 assert(!PyType_IS_GC(Py_TYPE(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005463 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005464 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5465 * we need to undo that. */
5466 _Py_DEC_REFTOTAL;
5467 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5468 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005469 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5470 * _Py_NewReference bumped tp_allocs: both of those need to be
5471 * undone.
5472 */
5473#ifdef COUNT_ALLOCS
Christian Heimese93237d2007-12-19 02:37:44 +00005474 --Py_TYPE(self)->tp_frees;
5475 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005476#endif
5477}
5478
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005479
5480/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005481 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005482 structure, which incorporates the additional structures used for numbers,
5483 sequences and mappings.
5484 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005485 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005486 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5487 terminated with an all-zero entry. (This table is further initialized and
5488 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005489
Guido van Rossum6d204072001-10-21 00:44:31 +00005490typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005491
5492#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005493#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005494#undef ETSLOT
5495#undef SQSLOT
5496#undef MPSLOT
5497#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005498#undef UNSLOT
5499#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005500#undef BINSLOT
5501#undef RBINSLOT
5502
Guido van Rossum6d204072001-10-21 00:44:31 +00005503#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005504 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5505 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005506#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5507 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005508 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005509#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005510 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005511 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005512#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5513 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5514#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5515 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5516#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5517 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5518#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5519 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5520 "x." NAME "() <==> " DOC)
5521#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5522 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5523 "x." NAME "(y) <==> x" DOC "y")
5524#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5525 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5526 "x." NAME "(y) <==> x" DOC "y")
5527#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5528 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5529 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005530#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5531 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5532 "x." NAME "(y) <==> " DOC)
5533#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5534 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5535 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005536
5537static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005538 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005539 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005540 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5541 The logic in abstract.c always falls back to nb_add/nb_multiply in
5542 this case. Defining both the nb_* and the sq_* slots to call the
5543 user-defined methods has unexpected side-effects, as shown by
5544 test_descr.notimplemented() */
5545 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005546 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00005547 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005548 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005549 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005550 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005551 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5552 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005553 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005554 "x.__getslice__(i, j) <==> x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005555 \n\
5556 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005557 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005558 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005559 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005560 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005561 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005562 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005563 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005564 \n\
5565 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005566 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005567 "x.__delslice__(i, j) <==> del x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005568 \n\
5569 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005570 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5571 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005572 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005573 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005574 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005575 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005576
Martin v. Löwis18e16552006-02-15 17:27:45 +00005577 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005578 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005579 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005580 wrap_binaryfunc,
5581 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005582 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005583 wrap_objobjargproc,
5584 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005585 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005586 wrap_delitem,
5587 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005588
Guido van Rossum6d204072001-10-21 00:44:31 +00005589 BINSLOT("__add__", nb_add, slot_nb_add,
5590 "+"),
5591 RBINSLOT("__radd__", nb_add, slot_nb_add,
5592 "+"),
5593 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5594 "-"),
5595 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5596 "-"),
5597 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5598 "*"),
5599 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5600 "*"),
5601 BINSLOT("__div__", nb_divide, slot_nb_divide,
5602 "/"),
5603 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5604 "/"),
5605 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5606 "%"),
5607 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5608 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005609 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005610 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005611 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005612 "divmod(y, x)"),
5613 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5614 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5615 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5616 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5617 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5618 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5619 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5620 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005621 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005622 "x != 0"),
5623 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5624 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5625 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5626 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5627 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5628 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5629 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5630 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5631 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5632 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5633 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5634 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5635 "x.__coerce__(y) <==> coerce(x, y)"),
5636 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5637 "int(x)"),
5638 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5639 "long(x)"),
5640 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5641 "float(x)"),
5642 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5643 "oct(x)"),
5644 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5645 "hex(x)"),
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005646 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005647 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005648 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5649 wrap_binaryfunc, "+"),
5650 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5651 wrap_binaryfunc, "-"),
5652 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5653 wrap_binaryfunc, "*"),
5654 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5655 wrap_binaryfunc, "/"),
5656 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5657 wrap_binaryfunc, "%"),
5658 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005659 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005660 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5661 wrap_binaryfunc, "<<"),
5662 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5663 wrap_binaryfunc, ">>"),
5664 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5665 wrap_binaryfunc, "&"),
5666 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5667 wrap_binaryfunc, "^"),
5668 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5669 wrap_binaryfunc, "|"),
5670 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5671 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5672 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5673 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5674 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5675 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5676 IBSLOT("__itruediv__", nb_inplace_true_divide,
5677 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005678
Guido van Rossum6d204072001-10-21 00:44:31 +00005679 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5680 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005681 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005682 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5683 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005684 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005685 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5686 "x.__cmp__(y) <==> cmp(x,y)"),
5687 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5688 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005689 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5690 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005691 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005692 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5693 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5694 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5695 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5696 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5697 "x.__setattr__('name', value) <==> x.name = value"),
5698 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5699 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5700 "x.__delattr__('name') <==> del x.name"),
5701 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5702 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5703 "x.__lt__(y) <==> x<y"),
5704 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5705 "x.__le__(y) <==> x<=y"),
5706 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5707 "x.__eq__(y) <==> x==y"),
5708 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5709 "x.__ne__(y) <==> x!=y"),
5710 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5711 "x.__gt__(y) <==> x>y"),
5712 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5713 "x.__ge__(y) <==> x>=y"),
5714 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5715 "x.__iter__() <==> iter(x)"),
5716 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5717 "x.next() -> the next value, or raise StopIteration"),
5718 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5719 "descr.__get__(obj[, type]) -> value"),
5720 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5721 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005722 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5723 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005724 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005725 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005726 "see x.__class__.__doc__ for signature",
5727 PyWrapperFlag_KEYWORDS),
5728 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005729 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005730 {NULL}
5731};
5732
Guido van Rossumc334df52002-04-04 23:44:47 +00005733/* Given a type pointer and an offset gotten from a slotdef entry, return a
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005734 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005735 the offset to the type pointer, since it takes care to indirect through the
5736 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5737 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005738static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005739slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005740{
5741 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005742 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005743
Guido van Rossume5c691a2003-03-07 15:13:17 +00005744 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005745 assert(offset >= 0);
Skip Montanaro429433b2006-04-18 00:35:43 +00005746 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5747 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005748 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005749 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005750 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005751 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005752 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005753 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005754 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005755 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005756 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005757 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005758 }
5759 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005760 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005761 }
5762 if (ptr != NULL)
5763 ptr += offset;
5764 return (void **)ptr;
5765}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005766
Guido van Rossumc334df52002-04-04 23:44:47 +00005767/* Length of array of slotdef pointers used to store slots with the
5768 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5769 the same __name__, for any __name__. Since that's a static property, it is
5770 appropriate to declare fixed-size arrays for this. */
5771#define MAX_EQUIV 10
5772
5773/* Return a slot pointer for a given name, but ONLY if the attribute has
5774 exactly one slot function. The name must be an interned string. */
5775static void **
5776resolve_slotdups(PyTypeObject *type, PyObject *name)
5777{
5778 /* XXX Maybe this could be optimized more -- but is it worth it? */
5779
5780 /* pname and ptrs act as a little cache */
5781 static PyObject *pname;
5782 static slotdef *ptrs[MAX_EQUIV];
5783 slotdef *p, **pp;
5784 void **res, **ptr;
5785
5786 if (pname != name) {
5787 /* Collect all slotdefs that match name into ptrs. */
5788 pname = name;
5789 pp = ptrs;
5790 for (p = slotdefs; p->name_strobj; p++) {
5791 if (p->name_strobj == name)
5792 *pp++ = p;
5793 }
5794 *pp = NULL;
5795 }
5796
5797 /* Look in all matching slots of the type; if exactly one of these has
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005798 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005799 res = NULL;
5800 for (pp = ptrs; *pp; pp++) {
5801 ptr = slotptr(type, (*pp)->offset);
5802 if (ptr == NULL || *ptr == NULL)
5803 continue;
5804 if (res != NULL)
5805 return NULL;
5806 res = ptr;
5807 }
5808 return res;
5809}
5810
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005811/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005812 does some incredibly complex thinking and then sticks something into the
5813 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5814 interests, and then stores a generic wrapper or a specific function into
5815 the slot.) Return a pointer to the next slotdef with a different offset,
5816 because that's convenient for fixup_slot_dispatchers(). */
5817static slotdef *
5818update_one_slot(PyTypeObject *type, slotdef *p)
5819{
5820 PyObject *descr;
5821 PyWrapperDescrObject *d;
5822 void *generic = NULL, *specific = NULL;
5823 int use_generic = 0;
5824 int offset = p->offset;
5825 void **ptr = slotptr(type, offset);
5826
5827 if (ptr == NULL) {
5828 do {
5829 ++p;
5830 } while (p->offset == offset);
5831 return p;
5832 }
5833 do {
5834 descr = _PyType_Lookup(type, p->name_strobj);
5835 if (descr == NULL)
5836 continue;
Christian Heimese93237d2007-12-19 02:37:44 +00005837 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00005838 void **tptr = resolve_slotdups(type, p->name_strobj);
5839 if (tptr == NULL || tptr == ptr)
5840 generic = p->function;
5841 d = (PyWrapperDescrObject *)descr;
5842 if (d->d_base->wrapper == p->wrapper &&
5843 PyType_IsSubtype(type, d->d_type))
5844 {
5845 if (specific == NULL ||
5846 specific == d->d_wrapped)
5847 specific = d->d_wrapped;
5848 else
5849 use_generic = 1;
5850 }
5851 }
Christian Heimese93237d2007-12-19 02:37:44 +00005852 else if (Py_TYPE(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00005853 PyCFunction_GET_FUNCTION(descr) ==
5854 (PyCFunction)tp_new_wrapper &&
5855 strcmp(p->name, "__new__") == 0)
5856 {
5857 /* The __new__ wrapper is not a wrapper descriptor,
5858 so must be special-cased differently.
5859 If we don't do this, creating an instance will
5860 always use slot_tp_new which will look up
5861 __new__ in the MRO which will call tp_new_wrapper
5862 which will look through the base classes looking
5863 for a static base and call its tp_new (usually
5864 PyType_GenericNew), after performing various
5865 sanity checks and constructing a new argument
5866 list. Cut all that nonsense short -- this speeds
5867 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005868 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005869 /* XXX I'm not 100% sure that there isn't a hole
5870 in this reasoning that requires additional
5871 sanity checks. I'll buy the first person to
5872 point out a bug in this reasoning a beer. */
5873 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005874 else {
5875 use_generic = 1;
5876 generic = p->function;
5877 }
5878 } while ((++p)->offset == offset);
5879 if (specific && !use_generic)
5880 *ptr = specific;
5881 else
5882 *ptr = generic;
5883 return p;
5884}
5885
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005886/* In the type, update the slots whose slotdefs are gathered in the pp array.
5887 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005888static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005889update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005890{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005891 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005892
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005893 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005894 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005895 return 0;
5896}
5897
Guido van Rossumc334df52002-04-04 23:44:47 +00005898/* Comparison function for qsort() to compare slotdefs by their offset, and
5899 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005900static int
5901slotdef_cmp(const void *aa, const void *bb)
5902{
5903 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5904 int c = a->offset - b->offset;
5905 if (c != 0)
5906 return c;
5907 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005908 /* Cannot use a-b, as this gives off_t,
5909 which may lose precision when converted to int. */
5910 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005911}
5912
Guido van Rossumc334df52002-04-04 23:44:47 +00005913/* Initialize the slotdefs table by adding interned string objects for the
5914 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005915static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005916init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005917{
5918 slotdef *p;
5919 static int initialized = 0;
5920
5921 if (initialized)
5922 return;
5923 for (p = slotdefs; p->name; p++) {
5924 p->name_strobj = PyString_InternFromString(p->name);
5925 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005926 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005927 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005928 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5929 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005930 initialized = 1;
5931}
5932
Guido van Rossumc334df52002-04-04 23:44:47 +00005933/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005934static int
5935update_slot(PyTypeObject *type, PyObject *name)
5936{
Guido van Rossumc334df52002-04-04 23:44:47 +00005937 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005938 slotdef *p;
5939 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005940 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005941
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00005942 /* Clear the VALID_VERSION flag of 'type' and all its
5943 subclasses. This could possibly be unified with the
5944 update_subclasses() recursion below, but carefully:
5945 they each have their own conditions on which to stop
5946 recursing into subclasses. */
5947 type_modified(type);
5948
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005949 init_slotdefs();
5950 pp = ptrs;
5951 for (p = slotdefs; p->name; p++) {
5952 /* XXX assume name is interned! */
5953 if (p->name_strobj == name)
5954 *pp++ = p;
5955 }
5956 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005957 for (pp = ptrs; *pp; pp++) {
5958 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005959 offset = p->offset;
5960 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005961 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005962 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005963 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005964 if (ptrs[0] == NULL)
5965 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005966 return update_subclasses(type, name,
5967 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005968}
5969
Guido van Rossumc334df52002-04-04 23:44:47 +00005970/* Store the proper functions in the slot dispatches at class (type)
5971 definition time, based upon which operations the class overrides in its
5972 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005973static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005974fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005975{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005976 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005977
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005978 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005979 for (p = slotdefs; p->name; )
5980 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005981}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005982
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005983static void
5984update_all_slots(PyTypeObject* type)
5985{
5986 slotdef *p;
5987
5988 init_slotdefs();
5989 for (p = slotdefs; p->name; p++) {
5990 /* update_slot returns int but can't actually fail */
5991 update_slot(type, p->name_strobj);
5992 }
5993}
5994
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005995/* recurse_down_subclasses() and update_subclasses() are mutually
5996 recursive functions to call a callback for all subclasses,
5997 but refraining from recursing into subclasses that define 'name'. */
5998
5999static int
6000update_subclasses(PyTypeObject *type, PyObject *name,
6001 update_callback callback, void *data)
6002{
6003 if (callback(type, data) < 0)
6004 return -1;
6005 return recurse_down_subclasses(type, name, callback, data);
6006}
6007
6008static int
6009recurse_down_subclasses(PyTypeObject *type, PyObject *name,
6010 update_callback callback, void *data)
6011{
6012 PyTypeObject *subclass;
6013 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006014 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006015
6016 subclasses = type->tp_subclasses;
6017 if (subclasses == NULL)
6018 return 0;
6019 assert(PyList_Check(subclasses));
6020 n = PyList_GET_SIZE(subclasses);
6021 for (i = 0; i < n; i++) {
6022 ref = PyList_GET_ITEM(subclasses, i);
6023 assert(PyWeakref_CheckRef(ref));
6024 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6025 assert(subclass != NULL);
6026 if ((PyObject *)subclass == Py_None)
6027 continue;
6028 assert(PyType_Check(subclass));
6029 /* Avoid recursing down into unaffected classes */
6030 dict = subclass->tp_dict;
6031 if (dict != NULL && PyDict_Check(dict) &&
6032 PyDict_GetItem(dict, name) != NULL)
6033 continue;
6034 if (update_subclasses(subclass, name, callback, data) < 0)
6035 return -1;
6036 }
6037 return 0;
6038}
6039
Guido van Rossum6d204072001-10-21 00:44:31 +00006040/* This function is called by PyType_Ready() to populate the type's
6041 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006042 function slot (like tp_repr) that's defined in the type, one or more
6043 corresponding descriptors are added in the type's tp_dict dictionary
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006044 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006045 cause more than one descriptor to be added (for example, the nb_add
6046 slot adds both __add__ and __radd__ descriptors) and some function
6047 slots compete for the same descriptor (for example both sq_item and
6048 mp_subscript generate a __getitem__ descriptor).
6049
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006050 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006051 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006052 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006053 between competing slots: the members of PyHeapTypeObject are listed
6054 from most general to least general, so the most general slot is
6055 preferred. In particular, because as_mapping comes before as_sequence,
6056 for a type that defines both mp_subscript and sq_item, mp_subscript
6057 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006058
6059 This only adds new descriptors and doesn't overwrite entries in
6060 tp_dict that were previously defined. The descriptors contain a
6061 reference to the C function they must call, so that it's safe if they
6062 are copied into a subtype's __dict__ and the subtype has a different
6063 C function in its slot -- calling the method defined by the
6064 descriptor will call the C function that was used to create it,
6065 rather than the C function present in the slot when it is called.
6066 (This is important because a subtype may have a C function in the
6067 slot that calls the method from the dictionary, and we want to avoid
6068 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006069
6070static int
6071add_operators(PyTypeObject *type)
6072{
6073 PyObject *dict = type->tp_dict;
6074 slotdef *p;
6075 PyObject *descr;
6076 void **ptr;
6077
6078 init_slotdefs();
6079 for (p = slotdefs; p->name; p++) {
6080 if (p->wrapper == NULL)
6081 continue;
6082 ptr = slotptr(type, p->offset);
6083 if (!ptr || !*ptr)
6084 continue;
6085 if (PyDict_GetItem(dict, p->name_strobj))
6086 continue;
6087 descr = PyDescr_NewWrapper(type, p, *ptr);
6088 if (descr == NULL)
6089 return -1;
6090 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6091 return -1;
6092 Py_DECREF(descr);
6093 }
6094 if (type->tp_new != NULL) {
6095 if (add_tp_new_wrapper(type) < 0)
6096 return -1;
6097 }
6098 return 0;
6099}
6100
Guido van Rossum705f0f52001-08-24 16:47:00 +00006101
6102/* Cooperative 'super' */
6103
6104typedef struct {
6105 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00006106 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006107 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006108 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006109} superobject;
6110
Guido van Rossum6f799372001-09-20 20:46:19 +00006111static PyMemberDef super_members[] = {
6112 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6113 "the class invoking super()"},
6114 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6115 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006116 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00006117 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006118 {0}
6119};
6120
Guido van Rossum705f0f52001-08-24 16:47:00 +00006121static void
6122super_dealloc(PyObject *self)
6123{
6124 superobject *su = (superobject *)self;
6125
Guido van Rossum048eb752001-10-02 21:24:57 +00006126 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006127 Py_XDECREF(su->obj);
6128 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006129 Py_XDECREF(su->obj_type);
Christian Heimese93237d2007-12-19 02:37:44 +00006130 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006131}
6132
6133static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006134super_repr(PyObject *self)
6135{
6136 superobject *su = (superobject *)self;
6137
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006138 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006139 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00006140 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006141 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006142 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006143 else
6144 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00006145 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006146 su->type ? su->type->tp_name : "NULL");
6147}
6148
6149static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006150super_getattro(PyObject *self, PyObject *name)
6151{
6152 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006153 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006154
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006155 if (!skip) {
6156 /* We want __class__ to return the class of the super object
6157 (i.e. super, or a subclass), not the class of su->obj. */
6158 skip = (PyString_Check(name) &&
6159 PyString_GET_SIZE(name) == 9 &&
6160 strcmp(PyString_AS_STRING(name), "__class__") == 0);
6161 }
6162
6163 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00006164 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006165 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006166 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006167 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006168
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006169 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006170 mro = starttype->tp_mro;
6171
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006172 if (mro == NULL)
6173 n = 0;
6174 else {
6175 assert(PyTuple_Check(mro));
6176 n = PyTuple_GET_SIZE(mro);
6177 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006178 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00006179 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00006180 break;
6181 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006182 i++;
6183 res = NULL;
6184 for (; i < n; i++) {
6185 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00006186 if (PyType_Check(tmp))
6187 dict = ((PyTypeObject *)tmp)->tp_dict;
6188 else if (PyClass_Check(tmp))
6189 dict = ((PyClassObject *)tmp)->cl_dict;
6190 else
6191 continue;
6192 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00006193 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00006194 Py_INCREF(res);
Christian Heimese93237d2007-12-19 02:37:44 +00006195 f = Py_TYPE(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006196 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006197 tmp = f(res,
6198 /* Only pass 'obj' param if
6199 this is instance-mode super
6200 (See SF ID #743627)
6201 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00006202 (su->obj == (PyObject *)
6203 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006204 ? (PyObject *)NULL
6205 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00006206 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006207 Py_DECREF(res);
6208 res = tmp;
6209 }
6210 return res;
6211 }
6212 }
6213 }
6214 return PyObject_GenericGetAttr(self, name);
6215}
6216
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006217static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006218supercheck(PyTypeObject *type, PyObject *obj)
6219{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006220 /* Check that a super() call makes sense. Return a type object.
6221
6222 obj can be a new-style class, or an instance of one:
6223
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006224 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006225 used for class methods; the return value is obj.
6226
6227 - If it is an instance, it must be an instance of 'type'. This is
6228 the normal case; the return value is obj.__class__.
6229
6230 But... when obj is an instance, we want to allow for the case where
Christian Heimese93237d2007-12-19 02:37:44 +00006231 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006232 This will allow using super() with a proxy for obj.
6233 */
6234
Guido van Rossum8e80a722003-02-18 19:22:22 +00006235 /* Check for first bullet above (special case) */
6236 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6237 Py_INCREF(obj);
6238 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006239 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006240
6241 /* Normal case */
Christian Heimese93237d2007-12-19 02:37:44 +00006242 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6243 Py_INCREF(Py_TYPE(obj));
6244 return Py_TYPE(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006245 }
6246 else {
6247 /* Try the slow way */
6248 static PyObject *class_str = NULL;
6249 PyObject *class_attr;
6250
6251 if (class_str == NULL) {
6252 class_str = PyString_FromString("__class__");
6253 if (class_str == NULL)
6254 return NULL;
6255 }
6256
6257 class_attr = PyObject_GetAttr(obj, class_str);
6258
6259 if (class_attr != NULL &&
6260 PyType_Check(class_attr) &&
Christian Heimese93237d2007-12-19 02:37:44 +00006261 (PyTypeObject *)class_attr != Py_TYPE(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006262 {
6263 int ok = PyType_IsSubtype(
6264 (PyTypeObject *)class_attr, type);
6265 if (ok)
6266 return (PyTypeObject *)class_attr;
6267 }
6268
6269 if (class_attr == NULL)
6270 PyErr_Clear();
6271 else
6272 Py_DECREF(class_attr);
6273 }
6274
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006275 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006276 "super(type, obj): "
6277 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006278 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006279}
6280
Guido van Rossum705f0f52001-08-24 16:47:00 +00006281static PyObject *
6282super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6283{
6284 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00006285 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006286
6287 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6288 /* Not binding to an object, or already bound */
6289 Py_INCREF(self);
6290 return self;
6291 }
Christian Heimese93237d2007-12-19 02:37:44 +00006292 if (Py_TYPE(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00006293 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006294 call its type */
Christian Heimese93237d2007-12-19 02:37:44 +00006295 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006296 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00006297 else {
6298 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006299 PyTypeObject *obj_type = supercheck(su->type, obj);
6300 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006301 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00006302 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006303 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00006304 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006305 return NULL;
6306 Py_INCREF(su->type);
6307 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00006308 newobj->type = su->type;
6309 newobj->obj = obj;
6310 newobj->obj_type = obj_type;
6311 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006312 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006313}
6314
6315static int
6316super_init(PyObject *self, PyObject *args, PyObject *kwds)
6317{
6318 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00006319 PyTypeObject *type;
6320 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006321 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006322
Georg Brandl5d59c092006-09-30 08:43:30 +00006323 if (!_PyArg_NoKeywords("super", kwds))
6324 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006325 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
6326 return -1;
6327 if (obj == Py_None)
6328 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006329 if (obj != NULL) {
6330 obj_type = supercheck(type, obj);
6331 if (obj_type == NULL)
6332 return -1;
6333 Py_INCREF(obj);
6334 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006335 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006336 su->type = type;
6337 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006338 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006339 return 0;
6340}
6341
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006342PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00006343"super(type) -> unbound super object\n"
6344"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006345"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006346"Typical use to call a cooperative superclass method:\n"
6347"class C(B):\n"
6348" def meth(self, arg):\n"
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006349" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006350
Guido van Rossum048eb752001-10-02 21:24:57 +00006351static int
6352super_traverse(PyObject *self, visitproc visit, void *arg)
6353{
6354 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006355
Thomas Woutersc6e55062006-04-15 21:47:09 +00006356 Py_VISIT(su->obj);
6357 Py_VISIT(su->type);
6358 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006359
6360 return 0;
6361}
6362
Guido van Rossum705f0f52001-08-24 16:47:00 +00006363PyTypeObject PySuper_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00006364 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00006365 "super", /* tp_name */
6366 sizeof(superobject), /* tp_basicsize */
6367 0, /* tp_itemsize */
6368 /* methods */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006369 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006370 0, /* tp_print */
6371 0, /* tp_getattr */
6372 0, /* tp_setattr */
6373 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006374 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006375 0, /* tp_as_number */
6376 0, /* tp_as_sequence */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006377 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006378 0, /* tp_hash */
6379 0, /* tp_call */
6380 0, /* tp_str */
6381 super_getattro, /* tp_getattro */
6382 0, /* tp_setattro */
6383 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006384 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6385 Py_TPFLAGS_BASETYPE, /* tp_flags */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006386 super_doc, /* tp_doc */
6387 super_traverse, /* tp_traverse */
6388 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006389 0, /* tp_richcompare */
6390 0, /* tp_weaklistoffset */
6391 0, /* tp_iter */
6392 0, /* tp_iternext */
6393 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006394 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006395 0, /* tp_getset */
6396 0, /* tp_base */
6397 0, /* tp_dict */
6398 super_descr_get, /* tp_descr_get */
6399 0, /* tp_descr_set */
6400 0, /* tp_dictoffset */
6401 super_init, /* tp_init */
6402 PyType_GenericAlloc, /* tp_alloc */
6403 PyType_GenericNew, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006404 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006405};