blob: 33b2023f0cae2e391e7f562954c2b270968a9257 [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"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00004#include "frameobject.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum9923ffe2002-06-04 19:52:53 +00007#include <ctype.h>
8
Christian Heimesa62da1d2008-01-12 19:39:10 +00009
10/* Support type attribute cache */
11
12/* The cache can keep references to the names alive for longer than
13 they normally would. This is why the maximum size is limited to
14 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
15 strings are used as attribute names. */
16#define MCACHE_MAX_ATTR_SIZE 100
17#define MCACHE_SIZE_EXP 10
18#define MCACHE_HASH(version, name_hash) \
19 (((unsigned int)(version) * (unsigned int)(name_hash)) \
20 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
21#define MCACHE_HASH_METHOD(type, name) \
22 MCACHE_HASH((type)->tp_version_tag, \
23 ((PyStringObject *)(name))->ob_shash)
24#define MCACHE_CACHEABLE_NAME(name) \
25 PyString_CheckExact(name) && \
26 PyString_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
27
28struct method_cache_entry {
29 unsigned int version;
30 PyObject *name; /* reference to exactly a str or None */
31 PyObject *value; /* borrowed */
32};
33
34static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
35static unsigned int next_version_tag = 0;
36
37static void
38type_modified(PyTypeObject *type)
39{
40 /* Invalidate any cached data for the specified type and all
41 subclasses. This function is called after the base
42 classes, mro, or attributes of the type are altered.
43
44 Invariants:
45
46 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
47 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
48 objects coming from non-recompiled extension modules)
49
50 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
51 it must first be set on all super types.
52
53 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
54 type (so it must first clear it on all subclasses). The
55 tp_version_tag value is meaningless unless this flag is set.
56 We don't assign new version tags eagerly, but only as
57 needed.
58 */
59 PyObject *raw, *ref;
60 Py_ssize_t i, n;
61
Christian Heimes412dc9c2008-01-27 18:55:54 +000062 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
Christian Heimesa62da1d2008-01-12 19:39:10 +000063 return;
64
65 raw = type->tp_subclasses;
66 if (raw != NULL) {
67 n = PyList_GET_SIZE(raw);
68 for (i = 0; i < n; i++) {
69 ref = PyList_GET_ITEM(raw, i);
70 ref = PyWeakref_GET_OBJECT(ref);
71 if (ref != Py_None) {
72 type_modified((PyTypeObject *)ref);
73 }
74 }
75 }
76 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
77}
78
79static void
80type_mro_modified(PyTypeObject *type, PyObject *bases) {
81 /*
82 Check that all base classes or elements of the mro of type are
83 able to be cached. This function is called after the base
84 classes or mro of the type are altered.
85
86 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
87 inherits from an old-style class, either directly or if it
88 appears in the MRO of a new-style class. No support either for
89 custom MROs that include types that are not officially super
90 types.
91
92 Called from mro_internal, which will subsequently be called on
93 each subclass when their mro is recursively updated.
94 */
95 Py_ssize_t i, n;
96 int clear = 0;
97
Christian Heimes412dc9c2008-01-27 18:55:54 +000098 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
Christian Heimesa62da1d2008-01-12 19:39:10 +000099 return;
100
101 n = PyTuple_GET_SIZE(bases);
102 for (i = 0; i < n; i++) {
103 PyObject *b = PyTuple_GET_ITEM(bases, i);
104 PyTypeObject *cls;
105
106 if (!PyType_Check(b) ) {
107 clear = 1;
108 break;
109 }
110
111 cls = (PyTypeObject *)b;
112
113 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
114 !PyType_IsSubtype(type, cls)) {
115 clear = 1;
116 break;
117 }
118 }
119
120 if (clear)
121 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
122 Py_TPFLAGS_VALID_VERSION_TAG);
123}
124
125static int
126assign_version_tag(PyTypeObject *type)
127{
128 /* Ensure that the tp_version_tag is valid and set
129 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
130 must first be done on all super classes. Return 0 if this
131 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
132 */
133 Py_ssize_t i, n;
134 PyObject *bases;
135
136 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
137 return 1;
138 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
139 return 0;
140 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
141 return 0;
142
143 type->tp_version_tag = next_version_tag++;
144 /* for stress-testing: next_version_tag &= 0xFF; */
145
146 if (type->tp_version_tag == 0) {
147 /* wrap-around or just starting Python - clear the whole
148 cache by filling names with references to Py_None.
149 Values are also set to NULL for added protection, as they
150 are borrowed reference */
151 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
152 method_cache[i].value = NULL;
153 Py_XDECREF(method_cache[i].name);
154 method_cache[i].name = Py_None;
155 Py_INCREF(Py_None);
156 }
157 /* mark all version tags as invalid */
158 type_modified(&PyBaseObject_Type);
159 return 1;
160 }
161 bases = type->tp_bases;
162 n = PyTuple_GET_SIZE(bases);
163 for (i = 0; i < n; i++) {
164 PyObject *b = PyTuple_GET_ITEM(bases, i);
165 assert(PyType_Check(b));
166 if (!assign_version_tag((PyTypeObject *)b))
167 return 0;
168 }
169 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
170 return 1;
171}
172
173
Guido van Rossum6f799372001-09-20 20:46:19 +0000174static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000175 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
176 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
177 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +0000178 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000179 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
180 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
181 {"__dictoffset__", T_LONG,
182 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000183 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
184 {0}
185};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000186
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000187static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000188type_name(PyTypeObject *type, void *context)
189{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000190 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000191
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000192 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +0000193 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000194
Georg Brandlc255c7b2006-02-20 22:27:28 +0000195 Py_INCREF(et->ht_name);
196 return et->ht_name;
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000197 }
198 else {
199 s = strrchr(type->tp_name, '.');
200 if (s == NULL)
201 s = type->tp_name;
202 else
203 s++;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000204 return PyUnicode_FromString(s);
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000205 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000206}
207
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000208static int
209type_set_name(PyTypeObject *type, PyObject *value, void *context)
210{
Guido van Rossume5c691a2003-03-07 15:13:17 +0000211 PyHeapTypeObject* et;
Neal Norwitz80e7f272007-08-26 06:45:23 +0000212 char *tp_name;
Guido van Rossume845c0f2007-11-02 23:07:07 +0000213 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000214
215 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
216 PyErr_Format(PyExc_TypeError,
217 "can't set %s.__name__", type->tp_name);
218 return -1;
219 }
220 if (!value) {
221 PyErr_Format(PyExc_TypeError,
222 "can't delete %s.__name__", type->tp_name);
223 return -1;
224 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000225 if (!PyUnicode_Check(value)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000226 PyErr_Format(PyExc_TypeError,
227 "can only assign string to %s.__name__, not '%s'",
Christian Heimes90aa7642007-12-19 02:45:37 +0000228 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000229 return -1;
230 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000231
232 /* Check absence of null characters */
233 tmp = PyUnicode_FromStringAndSize("\0", 1);
234 if (tmp == NULL)
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000235 return -1;
Guido van Rossume845c0f2007-11-02 23:07:07 +0000236 if (PyUnicode_Contains(value, tmp) != 0) {
237 Py_DECREF(tmp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000238 PyErr_Format(PyExc_ValueError,
239 "__name__ must not contain null bytes");
240 return -1;
241 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000242 Py_DECREF(tmp);
243
244 tp_name = PyUnicode_AsString(value);
245 if (tp_name == NULL)
246 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000247
Guido van Rossume5c691a2003-03-07 15:13:17 +0000248 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000249
250 Py_INCREF(value);
251
Georg Brandlc255c7b2006-02-20 22:27:28 +0000252 Py_DECREF(et->ht_name);
253 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000254
Neal Norwitz80e7f272007-08-26 06:45:23 +0000255 type->tp_name = tp_name;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000256
257 return 0;
258}
259
Guido van Rossumc3542212001-08-16 09:18:56 +0000260static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000261type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000262{
Guido van Rossumc3542212001-08-16 09:18:56 +0000263 PyObject *mod;
264 char *s;
265
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000266 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
267 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +0000268 if (!mod) {
269 PyErr_Format(PyExc_AttributeError, "__module__");
270 return 0;
271 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000272 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +0000273 return mod;
274 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000275 else {
276 s = strrchr(type->tp_name, '.');
277 if (s != NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +0000278 return PyUnicode_FromStringAndSize(
Thomas Wouters89f507f2006-12-13 04:49:30 +0000279 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Georg Brandl1a3284e2007-12-02 09:40:06 +0000280 return PyUnicode_FromString("builtins");
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000281 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000282}
283
Guido van Rossum3926a632001-09-25 16:25:58 +0000284static int
285type_set_module(PyTypeObject *type, PyObject *value, void *context)
286{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000287 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000288 PyErr_Format(PyExc_TypeError,
289 "can't set %s.__module__", type->tp_name);
290 return -1;
291 }
292 if (!value) {
293 PyErr_Format(PyExc_TypeError,
294 "can't delete %s.__module__", type->tp_name);
295 return -1;
296 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000297
Christian Heimesa62da1d2008-01-12 19:39:10 +0000298 type_modified(type);
299
Guido van Rossum3926a632001-09-25 16:25:58 +0000300 return PyDict_SetItemString(type->tp_dict, "__module__", value);
301}
302
Tim Peters6d6c1a32001-08-02 04:15:00 +0000303static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000304type_get_bases(PyTypeObject *type, void *context)
305{
306 Py_INCREF(type->tp_bases);
307 return type->tp_bases;
308}
309
310static PyTypeObject *best_base(PyObject *);
311static int mro_internal(PyTypeObject *);
312static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
313static int add_subclass(PyTypeObject*, PyTypeObject*);
314static void remove_subclass(PyTypeObject *, PyTypeObject *);
315static void update_all_slots(PyTypeObject *);
316
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000317typedef int (*update_callback)(PyTypeObject *, void *);
318static int update_subclasses(PyTypeObject *type, PyObject *name,
319 update_callback callback, void *data);
320static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
321 update_callback callback, void *data);
322
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000323static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000324mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000325{
326 PyTypeObject *subclass;
327 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000328 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000329
330 subclasses = type->tp_subclasses;
331 if (subclasses == NULL)
332 return 0;
333 assert(PyList_Check(subclasses));
334 n = PyList_GET_SIZE(subclasses);
335 for (i = 0; i < n; i++) {
336 ref = PyList_GET_ITEM(subclasses, i);
337 assert(PyWeakref_CheckRef(ref));
338 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
339 assert(subclass != NULL);
340 if ((PyObject *)subclass == Py_None)
341 continue;
342 assert(PyType_Check(subclass));
343 old_mro = subclass->tp_mro;
344 if (mro_internal(subclass) < 0) {
345 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000346 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000347 }
348 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000349 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000350 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000351 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000352 if (!tuple)
353 return -1;
354 if (PyList_Append(temp, tuple) < 0)
355 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000356 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000357 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000358 if (mro_subclasses(subclass, temp) < 0)
359 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000360 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000361 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000362}
363
364static int
365type_set_bases(PyTypeObject *type, PyObject *value, void *context)
366{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000367 Py_ssize_t i;
368 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000369 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000370 PyTypeObject *new_base, *old_base;
371 PyObject *old_bases, *old_mro;
372
373 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
374 PyErr_Format(PyExc_TypeError,
375 "can't set %s.__bases__", type->tp_name);
376 return -1;
377 }
378 if (!value) {
379 PyErr_Format(PyExc_TypeError,
380 "can't delete %s.__bases__", type->tp_name);
381 return -1;
382 }
383 if (!PyTuple_Check(value)) {
384 PyErr_Format(PyExc_TypeError,
385 "can only assign tuple to %s.__bases__, not %s",
Christian Heimes90aa7642007-12-19 02:45:37 +0000386 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000387 return -1;
388 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000389 if (PyTuple_GET_SIZE(value) == 0) {
390 PyErr_Format(PyExc_TypeError,
391 "can only assign non-empty tuple to %s.__bases__, not ()",
392 type->tp_name);
393 return -1;
394 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000395 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
396 ob = PyTuple_GET_ITEM(value, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000397 if (!PyType_Check(ob)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000398 PyErr_Format(
399 PyExc_TypeError,
400 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
Christian Heimes90aa7642007-12-19 02:45:37 +0000401 type->tp_name, Py_TYPE(ob)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000402 return -1;
403 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000404 if (PyType_Check(ob)) {
405 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
406 PyErr_SetString(PyExc_TypeError,
407 "a __bases__ item causes an inheritance cycle");
408 return -1;
409 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000410 }
411 }
412
413 new_base = best_base(value);
414
415 if (!new_base) {
416 return -1;
417 }
418
419 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
420 return -1;
421
422 Py_INCREF(new_base);
423 Py_INCREF(value);
424
425 old_bases = type->tp_bases;
426 old_base = type->tp_base;
427 old_mro = type->tp_mro;
428
429 type->tp_bases = value;
430 type->tp_base = new_base;
431
432 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000433 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000434 }
435
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000436 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000437 if (!temp)
438 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000439
440 r = mro_subclasses(type, temp);
441
442 if (r < 0) {
443 for (i = 0; i < PyList_Size(temp); i++) {
444 PyTypeObject* cls;
445 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000446 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
447 "", 2, 2, &cls, &mro);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000448 Py_INCREF(mro);
449 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000450 cls->tp_mro = mro;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000451 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000452 }
453 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000454 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000455 }
456
457 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000458
459 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000460 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000461 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000462 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000463
464 /* for now, sod that: just remove from all old_bases,
465 add to all new_bases */
466
467 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
468 ob = PyTuple_GET_ITEM(old_bases, i);
469 if (PyType_Check(ob)) {
470 remove_subclass(
471 (PyTypeObject*)ob, type);
472 }
473 }
474
475 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
476 ob = PyTuple_GET_ITEM(value, i);
477 if (PyType_Check(ob)) {
478 if (add_subclass((PyTypeObject*)ob, type) < 0)
479 r = -1;
480 }
481 }
482
483 update_all_slots(type);
484
485 Py_DECREF(old_bases);
486 Py_DECREF(old_base);
487 Py_DECREF(old_mro);
488
489 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000490
491 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000492 Py_DECREF(type->tp_bases);
493 Py_DECREF(type->tp_base);
494 if (type->tp_mro != old_mro) {
495 Py_DECREF(type->tp_mro);
496 }
497
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000498 type->tp_bases = old_bases;
499 type->tp_base = old_base;
500 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000501
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000502 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000503}
504
505static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000506type_dict(PyTypeObject *type, void *context)
507{
508 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000509 Py_INCREF(Py_None);
510 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000511 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000512 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000513}
514
Tim Peters24008312002-03-17 18:56:20 +0000515static PyObject *
516type_get_doc(PyTypeObject *type, void *context)
517{
518 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000519 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Neal Norwitza369c5a2007-08-25 07:41:59 +0000520 return PyUnicode_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000521 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000522 if (result == NULL) {
523 result = Py_None;
524 Py_INCREF(result);
525 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000526 else if (Py_TYPE(result)->tp_descr_get) {
527 result = Py_TYPE(result)->tp_descr_get(result, NULL,
Tim Peters2b858972002-04-18 04:12:28 +0000528 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000529 }
530 else {
531 Py_INCREF(result);
532 }
Tim Peters24008312002-03-17 18:56:20 +0000533 return result;
534}
535
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000536static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000537 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
538 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000539 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000540 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000541 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000542 {0}
543};
544
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000545static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000546type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000547{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000548 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000549 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000550
551 mod = type_module(type, NULL);
552 if (mod == NULL)
553 PyErr_Clear();
Martin v. Löwis5b222132007-06-10 09:51:05 +0000554 else if (!PyUnicode_Check(mod)) {
Guido van Rossumc3542212001-08-16 09:18:56 +0000555 Py_DECREF(mod);
556 mod = NULL;
557 }
558 name = type_name(type, NULL);
559 if (name == NULL)
560 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000561
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000562 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
563 kind = "class";
564 else
565 kind = "type";
566
Georg Brandl1a3284e2007-12-02 09:40:06 +0000567 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
Walter Dörwald75163602007-06-11 15:47:13 +0000568 rtn = PyUnicode_FromFormat("<%s '%U.%U'>", kind, mod, name);
Guido van Rossumc3542212001-08-16 09:18:56 +0000569 else
Walter Dörwald1ab83302007-05-18 17:15:44 +0000570 rtn = PyUnicode_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000571
Guido van Rossumc3542212001-08-16 09:18:56 +0000572 Py_XDECREF(mod);
573 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000574 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000575}
576
Tim Peters6d6c1a32001-08-02 04:15:00 +0000577static PyObject *
578type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
579{
580 PyObject *obj;
581
582 if (type->tp_new == NULL) {
583 PyErr_Format(PyExc_TypeError,
584 "cannot create '%.100s' instances",
585 type->tp_name);
586 return NULL;
587 }
588
Tim Peters3f996e72001-09-13 19:18:27 +0000589 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000590 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000591 /* Ugly exception: when the call was type(something),
592 don't call tp_init on the result. */
593 if (type == &PyType_Type &&
594 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
595 (kwds == NULL ||
596 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
597 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000598 /* If the returned object is not an instance of type,
599 it won't be initialized. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000600 if (!PyType_IsSubtype(Py_TYPE(obj), type))
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000601 return obj;
Christian Heimes90aa7642007-12-19 02:45:37 +0000602 type = Py_TYPE(obj);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000603 if (type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000604 type->tp_init(obj, args, kwds) < 0) {
605 Py_DECREF(obj);
606 obj = NULL;
607 }
608 }
609 return obj;
610}
611
612PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000613PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000614{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000615 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000616 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
617 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000618
619 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000620 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000621 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000622 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000623
Neil Schemenauerc806c882001-08-29 23:54:54 +0000624 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000625 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000626
Neil Schemenauerc806c882001-08-29 23:54:54 +0000627 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000628
Tim Peters6d6c1a32001-08-02 04:15:00 +0000629 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
630 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000631
Tim Peters6d6c1a32001-08-02 04:15:00 +0000632 if (type->tp_itemsize == 0)
633 PyObject_INIT(obj, type);
634 else
635 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000636
Tim Peters6d6c1a32001-08-02 04:15:00 +0000637 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000638 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000639 return obj;
640}
641
642PyObject *
643PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
644{
645 return type->tp_alloc(type, 0);
646}
647
Guido van Rossum9475a232001-10-05 20:51:39 +0000648/* Helpers for subtyping */
649
650static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000651traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
652{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000653 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000654 PyMemberDef *mp;
655
Christian Heimes90aa7642007-12-19 02:45:37 +0000656 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000657 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000658 for (i = 0; i < n; i++, mp++) {
659 if (mp->type == T_OBJECT_EX) {
660 char *addr = (char *)self + mp->offset;
661 PyObject *obj = *(PyObject **)addr;
662 if (obj != NULL) {
663 int err = visit(obj, arg);
664 if (err)
665 return err;
666 }
667 }
668 }
669 return 0;
670}
671
672static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000673subtype_traverse(PyObject *self, visitproc visit, void *arg)
674{
675 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000676 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000677
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000678 /* Find the nearest base with a different tp_traverse,
679 and traverse slots while we're at it */
Christian Heimes90aa7642007-12-19 02:45:37 +0000680 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000681 base = type;
682 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000683 if (Py_SIZE(base)) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000684 int err = traverse_slots(base, self, visit, arg);
685 if (err)
686 return err;
687 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000688 base = base->tp_base;
689 assert(base);
690 }
691
692 if (type->tp_dictoffset != base->tp_dictoffset) {
693 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000694 if (dictptr && *dictptr)
695 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000696 }
697
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000698 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000699 /* For a heaptype, the instances count as references
Guido van Rossumd8faa362007-04-27 19:54:29 +0000700 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000701 can find cycles involving this link. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000702 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000703
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000704 if (basetraverse)
705 return basetraverse(self, visit, arg);
706 return 0;
707}
708
709static void
710clear_slots(PyTypeObject *type, PyObject *self)
711{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000712 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000713 PyMemberDef *mp;
714
Christian Heimes90aa7642007-12-19 02:45:37 +0000715 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000716 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000717 for (i = 0; i < n; i++, mp++) {
718 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
719 char *addr = (char *)self + mp->offset;
720 PyObject *obj = *(PyObject **)addr;
721 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000722 *(PyObject **)addr = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000723 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000724 }
725 }
726 }
727}
728
729static int
730subtype_clear(PyObject *self)
731{
732 PyTypeObject *type, *base;
733 inquiry baseclear;
734
735 /* Find the nearest base with a different tp_clear
736 and clear slots while we're at it */
Christian Heimes90aa7642007-12-19 02:45:37 +0000737 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000738 base = type;
739 while ((baseclear = base->tp_clear) == subtype_clear) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000740 if (Py_SIZE(base))
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000741 clear_slots(base, self);
742 base = base->tp_base;
743 assert(base);
744 }
745
Guido van Rossuma3862092002-06-10 15:24:42 +0000746 /* There's no need to clear the instance dict (if any);
747 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000748
749 if (baseclear)
750 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000751 return 0;
752}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000753
754static void
755subtype_dealloc(PyObject *self)
756{
Guido van Rossum14227b42001-12-06 02:35:58 +0000757 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000758 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000759
Guido van Rossum22b13872002-08-06 21:41:44 +0000760 /* Extract the type; we expect it to be a heap type */
Christian Heimes90aa7642007-12-19 02:45:37 +0000761 type = Py_TYPE(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000762 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000763
Guido van Rossum22b13872002-08-06 21:41:44 +0000764 /* Test whether the type has GC exactly once */
765
766 if (!PyType_IS_GC(type)) {
767 /* It's really rare to find a dynamic type that doesn't have
768 GC; it can only happen when deriving from 'object' and not
769 adding any slots or instance variables. This allows
770 certain simplifications: there's no need to call
771 clear_slots(), or DECREF the dict, or clear weakrefs. */
772
773 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000774 if (type->tp_del) {
775 type->tp_del(self);
776 if (self->ob_refcnt > 0)
777 return;
778 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000779
780 /* Find the nearest base with a different tp_dealloc */
781 base = type;
782 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000783 assert(Py_SIZE(base) == 0);
Guido van Rossum22b13872002-08-06 21:41:44 +0000784 base = base->tp_base;
785 assert(base);
786 }
787
788 /* Call the base tp_dealloc() */
789 assert(basedealloc);
790 basedealloc(self);
791
792 /* Can't reference self beyond this point */
793 Py_DECREF(type);
794
795 /* Done */
796 return;
797 }
798
799 /* We get here only if the type has GC */
800
801 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000802 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000803 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000804 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000805 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000806 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000807 /* DO NOT restore GC tracking at this point. weakref callbacks
808 * (if any, and whether directly here or indirectly in something we
809 * call) may trigger GC, and if self is tracked at that point, it
810 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000811 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000812
Guido van Rossum59195fd2003-06-13 20:54:40 +0000813 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000814 base = type;
815 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000816 base = base->tp_base;
817 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000818 }
819
Guido van Rossumd8faa362007-04-27 19:54:29 +0000820 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000821 the finalizer (__del__), clearing slots, or clearing the instance
822 dict. */
823
Guido van Rossum1987c662003-05-29 14:29:23 +0000824 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
825 PyObject_ClearWeakRefs(self);
826
827 /* Maybe call finalizer; exit early if resurrected */
828 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000829 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000830 type->tp_del(self);
831 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000832 goto endlabel; /* resurrected */
833 else
834 _PyObject_GC_UNTRACK(self);
Thomas Woutersb2137042007-02-01 18:02:27 +0000835 /* New weakrefs could be created during the finalizer call.
836 If this occurs, clear them out without calling their
837 finalizers since they might rely on part of the object
838 being finalized that has already been destroyed. */
839 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
840 /* Modeled after GET_WEAKREFS_LISTPTR() */
841 PyWeakReference **list = (PyWeakReference **) \
842 PyObject_GET_WEAKREFS_LISTPTR(self);
843 while (*list)
844 _PyWeakref_ClearRef(*list);
845 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000846 }
847
Guido van Rossum59195fd2003-06-13 20:54:40 +0000848 /* Clear slots up to the nearest base with a different tp_dealloc */
849 base = type;
850 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000851 if (Py_SIZE(base))
Guido van Rossum59195fd2003-06-13 20:54:40 +0000852 clear_slots(base, self);
853 base = base->tp_base;
854 assert(base);
855 }
856
Tim Peters6d6c1a32001-08-02 04:15:00 +0000857 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000858 if (type->tp_dictoffset && !base->tp_dictoffset) {
859 PyObject **dictptr = _PyObject_GetDictPtr(self);
860 if (dictptr != NULL) {
861 PyObject *dict = *dictptr;
862 if (dict != NULL) {
863 Py_DECREF(dict);
864 *dictptr = NULL;
865 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000866 }
867 }
868
Tim Peters0bd743c2003-11-13 22:50:00 +0000869 /* Call the base tp_dealloc(); first retrack self if
870 * basedealloc knows about gc.
871 */
872 if (PyType_IS_GC(base))
873 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000874 assert(basedealloc);
875 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000876
877 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000878 Py_DECREF(type);
879
Guido van Rossum0906e072002-08-07 20:42:09 +0000880 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000881 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000882 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000883 --_PyTrash_delete_nesting;
884
885 /* Explanation of the weirdness around the trashcan macros:
886
887 Q. What do the trashcan macros do?
888
889 A. Read the comment titled "Trashcan mechanism" in object.h.
890 For one, this explains why there must be a call to GC-untrack
Guido van Rossumd8faa362007-04-27 19:54:29 +0000891 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000892 trashcan code, the answers to the following questions don't make
893 sense.
894
895 Q. Why do we GC-untrack before the trashcan and then immediately
896 GC-track again afterward?
897
898 A. In the case that the base class is GC-aware, the base class
Guido van Rossumd8faa362007-04-27 19:54:29 +0000899 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000900 UNTRACK macro, this will crash when the object is already
901 untracked. Because we don't know what the base class does, the
902 only safe thing is to make sure the object is tracked when we
903 call the base class dealloc. But... The trashcan begin macro
904 requires that the object is *untracked* before it is called. So
905 the dance becomes:
906
Guido van Rossumd8faa362007-04-27 19:54:29 +0000907 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000908 trashcan begin
909 GC track
910
Guido van Rossumd8faa362007-04-27 19:54:29 +0000911 Q. Why did the last question say "immediately GC-track again"?
912 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000913
Guido van Rossumd8faa362007-04-27 19:54:29 +0000914 A. Because the code *used* to re-track immediately. Bad Idea.
915 self has a refcount of 0, and if gc ever gets its hands on it
916 (which can happen if any weakref callback gets invoked), it
917 looks like trash to gc too, and gc also tries to delete self
918 then. But we're already deleting self. Double dealloction is
919 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +0000920
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000921 Q. Why the bizarre (net-zero) manipulation of
922 _PyTrash_delete_nesting around the trashcan macros?
923
924 A. Some base classes (e.g. list) also use the trashcan mechanism.
925 The following scenario used to be possible:
926
927 - suppose the trashcan level is one below the trashcan limit
928
929 - subtype_dealloc() is called
930
931 - the trashcan limit is not yet reached, so the trashcan level
Guido van Rossumd8faa362007-04-27 19:54:29 +0000932 is incremented and the code between trashcan begin and end is
933 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000934
935 - this destroys much of the object's contents, including its
Guido van Rossumd8faa362007-04-27 19:54:29 +0000936 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000937
938 - basedealloc() is called; this is really list_dealloc(), or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000939 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000940
941 - the trashcan limit is now reached, so the object is put on the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000942 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000943
944 - basedealloc() returns
945
946 - subtype_dealloc() decrefs the object's type
947
948 - subtype_dealloc() returns
949
950 - later, the trashcan code starts deleting the objects from its
Guido van Rossumd8faa362007-04-27 19:54:29 +0000951 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000952
953 - subtype_dealloc() is called *AGAIN* for the same object
954
955 - at the very least (if the destroyed slots and __dict__ don't
Guido van Rossumd8faa362007-04-27 19:54:29 +0000956 cause problems) the object's type gets decref'ed a second
957 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000958
959 The remedy is to make sure that if the code between trashcan
960 begin and end in subtype_dealloc() is called, the code between
961 trashcan begin and end in basedealloc() will also be called.
962 This is done by decrementing the level after passing into the
963 trashcan block, and incrementing it just before leaving the
964 block.
965
966 But now it's possible that a chain of objects consisting solely
967 of objects whose deallocator is subtype_dealloc() will defeat
968 the trashcan mechanism completely: the decremented level means
Guido van Rossumd8faa362007-04-27 19:54:29 +0000969 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000970 *increment* the level *before* entering the trashcan block, and
971 matchingly decrement it after leaving. This means the trashcan
972 code will trigger a little early, but that's no big deal.
973
974 Q. Are there any live examples of code in need of all this
975 complexity?
976
977 A. Yes. See SF bug 668433 for code that crashed (when Python was
978 compiled in debug mode) before the trashcan level manipulations
979 were added. For more discussion, see SF patches 581742, 575073
980 and bug 574207.
981 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000982}
983
Jeremy Hylton938ace62002-07-17 16:30:39 +0000984static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985
Tim Peters6d6c1a32001-08-02 04:15:00 +0000986/* type test with subclassing support */
987
988int
989PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
990{
991 PyObject *mro;
992
993 mro = a->tp_mro;
994 if (mro != NULL) {
995 /* Deal with multiple inheritance without recursion
996 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000997 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000998 assert(PyTuple_Check(mro));
999 n = PyTuple_GET_SIZE(mro);
1000 for (i = 0; i < n; i++) {
1001 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1002 return 1;
1003 }
1004 return 0;
1005 }
1006 else {
1007 /* a is not completely initilized yet; follow tp_base */
1008 do {
1009 if (a == b)
1010 return 1;
1011 a = a->tp_base;
1012 } while (a != NULL);
1013 return b == &PyBaseObject_Type;
1014 }
1015}
1016
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001017/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001018 without looking in the instance dictionary
1019 (so we can't use PyObject_GetAttr) but still binding
Guido van Rossumd8faa362007-04-27 19:54:29 +00001020 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001021 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001022 static variable used to cache the interned Python string.
1023
1024 Two variants:
1025
1026 - lookup_maybe() returns NULL without raising an exception
1027 when the _PyType_Lookup() call fails;
1028
1029 - lookup_method() always raises an exception upon errors.
1030*/
Guido van Rossum60718732001-08-28 17:47:51 +00001031
1032static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001033lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001034{
1035 PyObject *res;
1036
1037 if (*attrobj == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001038 *attrobj = PyUnicode_InternFromString(attrstr);
Guido van Rossum60718732001-08-28 17:47:51 +00001039 if (*attrobj == NULL)
1040 return NULL;
1041 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001042 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001043 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +00001044 descrgetfunc f;
Christian Heimes90aa7642007-12-19 02:45:37 +00001045 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
Guido van Rossum60718732001-08-28 17:47:51 +00001046 Py_INCREF(res);
1047 else
Christian Heimes90aa7642007-12-19 02:45:37 +00001048 res = f(res, self, (PyObject *)(Py_TYPE(self)));
Guido van Rossum60718732001-08-28 17:47:51 +00001049 }
1050 return res;
1051}
1052
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001053static PyObject *
1054lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1055{
1056 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1057 if (res == NULL && !PyErr_Occurred())
1058 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1059 return res;
1060}
1061
Guido van Rossum2730b132001-08-28 18:22:14 +00001062/* A variation of PyObject_CallMethod that uses lookup_method()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001063 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001064 as lookup_method to cache the interned name string object. */
1065
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001066static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001067call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1068{
1069 va_list va;
1070 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001071 va_start(va, format);
1072
Guido van Rossumda21c012001-10-03 00:50:18 +00001073 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001074 if (func == NULL) {
1075 va_end(va);
1076 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +00001077 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001078 return NULL;
1079 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001080
1081 if (format && *format)
1082 args = Py_VaBuildValue(format, va);
1083 else
1084 args = PyTuple_New(0);
1085
1086 va_end(va);
1087
1088 if (args == NULL)
1089 return NULL;
1090
1091 assert(PyTuple_Check(args));
1092 retval = PyObject_Call(func, args, NULL);
1093
1094 Py_DECREF(args);
1095 Py_DECREF(func);
1096
1097 return retval;
1098}
1099
1100/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1101
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001102static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001103call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1104{
1105 va_list va;
1106 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001107 va_start(va, format);
1108
Guido van Rossumda21c012001-10-03 00:50:18 +00001109 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +00001110 if (func == NULL) {
1111 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001112 if (!PyErr_Occurred()) {
1113 Py_INCREF(Py_NotImplemented);
1114 return Py_NotImplemented;
1115 }
Guido van Rossum717ce002001-09-14 16:58:08 +00001116 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001117 }
1118
1119 if (format && *format)
1120 args = Py_VaBuildValue(format, va);
1121 else
1122 args = PyTuple_New(0);
1123
1124 va_end(va);
1125
Guido van Rossum717ce002001-09-14 16:58:08 +00001126 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00001127 return NULL;
1128
Guido van Rossum717ce002001-09-14 16:58:08 +00001129 assert(PyTuple_Check(args));
1130 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001131
1132 Py_DECREF(args);
1133 Py_DECREF(func);
1134
1135 return retval;
1136}
1137
Tim Petersea7f75d2002-12-07 21:39:16 +00001138/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001139 Method resolution order algorithm C3 described in
1140 "A Monotonic Superclass Linearization for Dylan",
1141 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001142 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001143 (OOPSLA 1996)
1144
Guido van Rossum98f33732002-11-25 21:36:54 +00001145 Some notes about the rules implied by C3:
1146
Tim Petersea7f75d2002-12-07 21:39:16 +00001147 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001148 It isn't legal to repeat a class in a list of base classes.
1149
1150 The next three properties are the 3 constraints in "C3".
1151
Tim Petersea7f75d2002-12-07 21:39:16 +00001152 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001153 If A precedes B in C's MRO, then A will precede B in the MRO of all
1154 subclasses of C.
1155
1156 Monotonicity.
1157 The MRO of a class must be an extension without reordering of the
1158 MRO of each of its superclasses.
1159
1160 Extended Precedence Graph (EPG).
1161 Linearization is consistent if there is a path in the EPG from
1162 each class to all its successors in the linearization. See
1163 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001164 */
1165
Tim Petersea7f75d2002-12-07 21:39:16 +00001166static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001167tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001168 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001169 size = PyList_GET_SIZE(list);
1170
1171 for (j = whence+1; j < size; j++) {
1172 if (PyList_GET_ITEM(list, j) == o)
1173 return 1;
1174 }
1175 return 0;
1176}
1177
Guido van Rossum98f33732002-11-25 21:36:54 +00001178static PyObject *
1179class_name(PyObject *cls)
1180{
1181 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1182 if (name == NULL) {
1183 PyErr_Clear();
1184 Py_XDECREF(name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001185 name = PyObject_Repr(cls);
Guido van Rossum98f33732002-11-25 21:36:54 +00001186 }
1187 if (name == NULL)
1188 return NULL;
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001189 if (!PyUnicode_Check(name)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001190 Py_DECREF(name);
1191 return NULL;
1192 }
1193 return name;
1194}
1195
1196static int
1197check_duplicates(PyObject *list)
1198{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001199 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001200 /* Let's use a quadratic time algorithm,
1201 assuming that the bases lists is short.
1202 */
1203 n = PyList_GET_SIZE(list);
1204 for (i = 0; i < n; i++) {
1205 PyObject *o = PyList_GET_ITEM(list, i);
1206 for (j = i + 1; j < n; j++) {
1207 if (PyList_GET_ITEM(list, j) == o) {
1208 o = class_name(o);
1209 PyErr_Format(PyExc_TypeError,
1210 "duplicate base class %s",
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001211 o ? PyUnicode_AsString(o) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001212 Py_XDECREF(o);
1213 return -1;
1214 }
1215 }
1216 }
1217 return 0;
1218}
1219
1220/* Raise a TypeError for an MRO order disagreement.
1221
1222 It's hard to produce a good error message. In the absence of better
1223 insight into error reporting, report the classes that were candidates
Guido van Rossumd8faa362007-04-27 19:54:29 +00001224 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001225 order in which they should be put in the MRO, but it's hard to
1226 diagnose what constraint can't be satisfied.
1227*/
1228
1229static void
1230set_mro_error(PyObject *to_merge, int *remain)
1231{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001232 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001233 char buf[1000];
1234 PyObject *k, *v;
1235 PyObject *set = PyDict_New();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001236 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001237
1238 to_merge_size = PyList_GET_SIZE(to_merge);
1239 for (i = 0; i < to_merge_size; i++) {
1240 PyObject *L = PyList_GET_ITEM(to_merge, i);
1241 if (remain[i] < PyList_GET_SIZE(L)) {
1242 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001243 if (PyDict_SetItem(set, c, Py_None) < 0) {
1244 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001245 return;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001246 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001247 }
1248 }
1249 n = PyDict_Size(set);
1250
Raymond Hettingerf394df42003-04-06 19:13:41 +00001251 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1252consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001253 i = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001254 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001255 PyObject *name = class_name(k);
1256 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001257 name ? PyUnicode_AsString(name) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001258 Py_XDECREF(name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001259 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001260 buf[off++] = ',';
1261 buf[off] = '\0';
1262 }
1263 }
1264 PyErr_SetString(PyExc_TypeError, buf);
1265 Py_DECREF(set);
1266}
1267
Tim Petersea7f75d2002-12-07 21:39:16 +00001268static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001269pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001270 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001271 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001272 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001273
Guido van Rossum1f121312002-11-14 19:49:16 +00001274 to_merge_size = PyList_GET_SIZE(to_merge);
1275
Guido van Rossum98f33732002-11-25 21:36:54 +00001276 /* remain stores an index into each sublist of to_merge.
1277 remain[i] is the index of the next base in to_merge[i]
1278 that is not included in acc.
1279 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001280 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001281 if (remain == NULL)
1282 return -1;
1283 for (i = 0; i < to_merge_size; i++)
1284 remain[i] = 0;
1285
1286 again:
1287 empty_cnt = 0;
1288 for (i = 0; i < to_merge_size; i++) {
1289 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001290
Guido van Rossum1f121312002-11-14 19:49:16 +00001291 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1292
1293 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1294 empty_cnt++;
1295 continue;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001296 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001297
Guido van Rossum98f33732002-11-25 21:36:54 +00001298 /* Choose next candidate for MRO.
1299
1300 The input sequences alone can determine the choice.
1301 If not, choose the class which appears in the MRO
1302 of the earliest direct superclass of the new class.
1303 */
1304
Guido van Rossum1f121312002-11-14 19:49:16 +00001305 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1306 for (j = 0; j < to_merge_size; j++) {
1307 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001308 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001309 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001310 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001311 }
1312 ok = PyList_Append(acc, candidate);
1313 if (ok < 0) {
1314 PyMem_Free(remain);
1315 return -1;
1316 }
1317 for (j = 0; j < to_merge_size; j++) {
1318 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001319 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1320 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001321 remain[j]++;
1322 }
1323 }
1324 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001325 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001326 }
1327
Guido van Rossum98f33732002-11-25 21:36:54 +00001328 if (empty_cnt == to_merge_size) {
1329 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001330 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001331 }
1332 set_mro_error(to_merge, remain);
1333 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001334 return -1;
1335}
1336
Tim Peters6d6c1a32001-08-02 04:15:00 +00001337static PyObject *
1338mro_implementation(PyTypeObject *type)
1339{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001340 Py_ssize_t i, n;
1341 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001342 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001343 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001344
Christian Heimes412dc9c2008-01-27 18:55:54 +00001345 if (type->tp_dict == NULL) {
1346 if (PyType_Ready(type) < 0)
Guido van Rossum63517572002-06-18 16:44:57 +00001347 return NULL;
1348 }
1349
Guido van Rossum98f33732002-11-25 21:36:54 +00001350 /* Find a superclass linearization that honors the constraints
1351 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001352 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001353
1354 to_merge is a list of lists, where each list is a superclass
1355 linearization implied by a base class. The last element of
1356 to_merge is the declared list of bases.
1357 */
1358
Tim Peters6d6c1a32001-08-02 04:15:00 +00001359 bases = type->tp_bases;
1360 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001361
1362 to_merge = PyList_New(n+1);
1363 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001364 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001365
Tim Peters6d6c1a32001-08-02 04:15:00 +00001366 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001367 PyObject *base = PyTuple_GET_ITEM(bases, i);
1368 PyObject *parentMRO;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001369 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001370 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001371 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001373 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001374
1375 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001376 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001377
1378 bases_aslist = PySequence_List(bases);
1379 if (bases_aslist == NULL) {
1380 Py_DECREF(to_merge);
1381 return NULL;
1382 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001383 /* This is just a basic sanity check. */
1384 if (check_duplicates(bases_aslist) < 0) {
1385 Py_DECREF(to_merge);
1386 Py_DECREF(bases_aslist);
1387 return NULL;
1388 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001389 PyList_SET_ITEM(to_merge, n, bases_aslist);
1390
1391 result = Py_BuildValue("[O]", (PyObject *)type);
1392 if (result == NULL) {
1393 Py_DECREF(to_merge);
1394 return NULL;
1395 }
1396
1397 ok = pmerge(result, to_merge);
1398 Py_DECREF(to_merge);
1399 if (ok < 0) {
1400 Py_DECREF(result);
1401 return NULL;
1402 }
1403
Tim Peters6d6c1a32001-08-02 04:15:00 +00001404 return result;
1405}
1406
1407static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001408mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001409{
1410 PyTypeObject *type = (PyTypeObject *)self;
1411
Tim Peters6d6c1a32001-08-02 04:15:00 +00001412 return mro_implementation(type);
1413}
1414
1415static int
1416mro_internal(PyTypeObject *type)
1417{
1418 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001419 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001420
Christian Heimes90aa7642007-12-19 02:45:37 +00001421 if (Py_TYPE(type) == &PyType_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001422 result = mro_implementation(type);
1423 }
1424 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001425 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001426 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001427 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001428 if (mro == NULL)
1429 return -1;
1430 result = PyObject_CallObject(mro, NULL);
1431 Py_DECREF(mro);
1432 }
1433 if (result == NULL)
1434 return -1;
1435 tuple = PySequence_Tuple(result);
1436 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001437 if (tuple == NULL)
1438 return -1;
1439 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001440 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001441 PyObject *cls;
1442 PyTypeObject *solid;
1443
1444 solid = solid_base(type);
1445
1446 len = PyTuple_GET_SIZE(tuple);
1447
1448 for (i = 0; i < len; i++) {
1449 PyTypeObject *t;
1450 cls = PyTuple_GET_ITEM(tuple, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001451 if (!PyType_Check(cls)) {
Armin Rigo037d1e02005-12-29 17:07:39 +00001452 PyErr_Format(PyExc_TypeError,
1453 "mro() returned a non-class ('%.500s')",
Christian Heimes90aa7642007-12-19 02:45:37 +00001454 Py_TYPE(cls)->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001455 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001456 return -1;
1457 }
1458 t = (PyTypeObject*)cls;
1459 if (!PyType_IsSubtype(solid, solid_base(t))) {
1460 PyErr_Format(PyExc_TypeError,
1461 "mro() returned base with unsuitable layout ('%.500s')",
1462 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001463 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001464 return -1;
1465 }
1466 }
1467 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001468 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001469
1470 type_mro_modified(type, type->tp_mro);
1471 /* corner case: the old-style super class might have been hidden
1472 from the custom MRO */
1473 type_mro_modified(type, type->tp_bases);
1474
1475 type_modified(type);
1476
Tim Peters6d6c1a32001-08-02 04:15:00 +00001477 return 0;
1478}
1479
1480
1481/* Calculate the best base amongst multiple base classes.
1482 This is the first one that's on the path to the "solid base". */
1483
1484static PyTypeObject *
1485best_base(PyObject *bases)
1486{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001487 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001488 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001489 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001490
1491 assert(PyTuple_Check(bases));
1492 n = PyTuple_GET_SIZE(bases);
1493 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001494 base = NULL;
1495 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001496 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001497 base_proto = PyTuple_GET_ITEM(bases, i);
Tim Petersa91e9642001-11-14 23:32:33 +00001498 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001499 PyErr_SetString(
1500 PyExc_TypeError,
1501 "bases must be types");
1502 return NULL;
1503 }
Tim Petersa91e9642001-11-14 23:32:33 +00001504 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001505 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001506 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001507 return NULL;
1508 }
1509 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001510 if (winner == NULL) {
1511 winner = candidate;
1512 base = base_i;
1513 }
1514 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001515 ;
1516 else if (PyType_IsSubtype(candidate, winner)) {
1517 winner = candidate;
1518 base = base_i;
1519 }
1520 else {
1521 PyErr_SetString(
1522 PyExc_TypeError,
1523 "multiple bases have "
1524 "instance lay-out conflict");
1525 return NULL;
1526 }
1527 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001528 if (base == NULL)
1529 PyErr_SetString(PyExc_TypeError,
1530 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001531 return base;
1532}
1533
1534static int
1535extra_ivars(PyTypeObject *type, PyTypeObject *base)
1536{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001537 size_t t_size = type->tp_basicsize;
1538 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001539
Guido van Rossum9676b222001-08-17 20:32:36 +00001540 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001541 if (type->tp_itemsize || base->tp_itemsize) {
1542 /* If itemsize is involved, stricter rules */
1543 return t_size != b_size ||
1544 type->tp_itemsize != base->tp_itemsize;
1545 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001546 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001547 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1548 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001549 t_size -= sizeof(PyObject *);
1550 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001551 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1552 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001553 t_size -= sizeof(PyObject *);
1554
1555 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001556}
1557
1558static PyTypeObject *
1559solid_base(PyTypeObject *type)
1560{
1561 PyTypeObject *base;
1562
1563 if (type->tp_base)
1564 base = solid_base(type->tp_base);
1565 else
1566 base = &PyBaseObject_Type;
1567 if (extra_ivars(type, base))
1568 return type;
1569 else
1570 return base;
1571}
1572
Jeremy Hylton938ace62002-07-17 16:30:39 +00001573static void object_dealloc(PyObject *);
1574static int object_init(PyObject *, PyObject *, PyObject *);
1575static int update_slot(PyTypeObject *, PyObject *);
1576static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001577
Guido van Rossum360e4b82007-05-14 22:51:27 +00001578/*
1579 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1580 * inherited from various builtin types. The builtin base usually provides
1581 * its own __dict__ descriptor, so we use that when we can.
1582 */
1583static PyTypeObject *
1584get_builtin_base_with_dict(PyTypeObject *type)
1585{
1586 while (type->tp_base != NULL) {
1587 if (type->tp_dictoffset != 0 &&
1588 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1589 return type;
1590 type = type->tp_base;
1591 }
1592 return NULL;
1593}
1594
1595static PyObject *
1596get_dict_descriptor(PyTypeObject *type)
1597{
1598 static PyObject *dict_str;
1599 PyObject *descr;
1600
1601 if (dict_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001602 dict_str = PyUnicode_InternFromString("__dict__");
Guido van Rossum360e4b82007-05-14 22:51:27 +00001603 if (dict_str == NULL)
1604 return NULL;
1605 }
1606 descr = _PyType_Lookup(type, dict_str);
1607 if (descr == NULL || !PyDescr_IsData(descr))
1608 return NULL;
1609
1610 return descr;
1611}
1612
1613static void
1614raise_dict_descr_error(PyObject *obj)
1615{
1616 PyErr_Format(PyExc_TypeError,
1617 "this __dict__ descriptor does not support "
Christian Heimes90aa7642007-12-19 02:45:37 +00001618 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001619}
1620
Tim Peters6d6c1a32001-08-02 04:15:00 +00001621static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001622subtype_dict(PyObject *obj, void *context)
1623{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001624 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001625 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001626 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001627
Christian Heimes90aa7642007-12-19 02:45:37 +00001628 base = get_builtin_base_with_dict(Py_TYPE(obj));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001629 if (base != NULL) {
1630 descrgetfunc func;
1631 PyObject *descr = get_dict_descriptor(base);
1632 if (descr == NULL) {
1633 raise_dict_descr_error(obj);
1634 return NULL;
1635 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001636 func = Py_TYPE(descr)->tp_descr_get;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001637 if (func == NULL) {
1638 raise_dict_descr_error(obj);
1639 return NULL;
1640 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001641 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001642 }
1643
1644 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001645 if (dictptr == NULL) {
1646 PyErr_SetString(PyExc_AttributeError,
1647 "This object has no __dict__");
1648 return NULL;
1649 }
1650 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001651 if (dict == NULL)
1652 *dictptr = dict = PyDict_New();
1653 Py_XINCREF(dict);
1654 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001655}
1656
Guido van Rossum6661be32001-10-26 04:26:12 +00001657static int
1658subtype_setdict(PyObject *obj, PyObject *value, void *context)
1659{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001660 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001661 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001662 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001663
Christian Heimes90aa7642007-12-19 02:45:37 +00001664 base = get_builtin_base_with_dict(Py_TYPE(obj));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001665 if (base != NULL) {
1666 descrsetfunc func;
1667 PyObject *descr = get_dict_descriptor(base);
1668 if (descr == NULL) {
1669 raise_dict_descr_error(obj);
1670 return -1;
1671 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001672 func = Py_TYPE(descr)->tp_descr_set;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001673 if (func == NULL) {
1674 raise_dict_descr_error(obj);
1675 return -1;
1676 }
1677 return func(descr, obj, value);
1678 }
1679
1680 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001681 if (dictptr == NULL) {
1682 PyErr_SetString(PyExc_AttributeError,
1683 "This object has no __dict__");
1684 return -1;
1685 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001686 if (value != NULL && !PyDict_Check(value)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001687 PyErr_Format(PyExc_TypeError,
1688 "__dict__ must be set to a dictionary, "
Christian Heimes90aa7642007-12-19 02:45:37 +00001689 "not a '%.200s'", Py_TYPE(value)->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001690 return -1;
1691 }
1692 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001693 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001694 *dictptr = value;
1695 Py_XDECREF(dict);
1696 return 0;
1697}
1698
Guido van Rossumad47da02002-08-12 19:05:44 +00001699static PyObject *
1700subtype_getweakref(PyObject *obj, void *context)
1701{
1702 PyObject **weaklistptr;
1703 PyObject *result;
1704
Christian Heimes90aa7642007-12-19 02:45:37 +00001705 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001706 PyErr_SetString(PyExc_AttributeError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001707 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001708 return NULL;
1709 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001710 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1711 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1712 (size_t)(Py_TYPE(obj)->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001713 weaklistptr = (PyObject **)
Christian Heimes90aa7642007-12-19 02:45:37 +00001714 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001715 if (*weaklistptr == NULL)
1716 result = Py_None;
1717 else
1718 result = *weaklistptr;
1719 Py_INCREF(result);
1720 return result;
1721}
1722
Guido van Rossum373c7412003-01-07 13:41:37 +00001723/* Three variants on the subtype_getsets list. */
1724
1725static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001726 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001727 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001728 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001729 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001730 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001731};
1732
Guido van Rossum373c7412003-01-07 13:41:37 +00001733static PyGetSetDef subtype_getsets_dict_only[] = {
1734 {"__dict__", subtype_dict, subtype_setdict,
1735 PyDoc_STR("dictionary for instance variables (if defined)")},
1736 {0}
1737};
1738
1739static PyGetSetDef subtype_getsets_weakref_only[] = {
1740 {"__weakref__", subtype_getweakref, NULL,
1741 PyDoc_STR("list of weak references to the object (if defined)")},
1742 {0}
1743};
1744
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001745static int
1746valid_identifier(PyObject *s)
1747{
Martin v. Löwis5b222132007-06-10 09:51:05 +00001748 if (!PyUnicode_Check(s)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001749 PyErr_Format(PyExc_TypeError,
1750 "__slots__ items must be strings, not '%.200s'",
Christian Heimes90aa7642007-12-19 02:45:37 +00001751 Py_TYPE(s)->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001752 return 0;
1753 }
Georg Brandlf4780d02007-08-30 18:29:48 +00001754 if (!PyUnicode_IsIdentifier(s)) {
1755 PyErr_SetString(PyExc_TypeError,
1756 "__slots__ must be identifiers");
1757 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001758 }
1759 return 1;
1760}
1761
Guido van Rossumd8faa362007-04-27 19:54:29 +00001762/* Forward */
1763static int
1764object_init(PyObject *self, PyObject *args, PyObject *kwds);
1765
1766static int
1767type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1768{
1769 int res;
1770
1771 assert(args != NULL && PyTuple_Check(args));
1772 assert(kwds == NULL || PyDict_Check(kwds));
1773
1774 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1775 PyErr_SetString(PyExc_TypeError,
1776 "type.__init__() takes no keyword arguments");
1777 return -1;
1778 }
1779
1780 if (args != NULL && PyTuple_Check(args) &&
1781 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1782 PyErr_SetString(PyExc_TypeError,
1783 "type.__init__() takes 1 or 3 arguments");
1784 return -1;
1785 }
1786
1787 /* Call object.__init__(self) now. */
1788 /* XXX Could call super(type, cls).__init__() but what's the point? */
1789 args = PyTuple_GetSlice(args, 0, 0);
1790 res = object_init(cls, args, NULL);
1791 Py_DECREF(args);
1792 return res;
1793}
1794
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001795static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001796type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1797{
1798 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001799 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001800 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001801 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001802 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001803 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001804 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001805 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001806
Tim Peters3abca122001-10-27 19:37:48 +00001807 assert(args != NULL && PyTuple_Check(args));
1808 assert(kwds == NULL || PyDict_Check(kwds));
1809
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001810 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001811 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001812 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1813 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001814
1815 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1816 PyObject *x = PyTuple_GET_ITEM(args, 0);
Christian Heimes90aa7642007-12-19 02:45:37 +00001817 Py_INCREF(Py_TYPE(x));
1818 return (PyObject *) Py_TYPE(x);
Tim Peters3abca122001-10-27 19:37:48 +00001819 }
1820
1821 /* SF bug 475327 -- if that didn't trigger, we need 3
1822 arguments. but PyArg_ParseTupleAndKeywords below may give
1823 a msg saying type() needs exactly 3. */
1824 if (nargs + nkwds != 3) {
1825 PyErr_SetString(PyExc_TypeError,
1826 "type() takes 1 or 3 arguments");
1827 return NULL;
1828 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001829 }
1830
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001831 /* Check arguments: (name, bases, dict) */
Guido van Rossum98297ee2007-11-06 21:34:58 +00001832 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001833 &name,
1834 &PyTuple_Type, &bases,
1835 &PyDict_Type, &dict))
1836 return NULL;
1837
1838 /* Determine the proper metatype to deal with this,
1839 and check for metatype conflicts while we're at it.
1840 Note that if some other metatype wins to contract,
1841 it's possible that its instances are not types. */
1842 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001843 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844 for (i = 0; i < nbases; i++) {
1845 tmp = PyTuple_GET_ITEM(bases, i);
Christian Heimes90aa7642007-12-19 02:45:37 +00001846 tmptype = Py_TYPE(tmp);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001847 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001848 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001849 if (PyType_IsSubtype(tmptype, winner)) {
1850 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001851 continue;
1852 }
1853 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001854 "metaclass conflict: "
1855 "the metaclass of a derived class "
1856 "must be a (non-strict) subclass "
1857 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001858 return NULL;
1859 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001860 if (winner != metatype) {
1861 if (winner->tp_new != type_new) /* Pass it to the winner */
1862 return winner->tp_new(winner, args, kwds);
1863 metatype = winner;
1864 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001865
1866 /* Adjust for empty tuple bases */
1867 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001868 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001869 if (bases == NULL)
1870 return NULL;
1871 nbases = 1;
1872 }
1873 else
1874 Py_INCREF(bases);
1875
1876 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1877
1878 /* Calculate best base, and check that all bases are type objects */
1879 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001880 if (base == NULL) {
1881 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001882 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001883 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001884 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1885 PyErr_Format(PyExc_TypeError,
1886 "type '%.100s' is not an acceptable base type",
1887 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001888 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001889 return NULL;
1890 }
1891
Tim Peters6d6c1a32001-08-02 04:15:00 +00001892 /* Check for a __slots__ sequence variable in dict, and count it */
1893 slots = PyDict_GetItemString(dict, "__slots__");
1894 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001895 add_dict = 0;
1896 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001897 may_add_dict = base->tp_dictoffset == 0;
1898 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1899 if (slots == NULL) {
1900 if (may_add_dict) {
1901 add_dict++;
1902 }
1903 if (may_add_weak) {
1904 add_weak++;
1905 }
1906 }
1907 else {
1908 /* Have slots */
1909
Tim Peters6d6c1a32001-08-02 04:15:00 +00001910 /* Make it into a tuple */
Neal Norwitz80e7f272007-08-26 06:45:23 +00001911 if (PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001912 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001913 else
1914 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001915 if (slots == NULL) {
1916 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001917 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001918 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001919 assert(PyTuple_Check(slots));
1920
1921 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001922 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001923 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001924 PyErr_Format(PyExc_TypeError,
1925 "nonempty __slots__ "
1926 "not supported for subtype of '%s'",
1927 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001928 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001929 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001930 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001931 return NULL;
1932 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001933
1934 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001935 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001936 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001937 if (!valid_identifier(tmp))
1938 goto bad_slots;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001939 assert(PyUnicode_Check(tmp));
1940 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001941 if (!may_add_dict || add_dict) {
1942 PyErr_SetString(PyExc_TypeError,
1943 "__dict__ slot disallowed: "
1944 "we already got one");
1945 goto bad_slots;
1946 }
1947 add_dict++;
1948 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00001949 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001950 if (!may_add_weak || add_weak) {
1951 PyErr_SetString(PyExc_TypeError,
1952 "__weakref__ slot disallowed: "
1953 "either we already got one, "
1954 "or __itemsize__ != 0");
1955 goto bad_slots;
1956 }
1957 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001958 }
1959 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001960
Guido van Rossumd8faa362007-04-27 19:54:29 +00001961 /* Copy slots into a list, mangle names and sort them.
1962 Sorted names are needed for __class__ assignment.
1963 Convert them back to tuple at the end.
1964 */
1965 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001966 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001967 goto bad_slots;
1968 for (i = j = 0; i < nslots; i++) {
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001969 tmp = PyTuple_GET_ITEM(slots, i);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001970 if ((add_dict &&
1971 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
1972 (add_weak &&
1973 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
Guido van Rossumad47da02002-08-12 19:05:44 +00001974 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975 tmp =_Py_Mangle(name, tmp);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001976 if (!tmp)
1977 goto bad_slots;
1978 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00001979 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001980 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001981 assert(j == nslots - add_dict - add_weak);
1982 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001983 Py_DECREF(slots);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001984 if (PyList_Sort(newslots) == -1) {
1985 Py_DECREF(bases);
1986 Py_DECREF(newslots);
1987 return NULL;
1988 }
1989 slots = PyList_AsTuple(newslots);
1990 Py_DECREF(newslots);
1991 if (slots == NULL) {
1992 Py_DECREF(bases);
1993 return NULL;
1994 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001995
Guido van Rossumad47da02002-08-12 19:05:44 +00001996 /* Secondary bases may provide weakrefs or dict */
1997 if (nbases > 1 &&
1998 ((may_add_dict && !add_dict) ||
1999 (may_add_weak && !add_weak))) {
2000 for (i = 0; i < nbases; i++) {
2001 tmp = PyTuple_GET_ITEM(bases, i);
2002 if (tmp == (PyObject *)base)
2003 continue; /* Skip primary base */
Guido van Rossumad47da02002-08-12 19:05:44 +00002004 assert(PyType_Check(tmp));
2005 tmptype = (PyTypeObject *)tmp;
2006 if (may_add_dict && !add_dict &&
2007 tmptype->tp_dictoffset != 0)
2008 add_dict++;
2009 if (may_add_weak && !add_weak &&
2010 tmptype->tp_weaklistoffset != 0)
2011 add_weak++;
2012 if (may_add_dict && !add_dict)
2013 continue;
2014 if (may_add_weak && !add_weak)
2015 continue;
2016 /* Nothing more to check */
2017 break;
2018 }
2019 }
Guido van Rossum9676b222001-08-17 20:32:36 +00002020 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002021
2022 /* XXX From here until type is safely allocated,
2023 "return NULL" may leak slots! */
2024
2025 /* Allocate the type object */
2026 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00002027 if (type == NULL) {
2028 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002029 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002030 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00002031 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002032
2033 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002034 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002035 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002036 et->ht_name = name;
2037 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038
Guido van Rossumdc91b992001-08-08 22:26:22 +00002039 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002040 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2041 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002042 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2043 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002044
Guido van Rossumdc91b992001-08-08 22:26:22 +00002045 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002046 type->tp_as_number = &et->as_number;
2047 type->tp_as_sequence = &et->as_sequence;
2048 type->tp_as_mapping = &et->as_mapping;
2049 type->tp_as_buffer = &et->as_buffer;
Neal Norwitz80e7f272007-08-26 06:45:23 +00002050 type->tp_name = PyUnicode_AsString(name);
2051 if (!type->tp_name) {
2052 Py_DECREF(type);
2053 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002054 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002055
2056 /* Set tp_base and tp_bases */
2057 type->tp_bases = bases;
2058 Py_INCREF(base);
2059 type->tp_base = base;
2060
Guido van Rossum687ae002001-10-15 22:03:32 +00002061 /* Initialize tp_dict from passed-in dict */
2062 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002063 if (dict == NULL) {
2064 Py_DECREF(type);
2065 return NULL;
2066 }
2067
Guido van Rossumc3542212001-08-16 09:18:56 +00002068 /* Set __module__ in the dict */
2069 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2070 tmp = PyEval_GetGlobals();
2071 if (tmp != NULL) {
2072 tmp = PyDict_GetItemString(tmp, "__name__");
2073 if (tmp != NULL) {
2074 if (PyDict_SetItemString(dict, "__module__",
2075 tmp) < 0)
2076 return NULL;
2077 }
2078 }
2079 }
2080
Tim Peters2f93e282001-10-04 05:27:00 +00002081 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00002082 and is a string. The __doc__ accessor will first look for tp_doc;
2083 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00002084 */
2085 {
2086 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
Neal Norwitz6ea45d32007-08-26 04:19:43 +00002087 if (doc != NULL && PyUnicode_Check(doc)) {
Neal Norwitza369c5a2007-08-25 07:41:59 +00002088 size_t n;
Neal Norwitz6ea45d32007-08-26 04:19:43 +00002089 char *tp_doc;
2090 const char *str = PyUnicode_AsString(doc);
2091 if (str == NULL) {
2092 Py_DECREF(type);
2093 return NULL;
Tim Peters2f93e282001-10-04 05:27:00 +00002094 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00002095 n = strlen(str);
2096 tp_doc = (char *)PyObject_MALLOC(n+1);
2097 if (tp_doc == NULL) {
2098 Py_DECREF(type);
2099 return NULL;
Neal Norwitza369c5a2007-08-25 07:41:59 +00002100 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00002101 memcpy(tp_doc, str, n+1);
2102 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00002103 }
2104 }
2105
Tim Peters6d6c1a32001-08-02 04:15:00 +00002106 /* Special-case __new__: if it's a plain function,
2107 make it a static function */
2108 tmp = PyDict_GetItemString(dict, "__new__");
2109 if (tmp != NULL && PyFunction_Check(tmp)) {
2110 tmp = PyStaticMethod_New(tmp);
2111 if (tmp == NULL) {
2112 Py_DECREF(type);
2113 return NULL;
2114 }
2115 PyDict_SetItemString(dict, "__new__", tmp);
2116 Py_DECREF(tmp);
2117 }
2118
2119 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002120 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00002121 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002122 if (slots != NULL) {
2123 for (i = 0; i < nslots; i++, mp++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002124 mp->name = PyUnicode_AsString(
Tim Peters6d6c1a32001-08-02 04:15:00 +00002125 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00002126 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002127 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002128
2129 /* __dict__ and __weakref__ are already filtered out */
2130 assert(strcmp(mp->name, "__dict__") != 0);
2131 assert(strcmp(mp->name, "__weakref__") != 0);
2132
Tim Peters6d6c1a32001-08-02 04:15:00 +00002133 slotoffset += sizeof(PyObject *);
2134 }
2135 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002136 if (add_dict) {
2137 if (base->tp_itemsize)
2138 type->tp_dictoffset = -(long)sizeof(PyObject *);
2139 else
2140 type->tp_dictoffset = slotoffset;
2141 slotoffset += sizeof(PyObject *);
2142 }
2143 if (add_weak) {
2144 assert(!base->tp_itemsize);
2145 type->tp_weaklistoffset = slotoffset;
2146 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002147 }
2148 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002149 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002150 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002151
2152 if (type->tp_weaklistoffset && type->tp_dictoffset)
2153 type->tp_getset = subtype_getsets_full;
2154 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2155 type->tp_getset = subtype_getsets_weakref_only;
2156 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2157 type->tp_getset = subtype_getsets_dict_only;
2158 else
2159 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002160
2161 /* Special case some slots */
2162 if (type->tp_dictoffset != 0 || nslots > 0) {
2163 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2164 type->tp_getattro = PyObject_GenericGetAttr;
2165 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2166 type->tp_setattro = PyObject_GenericSetAttr;
2167 }
2168 type->tp_dealloc = subtype_dealloc;
2169
Guido van Rossum9475a232001-10-05 20:51:39 +00002170 /* Enable GC unless there are really no instance variables possible */
2171 if (!(type->tp_basicsize == sizeof(PyObject) &&
2172 type->tp_itemsize == 0))
2173 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2174
Tim Peters6d6c1a32001-08-02 04:15:00 +00002175 /* Always override allocation strategy to use regular heap */
2176 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002177 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002178 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002179 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002180 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002181 }
2182 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002183 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002184
2185 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002186 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002187 Py_DECREF(type);
2188 return NULL;
2189 }
2190
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002191 /* Put the proper slots in place */
2192 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002193
Tim Peters6d6c1a32001-08-02 04:15:00 +00002194 return (PyObject *)type;
2195}
2196
2197/* Internal API to look for a name through the MRO.
2198 This returns a borrowed reference, and doesn't set an exception! */
2199PyObject *
2200_PyType_Lookup(PyTypeObject *type, PyObject *name)
2201{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002202 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002203 PyObject *mro, *res, *base, *dict;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002204 unsigned int h;
2205
2206 if (MCACHE_CACHEABLE_NAME(name) &&
Christian Heimes412dc9c2008-01-27 18:55:54 +00002207 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
Christian Heimesa62da1d2008-01-12 19:39:10 +00002208 /* fast path */
2209 h = MCACHE_HASH_METHOD(type, name);
2210 if (method_cache[h].version == type->tp_version_tag &&
2211 method_cache[h].name == name)
2212 return method_cache[h].value;
2213 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002214
Guido van Rossum687ae002001-10-15 22:03:32 +00002215 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002216 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002217
2218 /* If mro is NULL, the type is either not yet initialized
2219 by PyType_Ready(), or already cleared by type_clear().
2220 Either way the safest thing to do is to return NULL. */
2221 if (mro == NULL)
2222 return NULL;
2223
Christian Heimesa62da1d2008-01-12 19:39:10 +00002224 res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002225 assert(PyTuple_Check(mro));
2226 n = PyTuple_GET_SIZE(mro);
2227 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002228 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002229 assert(PyType_Check(base));
2230 dict = ((PyTypeObject *)base)->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002231 assert(dict && PyDict_Check(dict));
2232 res = PyDict_GetItem(dict, name);
2233 if (res != NULL)
Christian Heimesa62da1d2008-01-12 19:39:10 +00002234 break;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002235 }
Christian Heimesa62da1d2008-01-12 19:39:10 +00002236
2237 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2238 h = MCACHE_HASH_METHOD(type, name);
2239 method_cache[h].version = type->tp_version_tag;
2240 method_cache[h].value = res; /* borrowed */
2241 Py_INCREF(name);
2242 Py_DECREF(method_cache[h].name);
2243 method_cache[h].name = name;
2244 }
2245 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002246}
2247
2248/* This is similar to PyObject_GenericGetAttr(),
2249 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2250static PyObject *
2251type_getattro(PyTypeObject *type, PyObject *name)
2252{
Christian Heimes90aa7642007-12-19 02:45:37 +00002253 PyTypeObject *metatype = Py_TYPE(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002254 PyObject *meta_attribute, *attribute;
2255 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002256
2257 /* Initialize this type (we'll assume the metatype is initialized) */
2258 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002259 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002260 return NULL;
2261 }
2262
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002263 /* No readable descriptor found yet */
2264 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002265
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002266 /* Look for the attribute in the metatype */
2267 meta_attribute = _PyType_Lookup(metatype, name);
2268
2269 if (meta_attribute != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002270 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002271
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002272 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2273 /* Data descriptors implement tp_descr_set to intercept
2274 * writes. Assume the attribute is not overridden in
2275 * type's tp_dict (and bases): call the descriptor now.
2276 */
2277 return meta_get(meta_attribute, (PyObject *)type,
2278 (PyObject *)metatype);
2279 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002280 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002281 }
2282
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002283 /* No data descriptor found on metatype. Look in tp_dict of this
2284 * type and its bases */
2285 attribute = _PyType_Lookup(type, name);
2286 if (attribute != NULL) {
2287 /* Implement descriptor functionality, if any */
Christian Heimes90aa7642007-12-19 02:45:37 +00002288 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002289
2290 Py_XDECREF(meta_attribute);
2291
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002292 if (local_get != NULL) {
2293 /* NULL 2nd argument indicates the descriptor was
2294 * found on the target object itself (or a base) */
2295 return local_get(attribute, (PyObject *)NULL,
2296 (PyObject *)type);
2297 }
Tim Peters34592512002-07-11 06:23:50 +00002298
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002299 Py_INCREF(attribute);
2300 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002301 }
2302
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002303 /* No attribute found in local __dict__ (or bases): use the
2304 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002305 if (meta_get != NULL) {
2306 PyObject *res;
2307 res = meta_get(meta_attribute, (PyObject *)type,
2308 (PyObject *)metatype);
2309 Py_DECREF(meta_attribute);
2310 return res;
2311 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002312
2313 /* If an ordinary attribute was found on the metatype, return it now */
2314 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002315 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002316 }
2317
2318 /* Give up */
2319 PyErr_Format(PyExc_AttributeError,
Walter Dörwald75163602007-06-11 15:47:13 +00002320 "type object '%.50s' has no attribute '%U'",
2321 type->tp_name, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002322 return NULL;
2323}
2324
2325static int
2326type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2327{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002328 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2329 PyErr_Format(
2330 PyExc_TypeError,
2331 "can't set attributes of built-in/extension type '%s'",
2332 type->tp_name);
2333 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002334 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002335 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2336 return -1;
2337 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002338}
2339
2340static void
2341type_dealloc(PyTypeObject *type)
2342{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002343 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002344
2345 /* Assert this is a heap-allocated type object */
2346 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002347 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002348 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002349 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002350 Py_XDECREF(type->tp_base);
2351 Py_XDECREF(type->tp_dict);
2352 Py_XDECREF(type->tp_bases);
2353 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002354 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002355 Py_XDECREF(type->tp_subclasses);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002356 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2357 * of most other objects. It's okay to cast it to char *.
2358 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002359 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002360 Py_XDECREF(et->ht_name);
2361 Py_XDECREF(et->ht_slots);
Christian Heimes90aa7642007-12-19 02:45:37 +00002362 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002363}
2364
Guido van Rossum1c450732001-10-08 15:18:27 +00002365static PyObject *
2366type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2367{
2368 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002369 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002370
2371 list = PyList_New(0);
2372 if (list == NULL)
2373 return NULL;
2374 raw = type->tp_subclasses;
2375 if (raw == NULL)
2376 return list;
2377 assert(PyList_Check(raw));
2378 n = PyList_GET_SIZE(raw);
2379 for (i = 0; i < n; i++) {
2380 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002381 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002382 ref = PyWeakref_GET_OBJECT(ref);
2383 if (ref != Py_None) {
2384 if (PyList_Append(list, ref) < 0) {
2385 Py_DECREF(list);
2386 return NULL;
2387 }
2388 }
2389 }
2390 return list;
2391}
2392
Guido van Rossum47374822007-08-02 16:48:17 +00002393static PyObject *
2394type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2395{
2396 return PyDict_New();
2397}
2398
Tim Peters6d6c1a32001-08-02 04:15:00 +00002399static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002400 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002401 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002402 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002403 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Guido van Rossum47374822007-08-02 16:48:17 +00002404 {"__prepare__", (PyCFunction)type_prepare,
2405 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2406 PyDoc_STR("__prepare__() -> dict\n"
2407 "used to create the namespace for the class statement")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002408 {0}
2409};
2410
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002411PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002412"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002413"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002414
Guido van Rossum048eb752001-10-02 21:24:57 +00002415static int
2416type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2417{
Guido van Rossuma3862092002-06-10 15:24:42 +00002418 /* Because of type_is_gc(), the collector only calls this
2419 for heaptypes. */
2420 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002421
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002422 Py_VISIT(type->tp_dict);
2423 Py_VISIT(type->tp_cache);
2424 Py_VISIT(type->tp_mro);
2425 Py_VISIT(type->tp_bases);
2426 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002427
2428 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002429 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002430 in cycles; tp_subclasses is a list of weak references,
2431 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002432
Guido van Rossum048eb752001-10-02 21:24:57 +00002433 return 0;
2434}
2435
2436static int
2437type_clear(PyTypeObject *type)
2438{
Guido van Rossuma3862092002-06-10 15:24:42 +00002439 /* Because of type_is_gc(), the collector only calls this
2440 for heaptypes. */
2441 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002442
Guido van Rossuma3862092002-06-10 15:24:42 +00002443 /* The only field we need to clear is tp_mro, which is part of a
2444 hard cycle (its first element is the class itself) that won't
2445 be broken otherwise (it's a tuple and tuples don't have a
2446 tp_clear handler). None of the other fields need to be
2447 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002448
Guido van Rossuma3862092002-06-10 15:24:42 +00002449 tp_dict:
2450 It is a dict, so the collector will call its tp_clear.
2451
2452 tp_cache:
2453 Not used; if it were, it would be a dict.
2454
2455 tp_bases, tp_base:
2456 If these are involved in a cycle, there must be at least
2457 one other, mutable object in the cycle, e.g. a base
2458 class's dict; the cycle will be broken that way.
2459
2460 tp_subclasses:
2461 A list of weak references can't be part of a cycle; and
2462 lists have their own tp_clear.
2463
Guido van Rossume5c691a2003-03-07 15:13:17 +00002464 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002465 A tuple of strings can't be part of a cycle.
2466 */
2467
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002468 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002469
2470 return 0;
2471}
2472
2473static int
2474type_is_gc(PyTypeObject *type)
2475{
2476 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2477}
2478
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002479PyTypeObject PyType_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002480 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002481 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002482 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002483 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002484 (destructor)type_dealloc, /* tp_dealloc */
2485 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002486 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002487 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002488 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002489 (reprfunc)type_repr, /* tp_repr */
2490 0, /* tp_as_number */
2491 0, /* tp_as_sequence */
2492 0, /* tp_as_mapping */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002493 0, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002494 (ternaryfunc)type_call, /* tp_call */
2495 0, /* tp_str */
2496 (getattrofunc)type_getattro, /* tp_getattro */
2497 (setattrofunc)type_setattro, /* tp_setattro */
2498 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002499 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002500 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002501 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002502 (traverseproc)type_traverse, /* tp_traverse */
2503 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002504 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002505 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002506 0, /* tp_iter */
2507 0, /* tp_iternext */
2508 type_methods, /* tp_methods */
2509 type_members, /* tp_members */
2510 type_getsets, /* tp_getset */
2511 0, /* tp_base */
2512 0, /* tp_dict */
2513 0, /* tp_descr_get */
2514 0, /* tp_descr_set */
2515 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002516 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002517 0, /* tp_alloc */
2518 type_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002519 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002520 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002521};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002522
2523
2524/* The base type of all types (eventually)... except itself. */
2525
Guido van Rossumd8faa362007-04-27 19:54:29 +00002526/* You may wonder why object.__new__() only complains about arguments
2527 when object.__init__() is not overridden, and vice versa.
2528
2529 Consider the use cases:
2530
2531 1. When neither is overridden, we want to hear complaints about
2532 excess (i.e., any) arguments, since their presence could
2533 indicate there's a bug.
2534
2535 2. When defining an Immutable type, we are likely to override only
2536 __new__(), since __init__() is called too late to initialize an
2537 Immutable object. Since __new__() defines the signature for the
2538 type, it would be a pain to have to override __init__() just to
2539 stop it from complaining about excess arguments.
2540
2541 3. When defining a Mutable type, we are likely to override only
2542 __init__(). So here the converse reasoning applies: we don't
2543 want to have to override __new__() just to stop it from
2544 complaining.
2545
2546 4. When __init__() is overridden, and the subclass __init__() calls
2547 object.__init__(), the latter should complain about excess
2548 arguments; ditto for __new__().
2549
2550 Use cases 2 and 3 make it unattractive to unconditionally check for
2551 excess arguments. The best solution that addresses all four use
2552 cases is as follows: __init__() complains about excess arguments
2553 unless __new__() is overridden and __init__() is not overridden
2554 (IOW, if __init__() is overridden or __new__() is not overridden);
2555 symmetrically, __new__() complains about excess arguments unless
2556 __init__() is overridden and __new__() is not overridden
2557 (IOW, if __new__() is overridden or __init__() is not overridden).
2558
2559 However, for backwards compatibility, this breaks too much code.
2560 Therefore, in 2.6, we'll *warn* about excess arguments when both
2561 methods are overridden; for all other cases we'll use the above
2562 rules.
2563
2564*/
2565
2566/* Forward */
2567static PyObject *
2568object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2569
2570static int
2571excess_args(PyObject *args, PyObject *kwds)
2572{
2573 return PyTuple_GET_SIZE(args) ||
2574 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2575}
2576
Tim Peters6d6c1a32001-08-02 04:15:00 +00002577static int
2578object_init(PyObject *self, PyObject *args, PyObject *kwds)
2579{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002580 int err = 0;
2581 if (excess_args(args, kwds)) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002582 PyTypeObject *type = Py_TYPE(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002583 if (type->tp_init != object_init &&
2584 type->tp_new != object_new)
2585 {
2586 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2587 "object.__init__() takes no parameters",
2588 1);
2589 }
2590 else if (type->tp_init != object_init ||
2591 type->tp_new == object_new)
2592 {
2593 PyErr_SetString(PyExc_TypeError,
2594 "object.__init__() takes no parameters");
2595 err = -1;
2596 }
2597 }
2598 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002599}
2600
Guido van Rossum298e4212003-02-13 16:30:16 +00002601static PyObject *
2602object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2603{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002604 int err = 0;
2605 if (excess_args(args, kwds)) {
2606 if (type->tp_new != object_new &&
2607 type->tp_init != object_init)
2608 {
2609 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2610 "object.__new__() takes no parameters",
2611 1);
2612 }
2613 else if (type->tp_new != object_new ||
2614 type->tp_init == object_init)
2615 {
2616 PyErr_SetString(PyExc_TypeError,
2617 "object.__new__() takes no parameters");
2618 err = -1;
2619 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002620 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002621 if (err < 0)
2622 return NULL;
Guido van Rossum298e4212003-02-13 16:30:16 +00002623 return type->tp_alloc(type, 0);
2624}
2625
Tim Peters6d6c1a32001-08-02 04:15:00 +00002626static void
2627object_dealloc(PyObject *self)
2628{
Christian Heimes90aa7642007-12-19 02:45:37 +00002629 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002630}
2631
Guido van Rossum8e248182001-08-12 05:17:56 +00002632static PyObject *
2633object_repr(PyObject *self)
2634{
Guido van Rossum76e69632001-08-16 18:52:43 +00002635 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002636 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002637
Christian Heimes90aa7642007-12-19 02:45:37 +00002638 type = Py_TYPE(self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002639 mod = type_module(type, NULL);
2640 if (mod == NULL)
2641 PyErr_Clear();
Martin v. Löwis5b222132007-06-10 09:51:05 +00002642 else if (!PyUnicode_Check(mod)) {
Guido van Rossum76e69632001-08-16 18:52:43 +00002643 Py_DECREF(mod);
2644 mod = NULL;
2645 }
2646 name = type_name(type, NULL);
2647 if (name == NULL)
2648 return NULL;
Georg Brandl1a3284e2007-12-02 09:40:06 +00002649 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
Walter Dörwald4dbd01b2007-06-11 14:03:45 +00002650 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002651 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00002652 rtn = PyUnicode_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002653 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002654 Py_XDECREF(mod);
2655 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002656 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002657}
2658
Guido van Rossumb8f63662001-08-15 23:57:02 +00002659static PyObject *
2660object_str(PyObject *self)
2661{
2662 unaryfunc f;
2663
Christian Heimes90aa7642007-12-19 02:45:37 +00002664 f = Py_TYPE(self)->tp_repr;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002665 if (f == NULL)
2666 f = object_repr;
2667 return f(self);
2668}
2669
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002670static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002671object_richcompare(PyObject *self, PyObject *other, int op)
2672{
2673 PyObject *res;
2674
2675 switch (op) {
2676
2677 case Py_EQ:
Guido van Rossumab078dd2008-01-06 00:09:11 +00002678 /* Return NotImplemented instead of False, so if two
2679 objects are compared, both get a chance at the
2680 comparison. See issue #1393. */
2681 res = (self == other) ? Py_True : Py_NotImplemented;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002682 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002683 break;
2684
2685 case Py_NE:
Guido van Rossume27dc722007-03-27 22:37:34 +00002686 /* By default, != returns the opposite of ==,
2687 unless the latter returns NotImplemented. */
2688 res = PyObject_RichCompare(self, other, Py_EQ);
2689 if (res != NULL && res != Py_NotImplemented) {
2690 int ok = PyObject_IsTrue(res);
2691 Py_DECREF(res);
2692 if (ok < 0)
2693 res = NULL;
2694 else {
2695 if (ok)
2696 res = Py_False;
2697 else
2698 res = Py_True;
2699 Py_INCREF(res);
2700 }
2701 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002702 break;
2703
2704 default:
2705 res = Py_NotImplemented;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002706 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002707 break;
2708 }
2709
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002710 return res;
2711}
2712
2713static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002714object_get_class(PyObject *self, void *closure)
2715{
Christian Heimes90aa7642007-12-19 02:45:37 +00002716 Py_INCREF(Py_TYPE(self));
2717 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002718}
2719
2720static int
2721equiv_structs(PyTypeObject *a, PyTypeObject *b)
2722{
2723 return a == b ||
2724 (a != NULL &&
2725 b != NULL &&
2726 a->tp_basicsize == b->tp_basicsize &&
2727 a->tp_itemsize == b->tp_itemsize &&
2728 a->tp_dictoffset == b->tp_dictoffset &&
2729 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2730 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2731 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2732}
2733
2734static int
2735same_slots_added(PyTypeObject *a, PyTypeObject *b)
2736{
2737 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002738 Py_ssize_t size;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002739 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002740
2741 if (base != b->tp_base)
2742 return 0;
2743 if (equiv_structs(a, base) && equiv_structs(b, base))
2744 return 1;
2745 size = base->tp_basicsize;
2746 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2747 size += sizeof(PyObject *);
2748 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2749 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002750
2751 /* Check slots compliance */
2752 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2753 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2754 if (slots_a && slots_b) {
2755 if (PyObject_Compare(slots_a, slots_b) != 0)
2756 return 0;
2757 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2758 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002759 return size == a->tp_basicsize && size == b->tp_basicsize;
2760}
2761
2762static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002763compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002764{
2765 PyTypeObject *newbase, *oldbase;
2766
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002767 if (newto->tp_dealloc != oldto->tp_dealloc ||
2768 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002769 {
2770 PyErr_Format(PyExc_TypeError,
2771 "%s assignment: "
2772 "'%s' deallocator differs from '%s'",
2773 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002774 newto->tp_name,
2775 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002776 return 0;
2777 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002778 newbase = newto;
2779 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002780 while (equiv_structs(newbase, newbase->tp_base))
2781 newbase = newbase->tp_base;
2782 while (equiv_structs(oldbase, oldbase->tp_base))
2783 oldbase = oldbase->tp_base;
2784 if (newbase != oldbase &&
2785 (newbase->tp_base != oldbase->tp_base ||
2786 !same_slots_added(newbase, oldbase))) {
2787 PyErr_Format(PyExc_TypeError,
2788 "%s assignment: "
2789 "'%s' object layout differs from '%s'",
2790 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002791 newto->tp_name,
2792 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002793 return 0;
2794 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002795
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002796 return 1;
2797}
2798
2799static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002800object_set_class(PyObject *self, PyObject *value, void *closure)
2801{
Christian Heimes90aa7642007-12-19 02:45:37 +00002802 PyTypeObject *oldto = Py_TYPE(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002803 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002804
Guido van Rossumb6b89422002-04-15 01:03:30 +00002805 if (value == NULL) {
2806 PyErr_SetString(PyExc_TypeError,
2807 "can't delete __class__ attribute");
2808 return -1;
2809 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002810 if (!PyType_Check(value)) {
2811 PyErr_Format(PyExc_TypeError,
2812 "__class__ must be set to new-style class, not '%s' object",
Christian Heimes90aa7642007-12-19 02:45:37 +00002813 Py_TYPE(value)->tp_name);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002814 return -1;
2815 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002816 newto = (PyTypeObject *)value;
2817 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2818 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002819 {
2820 PyErr_Format(PyExc_TypeError,
2821 "__class__ assignment: only for heap types");
2822 return -1;
2823 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002824 if (compatible_for_assignment(newto, oldto, "__class__")) {
2825 Py_INCREF(newto);
Christian Heimes90aa7642007-12-19 02:45:37 +00002826 Py_TYPE(self) = newto;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002827 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002828 return 0;
2829 }
2830 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002831 return -1;
2832 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002833}
2834
2835static PyGetSetDef object_getsets[] = {
2836 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002837 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002838 {0}
2839};
2840
Guido van Rossumc53f0092003-02-18 22:05:12 +00002841
Guido van Rossum036f9992003-02-21 22:02:54 +00002842/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2843 We fall back to helpers in copy_reg for:
2844 - pickle protocols < 2
2845 - calculating the list of slot names (done only once per class)
2846 - the __newobj__ function (which is used as a token but never called)
2847*/
2848
2849static PyObject *
2850import_copy_reg(void)
2851{
2852 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002853
2854 if (!copy_reg_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002855 copy_reg_str = PyUnicode_InternFromString("copy_reg");
Guido van Rossum3926a632001-09-25 16:25:58 +00002856 if (copy_reg_str == NULL)
2857 return NULL;
2858 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002859
2860 return PyImport_Import(copy_reg_str);
2861}
2862
2863static PyObject *
2864slotnames(PyObject *cls)
2865{
2866 PyObject *clsdict;
2867 PyObject *copy_reg;
2868 PyObject *slotnames;
2869
2870 if (!PyType_Check(cls)) {
2871 Py_INCREF(Py_None);
2872 return Py_None;
2873 }
2874
2875 clsdict = ((PyTypeObject *)cls)->tp_dict;
2876 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002877 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002878 Py_INCREF(slotnames);
2879 return slotnames;
2880 }
2881
2882 copy_reg = import_copy_reg();
2883 if (copy_reg == NULL)
2884 return NULL;
2885
2886 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2887 Py_DECREF(copy_reg);
2888 if (slotnames != NULL &&
2889 slotnames != Py_None &&
2890 !PyList_Check(slotnames))
2891 {
2892 PyErr_SetString(PyExc_TypeError,
2893 "copy_reg._slotnames didn't return a list or None");
2894 Py_DECREF(slotnames);
2895 slotnames = NULL;
2896 }
2897
2898 return slotnames;
2899}
2900
2901static PyObject *
2902reduce_2(PyObject *obj)
2903{
2904 PyObject *cls, *getnewargs;
2905 PyObject *args = NULL, *args2 = NULL;
2906 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2907 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2908 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002909 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002910
2911 cls = PyObject_GetAttrString(obj, "__class__");
2912 if (cls == NULL)
2913 return NULL;
2914
2915 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2916 if (getnewargs != NULL) {
2917 args = PyObject_CallObject(getnewargs, NULL);
2918 Py_DECREF(getnewargs);
2919 if (args != NULL && !PyTuple_Check(args)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002920 PyErr_Format(PyExc_TypeError,
2921 "__getnewargs__ should return a tuple, "
Christian Heimes90aa7642007-12-19 02:45:37 +00002922 "not '%.200s'", Py_TYPE(args)->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002923 goto end;
2924 }
2925 }
2926 else {
2927 PyErr_Clear();
2928 args = PyTuple_New(0);
2929 }
2930 if (args == NULL)
2931 goto end;
2932
2933 getstate = PyObject_GetAttrString(obj, "__getstate__");
2934 if (getstate != NULL) {
2935 state = PyObject_CallObject(getstate, NULL);
2936 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002937 if (state == NULL)
2938 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002939 }
2940 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002941 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002942 state = PyObject_GetAttrString(obj, "__dict__");
2943 if (state == NULL) {
2944 PyErr_Clear();
2945 state = Py_None;
2946 Py_INCREF(state);
2947 }
2948 names = slotnames(cls);
2949 if (names == NULL)
2950 goto end;
2951 if (names != Py_None) {
2952 assert(PyList_Check(names));
2953 slots = PyDict_New();
2954 if (slots == NULL)
2955 goto end;
2956 n = 0;
2957 /* Can't pre-compute the list size; the list
2958 is stored on the class so accessible to other
2959 threads, which may be run by DECREF */
2960 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2961 PyObject *name, *value;
2962 name = PyList_GET_ITEM(names, i);
2963 value = PyObject_GetAttr(obj, name);
2964 if (value == NULL)
2965 PyErr_Clear();
2966 else {
2967 int err = PyDict_SetItem(slots, name,
2968 value);
2969 Py_DECREF(value);
2970 if (err)
2971 goto end;
2972 n++;
2973 }
2974 }
2975 if (n) {
2976 state = Py_BuildValue("(NO)", state, slots);
2977 if (state == NULL)
2978 goto end;
2979 }
2980 }
2981 }
2982
2983 if (!PyList_Check(obj)) {
2984 listitems = Py_None;
2985 Py_INCREF(listitems);
2986 }
2987 else {
2988 listitems = PyObject_GetIter(obj);
2989 if (listitems == NULL)
2990 goto end;
2991 }
2992
2993 if (!PyDict_Check(obj)) {
2994 dictitems = Py_None;
2995 Py_INCREF(dictitems);
2996 }
2997 else {
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002998 PyObject *items = PyObject_CallMethod(obj, "items", "");
2999 if (items == NULL)
3000 goto end;
3001 dictitems = PyObject_GetIter(items);
3002 Py_DECREF(items);
Guido van Rossum036f9992003-02-21 22:02:54 +00003003 if (dictitems == NULL)
3004 goto end;
3005 }
3006
3007 copy_reg = import_copy_reg();
3008 if (copy_reg == NULL)
3009 goto end;
3010 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
3011 if (newobj == NULL)
3012 goto end;
3013
3014 n = PyTuple_GET_SIZE(args);
3015 args2 = PyTuple_New(n+1);
3016 if (args2 == NULL)
3017 goto end;
3018 PyTuple_SET_ITEM(args2, 0, cls);
3019 cls = NULL;
3020 for (i = 0; i < n; i++) {
3021 PyObject *v = PyTuple_GET_ITEM(args, i);
3022 Py_INCREF(v);
3023 PyTuple_SET_ITEM(args2, i+1, v);
3024 }
3025
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003026 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003027
3028 end:
3029 Py_XDECREF(cls);
3030 Py_XDECREF(args);
3031 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00003032 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00003033 Py_XDECREF(state);
3034 Py_XDECREF(names);
3035 Py_XDECREF(listitems);
3036 Py_XDECREF(dictitems);
3037 Py_XDECREF(copy_reg);
3038 Py_XDECREF(newobj);
3039 return res;
3040}
3041
Guido van Rossumd8faa362007-04-27 19:54:29 +00003042/*
3043 * There were two problems when object.__reduce__ and object.__reduce_ex__
3044 * were implemented in the same function:
3045 * - trying to pickle an object with a custom __reduce__ method that
3046 * fell back to object.__reduce__ in certain circumstances led to
3047 * infinite recursion at Python level and eventual RuntimeError.
3048 * - Pickling objects that lied about their type by overwriting the
3049 * __class__ descriptor could lead to infinite recursion at C level
3050 * and eventual segfault.
3051 *
3052 * Because of backwards compatibility, the two methods still have to
3053 * behave in the same way, even if this is not required by the pickle
3054 * protocol. This common functionality was moved to the _common_reduce
3055 * function.
3056 */
3057static PyObject *
3058_common_reduce(PyObject *self, int proto)
3059{
3060 PyObject *copy_reg, *res;
3061
3062 if (proto >= 2)
3063 return reduce_2(self);
3064
3065 copy_reg = import_copy_reg();
3066 if (!copy_reg)
3067 return NULL;
3068
3069 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
3070 Py_DECREF(copy_reg);
3071
3072 return res;
3073}
3074
3075static PyObject *
3076object_reduce(PyObject *self, PyObject *args)
3077{
3078 int proto = 0;
3079
3080 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3081 return NULL;
3082
3083 return _common_reduce(self, proto);
3084}
3085
Guido van Rossum036f9992003-02-21 22:02:54 +00003086static PyObject *
3087object_reduce_ex(PyObject *self, PyObject *args)
3088{
Guido van Rossumd8faa362007-04-27 19:54:29 +00003089 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003090 int proto = 0;
3091
3092 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3093 return NULL;
3094
3095 reduce = PyObject_GetAttrString(self, "__reduce__");
3096 if (reduce == NULL)
3097 PyErr_Clear();
3098 else {
3099 PyObject *cls, *clsreduce, *objreduce;
3100 int override;
3101 cls = PyObject_GetAttrString(self, "__class__");
3102 if (cls == NULL) {
3103 Py_DECREF(reduce);
3104 return NULL;
3105 }
3106 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3107 Py_DECREF(cls);
3108 if (clsreduce == NULL) {
3109 Py_DECREF(reduce);
3110 return NULL;
3111 }
3112 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3113 "__reduce__");
3114 override = (clsreduce != objreduce);
3115 Py_DECREF(clsreduce);
3116 if (override) {
3117 res = PyObject_CallObject(reduce, NULL);
3118 Py_DECREF(reduce);
3119 return res;
3120 }
3121 else
3122 Py_DECREF(reduce);
3123 }
3124
Guido van Rossumd8faa362007-04-27 19:54:29 +00003125 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003126}
3127
Eric Smith8c663262007-08-25 02:26:07 +00003128
3129/*
3130 from PEP 3101, this code implements:
3131
3132 class object:
3133 def __format__(self, format_spec):
3134 return format(str(self), format_spec)
3135*/
3136static PyObject *
3137object_format(PyObject *self, PyObject *args)
3138{
3139 PyObject *format_spec;
3140 PyObject *self_as_str = NULL;
3141 PyObject *result = NULL;
3142 PyObject *format_meth = NULL;
3143
Eric Smithfc6e8fe2008-01-11 00:17:22 +00003144 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
Eric Smith8c663262007-08-25 02:26:07 +00003145 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003146
Thomas Heller519a0422007-11-15 20:48:54 +00003147 self_as_str = PyObject_Str(self);
Eric Smith8c663262007-08-25 02:26:07 +00003148 if (self_as_str != NULL) {
3149 /* find the format function */
3150 format_meth = PyObject_GetAttrString(self_as_str, "__format__");
3151 if (format_meth != NULL) {
3152 /* and call it */
3153 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
3154 }
3155 }
3156
3157 Py_XDECREF(self_as_str);
3158 Py_XDECREF(format_meth);
3159
3160 return result;
3161}
3162
Guido van Rossum3926a632001-09-25 16:25:58 +00003163static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00003164 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3165 PyDoc_STR("helper for pickle")},
Guido van Rossumd8faa362007-04-27 19:54:29 +00003166 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003167 PyDoc_STR("helper for pickle")},
Eric Smith8c663262007-08-25 02:26:07 +00003168 {"__format__", object_format, METH_VARARGS,
3169 PyDoc_STR("default object formatter")},
Guido van Rossum3926a632001-09-25 16:25:58 +00003170 {0}
3171};
3172
Guido van Rossum036f9992003-02-21 22:02:54 +00003173
Tim Peters6d6c1a32001-08-02 04:15:00 +00003174PyTypeObject PyBaseObject_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003175 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003176 "object", /* tp_name */
3177 sizeof(PyObject), /* tp_basicsize */
3178 0, /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003179 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003180 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003181 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003182 0, /* tp_setattr */
3183 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003184 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003185 0, /* tp_as_number */
3186 0, /* tp_as_sequence */
3187 0, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003188 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003189 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003190 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003191 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003192 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003193 0, /* tp_as_buffer */
3194 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003195 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003196 0, /* tp_traverse */
3197 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003198 object_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003199 0, /* tp_weaklistoffset */
3200 0, /* tp_iter */
3201 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00003202 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003203 0, /* tp_members */
3204 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003205 0, /* tp_base */
3206 0, /* tp_dict */
3207 0, /* tp_descr_get */
3208 0, /* tp_descr_set */
3209 0, /* tp_dictoffset */
3210 object_init, /* tp_init */
3211 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003212 object_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003213 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003214};
3215
3216
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003217/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003218
3219static int
3220add_methods(PyTypeObject *type, PyMethodDef *meth)
3221{
Guido van Rossum687ae002001-10-15 22:03:32 +00003222 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003223
3224 for (; meth->ml_name != NULL; meth++) {
3225 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003226 if (PyDict_GetItemString(dict, meth->ml_name) &&
3227 !(meth->ml_flags & METH_COEXIST))
3228 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003229 if (meth->ml_flags & METH_CLASS) {
3230 if (meth->ml_flags & METH_STATIC) {
3231 PyErr_SetString(PyExc_ValueError,
3232 "method cannot be both class and static");
3233 return -1;
3234 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003235 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003236 }
3237 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003238 PyObject *cfunc = PyCFunction_New(meth, NULL);
3239 if (cfunc == NULL)
3240 return -1;
3241 descr = PyStaticMethod_New(cfunc);
3242 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003243 }
3244 else {
3245 descr = PyDescr_NewMethod(type, meth);
3246 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003247 if (descr == NULL)
3248 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003249 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003250 return -1;
3251 Py_DECREF(descr);
3252 }
3253 return 0;
3254}
3255
3256static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003257add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003258{
Guido van Rossum687ae002001-10-15 22:03:32 +00003259 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003260
3261 for (; memb->name != NULL; memb++) {
3262 PyObject *descr;
3263 if (PyDict_GetItemString(dict, memb->name))
3264 continue;
3265 descr = PyDescr_NewMember(type, memb);
3266 if (descr == NULL)
3267 return -1;
3268 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3269 return -1;
3270 Py_DECREF(descr);
3271 }
3272 return 0;
3273}
3274
3275static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003276add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003277{
Guido van Rossum687ae002001-10-15 22:03:32 +00003278 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003279
3280 for (; gsp->name != NULL; gsp++) {
3281 PyObject *descr;
3282 if (PyDict_GetItemString(dict, gsp->name))
3283 continue;
3284 descr = PyDescr_NewGetSet(type, gsp);
3285
3286 if (descr == NULL)
3287 return -1;
3288 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3289 return -1;
3290 Py_DECREF(descr);
3291 }
3292 return 0;
3293}
3294
Guido van Rossum13d52f02001-08-10 21:24:08 +00003295static void
3296inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003297{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003298 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003299
Guido van Rossum13d52f02001-08-10 21:24:08 +00003300 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003301 oldsize = base->tp_basicsize;
3302 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3303 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3304 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003305 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003306 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003307 if (type->tp_traverse == NULL)
3308 type->tp_traverse = base->tp_traverse;
3309 if (type->tp_clear == NULL)
3310 type->tp_clear = base->tp_clear;
3311 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003312 {
Guido van Rossumf884b742001-12-17 17:14:22 +00003313 /* The condition below could use some explanation.
3314 It appears that tp_new is not inherited for static types
3315 whose base class is 'object'; this seems to be a precaution
3316 so that old extension types don't suddenly become
3317 callable (object.__new__ wouldn't insure the invariants
3318 that the extension type's own factory function ensures).
3319 Heap types, of course, are under our control, so they do
3320 inherit tp_new; static extension types that specify some
3321 other built-in type as the default are considered
3322 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003323 if (base != &PyBaseObject_Type ||
3324 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3325 if (type->tp_new == NULL)
3326 type->tp_new = base->tp_new;
3327 }
3328 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003329 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003330
3331 /* Copy other non-function slots */
3332
3333#undef COPYVAL
3334#define COPYVAL(SLOT) \
3335 if (type->SLOT == 0) type->SLOT = base->SLOT
3336
3337 COPYVAL(tp_itemsize);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003338 COPYVAL(tp_weaklistoffset);
3339 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003340
3341 /* Setup fast subclass flags */
3342 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3343 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3344 else if (PyType_IsSubtype(base, &PyType_Type))
3345 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3346 else if (PyType_IsSubtype(base, &PyLong_Type))
3347 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3348 else if (PyType_IsSubtype(base, &PyString_Type))
3349 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
3350 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3351 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3352 else if (PyType_IsSubtype(base, &PyTuple_Type))
3353 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3354 else if (PyType_IsSubtype(base, &PyList_Type))
3355 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3356 else if (PyType_IsSubtype(base, &PyDict_Type))
3357 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003358}
3359
Guido van Rossumf5243f02008-01-01 04:06:48 +00003360static char *hash_name_op[] = {
Guido van Rossum38938152006-08-21 23:36:26 +00003361 "__eq__",
Guido van Rossum38938152006-08-21 23:36:26 +00003362 "__cmp__",
3363 "__hash__",
Guido van Rossumf5243f02008-01-01 04:06:48 +00003364 NULL
Guido van Rossum38938152006-08-21 23:36:26 +00003365};
3366
3367static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003368overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003369{
Guido van Rossumf5243f02008-01-01 04:06:48 +00003370 char **p;
Guido van Rossum38938152006-08-21 23:36:26 +00003371 PyObject *dict = type->tp_dict;
3372
3373 assert(dict != NULL);
Guido van Rossumf5243f02008-01-01 04:06:48 +00003374 for (p = hash_name_op; *p; p++) {
3375 if (PyDict_GetItemString(dict, *p) != NULL)
Guido van Rossum38938152006-08-21 23:36:26 +00003376 return 1;
3377 }
3378 return 0;
3379}
3380
Guido van Rossum13d52f02001-08-10 21:24:08 +00003381static void
3382inherit_slots(PyTypeObject *type, PyTypeObject *base)
3383{
3384 PyTypeObject *basebase;
3385
3386#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003387#undef COPYSLOT
3388#undef COPYNUM
3389#undef COPYSEQ
3390#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003391#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003392
3393#define SLOTDEFINED(SLOT) \
3394 (base->SLOT != 0 && \
3395 (basebase == NULL || base->SLOT != basebase->SLOT))
3396
Tim Peters6d6c1a32001-08-02 04:15:00 +00003397#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003398 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003399
3400#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3401#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3402#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003403#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003404
Guido van Rossum13d52f02001-08-10 21:24:08 +00003405 /* This won't inherit indirect slots (from tp_as_number etc.)
3406 if type doesn't provide the space. */
3407
3408 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3409 basebase = base->tp_base;
3410 if (basebase->tp_as_number == NULL)
3411 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003412 COPYNUM(nb_add);
3413 COPYNUM(nb_subtract);
3414 COPYNUM(nb_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003415 COPYNUM(nb_remainder);
3416 COPYNUM(nb_divmod);
3417 COPYNUM(nb_power);
3418 COPYNUM(nb_negative);
3419 COPYNUM(nb_positive);
3420 COPYNUM(nb_absolute);
Jack Diederich4dafcc42006-11-28 19:15:13 +00003421 COPYNUM(nb_bool);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003422 COPYNUM(nb_invert);
3423 COPYNUM(nb_lshift);
3424 COPYNUM(nb_rshift);
3425 COPYNUM(nb_and);
3426 COPYNUM(nb_xor);
3427 COPYNUM(nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003428 COPYNUM(nb_int);
3429 COPYNUM(nb_long);
3430 COPYNUM(nb_float);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003431 COPYNUM(nb_inplace_add);
3432 COPYNUM(nb_inplace_subtract);
3433 COPYNUM(nb_inplace_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003434 COPYNUM(nb_inplace_remainder);
3435 COPYNUM(nb_inplace_power);
3436 COPYNUM(nb_inplace_lshift);
3437 COPYNUM(nb_inplace_rshift);
3438 COPYNUM(nb_inplace_and);
3439 COPYNUM(nb_inplace_xor);
3440 COPYNUM(nb_inplace_or);
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003441 COPYNUM(nb_true_divide);
3442 COPYNUM(nb_floor_divide);
3443 COPYNUM(nb_inplace_true_divide);
3444 COPYNUM(nb_inplace_floor_divide);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003445 COPYNUM(nb_index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003446 }
3447
Guido van Rossum13d52f02001-08-10 21:24:08 +00003448 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3449 basebase = base->tp_base;
3450 if (basebase->tp_as_sequence == NULL)
3451 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003452 COPYSEQ(sq_length);
3453 COPYSEQ(sq_concat);
3454 COPYSEQ(sq_repeat);
3455 COPYSEQ(sq_item);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003456 COPYSEQ(sq_ass_item);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003457 COPYSEQ(sq_contains);
3458 COPYSEQ(sq_inplace_concat);
3459 COPYSEQ(sq_inplace_repeat);
3460 }
3461
Guido van Rossum13d52f02001-08-10 21:24:08 +00003462 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3463 basebase = base->tp_base;
3464 if (basebase->tp_as_mapping == NULL)
3465 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003466 COPYMAP(mp_length);
3467 COPYMAP(mp_subscript);
3468 COPYMAP(mp_ass_subscript);
3469 }
3470
Tim Petersfc57ccb2001-10-12 02:38:24 +00003471 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3472 basebase = base->tp_base;
3473 if (basebase->tp_as_buffer == NULL)
3474 basebase = NULL;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00003475 COPYBUF(bf_getbuffer);
3476 COPYBUF(bf_releasebuffer);
Tim Petersfc57ccb2001-10-12 02:38:24 +00003477 }
3478
Guido van Rossum13d52f02001-08-10 21:24:08 +00003479 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003480
Tim Peters6d6c1a32001-08-02 04:15:00 +00003481 COPYSLOT(tp_dealloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003482 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3483 type->tp_getattr = base->tp_getattr;
3484 type->tp_getattro = base->tp_getattro;
3485 }
3486 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3487 type->tp_setattr = base->tp_setattr;
3488 type->tp_setattro = base->tp_setattro;
3489 }
3490 /* tp_compare see tp_richcompare */
3491 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003492 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003493 COPYSLOT(tp_call);
3494 COPYSLOT(tp_str);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003495 {
Guido van Rossum38938152006-08-21 23:36:26 +00003496 /* Copy comparison-related slots only when
3497 not overriding them anywhere */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003498 if (type->tp_compare == NULL &&
3499 type->tp_richcompare == NULL &&
Guido van Rossum38938152006-08-21 23:36:26 +00003500 type->tp_hash == NULL &&
Guido van Rossumf5243f02008-01-01 04:06:48 +00003501 !overrides_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003502 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003503 type->tp_compare = base->tp_compare;
3504 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003505 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003506 }
3507 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003508 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003509 COPYSLOT(tp_iter);
3510 COPYSLOT(tp_iternext);
3511 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003512 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003513 COPYSLOT(tp_descr_get);
3514 COPYSLOT(tp_descr_set);
3515 COPYSLOT(tp_dictoffset);
3516 COPYSLOT(tp_init);
3517 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003518 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003519 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3520 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3521 /* They agree about gc. */
3522 COPYSLOT(tp_free);
3523 }
3524 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3525 type->tp_free == NULL &&
Neal Norwitz30d1c512007-08-19 22:48:23 +00003526 base->tp_free == PyObject_Free) {
Tim Peters3cfe7542003-05-21 21:29:48 +00003527 /* A bit of magic to plug in the correct default
3528 * tp_free function when a derived class adds gc,
3529 * didn't define tp_free, and the base uses the
3530 * default non-gc tp_free.
3531 */
3532 type->tp_free = PyObject_GC_Del;
3533 }
3534 /* else they didn't agree about gc, and there isn't something
3535 * obvious to be done -- the type is on its own.
3536 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003537 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003538}
3539
Jeremy Hylton938ace62002-07-17 16:30:39 +00003540static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003541
Tim Peters6d6c1a32001-08-02 04:15:00 +00003542int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003543PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003544{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003545 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003546 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003547 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003548
Guido van Rossumcab05802002-06-10 15:29:03 +00003549 if (type->tp_flags & Py_TPFLAGS_READY) {
3550 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003551 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003552 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003553 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003554
3555 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003556
Tim Peters36eb4df2003-03-23 03:33:13 +00003557#ifdef Py_TRACE_REFS
3558 /* PyType_Ready is the closest thing we have to a choke point
3559 * for type objects, so is the best place I can think of to try
3560 * to get type objects into the doubly-linked list of all objects.
3561 * Still, not all type objects go thru PyType_Ready.
3562 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003563 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003564#endif
3565
Tim Peters6d6c1a32001-08-02 04:15:00 +00003566 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3567 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003568 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003569 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003570 Py_INCREF(base);
3571 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003572
Guido van Rossumd8faa362007-04-27 19:54:29 +00003573 /* Now the only way base can still be NULL is if type is
3574 * &PyBaseObject_Type.
3575 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003576
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003577 /* Initialize the base class */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003578 if (base != NULL && base->tp_dict == NULL) {
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003579 if (PyType_Ready(base) < 0)
3580 goto error;
3581 }
3582
Guido van Rossumd8faa362007-04-27 19:54:29 +00003583 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003584 compilable separately on Windows can call PyType_Ready() instead of
3585 initializing the ob_type field of their type objects. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003586 /* The test for base != NULL is really unnecessary, since base is only
3587 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3588 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3589 know that. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003590 if (Py_TYPE(type) == NULL && base != NULL)
3591 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003592
Tim Peters6d6c1a32001-08-02 04:15:00 +00003593 /* Initialize tp_bases */
3594 bases = type->tp_bases;
3595 if (bases == NULL) {
3596 if (base == NULL)
3597 bases = PyTuple_New(0);
3598 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003599 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003600 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003601 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003602 type->tp_bases = bases;
3603 }
3604
Guido van Rossum687ae002001-10-15 22:03:32 +00003605 /* Initialize tp_dict */
3606 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003607 if (dict == NULL) {
3608 dict = PyDict_New();
3609 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003610 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003611 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003612 }
3613
Guido van Rossum687ae002001-10-15 22:03:32 +00003614 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003615 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003616 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003617 if (type->tp_methods != NULL) {
3618 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003619 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003620 }
3621 if (type->tp_members != NULL) {
3622 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003623 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003624 }
3625 if (type->tp_getset != NULL) {
3626 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003627 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003628 }
3629
Tim Peters6d6c1a32001-08-02 04:15:00 +00003630 /* Calculate method resolution order */
3631 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003632 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003633 }
3634
Guido van Rossum13d52f02001-08-10 21:24:08 +00003635 /* Inherit special flags from dominant base */
3636 if (type->tp_base != NULL)
3637 inherit_special(type, type->tp_base);
3638
Tim Peters6d6c1a32001-08-02 04:15:00 +00003639 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003640 bases = type->tp_mro;
3641 assert(bases != NULL);
3642 assert(PyTuple_Check(bases));
3643 n = PyTuple_GET_SIZE(bases);
3644 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003645 PyObject *b = PyTuple_GET_ITEM(bases, i);
3646 if (PyType_Check(b))
3647 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003648 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003649
Tim Peters3cfe7542003-05-21 21:29:48 +00003650 /* Sanity check for tp_free. */
3651 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3652 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003653 /* This base class needs to call tp_free, but doesn't have
3654 * one, or its tp_free is for non-gc'ed objects.
3655 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003656 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3657 "gc and is a base type but has inappropriate "
3658 "tp_free slot",
3659 type->tp_name);
3660 goto error;
3661 }
3662
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003663 /* if the type dictionary doesn't contain a __doc__, set it from
3664 the tp_doc slot.
3665 */
3666 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3667 if (type->tp_doc != NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +00003668 PyObject *doc = PyUnicode_FromString(type->tp_doc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003669 if (doc == NULL)
3670 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003671 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3672 Py_DECREF(doc);
3673 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003674 PyDict_SetItemString(type->tp_dict,
3675 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003676 }
3677 }
3678
Guido van Rossum38938152006-08-21 23:36:26 +00003679 /* Hack for tp_hash and __hash__.
3680 If after all that, tp_hash is still NULL, and __hash__ is not in
3681 tp_dict, set tp_dict['__hash__'] equal to None.
3682 This signals that __hash__ is not inherited.
3683 */
3684 if (type->tp_hash == NULL) {
3685 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3686 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3687 goto error;
3688 }
3689 }
3690
Guido van Rossum13d52f02001-08-10 21:24:08 +00003691 /* Some more special stuff */
3692 base = type->tp_base;
3693 if (base != NULL) {
3694 if (type->tp_as_number == NULL)
3695 type->tp_as_number = base->tp_as_number;
3696 if (type->tp_as_sequence == NULL)
3697 type->tp_as_sequence = base->tp_as_sequence;
3698 if (type->tp_as_mapping == NULL)
3699 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003700 if (type->tp_as_buffer == NULL)
3701 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003702 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003703
Guido van Rossum1c450732001-10-08 15:18:27 +00003704 /* Link into each base class's list of subclasses */
3705 bases = type->tp_bases;
3706 n = PyTuple_GET_SIZE(bases);
3707 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003708 PyObject *b = PyTuple_GET_ITEM(bases, i);
3709 if (PyType_Check(b) &&
3710 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003711 goto error;
3712 }
3713
Guido van Rossum13d52f02001-08-10 21:24:08 +00003714 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003715 assert(type->tp_dict != NULL);
3716 type->tp_flags =
3717 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003718 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003719
3720 error:
3721 type->tp_flags &= ~Py_TPFLAGS_READYING;
3722 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003723}
3724
Guido van Rossum1c450732001-10-08 15:18:27 +00003725static int
3726add_subclass(PyTypeObject *base, PyTypeObject *type)
3727{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003728 Py_ssize_t i;
3729 int result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003730 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003731
3732 list = base->tp_subclasses;
3733 if (list == NULL) {
3734 base->tp_subclasses = list = PyList_New(0);
3735 if (list == NULL)
3736 return -1;
3737 }
3738 assert(PyList_Check(list));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003739 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003740 i = PyList_GET_SIZE(list);
3741 while (--i >= 0) {
3742 ref = PyList_GET_ITEM(list, i);
3743 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003744 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003745 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003746 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003747 result = PyList_Append(list, newobj);
3748 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003749 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003750}
3751
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003752static void
3753remove_subclass(PyTypeObject *base, PyTypeObject *type)
3754{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003755 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003756 PyObject *list, *ref;
3757
3758 list = base->tp_subclasses;
3759 if (list == NULL) {
3760 return;
3761 }
3762 assert(PyList_Check(list));
3763 i = PyList_GET_SIZE(list);
3764 while (--i >= 0) {
3765 ref = PyList_GET_ITEM(list, i);
3766 assert(PyWeakref_CheckRef(ref));
3767 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3768 /* this can't fail, right? */
3769 PySequence_DelItem(list, i);
3770 return;
3771 }
3772 }
3773}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003774
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003775static int
3776check_num_args(PyObject *ob, int n)
3777{
3778 if (!PyTuple_CheckExact(ob)) {
3779 PyErr_SetString(PyExc_SystemError,
3780 "PyArg_UnpackTuple() argument list is not a tuple");
3781 return 0;
3782 }
3783 if (n == PyTuple_GET_SIZE(ob))
3784 return 1;
3785 PyErr_Format(
3786 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003787 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003788 return 0;
3789}
3790
Tim Peters6d6c1a32001-08-02 04:15:00 +00003791/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3792
3793/* There's a wrapper *function* for each distinct function typedef used
Guido van Rossumd8faa362007-04-27 19:54:29 +00003794 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003795 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3796 Most tables have only one entry; the tables for binary operators have two
3797 entries, one regular and one with reversed arguments. */
3798
3799static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003800wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003801{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003802 lenfunc func = (lenfunc)wrapped;
3803 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003804
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003805 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003806 return NULL;
3807 res = (*func)(self);
3808 if (res == -1 && PyErr_Occurred())
3809 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00003810 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003811}
3812
Tim Peters6d6c1a32001-08-02 04:15:00 +00003813static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003814wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3815{
3816 inquiry func = (inquiry)wrapped;
3817 int res;
3818
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003819 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003820 return NULL;
3821 res = (*func)(self);
3822 if (res == -1 && PyErr_Occurred())
3823 return NULL;
3824 return PyBool_FromLong((long)res);
3825}
3826
3827static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003828wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3829{
3830 binaryfunc func = (binaryfunc)wrapped;
3831 PyObject *other;
3832
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003833 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003834 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003835 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003836 return (*func)(self, other);
3837}
3838
3839static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003840wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3841{
3842 binaryfunc func = (binaryfunc)wrapped;
3843 PyObject *other;
3844
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003845 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003846 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003847 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003848 return (*func)(self, other);
3849}
3850
3851static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003852wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3853{
3854 binaryfunc func = (binaryfunc)wrapped;
3855 PyObject *other;
3856
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003857 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003858 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003859 other = PyTuple_GET_ITEM(args, 0);
Christian Heimes90aa7642007-12-19 02:45:37 +00003860 if (!PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003861 Py_INCREF(Py_NotImplemented);
3862 return Py_NotImplemented;
3863 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003864 return (*func)(other, self);
3865}
3866
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003867static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003868wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3869{
3870 ternaryfunc func = (ternaryfunc)wrapped;
3871 PyObject *other;
3872 PyObject *third = Py_None;
3873
3874 /* Note: This wrapper only works for __pow__() */
3875
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003876 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003877 return NULL;
3878 return (*func)(self, other, third);
3879}
3880
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003881static PyObject *
3882wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3883{
3884 ternaryfunc func = (ternaryfunc)wrapped;
3885 PyObject *other;
3886 PyObject *third = Py_None;
3887
3888 /* Note: This wrapper only works for __pow__() */
3889
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003890 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003891 return NULL;
3892 return (*func)(other, self, third);
3893}
3894
Tim Peters6d6c1a32001-08-02 04:15:00 +00003895static PyObject *
3896wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3897{
3898 unaryfunc func = (unaryfunc)wrapped;
3899
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003900 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003901 return NULL;
3902 return (*func)(self);
3903}
3904
Tim Peters6d6c1a32001-08-02 04:15:00 +00003905static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003906wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003907{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003908 ssizeargfunc func = (ssizeargfunc)wrapped;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003909 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003910 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003911
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003912 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3913 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003914 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003915 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003916 return NULL;
3917 return (*func)(self, i);
3918}
3919
Martin v. Löwis18e16552006-02-15 17:27:45 +00003920static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003921getindex(PyObject *self, PyObject *arg)
3922{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003923 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003924
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003925 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003926 if (i == -1 && PyErr_Occurred())
3927 return -1;
3928 if (i < 0) {
Christian Heimes90aa7642007-12-19 02:45:37 +00003929 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003930 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003931 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003932 if (n < 0)
3933 return -1;
3934 i += n;
3935 }
3936 }
3937 return i;
3938}
3939
3940static PyObject *
3941wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3942{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003943 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003944 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003945 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003946
Guido van Rossumf4593e02001-10-03 12:09:30 +00003947 if (PyTuple_GET_SIZE(args) == 1) {
3948 arg = PyTuple_GET_ITEM(args, 0);
3949 i = getindex(self, arg);
3950 if (i == -1 && PyErr_Occurred())
3951 return NULL;
3952 return (*func)(self, i);
3953 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003954 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003955 assert(PyErr_Occurred());
3956 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003957}
3958
Tim Peters6d6c1a32001-08-02 04:15:00 +00003959static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003960wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003961{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003962 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3963 Py_ssize_t i;
3964 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003965 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003966
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003967 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003968 return NULL;
3969 i = getindex(self, arg);
3970 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003971 return NULL;
3972 res = (*func)(self, i, value);
3973 if (res == -1 && PyErr_Occurred())
3974 return NULL;
3975 Py_INCREF(Py_None);
3976 return Py_None;
3977}
3978
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003979static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003980wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003981{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003982 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3983 Py_ssize_t i;
3984 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003985 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003986
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003987 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003988 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003989 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003990 i = getindex(self, arg);
3991 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003992 return NULL;
3993 res = (*func)(self, i, NULL);
3994 if (res == -1 && PyErr_Occurred())
3995 return NULL;
3996 Py_INCREF(Py_None);
3997 return Py_None;
3998}
3999
Tim Peters6d6c1a32001-08-02 04:15:00 +00004000/* XXX objobjproc is a misnomer; should be objargpred */
4001static PyObject *
4002wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4003{
4004 objobjproc func = (objobjproc)wrapped;
4005 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004006 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004007
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004008 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004009 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004010 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004011 res = (*func)(self, value);
4012 if (res == -1 && PyErr_Occurred())
4013 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004014 else
4015 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004016}
4017
Tim Peters6d6c1a32001-08-02 04:15:00 +00004018static PyObject *
4019wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4020{
4021 objobjargproc func = (objobjargproc)wrapped;
4022 int res;
4023 PyObject *key, *value;
4024
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004025 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004026 return NULL;
4027 res = (*func)(self, key, value);
4028 if (res == -1 && PyErr_Occurred())
4029 return NULL;
4030 Py_INCREF(Py_None);
4031 return Py_None;
4032}
4033
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004034static PyObject *
4035wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4036{
4037 objobjargproc func = (objobjargproc)wrapped;
4038 int res;
4039 PyObject *key;
4040
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004041 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004042 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004043 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004044 res = (*func)(self, key, NULL);
4045 if (res == -1 && PyErr_Occurred())
4046 return NULL;
4047 Py_INCREF(Py_None);
4048 return Py_None;
4049}
4050
Tim Peters6d6c1a32001-08-02 04:15:00 +00004051static PyObject *
4052wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
4053{
4054 cmpfunc func = (cmpfunc)wrapped;
4055 int res;
4056 PyObject *other;
4057
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004058 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004059 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004060 other = PyTuple_GET_ITEM(args, 0);
Christian Heimes90aa7642007-12-19 02:45:37 +00004061 if (Py_TYPE(other)->tp_compare != func &&
4062 !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
Guido van Rossumceccae52001-09-18 20:03:57 +00004063 PyErr_Format(
4064 PyExc_TypeError,
4065 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
Christian Heimes90aa7642007-12-19 02:45:37 +00004066 Py_TYPE(self)->tp_name,
4067 Py_TYPE(self)->tp_name,
4068 Py_TYPE(other)->tp_name);
Guido van Rossumceccae52001-09-18 20:03:57 +00004069 return NULL;
4070 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004071 res = (*func)(self, other);
4072 if (PyErr_Occurred())
4073 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00004074 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004075}
4076
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004077/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004078 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004079static int
4080hackcheck(PyObject *self, setattrofunc func, char *what)
4081{
Christian Heimes90aa7642007-12-19 02:45:37 +00004082 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004083 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4084 type = type->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004085 /* If type is NULL now, this is a really weird type.
4086 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004087 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004088 PyErr_Format(PyExc_TypeError,
4089 "can't apply this %s to %s object",
4090 what,
4091 type->tp_name);
4092 return 0;
4093 }
4094 return 1;
4095}
4096
Tim Peters6d6c1a32001-08-02 04:15:00 +00004097static PyObject *
4098wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4099{
4100 setattrofunc func = (setattrofunc)wrapped;
4101 int res;
4102 PyObject *name, *value;
4103
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004104 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004105 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004106 if (!hackcheck(self, func, "__setattr__"))
4107 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004108 res = (*func)(self, name, value);
4109 if (res < 0)
4110 return NULL;
4111 Py_INCREF(Py_None);
4112 return Py_None;
4113}
4114
4115static PyObject *
4116wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4117{
4118 setattrofunc func = (setattrofunc)wrapped;
4119 int res;
4120 PyObject *name;
4121
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004122 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004123 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004124 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004125 if (!hackcheck(self, func, "__delattr__"))
4126 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004127 res = (*func)(self, name, NULL);
4128 if (res < 0)
4129 return NULL;
4130 Py_INCREF(Py_None);
4131 return Py_None;
4132}
4133
Tim Peters6d6c1a32001-08-02 04:15:00 +00004134static PyObject *
4135wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4136{
4137 hashfunc func = (hashfunc)wrapped;
4138 long res;
4139
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004140 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004141 return NULL;
4142 res = (*func)(self);
4143 if (res == -1 && PyErr_Occurred())
4144 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00004145 return PyLong_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004146}
4147
Tim Peters6d6c1a32001-08-02 04:15:00 +00004148static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004149wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004150{
4151 ternaryfunc func = (ternaryfunc)wrapped;
4152
Guido van Rossumc8e56452001-10-22 00:43:43 +00004153 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004154}
4155
Tim Peters6d6c1a32001-08-02 04:15:00 +00004156static PyObject *
4157wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4158{
4159 richcmpfunc func = (richcmpfunc)wrapped;
4160 PyObject *other;
4161
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004162 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004163 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004164 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004165 return (*func)(self, other, op);
4166}
4167
4168#undef RICHCMP_WRAPPER
4169#define RICHCMP_WRAPPER(NAME, OP) \
4170static PyObject * \
4171richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4172{ \
4173 return wrap_richcmpfunc(self, args, wrapped, OP); \
4174}
4175
Jack Jansen8e938b42001-08-08 15:29:49 +00004176RICHCMP_WRAPPER(lt, Py_LT)
4177RICHCMP_WRAPPER(le, Py_LE)
4178RICHCMP_WRAPPER(eq, Py_EQ)
4179RICHCMP_WRAPPER(ne, Py_NE)
4180RICHCMP_WRAPPER(gt, Py_GT)
4181RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004182
Tim Peters6d6c1a32001-08-02 04:15:00 +00004183static PyObject *
4184wrap_next(PyObject *self, PyObject *args, void *wrapped)
4185{
4186 unaryfunc func = (unaryfunc)wrapped;
4187 PyObject *res;
4188
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004189 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004190 return NULL;
4191 res = (*func)(self);
4192 if (res == NULL && !PyErr_Occurred())
4193 PyErr_SetNone(PyExc_StopIteration);
4194 return res;
4195}
4196
Tim Peters6d6c1a32001-08-02 04:15:00 +00004197static PyObject *
4198wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4199{
4200 descrgetfunc func = (descrgetfunc)wrapped;
4201 PyObject *obj;
4202 PyObject *type = NULL;
4203
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004204 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004205 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004206 if (obj == Py_None)
4207 obj = NULL;
4208 if (type == Py_None)
4209 type = NULL;
4210 if (type == NULL &&obj == NULL) {
4211 PyErr_SetString(PyExc_TypeError,
4212 "__get__(None, None) is invalid");
4213 return NULL;
4214 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004215 return (*func)(self, obj, type);
4216}
4217
Tim Peters6d6c1a32001-08-02 04:15:00 +00004218static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004219wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004220{
4221 descrsetfunc func = (descrsetfunc)wrapped;
4222 PyObject *obj, *value;
4223 int ret;
4224
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004225 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004226 return NULL;
4227 ret = (*func)(self, obj, value);
4228 if (ret < 0)
4229 return NULL;
4230 Py_INCREF(Py_None);
4231 return Py_None;
4232}
Guido van Rossum22b13872002-08-06 21:41:44 +00004233
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004234static PyObject *
4235wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4236{
4237 descrsetfunc func = (descrsetfunc)wrapped;
4238 PyObject *obj;
4239 int ret;
4240
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004241 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004242 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004243 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004244 ret = (*func)(self, obj, NULL);
4245 if (ret < 0)
4246 return NULL;
4247 Py_INCREF(Py_None);
4248 return Py_None;
4249}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004250
Tim Peters6d6c1a32001-08-02 04:15:00 +00004251static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004252wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004253{
4254 initproc func = (initproc)wrapped;
4255
Guido van Rossumc8e56452001-10-22 00:43:43 +00004256 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004257 return NULL;
4258 Py_INCREF(Py_None);
4259 return Py_None;
4260}
4261
Tim Peters6d6c1a32001-08-02 04:15:00 +00004262static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004263tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004264{
Barry Warsaw60f01882001-08-22 19:24:42 +00004265 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004266 PyObject *arg0, *res;
4267
4268 if (self == NULL || !PyType_Check(self))
4269 Py_FatalError("__new__() called with non-type 'self'");
4270 type = (PyTypeObject *)self;
4271 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004272 PyErr_Format(PyExc_TypeError,
4273 "%s.__new__(): not enough arguments",
4274 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004275 return NULL;
4276 }
4277 arg0 = PyTuple_GET_ITEM(args, 0);
4278 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004279 PyErr_Format(PyExc_TypeError,
4280 "%s.__new__(X): X is not a type object (%s)",
4281 type->tp_name,
Christian Heimes90aa7642007-12-19 02:45:37 +00004282 Py_TYPE(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004283 return NULL;
4284 }
4285 subtype = (PyTypeObject *)arg0;
4286 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004287 PyErr_Format(PyExc_TypeError,
4288 "%s.__new__(%s): %s is not a subtype of %s",
4289 type->tp_name,
4290 subtype->tp_name,
4291 subtype->tp_name,
4292 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004293 return NULL;
4294 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004295
4296 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004297 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004298 most derived base that's not a heap type is this type. */
4299 staticbase = subtype;
4300 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4301 staticbase = staticbase->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004302 /* If staticbase is NULL now, it is a really weird type.
4303 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004304 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004305 PyErr_Format(PyExc_TypeError,
4306 "%s.__new__(%s) is not safe, use %s.__new__()",
4307 type->tp_name,
4308 subtype->tp_name,
4309 staticbase == NULL ? "?" : staticbase->tp_name);
4310 return NULL;
4311 }
4312
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004313 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4314 if (args == NULL)
4315 return NULL;
4316 res = type->tp_new(subtype, args, kwds);
4317 Py_DECREF(args);
4318 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004319}
4320
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004321static struct PyMethodDef tp_new_methoddef[] = {
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004322 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004323 PyDoc_STR("T.__new__(S, ...) -> "
Guido van Rossumd8faa362007-04-27 19:54:29 +00004324 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004325 {0}
4326};
4327
4328static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004329add_tp_new_wrapper(PyTypeObject *type)
4330{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004331 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004332
Guido van Rossum687ae002001-10-15 22:03:32 +00004333 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004334 return 0;
4335 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004336 if (func == NULL)
4337 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004338 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004339 Py_DECREF(func);
4340 return -1;
4341 }
4342 Py_DECREF(func);
4343 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004344}
4345
Guido van Rossumf040ede2001-08-07 16:40:56 +00004346/* Slot wrappers that call the corresponding __foo__ slot. See comments
4347 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004348
Guido van Rossumdc91b992001-08-08 22:26:22 +00004349#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004350static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004351FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004352{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004353 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004354 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004355}
4356
Guido van Rossumdc91b992001-08-08 22:26:22 +00004357#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004358static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004359FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004360{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004361 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004362 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004363}
4364
Guido van Rossumcd118802003-01-06 22:57:47 +00004365/* Boolean helper for SLOT1BINFULL().
4366 right.__class__ is a nontrivial subclass of left.__class__. */
4367static int
4368method_is_overloaded(PyObject *left, PyObject *right, char *name)
4369{
4370 PyObject *a, *b;
4371 int ok;
4372
Christian Heimes90aa7642007-12-19 02:45:37 +00004373 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004374 if (b == NULL) {
4375 PyErr_Clear();
4376 /* If right doesn't have it, it's not overloaded */
4377 return 0;
4378 }
4379
Christian Heimes90aa7642007-12-19 02:45:37 +00004380 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004381 if (a == NULL) {
4382 PyErr_Clear();
4383 Py_DECREF(b);
4384 /* If right has it but left doesn't, it's overloaded */
4385 return 1;
4386 }
4387
4388 ok = PyObject_RichCompareBool(a, b, Py_NE);
4389 Py_DECREF(a);
4390 Py_DECREF(b);
4391 if (ok < 0) {
4392 PyErr_Clear();
4393 return 0;
4394 }
4395
4396 return ok;
4397}
4398
Guido van Rossumdc91b992001-08-08 22:26:22 +00004399
4400#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004401static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004402FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004403{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004404 static PyObject *cache_str, *rcache_str; \
Christian Heimes90aa7642007-12-19 02:45:37 +00004405 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4406 Py_TYPE(other)->tp_as_number != NULL && \
4407 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4408 if (Py_TYPE(self)->tp_as_number != NULL && \
4409 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004410 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004411 if (do_other && \
Christian Heimes90aa7642007-12-19 02:45:37 +00004412 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004413 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004414 r = call_maybe( \
4415 other, ROPSTR, &rcache_str, "(O)", self); \
4416 if (r != Py_NotImplemented) \
4417 return r; \
4418 Py_DECREF(r); \
4419 do_other = 0; \
4420 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004421 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004422 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004423 if (r != Py_NotImplemented || \
Christian Heimes90aa7642007-12-19 02:45:37 +00004424 Py_TYPE(other) == Py_TYPE(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004425 return r; \
4426 Py_DECREF(r); \
4427 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004428 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004429 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004430 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004431 } \
4432 Py_INCREF(Py_NotImplemented); \
4433 return Py_NotImplemented; \
4434}
4435
4436#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4437 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4438
4439#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4440static PyObject * \
4441FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4442{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004443 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004444 return call_method(self, OPSTR, &cache_str, \
4445 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004446}
4447
Martin v. Löwis18e16552006-02-15 17:27:45 +00004448static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004449slot_sq_length(PyObject *self)
4450{
Guido van Rossum2730b132001-08-28 18:22:14 +00004451 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004452 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004453 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004454
4455 if (res == NULL)
4456 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00004457 len = PyLong_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004458 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004459 if (len < 0) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00004460 if (!PyErr_Occurred())
4461 PyErr_SetString(PyExc_ValueError,
4462 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004463 return -1;
4464 }
Guido van Rossum26111622001-10-01 16:42:49 +00004465 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004466}
4467
Guido van Rossumf4593e02001-10-03 12:09:30 +00004468/* Super-optimized version of slot_sq_item.
4469 Other slots could do the same... */
4470static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004471slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004472{
4473 static PyObject *getitem_str;
4474 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4475 descrgetfunc f;
4476
4477 if (getitem_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004478 getitem_str = PyUnicode_InternFromString("__getitem__");
Guido van Rossumf4593e02001-10-03 12:09:30 +00004479 if (getitem_str == NULL)
4480 return NULL;
4481 }
Christian Heimes90aa7642007-12-19 02:45:37 +00004482 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004483 if (func != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +00004484 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004485 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004486 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00004487 func = f(func, self, (PyObject *)(Py_TYPE(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004488 if (func == NULL) {
4489 return NULL;
4490 }
4491 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004492 ival = PyLong_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004493 if (ival != NULL) {
4494 args = PyTuple_New(1);
4495 if (args != NULL) {
4496 PyTuple_SET_ITEM(args, 0, ival);
4497 retval = PyObject_Call(func, args, NULL);
4498 Py_XDECREF(args);
4499 Py_XDECREF(func);
4500 return retval;
4501 }
4502 }
4503 }
4504 else {
4505 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4506 }
4507 Py_XDECREF(args);
4508 Py_XDECREF(ival);
4509 Py_XDECREF(func);
4510 return NULL;
4511}
4512
Tim Peters6d6c1a32001-08-02 04:15:00 +00004513static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004514slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004515{
4516 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004517 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004518
4519 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004520 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004521 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004522 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004523 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004524 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004525 if (res == NULL)
4526 return -1;
4527 Py_DECREF(res);
4528 return 0;
4529}
4530
4531static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00004532slot_sq_contains(PyObject *self, PyObject *value)
4533{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004534 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004535 int result = -1;
4536
Guido van Rossum60718732001-08-28 17:47:51 +00004537 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004538
Guido van Rossum55f20992001-10-01 17:18:22 +00004539 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004540 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004541 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004542 if (args == NULL)
4543 res = NULL;
4544 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004545 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004546 Py_DECREF(args);
4547 }
4548 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004549 if (res != NULL) {
4550 result = PyObject_IsTrue(res);
4551 Py_DECREF(res);
4552 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004553 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004554 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004555 /* Possible results: -1 and 1 */
4556 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004557 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004558 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004559 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004560}
4561
Tim Peters6d6c1a32001-08-02 04:15:00 +00004562#define slot_mp_length slot_sq_length
4563
Guido van Rossumdc91b992001-08-08 22:26:22 +00004564SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004565
4566static int
4567slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4568{
4569 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004570 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004571
4572 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004573 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004574 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004575 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004576 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004577 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004578 if (res == NULL)
4579 return -1;
4580 Py_DECREF(res);
4581 return 0;
4582}
4583
Guido van Rossumdc91b992001-08-08 22:26:22 +00004584SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4585SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4586SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004587SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4588SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4589
Jeremy Hylton938ace62002-07-17 16:30:39 +00004590static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004591
4592SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4593 nb_power, "__pow__", "__rpow__")
4594
4595static PyObject *
4596slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4597{
Guido van Rossum2730b132001-08-28 18:22:14 +00004598 static PyObject *pow_str;
4599
Guido van Rossumdc91b992001-08-08 22:26:22 +00004600 if (modulus == Py_None)
4601 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004602 /* Three-arg power doesn't use __rpow__. But ternary_op
4603 can call this when the second argument's type uses
4604 slot_nb_power, so check before calling self.__pow__. */
Christian Heimes90aa7642007-12-19 02:45:37 +00004605 if (Py_TYPE(self)->tp_as_number != NULL &&
4606 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00004607 return call_method(self, "__pow__", &pow_str,
4608 "(OO)", other, modulus);
4609 }
4610 Py_INCREF(Py_NotImplemented);
4611 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004612}
4613
4614SLOT0(slot_nb_negative, "__neg__")
4615SLOT0(slot_nb_positive, "__pos__")
4616SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004617
4618static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004619slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004620{
Tim Petersea7f75d2002-12-07 21:39:16 +00004621 PyObject *func, *args;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004622 static PyObject *bool_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004623 int result = -1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004624 int from_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004625
Jack Diederich4dafcc42006-11-28 19:15:13 +00004626 func = lookup_maybe(self, "__bool__", &bool_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004627 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004628 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004629 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004630 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004631 if (func == NULL)
4632 return PyErr_Occurred() ? -1 : 1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004633 from_len = 1;
Tim Petersea7f75d2002-12-07 21:39:16 +00004634 }
4635 args = PyTuple_New(0);
4636 if (args != NULL) {
4637 PyObject *temp = PyObject_Call(func, args, NULL);
4638 Py_DECREF(args);
4639 if (temp != NULL) {
Jack Diederich4dafcc42006-11-28 19:15:13 +00004640 if (from_len) {
4641 /* enforced by slot_nb_len */
Jeremy Hylton090a3492003-06-27 16:46:45 +00004642 result = PyObject_IsTrue(temp);
Jack Diederich4dafcc42006-11-28 19:15:13 +00004643 }
4644 else if (PyBool_Check(temp)) {
4645 result = PyObject_IsTrue(temp);
4646 }
Jeremy Hylton090a3492003-06-27 16:46:45 +00004647 else {
4648 PyErr_Format(PyExc_TypeError,
Jack Diederich4dafcc42006-11-28 19:15:13 +00004649 "__bool__ should return "
4650 "bool, returned %s",
Christian Heimes90aa7642007-12-19 02:45:37 +00004651 Py_TYPE(temp)->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004652 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004653 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004654 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004655 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004656 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004657 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004658 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004659}
4660
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004661
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004662static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004663slot_nb_index(PyObject *self)
4664{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004665 static PyObject *index_str;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004666 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004667}
4668
4669
Guido van Rossumdc91b992001-08-08 22:26:22 +00004670SLOT0(slot_nb_invert, "__invert__")
4671SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4672SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4673SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4674SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4675SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004676
Guido van Rossumdc91b992001-08-08 22:26:22 +00004677SLOT0(slot_nb_int, "__int__")
4678SLOT0(slot_nb_long, "__long__")
4679SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004680SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4681SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4682SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004683SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004684/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4685static PyObject *
4686slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4687{
4688 static PyObject *cache_str;
4689 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4690}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004691SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4692SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4693SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4694SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4695SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4696SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4697 "__floordiv__", "__rfloordiv__")
4698SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4699SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4700SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004701
4702static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004703half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004704{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004705 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004706 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004707 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004708
Guido van Rossum60718732001-08-28 17:47:51 +00004709 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004710 if (func == NULL) {
4711 PyErr_Clear();
4712 }
4713 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004714 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004715 if (args == NULL)
4716 res = NULL;
4717 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004718 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004719 Py_DECREF(args);
4720 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004721 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004722 if (res != Py_NotImplemented) {
4723 if (res == NULL)
4724 return -2;
Christian Heimes217cfd12007-12-02 14:31:20 +00004725 c = PyLong_AsLong(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004726 Py_DECREF(res);
4727 if (c == -1 && PyErr_Occurred())
4728 return -2;
4729 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4730 }
4731 Py_DECREF(res);
4732 }
4733 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004734}
4735
Guido van Rossumab3b0342001-09-18 20:38:53 +00004736/* This slot is published for the benefit of try_3way_compare in object.c */
4737int
4738_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004739{
4740 int c;
4741
Christian Heimes90aa7642007-12-19 02:45:37 +00004742 if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004743 c = half_compare(self, other);
4744 if (c <= 1)
4745 return c;
4746 }
Christian Heimes90aa7642007-12-19 02:45:37 +00004747 if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004748 c = half_compare(other, self);
4749 if (c < -1)
4750 return -2;
4751 if (c <= 1)
4752 return -c;
4753 }
4754 return (void *)self < (void *)other ? -1 :
4755 (void *)self > (void *)other ? 1 : 0;
4756}
4757
4758static PyObject *
4759slot_tp_repr(PyObject *self)
4760{
4761 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004762 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004763
Guido van Rossum60718732001-08-28 17:47:51 +00004764 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004765 if (func != NULL) {
4766 res = PyEval_CallObject(func, NULL);
4767 Py_DECREF(func);
4768 return res;
4769 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004770 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004771 return PyUnicode_FromFormat("<%s object at %p>",
Christian Heimes90aa7642007-12-19 02:45:37 +00004772 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004773}
4774
4775static PyObject *
4776slot_tp_str(PyObject *self)
4777{
4778 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004779 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004780
Guido van Rossum60718732001-08-28 17:47:51 +00004781 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004782 if (func != NULL) {
4783 res = PyEval_CallObject(func, NULL);
4784 Py_DECREF(func);
4785 return res;
4786 }
4787 else {
Walter Dörwald1ab83302007-05-18 17:15:44 +00004788 PyObject *ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004789 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004790 res = slot_tp_repr(self);
4791 if (!res)
4792 return NULL;
4793 ress = _PyUnicode_AsDefaultEncodedString(res, NULL);
4794 Py_DECREF(res);
4795 return ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004796 }
4797}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004798
4799static long
4800slot_tp_hash(PyObject *self)
4801{
Guido van Rossum4011a242006-08-17 23:09:57 +00004802 PyObject *func, *res;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004803 static PyObject *hash_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004804 long h;
4805
Guido van Rossum60718732001-08-28 17:47:51 +00004806 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004807
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004808 if (func == Py_None) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004809 Py_DECREF(func);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004810 func = NULL;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004811 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004812
4813 if (func == NULL) {
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004814 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
Christian Heimes90aa7642007-12-19 02:45:37 +00004815 Py_TYPE(self)->tp_name);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004816 return -1;
4817 }
4818
Guido van Rossum4011a242006-08-17 23:09:57 +00004819 res = PyEval_CallObject(func, NULL);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004820 Py_DECREF(func);
4821 if (res == NULL)
4822 return -1;
4823 if (PyLong_Check(res))
4824 h = PyLong_Type.tp_hash(res);
4825 else
Christian Heimes217cfd12007-12-02 14:31:20 +00004826 h = PyLong_AsLong(res);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004827 Py_DECREF(res);
4828 if (h == -1 && !PyErr_Occurred())
4829 h = -2;
4830 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004831}
4832
4833static PyObject *
4834slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4835{
Guido van Rossum60718732001-08-28 17:47:51 +00004836 static PyObject *call_str;
4837 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004838 PyObject *res;
4839
4840 if (meth == NULL)
4841 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004842
Tim Peters6d6c1a32001-08-02 04:15:00 +00004843 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004844
Tim Peters6d6c1a32001-08-02 04:15:00 +00004845 Py_DECREF(meth);
4846 return res;
4847}
4848
Guido van Rossum14a6f832001-10-17 13:59:09 +00004849/* There are two slot dispatch functions for tp_getattro.
4850
4851 - slot_tp_getattro() is used when __getattribute__ is overridden
4852 but no __getattr__ hook is present;
4853
4854 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4855
Guido van Rossumc334df52002-04-04 23:44:47 +00004856 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4857 detects the absence of __getattr__ and then installs the simpler slot if
4858 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004859
Tim Peters6d6c1a32001-08-02 04:15:00 +00004860static PyObject *
4861slot_tp_getattro(PyObject *self, PyObject *name)
4862{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004863 static PyObject *getattribute_str = NULL;
4864 return call_method(self, "__getattribute__", &getattribute_str,
4865 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004866}
4867
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004868static PyObject *
4869slot_tp_getattr_hook(PyObject *self, PyObject *name)
4870{
Christian Heimes90aa7642007-12-19 02:45:37 +00004871 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004872 PyObject *getattr, *getattribute, *res;
4873 static PyObject *getattribute_str = NULL;
4874 static PyObject *getattr_str = NULL;
4875
4876 if (getattr_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004877 getattr_str = PyUnicode_InternFromString("__getattr__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004878 if (getattr_str == NULL)
4879 return NULL;
4880 }
4881 if (getattribute_str == NULL) {
4882 getattribute_str =
Martin v. Löwis5b222132007-06-10 09:51:05 +00004883 PyUnicode_InternFromString("__getattribute__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004884 if (getattribute_str == NULL)
4885 return NULL;
4886 }
4887 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004888 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004889 /* No __getattr__ hook: use a simpler dispatcher */
4890 tp->tp_getattro = slot_tp_getattro;
4891 return slot_tp_getattro(self, name);
4892 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004893 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004894 if (getattribute == NULL ||
Christian Heimes90aa7642007-12-19 02:45:37 +00004895 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00004896 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4897 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004898 res = PyObject_GenericGetAttr(self, name);
4899 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00004900 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004901 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004902 PyErr_Clear();
Thomas Wouters477c8d52006-05-27 19:21:47 +00004903 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004904 }
4905 return res;
4906}
4907
Tim Peters6d6c1a32001-08-02 04:15:00 +00004908static int
4909slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4910{
4911 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004912 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004913
4914 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004915 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004916 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004917 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004918 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004919 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004920 if (res == NULL)
4921 return -1;
4922 Py_DECREF(res);
4923 return 0;
4924}
4925
Guido van Rossumf5243f02008-01-01 04:06:48 +00004926static char *name_op[] = {
4927 "__lt__",
4928 "__le__",
4929 "__eq__",
4930 "__ne__",
4931 "__gt__",
4932 "__ge__",
4933};
4934
Tim Peters6d6c1a32001-08-02 04:15:00 +00004935static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004936half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004937{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004938 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004939 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004940
Guido van Rossum60718732001-08-28 17:47:51 +00004941 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004942 if (func == NULL) {
4943 PyErr_Clear();
4944 Py_INCREF(Py_NotImplemented);
4945 return Py_NotImplemented;
4946 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004947 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004948 if (args == NULL)
4949 res = NULL;
4950 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004951 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004952 Py_DECREF(args);
4953 }
4954 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004955 return res;
4956}
4957
Guido van Rossumb8f63662001-08-15 23:57:02 +00004958static PyObject *
4959slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4960{
4961 PyObject *res;
4962
Christian Heimes90aa7642007-12-19 02:45:37 +00004963 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004964 res = half_richcompare(self, other, op);
4965 if (res != Py_NotImplemented)
4966 return res;
4967 Py_DECREF(res);
4968 }
Christian Heimes90aa7642007-12-19 02:45:37 +00004969 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004970 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004971 if (res != Py_NotImplemented) {
4972 return res;
4973 }
4974 Py_DECREF(res);
4975 }
4976 Py_INCREF(Py_NotImplemented);
4977 return Py_NotImplemented;
4978}
4979
4980static PyObject *
4981slot_tp_iter(PyObject *self)
4982{
4983 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004984 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004985
Guido van Rossum60718732001-08-28 17:47:51 +00004986 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004987 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004988 PyObject *args;
4989 args = res = PyTuple_New(0);
4990 if (args != NULL) {
4991 res = PyObject_Call(func, args, NULL);
4992 Py_DECREF(args);
4993 }
4994 Py_DECREF(func);
4995 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004996 }
4997 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004998 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004999 if (func == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005000 PyErr_Format(PyExc_TypeError,
5001 "'%.200s' object is not iterable",
Christian Heimes90aa7642007-12-19 02:45:37 +00005002 Py_TYPE(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005003 return NULL;
5004 }
5005 Py_DECREF(func);
5006 return PySeqIter_New(self);
5007}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005008
5009static PyObject *
5010slot_tp_iternext(PyObject *self)
5011{
Guido van Rossum2730b132001-08-28 18:22:14 +00005012 static PyObject *next_str;
Georg Brandla18af4e2007-04-21 15:47:16 +00005013 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005014}
5015
Guido van Rossum1a493502001-08-17 16:47:50 +00005016static PyObject *
5017slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5018{
Christian Heimes90aa7642007-12-19 02:45:37 +00005019 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00005020 PyObject *get;
5021 static PyObject *get_str = NULL;
5022
5023 if (get_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005024 get_str = PyUnicode_InternFromString("__get__");
Guido van Rossum1a493502001-08-17 16:47:50 +00005025 if (get_str == NULL)
5026 return NULL;
5027 }
5028 get = _PyType_Lookup(tp, get_str);
5029 if (get == NULL) {
5030 /* Avoid further slowdowns */
5031 if (tp->tp_descr_get == slot_tp_descr_get)
5032 tp->tp_descr_get = NULL;
5033 Py_INCREF(self);
5034 return self;
5035 }
Guido van Rossum2c252392001-08-24 10:13:31 +00005036 if (obj == NULL)
5037 obj = Py_None;
5038 if (type == NULL)
5039 type = Py_None;
Thomas Wouters477c8d52006-05-27 19:21:47 +00005040 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005041}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005042
5043static int
5044slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5045{
Guido van Rossum2c252392001-08-24 10:13:31 +00005046 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005047 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005048
5049 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00005050 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005051 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00005052 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005053 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005054 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005055 if (res == NULL)
5056 return -1;
5057 Py_DECREF(res);
5058 return 0;
5059}
5060
5061static int
5062slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5063{
Guido van Rossum60718732001-08-28 17:47:51 +00005064 static PyObject *init_str;
5065 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005066 PyObject *res;
5067
5068 if (meth == NULL)
5069 return -1;
5070 res = PyObject_Call(meth, args, kwds);
5071 Py_DECREF(meth);
5072 if (res == NULL)
5073 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005074 if (res != Py_None) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005075 PyErr_Format(PyExc_TypeError,
5076 "__init__() should return None, not '%.200s'",
Christian Heimes90aa7642007-12-19 02:45:37 +00005077 Py_TYPE(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005078 Py_DECREF(res);
5079 return -1;
5080 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005081 Py_DECREF(res);
5082 return 0;
5083}
5084
5085static PyObject *
5086slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5087{
Guido van Rossum7bed2132002-08-08 21:57:53 +00005088 static PyObject *new_str;
5089 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005090 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005091 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005092
Guido van Rossum7bed2132002-08-08 21:57:53 +00005093 if (new_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005094 new_str = PyUnicode_InternFromString("__new__");
Guido van Rossum7bed2132002-08-08 21:57:53 +00005095 if (new_str == NULL)
5096 return NULL;
5097 }
5098 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005099 if (func == NULL)
5100 return NULL;
5101 assert(PyTuple_Check(args));
5102 n = PyTuple_GET_SIZE(args);
5103 newargs = PyTuple_New(n+1);
5104 if (newargs == NULL)
5105 return NULL;
5106 Py_INCREF(type);
5107 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5108 for (i = 0; i < n; i++) {
5109 x = PyTuple_GET_ITEM(args, i);
5110 Py_INCREF(x);
5111 PyTuple_SET_ITEM(newargs, i+1, x);
5112 }
5113 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005114 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005115 Py_DECREF(func);
5116 return x;
5117}
5118
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005119static void
5120slot_tp_del(PyObject *self)
5121{
5122 static PyObject *del_str = NULL;
5123 PyObject *del, *res;
5124 PyObject *error_type, *error_value, *error_traceback;
5125
5126 /* Temporarily resurrect the object. */
5127 assert(self->ob_refcnt == 0);
5128 self->ob_refcnt = 1;
5129
5130 /* Save the current exception, if any. */
5131 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5132
5133 /* Execute __del__ method, if any. */
5134 del = lookup_maybe(self, "__del__", &del_str);
5135 if (del != NULL) {
5136 res = PyEval_CallObject(del, NULL);
5137 if (res == NULL)
5138 PyErr_WriteUnraisable(del);
5139 else
5140 Py_DECREF(res);
5141 Py_DECREF(del);
5142 }
5143
5144 /* Restore the saved exception. */
5145 PyErr_Restore(error_type, error_value, error_traceback);
5146
5147 /* Undo the temporary resurrection; can't use DECREF here, it would
5148 * cause a recursive call.
5149 */
5150 assert(self->ob_refcnt > 0);
5151 if (--self->ob_refcnt == 0)
5152 return; /* this is the normal path out */
5153
5154 /* __del__ resurrected it! Make it look like the original Py_DECREF
5155 * never happened.
5156 */
5157 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005158 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005159 _Py_NewReference(self);
5160 self->ob_refcnt = refcnt;
5161 }
Christian Heimes90aa7642007-12-19 02:45:37 +00005162 assert(!PyType_IS_GC(Py_TYPE(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005163 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005164 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5165 * we need to undo that. */
5166 _Py_DEC_REFTOTAL;
5167 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5168 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005169 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5170 * _Py_NewReference bumped tp_allocs: both of those need to be
5171 * undone.
5172 */
5173#ifdef COUNT_ALLOCS
Christian Heimes90aa7642007-12-19 02:45:37 +00005174 --Py_TYPE(self)->tp_frees;
5175 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005176#endif
5177}
5178
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005179
5180/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005181 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005182 structure, which incorporates the additional structures used for numbers,
5183 sequences and mappings.
5184 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005185 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005186 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5187 terminated with an all-zero entry. (This table is further initialized and
5188 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005189
Guido van Rossum6d204072001-10-21 00:44:31 +00005190typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005191
5192#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005193#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005194#undef ETSLOT
5195#undef SQSLOT
5196#undef MPSLOT
5197#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005198#undef UNSLOT
5199#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005200#undef BINSLOT
5201#undef RBINSLOT
5202
Guido van Rossum6d204072001-10-21 00:44:31 +00005203#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005204 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5205 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005206#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5207 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005208 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005209#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005210 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005211 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005212#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5213 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5214#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5215 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5216#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5217 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5218#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5219 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5220 "x." NAME "() <==> " DOC)
5221#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5222 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5223 "x." NAME "(y) <==> x" DOC "y")
5224#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5225 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5226 "x." NAME "(y) <==> x" DOC "y")
5227#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5228 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5229 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005230#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5231 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5232 "x." NAME "(y) <==> " DOC)
5233#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5234 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5235 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005236
5237static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005238 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005239 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005240 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5241 The logic in abstract.c always falls back to nb_add/nb_multiply in
5242 this case. Defining both the nb_* and the sq_* slots to call the
5243 user-defined methods has unexpected side-effects, as shown by
5244 test_descr.notimplemented() */
5245 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005246 "x.__add__(y) <==> x+y"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005247 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005248 "x.__mul__(n) <==> x*n"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005249 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005250 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005251 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5252 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005253 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005254 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005255 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005256 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005257 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5258 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005259 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005260 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005261 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005262 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005263
Martin v. Löwis18e16552006-02-15 17:27:45 +00005264 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005265 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005266 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005267 wrap_binaryfunc,
5268 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005269 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005270 wrap_objobjargproc,
5271 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005272 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005273 wrap_delitem,
5274 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005275
Guido van Rossum6d204072001-10-21 00:44:31 +00005276 BINSLOT("__add__", nb_add, slot_nb_add,
5277 "+"),
5278 RBINSLOT("__radd__", nb_add, slot_nb_add,
5279 "+"),
5280 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5281 "-"),
5282 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5283 "-"),
5284 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5285 "*"),
5286 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5287 "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005288 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5289 "%"),
5290 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5291 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005292 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005293 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005294 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005295 "divmod(y, x)"),
5296 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5297 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5298 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5299 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5300 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5301 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5302 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5303 "abs(x)"),
Jack Diederich4dafcc42006-11-28 19:15:13 +00005304 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005305 "x != 0"),
5306 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5307 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5308 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5309 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5310 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5311 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5312 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5313 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5314 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5315 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5316 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005317 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5318 "int(x)"),
5319 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5320 "long(x)"),
5321 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5322 "float(x)"),
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005323 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005324 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005325 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5326 wrap_binaryfunc, "+"),
5327 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5328 wrap_binaryfunc, "-"),
5329 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5330 wrap_binaryfunc, "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005331 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5332 wrap_binaryfunc, "%"),
5333 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005334 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005335 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5336 wrap_binaryfunc, "<<"),
5337 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5338 wrap_binaryfunc, ">>"),
5339 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5340 wrap_binaryfunc, "&"),
5341 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5342 wrap_binaryfunc, "^"),
5343 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5344 wrap_binaryfunc, "|"),
5345 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5346 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5347 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5348 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5349 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5350 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5351 IBSLOT("__itruediv__", nb_inplace_true_divide,
5352 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005353
Guido van Rossum6d204072001-10-21 00:44:31 +00005354 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5355 "x.__str__() <==> str(x)"),
5356 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5357 "x.__repr__() <==> repr(x)"),
5358 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5359 "x.__cmp__(y) <==> cmp(x,y)"),
5360 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5361 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005362 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5363 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005364 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005365 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5366 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5367 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5368 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5369 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5370 "x.__setattr__('name', value) <==> x.name = value"),
5371 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5372 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5373 "x.__delattr__('name') <==> del x.name"),
5374 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5375 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5376 "x.__lt__(y) <==> x<y"),
5377 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5378 "x.__le__(y) <==> x<=y"),
5379 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5380 "x.__eq__(y) <==> x==y"),
5381 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5382 "x.__ne__(y) <==> x!=y"),
5383 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5384 "x.__gt__(y) <==> x>y"),
5385 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5386 "x.__ge__(y) <==> x>=y"),
5387 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5388 "x.__iter__() <==> iter(x)"),
Georg Brandla18af4e2007-04-21 15:47:16 +00005389 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5390 "x.__next__() <==> next(x)"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005391 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5392 "descr.__get__(obj[, type]) -> value"),
5393 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5394 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005395 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5396 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005397 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005398 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005399 "see x.__class__.__doc__ for signature",
5400 PyWrapperFlag_KEYWORDS),
5401 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005402 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005403 {NULL}
5404};
5405
Guido van Rossumc334df52002-04-04 23:44:47 +00005406/* Given a type pointer and an offset gotten from a slotdef entry, return a
Guido van Rossumd8faa362007-04-27 19:54:29 +00005407 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005408 the offset to the type pointer, since it takes care to indirect through the
5409 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5410 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005411static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005412slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005413{
5414 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005415 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005416
Guido van Rossume5c691a2003-03-07 15:13:17 +00005417 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005418 assert(offset >= 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005419 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5420 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5421 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005422 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005423 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005424 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5425 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005426 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005427 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005428 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5429 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005430 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005431 }
5432 else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005433 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005434 }
5435 if (ptr != NULL)
5436 ptr += offset;
5437 return (void **)ptr;
5438}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005439
Guido van Rossumc334df52002-04-04 23:44:47 +00005440/* Length of array of slotdef pointers used to store slots with the
5441 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5442 the same __name__, for any __name__. Since that's a static property, it is
5443 appropriate to declare fixed-size arrays for this. */
5444#define MAX_EQUIV 10
5445
5446/* Return a slot pointer for a given name, but ONLY if the attribute has
5447 exactly one slot function. The name must be an interned string. */
5448static void **
5449resolve_slotdups(PyTypeObject *type, PyObject *name)
5450{
5451 /* XXX Maybe this could be optimized more -- but is it worth it? */
5452
5453 /* pname and ptrs act as a little cache */
5454 static PyObject *pname;
5455 static slotdef *ptrs[MAX_EQUIV];
5456 slotdef *p, **pp;
5457 void **res, **ptr;
5458
5459 if (pname != name) {
5460 /* Collect all slotdefs that match name into ptrs. */
5461 pname = name;
5462 pp = ptrs;
5463 for (p = slotdefs; p->name_strobj; p++) {
5464 if (p->name_strobj == name)
5465 *pp++ = p;
5466 }
5467 *pp = NULL;
5468 }
5469
5470 /* Look in all matching slots of the type; if exactly one of these has
Guido van Rossumd8faa362007-04-27 19:54:29 +00005471 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005472 res = NULL;
5473 for (pp = ptrs; *pp; pp++) {
5474 ptr = slotptr(type, (*pp)->offset);
5475 if (ptr == NULL || *ptr == NULL)
5476 continue;
5477 if (res != NULL)
5478 return NULL;
5479 res = ptr;
5480 }
5481 return res;
5482}
5483
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005484/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005485 does some incredibly complex thinking and then sticks something into the
5486 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5487 interests, and then stores a generic wrapper or a specific function into
5488 the slot.) Return a pointer to the next slotdef with a different offset,
5489 because that's convenient for fixup_slot_dispatchers(). */
5490static slotdef *
5491update_one_slot(PyTypeObject *type, slotdef *p)
5492{
5493 PyObject *descr;
5494 PyWrapperDescrObject *d;
5495 void *generic = NULL, *specific = NULL;
5496 int use_generic = 0;
5497 int offset = p->offset;
5498 void **ptr = slotptr(type, offset);
5499
5500 if (ptr == NULL) {
5501 do {
5502 ++p;
5503 } while (p->offset == offset);
5504 return p;
5505 }
5506 do {
5507 descr = _PyType_Lookup(type, p->name_strobj);
5508 if (descr == NULL)
5509 continue;
Christian Heimes90aa7642007-12-19 02:45:37 +00005510 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00005511 void **tptr = resolve_slotdups(type, p->name_strobj);
5512 if (tptr == NULL || tptr == ptr)
5513 generic = p->function;
5514 d = (PyWrapperDescrObject *)descr;
5515 if (d->d_base->wrapper == p->wrapper &&
5516 PyType_IsSubtype(type, d->d_type))
5517 {
5518 if (specific == NULL ||
5519 specific == d->d_wrapped)
5520 specific = d->d_wrapped;
5521 else
5522 use_generic = 1;
5523 }
5524 }
Christian Heimes90aa7642007-12-19 02:45:37 +00005525 else if (Py_TYPE(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00005526 PyCFunction_GET_FUNCTION(descr) ==
5527 (PyCFunction)tp_new_wrapper &&
5528 strcmp(p->name, "__new__") == 0)
5529 {
5530 /* The __new__ wrapper is not a wrapper descriptor,
5531 so must be special-cased differently.
5532 If we don't do this, creating an instance will
5533 always use slot_tp_new which will look up
5534 __new__ in the MRO which will call tp_new_wrapper
5535 which will look through the base classes looking
5536 for a static base and call its tp_new (usually
5537 PyType_GenericNew), after performing various
5538 sanity checks and constructing a new argument
5539 list. Cut all that nonsense short -- this speeds
5540 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005541 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005542 /* XXX I'm not 100% sure that there isn't a hole
5543 in this reasoning that requires additional
5544 sanity checks. I'll buy the first person to
5545 point out a bug in this reasoning a beer. */
5546 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005547 else {
5548 use_generic = 1;
5549 generic = p->function;
5550 }
5551 } while ((++p)->offset == offset);
5552 if (specific && !use_generic)
5553 *ptr = specific;
5554 else
5555 *ptr = generic;
5556 return p;
5557}
5558
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005559/* In the type, update the slots whose slotdefs are gathered in the pp array.
5560 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005561static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005562update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005563{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005564 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005565
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005566 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005567 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005568 return 0;
5569}
5570
Guido van Rossumc334df52002-04-04 23:44:47 +00005571/* Comparison function for qsort() to compare slotdefs by their offset, and
5572 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005573static int
5574slotdef_cmp(const void *aa, const void *bb)
5575{
5576 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5577 int c = a->offset - b->offset;
5578 if (c != 0)
5579 return c;
5580 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005581 /* Cannot use a-b, as this gives off_t,
5582 which may lose precision when converted to int. */
5583 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005584}
5585
Guido van Rossumc334df52002-04-04 23:44:47 +00005586/* Initialize the slotdefs table by adding interned string objects for the
5587 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005588static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005589init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005590{
5591 slotdef *p;
5592 static int initialized = 0;
5593
5594 if (initialized)
5595 return;
5596 for (p = slotdefs; p->name; p++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005597 p->name_strobj = PyUnicode_InternFromString(p->name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005598 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005599 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005600 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005601 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5602 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005603 initialized = 1;
5604}
5605
Guido van Rossumc334df52002-04-04 23:44:47 +00005606/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005607static int
5608update_slot(PyTypeObject *type, PyObject *name)
5609{
Guido van Rossumc334df52002-04-04 23:44:47 +00005610 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005611 slotdef *p;
5612 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005613 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005614
Christian Heimesa62da1d2008-01-12 19:39:10 +00005615 /* Clear the VALID_VERSION flag of 'type' and all its
5616 subclasses. This could possibly be unified with the
5617 update_subclasses() recursion below, but carefully:
5618 they each have their own conditions on which to stop
5619 recursing into subclasses. */
5620 type_modified(type);
5621
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005622 init_slotdefs();
5623 pp = ptrs;
5624 for (p = slotdefs; p->name; p++) {
5625 /* XXX assume name is interned! */
5626 if (p->name_strobj == name)
5627 *pp++ = p;
5628 }
5629 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005630 for (pp = ptrs; *pp; pp++) {
5631 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005632 offset = p->offset;
5633 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005634 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005635 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005636 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005637 if (ptrs[0] == NULL)
5638 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005639 return update_subclasses(type, name,
5640 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005641}
5642
Guido van Rossumc334df52002-04-04 23:44:47 +00005643/* Store the proper functions in the slot dispatches at class (type)
5644 definition time, based upon which operations the class overrides in its
5645 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005646static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005647fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005648{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005649 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005650
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005651 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005652 for (p = slotdefs; p->name; )
5653 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005654}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005655
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005656static void
5657update_all_slots(PyTypeObject* type)
5658{
5659 slotdef *p;
5660
5661 init_slotdefs();
5662 for (p = slotdefs; p->name; p++) {
5663 /* update_slot returns int but can't actually fail */
5664 update_slot(type, p->name_strobj);
5665 }
5666}
5667
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005668/* recurse_down_subclasses() and update_subclasses() are mutually
5669 recursive functions to call a callback for all subclasses,
5670 but refraining from recursing into subclasses that define 'name'. */
5671
5672static int
5673update_subclasses(PyTypeObject *type, PyObject *name,
5674 update_callback callback, void *data)
5675{
5676 if (callback(type, data) < 0)
5677 return -1;
5678 return recurse_down_subclasses(type, name, callback, data);
5679}
5680
5681static int
5682recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5683 update_callback callback, void *data)
5684{
5685 PyTypeObject *subclass;
5686 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005687 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005688
5689 subclasses = type->tp_subclasses;
5690 if (subclasses == NULL)
5691 return 0;
5692 assert(PyList_Check(subclasses));
5693 n = PyList_GET_SIZE(subclasses);
5694 for (i = 0; i < n; i++) {
5695 ref = PyList_GET_ITEM(subclasses, i);
5696 assert(PyWeakref_CheckRef(ref));
5697 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5698 assert(subclass != NULL);
5699 if ((PyObject *)subclass == Py_None)
5700 continue;
5701 assert(PyType_Check(subclass));
5702 /* Avoid recursing down into unaffected classes */
5703 dict = subclass->tp_dict;
5704 if (dict != NULL && PyDict_Check(dict) &&
5705 PyDict_GetItem(dict, name) != NULL)
5706 continue;
5707 if (update_subclasses(subclass, name, callback, data) < 0)
5708 return -1;
5709 }
5710 return 0;
5711}
5712
Guido van Rossum6d204072001-10-21 00:44:31 +00005713/* This function is called by PyType_Ready() to populate the type's
5714 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005715 function slot (like tp_repr) that's defined in the type, one or more
5716 corresponding descriptors are added in the type's tp_dict dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +00005717 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005718 cause more than one descriptor to be added (for example, the nb_add
5719 slot adds both __add__ and __radd__ descriptors) and some function
5720 slots compete for the same descriptor (for example both sq_item and
5721 mp_subscript generate a __getitem__ descriptor).
5722
Guido van Rossumd8faa362007-04-27 19:54:29 +00005723 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005724 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005725 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005726 between competing slots: the members of PyHeapTypeObject are listed
5727 from most general to least general, so the most general slot is
5728 preferred. In particular, because as_mapping comes before as_sequence,
5729 for a type that defines both mp_subscript and sq_item, mp_subscript
5730 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005731
5732 This only adds new descriptors and doesn't overwrite entries in
5733 tp_dict that were previously defined. The descriptors contain a
5734 reference to the C function they must call, so that it's safe if they
5735 are copied into a subtype's __dict__ and the subtype has a different
5736 C function in its slot -- calling the method defined by the
5737 descriptor will call the C function that was used to create it,
5738 rather than the C function present in the slot when it is called.
5739 (This is important because a subtype may have a C function in the
5740 slot that calls the method from the dictionary, and we want to avoid
5741 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005742
5743static int
5744add_operators(PyTypeObject *type)
5745{
5746 PyObject *dict = type->tp_dict;
5747 slotdef *p;
5748 PyObject *descr;
5749 void **ptr;
5750
5751 init_slotdefs();
5752 for (p = slotdefs; p->name; p++) {
5753 if (p->wrapper == NULL)
5754 continue;
5755 ptr = slotptr(type, p->offset);
5756 if (!ptr || !*ptr)
5757 continue;
5758 if (PyDict_GetItem(dict, p->name_strobj))
5759 continue;
5760 descr = PyDescr_NewWrapper(type, p, *ptr);
5761 if (descr == NULL)
5762 return -1;
5763 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5764 return -1;
5765 Py_DECREF(descr);
5766 }
5767 if (type->tp_new != NULL) {
5768 if (add_tp_new_wrapper(type) < 0)
5769 return -1;
5770 }
5771 return 0;
5772}
5773
Guido van Rossum705f0f52001-08-24 16:47:00 +00005774
5775/* Cooperative 'super' */
5776
5777typedef struct {
5778 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005779 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005780 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005781 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005782} superobject;
5783
Guido van Rossum6f799372001-09-20 20:46:19 +00005784static PyMemberDef super_members[] = {
5785 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5786 "the class invoking super()"},
5787 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5788 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005789 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005790 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005791 {0}
5792};
5793
Guido van Rossum705f0f52001-08-24 16:47:00 +00005794static void
5795super_dealloc(PyObject *self)
5796{
5797 superobject *su = (superobject *)self;
5798
Guido van Rossum048eb752001-10-02 21:24:57 +00005799 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005800 Py_XDECREF(su->obj);
5801 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005802 Py_XDECREF(su->obj_type);
Christian Heimes90aa7642007-12-19 02:45:37 +00005803 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005804}
5805
5806static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005807super_repr(PyObject *self)
5808{
5809 superobject *su = (superobject *)self;
5810
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005811 if (su->obj_type)
Walter Dörwald1ab83302007-05-18 17:15:44 +00005812 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005813 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005814 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005815 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005816 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00005817 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005818 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005819 su->type ? su->type->tp_name : "NULL");
5820}
5821
5822static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005823super_getattro(PyObject *self, PyObject *name)
5824{
5825 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005826 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005827
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005828 if (!skip) {
5829 /* We want __class__ to return the class of the super object
5830 (i.e. super, or a subclass), not the class of su->obj. */
Martin v. Löwis5b222132007-06-10 09:51:05 +00005831 skip = (PyUnicode_Check(name) &&
5832 PyUnicode_GET_SIZE(name) == 9 &&
5833 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005834 }
5835
5836 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005837 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005838 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005839 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005840 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005841
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005842 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005843 mro = starttype->tp_mro;
5844
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005845 if (mro == NULL)
5846 n = 0;
5847 else {
5848 assert(PyTuple_Check(mro));
5849 n = PyTuple_GET_SIZE(mro);
5850 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005851 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005852 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005853 break;
5854 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005855 i++;
5856 res = NULL;
5857 for (; i < n; i++) {
5858 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005859 if (PyType_Check(tmp))
5860 dict = ((PyTypeObject *)tmp)->tp_dict;
Tim Petersa91e9642001-11-14 23:32:33 +00005861 else
5862 continue;
5863 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005864 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005865 Py_INCREF(res);
Christian Heimes90aa7642007-12-19 02:45:37 +00005866 f = Py_TYPE(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005867 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005868 tmp = f(res,
5869 /* Only pass 'obj' param if
5870 this is instance-mode super
5871 (See SF ID #743627)
5872 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005873 (su->obj == (PyObject *)
5874 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005875 ? (PyObject *)NULL
5876 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005877 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005878 Py_DECREF(res);
5879 res = tmp;
5880 }
5881 return res;
5882 }
5883 }
5884 }
5885 return PyObject_GenericGetAttr(self, name);
5886}
5887
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005888static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005889supercheck(PyTypeObject *type, PyObject *obj)
5890{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005891 /* Check that a super() call makes sense. Return a type object.
5892
5893 obj can be a new-style class, or an instance of one:
5894
Guido van Rossumd8faa362007-04-27 19:54:29 +00005895 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005896 used for class methods; the return value is obj.
5897
5898 - If it is an instance, it must be an instance of 'type'. This is
5899 the normal case; the return value is obj.__class__.
5900
5901 But... when obj is an instance, we want to allow for the case where
Christian Heimes90aa7642007-12-19 02:45:37 +00005902 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005903 This will allow using super() with a proxy for obj.
5904 */
5905
Guido van Rossum8e80a722003-02-18 19:22:22 +00005906 /* Check for first bullet above (special case) */
5907 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5908 Py_INCREF(obj);
5909 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005910 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005911
5912 /* Normal case */
Christian Heimes90aa7642007-12-19 02:45:37 +00005913 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
5914 Py_INCREF(Py_TYPE(obj));
5915 return Py_TYPE(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005916 }
5917 else {
5918 /* Try the slow way */
5919 static PyObject *class_str = NULL;
5920 PyObject *class_attr;
5921
5922 if (class_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005923 class_str = PyUnicode_FromString("__class__");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005924 if (class_str == NULL)
5925 return NULL;
5926 }
5927
5928 class_attr = PyObject_GetAttr(obj, class_str);
5929
5930 if (class_attr != NULL &&
5931 PyType_Check(class_attr) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00005932 (PyTypeObject *)class_attr != Py_TYPE(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005933 {
5934 int ok = PyType_IsSubtype(
5935 (PyTypeObject *)class_attr, type);
5936 if (ok)
5937 return (PyTypeObject *)class_attr;
5938 }
5939
5940 if (class_attr == NULL)
5941 PyErr_Clear();
5942 else
5943 Py_DECREF(class_attr);
5944 }
5945
Guido van Rossumd8faa362007-04-27 19:54:29 +00005946 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005947 "super(type, obj): "
5948 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005949 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005950}
5951
Guido van Rossum705f0f52001-08-24 16:47:00 +00005952static PyObject *
5953super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5954{
5955 superobject *su = (superobject *)self;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005956 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005957
5958 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5959 /* Not binding to an object, or already bound */
5960 Py_INCREF(self);
5961 return self;
5962 }
Christian Heimes90aa7642007-12-19 02:45:37 +00005963 if (Py_TYPE(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005964 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005965 call its type */
Christian Heimes90aa7642007-12-19 02:45:37 +00005966 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
Guido van Rossumd8faa362007-04-27 19:54:29 +00005967 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005968 else {
5969 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005970 PyTypeObject *obj_type = supercheck(su->type, obj);
5971 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005972 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005973 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005974 NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005975 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005976 return NULL;
5977 Py_INCREF(su->type);
5978 Py_INCREF(obj);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005979 newobj->type = su->type;
5980 newobj->obj = obj;
5981 newobj->obj_type = obj_type;
5982 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005983 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005984}
5985
5986static int
5987super_init(PyObject *self, PyObject *args, PyObject *kwds)
5988{
5989 superobject *su = (superobject *)self;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005990 PyTypeObject *type = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00005991 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005992 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005993
Thomas Wouters89f507f2006-12-13 04:49:30 +00005994 if (!_PyArg_NoKeywords("super", kwds))
5995 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005996 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005997 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005998
5999 if (type == NULL) {
6000 /* Call super(), without args -- fill in from __class__
6001 and first local variable on the stack. */
6002 PyFrameObject *f = PyThreadState_GET()->frame;
6003 PyCodeObject *co = f->f_code;
6004 int i, n;
6005 if (co == NULL) {
6006 PyErr_SetString(PyExc_SystemError,
6007 "super(): no code object");
6008 return -1;
6009 }
6010 if (co->co_argcount == 0) {
6011 PyErr_SetString(PyExc_SystemError,
6012 "super(): no arguments");
6013 return -1;
6014 }
6015 obj = f->f_localsplus[0];
6016 if (obj == NULL) {
6017 PyErr_SetString(PyExc_SystemError,
6018 "super(): arg[0] deleted");
6019 return -1;
6020 }
6021 if (co->co_freevars == NULL)
6022 n = 0;
6023 else {
6024 assert(PyTuple_Check(co->co_freevars));
6025 n = PyTuple_GET_SIZE(co->co_freevars);
6026 }
6027 for (i = 0; i < n; i++) {
6028 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6029 assert(PyUnicode_Check(name));
6030 if (!PyUnicode_CompareWithASCIIString(name,
6031 "__class__")) {
6032 PyObject *cell =
6033 f->f_localsplus[co->co_nlocals + i];
6034 if (cell == NULL || !PyCell_Check(cell)) {
6035 PyErr_SetString(PyExc_SystemError,
6036 "super(): bad __class__ cell");
6037 return -1;
6038 }
6039 type = (PyTypeObject *) PyCell_GET(cell);
6040 if (type == NULL) {
6041 PyErr_SetString(PyExc_SystemError,
6042 "super(): empty __class__ cell");
6043 return -1;
6044 }
6045 if (!PyType_Check(type)) {
6046 PyErr_Format(PyExc_SystemError,
6047 "super(): __class__ is not a type (%s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00006048 Py_TYPE(type)->tp_name);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006049 return -1;
6050 }
6051 break;
6052 }
6053 }
6054 if (type == NULL) {
6055 PyErr_SetString(PyExc_SystemError,
6056 "super(): __class__ cell not found");
6057 return -1;
6058 }
6059 }
6060
Guido van Rossum705f0f52001-08-24 16:47:00 +00006061 if (obj == Py_None)
6062 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006063 if (obj != NULL) {
6064 obj_type = supercheck(type, obj);
6065 if (obj_type == NULL)
6066 return -1;
6067 Py_INCREF(obj);
6068 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006069 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006070 su->type = type;
6071 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006072 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006073 return 0;
6074}
6075
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006076PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006077"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006078"super(type) -> unbound super object\n"
6079"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006080"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006081"Typical use to call a cooperative superclass method:\n"
6082"class C(B):\n"
6083" def meth(self, arg):\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006084" super().meth(arg)\n"
6085"This works for class methods too:\n"
6086"class C(B):\n"
6087" @classmethod\n"
6088" def cmeth(cls, arg):\n"
6089" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006090
Guido van Rossum048eb752001-10-02 21:24:57 +00006091static int
6092super_traverse(PyObject *self, visitproc visit, void *arg)
6093{
6094 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006095
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006096 Py_VISIT(su->obj);
6097 Py_VISIT(su->type);
6098 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006099
6100 return 0;
6101}
6102
Guido van Rossum705f0f52001-08-24 16:47:00 +00006103PyTypeObject PySuper_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00006104 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00006105 "super", /* tp_name */
6106 sizeof(superobject), /* tp_basicsize */
6107 0, /* tp_itemsize */
6108 /* methods */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006109 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006110 0, /* tp_print */
6111 0, /* tp_getattr */
6112 0, /* tp_setattr */
6113 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006114 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006115 0, /* tp_as_number */
6116 0, /* tp_as_sequence */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006117 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006118 0, /* tp_hash */
6119 0, /* tp_call */
6120 0, /* tp_str */
6121 super_getattro, /* tp_getattro */
6122 0, /* tp_setattro */
6123 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006124 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6125 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006126 super_doc, /* tp_doc */
6127 super_traverse, /* tp_traverse */
6128 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006129 0, /* tp_richcompare */
6130 0, /* tp_weaklistoffset */
6131 0, /* tp_iter */
6132 0, /* tp_iternext */
6133 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006134 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006135 0, /* tp_getset */
6136 0, /* tp_base */
6137 0, /* tp_dict */
6138 super_descr_get, /* tp_descr_get */
6139 0, /* tp_descr_set */
6140 0, /* tp_dictoffset */
6141 super_init, /* tp_init */
6142 PyType_GenericAlloc, /* tp_alloc */
6143 PyType_GenericNew, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006144 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006145};