blob: 88ce67f70d4b4be78948f66e8ec94309de686000 [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, \
Georg Brandl1bcf35a2008-05-25 09:32:09 +000023 ((PyUnicodeObject *)(name))->hash)
Christian Heimesa62da1d2008-01-12 19:39:10 +000024#define MCACHE_CACHEABLE_NAME(name) \
Georg Brandl1bcf35a2008-05-25 09:32:09 +000025 PyUnicode_CheckExact(name) && \
26 PyUnicode_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
Christian Heimesa62da1d2008-01-12 19:39:10 +000027
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;
Christian Heimes26855632008-01-27 23:50:43 +000036static void type_modified(PyTypeObject *);
37
38unsigned int
39PyType_ClearCache(void)
40{
41 Py_ssize_t i;
42 unsigned int cur_version_tag = next_version_tag - 1;
43
44 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
45 method_cache[i].version = 0;
46 Py_CLEAR(method_cache[i].name);
47 method_cache[i].value = NULL;
48 }
49 next_version_tag = 0;
50 /* mark all version tags as invalid */
51 type_modified(&PyBaseObject_Type);
52 return cur_version_tag;
53}
Christian Heimesa62da1d2008-01-12 19:39:10 +000054
55static void
56type_modified(PyTypeObject *type)
57{
58 /* Invalidate any cached data for the specified type and all
59 subclasses. This function is called after the base
60 classes, mro, or attributes of the type are altered.
61
62 Invariants:
63
64 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
65 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
66 objects coming from non-recompiled extension modules)
67
68 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
69 it must first be set on all super types.
70
71 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
72 type (so it must first clear it on all subclasses). The
73 tp_version_tag value is meaningless unless this flag is set.
74 We don't assign new version tags eagerly, but only as
75 needed.
76 */
77 PyObject *raw, *ref;
78 Py_ssize_t i, n;
79
Christian Heimes412dc9c2008-01-27 18:55:54 +000080 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
Christian Heimesa62da1d2008-01-12 19:39:10 +000081 return;
82
83 raw = type->tp_subclasses;
84 if (raw != NULL) {
85 n = PyList_GET_SIZE(raw);
86 for (i = 0; i < n; i++) {
87 ref = PyList_GET_ITEM(raw, i);
88 ref = PyWeakref_GET_OBJECT(ref);
89 if (ref != Py_None) {
90 type_modified((PyTypeObject *)ref);
91 }
92 }
93 }
94 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
95}
96
97static void
98type_mro_modified(PyTypeObject *type, PyObject *bases) {
99 /*
100 Check that all base classes or elements of the mro of type are
101 able to be cached. This function is called after the base
102 classes or mro of the type are altered.
103
104 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
105 inherits from an old-style class, either directly or if it
106 appears in the MRO of a new-style class. No support either for
107 custom MROs that include types that are not officially super
108 types.
109
110 Called from mro_internal, which will subsequently be called on
111 each subclass when their mro is recursively updated.
112 */
113 Py_ssize_t i, n;
114 int clear = 0;
115
Christian Heimes412dc9c2008-01-27 18:55:54 +0000116 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
Christian Heimesa62da1d2008-01-12 19:39:10 +0000117 return;
118
119 n = PyTuple_GET_SIZE(bases);
120 for (i = 0; i < n; i++) {
121 PyObject *b = PyTuple_GET_ITEM(bases, i);
122 PyTypeObject *cls;
123
124 if (!PyType_Check(b) ) {
125 clear = 1;
126 break;
127 }
128
129 cls = (PyTypeObject *)b;
130
131 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
132 !PyType_IsSubtype(type, cls)) {
133 clear = 1;
134 break;
135 }
136 }
137
138 if (clear)
139 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
140 Py_TPFLAGS_VALID_VERSION_TAG);
141}
142
143static int
144assign_version_tag(PyTypeObject *type)
145{
146 /* Ensure that the tp_version_tag is valid and set
147 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
148 must first be done on all super classes. Return 0 if this
149 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
150 */
151 Py_ssize_t i, n;
152 PyObject *bases;
153
154 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
155 return 1;
156 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
157 return 0;
158 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
159 return 0;
160
161 type->tp_version_tag = next_version_tag++;
162 /* for stress-testing: next_version_tag &= 0xFF; */
163
164 if (type->tp_version_tag == 0) {
165 /* wrap-around or just starting Python - clear the whole
166 cache by filling names with references to Py_None.
167 Values are also set to NULL for added protection, as they
168 are borrowed reference */
169 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
170 method_cache[i].value = NULL;
171 Py_XDECREF(method_cache[i].name);
172 method_cache[i].name = Py_None;
173 Py_INCREF(Py_None);
174 }
175 /* mark all version tags as invalid */
176 type_modified(&PyBaseObject_Type);
177 return 1;
178 }
179 bases = type->tp_bases;
180 n = PyTuple_GET_SIZE(bases);
181 for (i = 0; i < n; i++) {
182 PyObject *b = PyTuple_GET_ITEM(bases, i);
183 assert(PyType_Check(b));
184 if (!assign_version_tag((PyTypeObject *)b))
185 return 0;
186 }
187 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
188 return 1;
189}
190
191
Guido van Rossum6f799372001-09-20 20:46:19 +0000192static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000193 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
194 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
195 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +0000196 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000197 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
198 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
199 {"__dictoffset__", T_LONG,
200 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000201 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
202 {0}
203};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000204
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000205static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000206type_name(PyTypeObject *type, void *context)
207{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000208 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000209
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000210 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +0000211 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000212
Georg Brandlc255c7b2006-02-20 22:27:28 +0000213 Py_INCREF(et->ht_name);
214 return et->ht_name;
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000215 }
216 else {
217 s = strrchr(type->tp_name, '.');
218 if (s == NULL)
219 s = type->tp_name;
220 else
221 s++;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000222 return PyUnicode_FromString(s);
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000223 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000224}
225
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000226static int
227type_set_name(PyTypeObject *type, PyObject *value, void *context)
228{
Guido van Rossume5c691a2003-03-07 15:13:17 +0000229 PyHeapTypeObject* et;
Neal Norwitz80e7f272007-08-26 06:45:23 +0000230 char *tp_name;
Guido van Rossume845c0f2007-11-02 23:07:07 +0000231 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000232
233 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
234 PyErr_Format(PyExc_TypeError,
235 "can't set %s.__name__", type->tp_name);
236 return -1;
237 }
238 if (!value) {
239 PyErr_Format(PyExc_TypeError,
240 "can't delete %s.__name__", type->tp_name);
241 return -1;
242 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000243 if (!PyUnicode_Check(value)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000244 PyErr_Format(PyExc_TypeError,
245 "can only assign string to %s.__name__, not '%s'",
Christian Heimes90aa7642007-12-19 02:45:37 +0000246 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000247 return -1;
248 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000249
250 /* Check absence of null characters */
251 tmp = PyUnicode_FromStringAndSize("\0", 1);
252 if (tmp == NULL)
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000253 return -1;
Guido van Rossume845c0f2007-11-02 23:07:07 +0000254 if (PyUnicode_Contains(value, tmp) != 0) {
255 Py_DECREF(tmp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000256 PyErr_Format(PyExc_ValueError,
257 "__name__ must not contain null bytes");
258 return -1;
259 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000260 Py_DECREF(tmp);
261
262 tp_name = PyUnicode_AsString(value);
263 if (tp_name == NULL)
264 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000265
Guido van Rossume5c691a2003-03-07 15:13:17 +0000266 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000267
268 Py_INCREF(value);
269
Georg Brandlc255c7b2006-02-20 22:27:28 +0000270 Py_DECREF(et->ht_name);
271 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000272
Neal Norwitz80e7f272007-08-26 06:45:23 +0000273 type->tp_name = tp_name;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000274
275 return 0;
276}
277
Guido van Rossumc3542212001-08-16 09:18:56 +0000278static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000279type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000280{
Guido van Rossumc3542212001-08-16 09:18:56 +0000281 PyObject *mod;
282 char *s;
283
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000284 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
285 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +0000286 if (!mod) {
287 PyErr_Format(PyExc_AttributeError, "__module__");
288 return 0;
289 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000290 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +0000291 return mod;
292 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000293 else {
294 s = strrchr(type->tp_name, '.');
295 if (s != NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +0000296 return PyUnicode_FromStringAndSize(
Thomas Wouters89f507f2006-12-13 04:49:30 +0000297 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Georg Brandl1a3284e2007-12-02 09:40:06 +0000298 return PyUnicode_FromString("builtins");
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000299 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000300}
301
Guido van Rossum3926a632001-09-25 16:25:58 +0000302static int
303type_set_module(PyTypeObject *type, PyObject *value, void *context)
304{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000305 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000306 PyErr_Format(PyExc_TypeError,
307 "can't set %s.__module__", type->tp_name);
308 return -1;
309 }
310 if (!value) {
311 PyErr_Format(PyExc_TypeError,
312 "can't delete %s.__module__", type->tp_name);
313 return -1;
314 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000315
Christian Heimesa62da1d2008-01-12 19:39:10 +0000316 type_modified(type);
317
Guido van Rossum3926a632001-09-25 16:25:58 +0000318 return PyDict_SetItemString(type->tp_dict, "__module__", value);
319}
320
Tim Peters6d6c1a32001-08-02 04:15:00 +0000321static PyObject *
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000322type_abstractmethods(PyTypeObject *type, void *context)
323{
324 PyObject *mod = PyDict_GetItemString(type->tp_dict,
325 "__abstractmethods__");
326 if (!mod) {
327 PyErr_Format(PyExc_AttributeError, "__abstractmethods__");
328 return NULL;
329 }
330 Py_XINCREF(mod);
331 return mod;
332}
333
334static int
335type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
336{
337 /* __abstractmethods__ should only be set once on a type, in
338 abc.ABCMeta.__new__, so this function doesn't do anything
339 special to update subclasses.
340 */
341 int res = PyDict_SetItemString(type->tp_dict,
342 "__abstractmethods__", value);
343 if (res == 0) {
344 type_modified(type);
345 if (value && PyObject_IsTrue(value)) {
346 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
347 }
348 else {
349 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
350 }
351 }
352 return res;
353}
354
355static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000356type_get_bases(PyTypeObject *type, void *context)
357{
358 Py_INCREF(type->tp_bases);
359 return type->tp_bases;
360}
361
362static PyTypeObject *best_base(PyObject *);
363static int mro_internal(PyTypeObject *);
364static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
365static int add_subclass(PyTypeObject*, PyTypeObject*);
366static void remove_subclass(PyTypeObject *, PyTypeObject *);
367static void update_all_slots(PyTypeObject *);
368
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000369typedef int (*update_callback)(PyTypeObject *, void *);
370static int update_subclasses(PyTypeObject *type, PyObject *name,
371 update_callback callback, void *data);
372static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
373 update_callback callback, void *data);
374
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000375static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000376mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000377{
378 PyTypeObject *subclass;
379 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000380 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000381
382 subclasses = type->tp_subclasses;
383 if (subclasses == NULL)
384 return 0;
385 assert(PyList_Check(subclasses));
386 n = PyList_GET_SIZE(subclasses);
387 for (i = 0; i < n; i++) {
388 ref = PyList_GET_ITEM(subclasses, i);
389 assert(PyWeakref_CheckRef(ref));
390 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
391 assert(subclass != NULL);
392 if ((PyObject *)subclass == Py_None)
393 continue;
394 assert(PyType_Check(subclass));
395 old_mro = subclass->tp_mro;
396 if (mro_internal(subclass) < 0) {
397 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000398 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000399 }
400 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000401 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000402 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000403 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000404 if (!tuple)
405 return -1;
406 if (PyList_Append(temp, tuple) < 0)
407 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000408 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000409 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000410 if (mro_subclasses(subclass, temp) < 0)
411 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000412 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000413 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000414}
415
416static int
417type_set_bases(PyTypeObject *type, PyObject *value, void *context)
418{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000419 Py_ssize_t i;
420 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000421 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000422 PyTypeObject *new_base, *old_base;
423 PyObject *old_bases, *old_mro;
424
425 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
426 PyErr_Format(PyExc_TypeError,
427 "can't set %s.__bases__", type->tp_name);
428 return -1;
429 }
430 if (!value) {
431 PyErr_Format(PyExc_TypeError,
432 "can't delete %s.__bases__", type->tp_name);
433 return -1;
434 }
435 if (!PyTuple_Check(value)) {
436 PyErr_Format(PyExc_TypeError,
437 "can only assign tuple to %s.__bases__, not %s",
Christian Heimes90aa7642007-12-19 02:45:37 +0000438 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000439 return -1;
440 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000441 if (PyTuple_GET_SIZE(value) == 0) {
442 PyErr_Format(PyExc_TypeError,
443 "can only assign non-empty tuple to %s.__bases__, not ()",
444 type->tp_name);
445 return -1;
446 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000447 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
448 ob = PyTuple_GET_ITEM(value, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000449 if (!PyType_Check(ob)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000450 PyErr_Format(
451 PyExc_TypeError,
452 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
Christian Heimes90aa7642007-12-19 02:45:37 +0000453 type->tp_name, Py_TYPE(ob)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000454 return -1;
455 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000456 if (PyType_Check(ob)) {
457 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
458 PyErr_SetString(PyExc_TypeError,
459 "a __bases__ item causes an inheritance cycle");
460 return -1;
461 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000462 }
463 }
464
465 new_base = best_base(value);
466
467 if (!new_base) {
468 return -1;
469 }
470
471 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
472 return -1;
473
474 Py_INCREF(new_base);
475 Py_INCREF(value);
476
477 old_bases = type->tp_bases;
478 old_base = type->tp_base;
479 old_mro = type->tp_mro;
480
481 type->tp_bases = value;
482 type->tp_base = new_base;
483
484 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000485 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000486 }
487
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000488 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000489 if (!temp)
490 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000491
492 r = mro_subclasses(type, temp);
493
494 if (r < 0) {
495 for (i = 0; i < PyList_Size(temp); i++) {
496 PyTypeObject* cls;
497 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000498 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
499 "", 2, 2, &cls, &mro);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000500 Py_INCREF(mro);
501 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000502 cls->tp_mro = mro;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000503 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000504 }
505 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000506 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000507 }
508
509 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000510
511 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000512 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000513 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000514 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000515
516 /* for now, sod that: just remove from all old_bases,
517 add to all new_bases */
518
519 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
520 ob = PyTuple_GET_ITEM(old_bases, i);
521 if (PyType_Check(ob)) {
522 remove_subclass(
523 (PyTypeObject*)ob, type);
524 }
525 }
526
527 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
528 ob = PyTuple_GET_ITEM(value, i);
529 if (PyType_Check(ob)) {
530 if (add_subclass((PyTypeObject*)ob, type) < 0)
531 r = -1;
532 }
533 }
534
535 update_all_slots(type);
536
537 Py_DECREF(old_bases);
538 Py_DECREF(old_base);
539 Py_DECREF(old_mro);
540
541 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000542
543 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000544 Py_DECREF(type->tp_bases);
545 Py_DECREF(type->tp_base);
546 if (type->tp_mro != old_mro) {
547 Py_DECREF(type->tp_mro);
548 }
549
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000550 type->tp_bases = old_bases;
551 type->tp_base = old_base;
552 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000553
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000554 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000555}
556
557static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000558type_dict(PyTypeObject *type, void *context)
559{
560 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000561 Py_INCREF(Py_None);
562 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000563 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000564 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000565}
566
Tim Peters24008312002-03-17 18:56:20 +0000567static PyObject *
568type_get_doc(PyTypeObject *type, void *context)
569{
570 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000571 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Neal Norwitza369c5a2007-08-25 07:41:59 +0000572 return PyUnicode_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000573 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000574 if (result == NULL) {
575 result = Py_None;
576 Py_INCREF(result);
577 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000578 else if (Py_TYPE(result)->tp_descr_get) {
579 result = Py_TYPE(result)->tp_descr_get(result, NULL,
Tim Peters2b858972002-04-18 04:12:28 +0000580 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000581 }
582 else {
583 Py_INCREF(result);
584 }
Tim Peters24008312002-03-17 18:56:20 +0000585 return result;
586}
587
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000588static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000589 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
590 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000591 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000592 {"__abstractmethods__", (getter)type_abstractmethods,
593 (setter)type_set_abstractmethods, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000594 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000595 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000596 {0}
597};
598
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000599static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000600type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000601{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000602 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000603
604 mod = type_module(type, NULL);
605 if (mod == NULL)
606 PyErr_Clear();
Martin v. Löwis5b222132007-06-10 09:51:05 +0000607 else if (!PyUnicode_Check(mod)) {
Guido van Rossumc3542212001-08-16 09:18:56 +0000608 Py_DECREF(mod);
609 mod = NULL;
610 }
611 name = type_name(type, NULL);
612 if (name == NULL)
613 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000614
Georg Brandl1a3284e2007-12-02 09:40:06 +0000615 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
Martin v. Löwis250ad612008-04-07 05:43:42 +0000616 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
Guido van Rossumc3542212001-08-16 09:18:56 +0000617 else
Martin v. Löwis250ad612008-04-07 05:43:42 +0000618 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000619
Guido van Rossumc3542212001-08-16 09:18:56 +0000620 Py_XDECREF(mod);
621 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000622 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000623}
624
Tim Peters6d6c1a32001-08-02 04:15:00 +0000625static PyObject *
626type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
627{
628 PyObject *obj;
629
630 if (type->tp_new == NULL) {
631 PyErr_Format(PyExc_TypeError,
632 "cannot create '%.100s' instances",
633 type->tp_name);
634 return NULL;
635 }
636
Tim Peters3f996e72001-09-13 19:18:27 +0000637 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000638 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000639 /* Ugly exception: when the call was type(something),
640 don't call tp_init on the result. */
641 if (type == &PyType_Type &&
642 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
643 (kwds == NULL ||
644 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
645 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000646 /* If the returned object is not an instance of type,
647 it won't be initialized. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000648 if (!PyType_IsSubtype(Py_TYPE(obj), type))
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000649 return obj;
Christian Heimes90aa7642007-12-19 02:45:37 +0000650 type = Py_TYPE(obj);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000651 if (type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000652 type->tp_init(obj, args, kwds) < 0) {
653 Py_DECREF(obj);
654 obj = NULL;
655 }
656 }
657 return obj;
658}
659
660PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000661PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000662{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000663 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000664 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
665 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000666
667 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000668 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000669 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000670 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000671
Neil Schemenauerc806c882001-08-29 23:54:54 +0000672 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000673 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000674
Neil Schemenauerc806c882001-08-29 23:54:54 +0000675 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000676
Tim Peters6d6c1a32001-08-02 04:15:00 +0000677 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
678 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000679
Tim Peters6d6c1a32001-08-02 04:15:00 +0000680 if (type->tp_itemsize == 0)
681 PyObject_INIT(obj, type);
682 else
683 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000684
Tim Peters6d6c1a32001-08-02 04:15:00 +0000685 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000686 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000687 return obj;
688}
689
690PyObject *
691PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
692{
693 return type->tp_alloc(type, 0);
694}
695
Guido van Rossum9475a232001-10-05 20:51:39 +0000696/* Helpers for subtyping */
697
698static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000699traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
700{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000701 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000702 PyMemberDef *mp;
703
Christian Heimes90aa7642007-12-19 02:45:37 +0000704 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000705 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000706 for (i = 0; i < n; i++, mp++) {
707 if (mp->type == T_OBJECT_EX) {
708 char *addr = (char *)self + mp->offset;
709 PyObject *obj = *(PyObject **)addr;
710 if (obj != NULL) {
711 int err = visit(obj, arg);
712 if (err)
713 return err;
714 }
715 }
716 }
717 return 0;
718}
719
720static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000721subtype_traverse(PyObject *self, visitproc visit, void *arg)
722{
723 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000724 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000725
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000726 /* Find the nearest base with a different tp_traverse,
727 and traverse slots while we're at it */
Christian Heimes90aa7642007-12-19 02:45:37 +0000728 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000729 base = type;
730 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000731 if (Py_SIZE(base)) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000732 int err = traverse_slots(base, self, visit, arg);
733 if (err)
734 return err;
735 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000736 base = base->tp_base;
737 assert(base);
738 }
739
740 if (type->tp_dictoffset != base->tp_dictoffset) {
741 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000742 if (dictptr && *dictptr)
743 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000744 }
745
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000746 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000747 /* For a heaptype, the instances count as references
Guido van Rossumd8faa362007-04-27 19:54:29 +0000748 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000749 can find cycles involving this link. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000750 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000751
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000752 if (basetraverse)
753 return basetraverse(self, visit, arg);
754 return 0;
755}
756
757static void
758clear_slots(PyTypeObject *type, PyObject *self)
759{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000760 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000761 PyMemberDef *mp;
762
Christian Heimes90aa7642007-12-19 02:45:37 +0000763 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000764 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000765 for (i = 0; i < n; i++, mp++) {
766 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
767 char *addr = (char *)self + mp->offset;
768 PyObject *obj = *(PyObject **)addr;
769 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000770 *(PyObject **)addr = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000771 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000772 }
773 }
774 }
775}
776
777static int
778subtype_clear(PyObject *self)
779{
780 PyTypeObject *type, *base;
781 inquiry baseclear;
782
783 /* Find the nearest base with a different tp_clear
784 and clear slots while we're at it */
Christian Heimes90aa7642007-12-19 02:45:37 +0000785 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000786 base = type;
787 while ((baseclear = base->tp_clear) == subtype_clear) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000788 if (Py_SIZE(base))
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000789 clear_slots(base, self);
790 base = base->tp_base;
791 assert(base);
792 }
793
Guido van Rossuma3862092002-06-10 15:24:42 +0000794 /* There's no need to clear the instance dict (if any);
795 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000796
797 if (baseclear)
798 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000799 return 0;
800}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000801
802static void
803subtype_dealloc(PyObject *self)
804{
Guido van Rossum14227b42001-12-06 02:35:58 +0000805 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000806 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000807
Guido van Rossum22b13872002-08-06 21:41:44 +0000808 /* Extract the type; we expect it to be a heap type */
Christian Heimes90aa7642007-12-19 02:45:37 +0000809 type = Py_TYPE(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000810 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000811
Guido van Rossum22b13872002-08-06 21:41:44 +0000812 /* Test whether the type has GC exactly once */
813
814 if (!PyType_IS_GC(type)) {
815 /* It's really rare to find a dynamic type that doesn't have
816 GC; it can only happen when deriving from 'object' and not
817 adding any slots or instance variables. This allows
818 certain simplifications: there's no need to call
819 clear_slots(), or DECREF the dict, or clear weakrefs. */
820
821 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000822 if (type->tp_del) {
823 type->tp_del(self);
824 if (self->ob_refcnt > 0)
825 return;
826 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000827
828 /* Find the nearest base with a different tp_dealloc */
829 base = type;
830 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000831 assert(Py_SIZE(base) == 0);
Guido van Rossum22b13872002-08-06 21:41:44 +0000832 base = base->tp_base;
833 assert(base);
834 }
835
836 /* Call the base tp_dealloc() */
837 assert(basedealloc);
838 basedealloc(self);
839
840 /* Can't reference self beyond this point */
841 Py_DECREF(type);
842
843 /* Done */
844 return;
845 }
846
847 /* We get here only if the type has GC */
848
849 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000850 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000851 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000852 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000853 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000854 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000855 /* DO NOT restore GC tracking at this point. weakref callbacks
856 * (if any, and whether directly here or indirectly in something we
857 * call) may trigger GC, and if self is tracked at that point, it
858 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000859 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000860
Guido van Rossum59195fd2003-06-13 20:54:40 +0000861 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000862 base = type;
863 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000864 base = base->tp_base;
865 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000866 }
867
Guido van Rossumd8faa362007-04-27 19:54:29 +0000868 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000869 the finalizer (__del__), clearing slots, or clearing the instance
870 dict. */
871
Guido van Rossum1987c662003-05-29 14:29:23 +0000872 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
873 PyObject_ClearWeakRefs(self);
874
875 /* Maybe call finalizer; exit early if resurrected */
876 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000877 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000878 type->tp_del(self);
879 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000880 goto endlabel; /* resurrected */
881 else
882 _PyObject_GC_UNTRACK(self);
Thomas Woutersb2137042007-02-01 18:02:27 +0000883 /* New weakrefs could be created during the finalizer call.
884 If this occurs, clear them out without calling their
885 finalizers since they might rely on part of the object
886 being finalized that has already been destroyed. */
887 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
888 /* Modeled after GET_WEAKREFS_LISTPTR() */
889 PyWeakReference **list = (PyWeakReference **) \
890 PyObject_GET_WEAKREFS_LISTPTR(self);
891 while (*list)
892 _PyWeakref_ClearRef(*list);
893 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000894 }
895
Guido van Rossum59195fd2003-06-13 20:54:40 +0000896 /* Clear slots up to the nearest base with a different tp_dealloc */
897 base = type;
898 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000899 if (Py_SIZE(base))
Guido van Rossum59195fd2003-06-13 20:54:40 +0000900 clear_slots(base, self);
901 base = base->tp_base;
902 assert(base);
903 }
904
Tim Peters6d6c1a32001-08-02 04:15:00 +0000905 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000906 if (type->tp_dictoffset && !base->tp_dictoffset) {
907 PyObject **dictptr = _PyObject_GetDictPtr(self);
908 if (dictptr != NULL) {
909 PyObject *dict = *dictptr;
910 if (dict != NULL) {
911 Py_DECREF(dict);
912 *dictptr = NULL;
913 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000914 }
915 }
916
Tim Peters0bd743c2003-11-13 22:50:00 +0000917 /* Call the base tp_dealloc(); first retrack self if
918 * basedealloc knows about gc.
919 */
920 if (PyType_IS_GC(base))
921 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000922 assert(basedealloc);
923 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000924
925 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000926 Py_DECREF(type);
927
Guido van Rossum0906e072002-08-07 20:42:09 +0000928 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000929 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000930 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000931 --_PyTrash_delete_nesting;
932
933 /* Explanation of the weirdness around the trashcan macros:
934
935 Q. What do the trashcan macros do?
936
937 A. Read the comment titled "Trashcan mechanism" in object.h.
938 For one, this explains why there must be a call to GC-untrack
Guido van Rossumd8faa362007-04-27 19:54:29 +0000939 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000940 trashcan code, the answers to the following questions don't make
941 sense.
942
943 Q. Why do we GC-untrack before the trashcan and then immediately
944 GC-track again afterward?
945
946 A. In the case that the base class is GC-aware, the base class
Guido van Rossumd8faa362007-04-27 19:54:29 +0000947 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000948 UNTRACK macro, this will crash when the object is already
949 untracked. Because we don't know what the base class does, the
950 only safe thing is to make sure the object is tracked when we
951 call the base class dealloc. But... The trashcan begin macro
952 requires that the object is *untracked* before it is called. So
953 the dance becomes:
954
Guido van Rossumd8faa362007-04-27 19:54:29 +0000955 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000956 trashcan begin
957 GC track
958
Guido van Rossumd8faa362007-04-27 19:54:29 +0000959 Q. Why did the last question say "immediately GC-track again"?
960 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000961
Guido van Rossumd8faa362007-04-27 19:54:29 +0000962 A. Because the code *used* to re-track immediately. Bad Idea.
963 self has a refcount of 0, and if gc ever gets its hands on it
964 (which can happen if any weakref callback gets invoked), it
965 looks like trash to gc too, and gc also tries to delete self
966 then. But we're already deleting self. Double dealloction is
967 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +0000968
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000969 Q. Why the bizarre (net-zero) manipulation of
970 _PyTrash_delete_nesting around the trashcan macros?
971
972 A. Some base classes (e.g. list) also use the trashcan mechanism.
973 The following scenario used to be possible:
974
975 - suppose the trashcan level is one below the trashcan limit
976
977 - subtype_dealloc() is called
978
979 - the trashcan limit is not yet reached, so the trashcan level
Guido van Rossumd8faa362007-04-27 19:54:29 +0000980 is incremented and the code between trashcan begin and end is
981 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000982
983 - this destroys much of the object's contents, including its
Guido van Rossumd8faa362007-04-27 19:54:29 +0000984 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000985
986 - basedealloc() is called; this is really list_dealloc(), or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000987 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000988
989 - the trashcan limit is now reached, so the object is put on the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000990 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000991
992 - basedealloc() returns
993
994 - subtype_dealloc() decrefs the object's type
995
996 - subtype_dealloc() returns
997
998 - later, the trashcan code starts deleting the objects from its
Guido van Rossumd8faa362007-04-27 19:54:29 +0000999 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001000
1001 - subtype_dealloc() is called *AGAIN* for the same object
1002
1003 - at the very least (if the destroyed slots and __dict__ don't
Guido van Rossumd8faa362007-04-27 19:54:29 +00001004 cause problems) the object's type gets decref'ed a second
1005 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001006
1007 The remedy is to make sure that if the code between trashcan
1008 begin and end in subtype_dealloc() is called, the code between
1009 trashcan begin and end in basedealloc() will also be called.
1010 This is done by decrementing the level after passing into the
1011 trashcan block, and incrementing it just before leaving the
1012 block.
1013
1014 But now it's possible that a chain of objects consisting solely
1015 of objects whose deallocator is subtype_dealloc() will defeat
1016 the trashcan mechanism completely: the decremented level means
Guido van Rossumd8faa362007-04-27 19:54:29 +00001017 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001018 *increment* the level *before* entering the trashcan block, and
1019 matchingly decrement it after leaving. This means the trashcan
1020 code will trigger a little early, but that's no big deal.
1021
1022 Q. Are there any live examples of code in need of all this
1023 complexity?
1024
1025 A. Yes. See SF bug 668433 for code that crashed (when Python was
1026 compiled in debug mode) before the trashcan level manipulations
1027 were added. For more discussion, see SF patches 581742, 575073
1028 and bug 574207.
1029 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001030}
1031
Jeremy Hylton938ace62002-07-17 16:30:39 +00001032static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001033
Tim Peters6d6c1a32001-08-02 04:15:00 +00001034/* type test with subclassing support */
1035
1036int
1037PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1038{
1039 PyObject *mro;
1040
1041 mro = a->tp_mro;
1042 if (mro != NULL) {
1043 /* Deal with multiple inheritance without recursion
1044 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001045 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001046 assert(PyTuple_Check(mro));
1047 n = PyTuple_GET_SIZE(mro);
1048 for (i = 0; i < n; i++) {
1049 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1050 return 1;
1051 }
1052 return 0;
1053 }
1054 else {
1055 /* a is not completely initilized yet; follow tp_base */
1056 do {
1057 if (a == b)
1058 return 1;
1059 a = a->tp_base;
1060 } while (a != NULL);
1061 return b == &PyBaseObject_Type;
1062 }
1063}
1064
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001065/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001066 without looking in the instance dictionary
1067 (so we can't use PyObject_GetAttr) but still binding
Guido van Rossumd8faa362007-04-27 19:54:29 +00001068 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001069 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001070 static variable used to cache the interned Python string.
1071
1072 Two variants:
1073
1074 - lookup_maybe() returns NULL without raising an exception
1075 when the _PyType_Lookup() call fails;
1076
1077 - lookup_method() always raises an exception upon errors.
1078*/
Guido van Rossum60718732001-08-28 17:47:51 +00001079
1080static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001081lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001082{
1083 PyObject *res;
1084
1085 if (*attrobj == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001086 *attrobj = PyUnicode_InternFromString(attrstr);
Guido van Rossum60718732001-08-28 17:47:51 +00001087 if (*attrobj == NULL)
1088 return NULL;
1089 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001090 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001091 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +00001092 descrgetfunc f;
Christian Heimes90aa7642007-12-19 02:45:37 +00001093 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
Guido van Rossum60718732001-08-28 17:47:51 +00001094 Py_INCREF(res);
1095 else
Christian Heimes90aa7642007-12-19 02:45:37 +00001096 res = f(res, self, (PyObject *)(Py_TYPE(self)));
Guido van Rossum60718732001-08-28 17:47:51 +00001097 }
1098 return res;
1099}
1100
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001101static PyObject *
1102lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1103{
1104 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1105 if (res == NULL && !PyErr_Occurred())
1106 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1107 return res;
1108}
1109
Guido van Rossum2730b132001-08-28 18:22:14 +00001110/* A variation of PyObject_CallMethod that uses lookup_method()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001111 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001112 as lookup_method to cache the interned name string object. */
1113
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001114static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001115call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1116{
1117 va_list va;
1118 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001119 va_start(va, format);
1120
Guido van Rossumda21c012001-10-03 00:50:18 +00001121 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001122 if (func == NULL) {
1123 va_end(va);
1124 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +00001125 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001126 return NULL;
1127 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001128
1129 if (format && *format)
1130 args = Py_VaBuildValue(format, va);
1131 else
1132 args = PyTuple_New(0);
1133
1134 va_end(va);
1135
1136 if (args == NULL)
1137 return NULL;
1138
1139 assert(PyTuple_Check(args));
1140 retval = PyObject_Call(func, args, NULL);
1141
1142 Py_DECREF(args);
1143 Py_DECREF(func);
1144
1145 return retval;
1146}
1147
1148/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1149
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001150static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001151call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1152{
1153 va_list va;
1154 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001155 va_start(va, format);
1156
Guido van Rossumda21c012001-10-03 00:50:18 +00001157 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +00001158 if (func == NULL) {
1159 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001160 if (!PyErr_Occurred()) {
1161 Py_INCREF(Py_NotImplemented);
1162 return Py_NotImplemented;
1163 }
Guido van Rossum717ce002001-09-14 16:58:08 +00001164 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001165 }
1166
1167 if (format && *format)
1168 args = Py_VaBuildValue(format, va);
1169 else
1170 args = PyTuple_New(0);
1171
1172 va_end(va);
1173
Guido van Rossum717ce002001-09-14 16:58:08 +00001174 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00001175 return NULL;
1176
Guido van Rossum717ce002001-09-14 16:58:08 +00001177 assert(PyTuple_Check(args));
1178 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001179
1180 Py_DECREF(args);
1181 Py_DECREF(func);
1182
1183 return retval;
1184}
1185
Tim Petersea7f75d2002-12-07 21:39:16 +00001186/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001187 Method resolution order algorithm C3 described in
1188 "A Monotonic Superclass Linearization for Dylan",
1189 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001190 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001191 (OOPSLA 1996)
1192
Guido van Rossum98f33732002-11-25 21:36:54 +00001193 Some notes about the rules implied by C3:
1194
Tim Petersea7f75d2002-12-07 21:39:16 +00001195 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001196 It isn't legal to repeat a class in a list of base classes.
1197
1198 The next three properties are the 3 constraints in "C3".
1199
Tim Petersea7f75d2002-12-07 21:39:16 +00001200 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001201 If A precedes B in C's MRO, then A will precede B in the MRO of all
1202 subclasses of C.
1203
1204 Monotonicity.
1205 The MRO of a class must be an extension without reordering of the
1206 MRO of each of its superclasses.
1207
1208 Extended Precedence Graph (EPG).
1209 Linearization is consistent if there is a path in the EPG from
1210 each class to all its successors in the linearization. See
1211 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001212 */
1213
Tim Petersea7f75d2002-12-07 21:39:16 +00001214static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001215tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001216 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001217 size = PyList_GET_SIZE(list);
1218
1219 for (j = whence+1; j < size; j++) {
1220 if (PyList_GET_ITEM(list, j) == o)
1221 return 1;
1222 }
1223 return 0;
1224}
1225
Guido van Rossum98f33732002-11-25 21:36:54 +00001226static PyObject *
1227class_name(PyObject *cls)
1228{
1229 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1230 if (name == NULL) {
1231 PyErr_Clear();
1232 Py_XDECREF(name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001233 name = PyObject_Repr(cls);
Guido van Rossum98f33732002-11-25 21:36:54 +00001234 }
1235 if (name == NULL)
1236 return NULL;
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001237 if (!PyUnicode_Check(name)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001238 Py_DECREF(name);
1239 return NULL;
1240 }
1241 return name;
1242}
1243
1244static int
1245check_duplicates(PyObject *list)
1246{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001247 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001248 /* Let's use a quadratic time algorithm,
1249 assuming that the bases lists is short.
1250 */
1251 n = PyList_GET_SIZE(list);
1252 for (i = 0; i < n; i++) {
1253 PyObject *o = PyList_GET_ITEM(list, i);
1254 for (j = i + 1; j < n; j++) {
1255 if (PyList_GET_ITEM(list, j) == o) {
1256 o = class_name(o);
1257 PyErr_Format(PyExc_TypeError,
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00001258 "duplicate base class %.400s",
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001259 o ? PyUnicode_AsString(o) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001260 Py_XDECREF(o);
1261 return -1;
1262 }
1263 }
1264 }
1265 return 0;
1266}
1267
1268/* Raise a TypeError for an MRO order disagreement.
1269
1270 It's hard to produce a good error message. In the absence of better
1271 insight into error reporting, report the classes that were candidates
Guido van Rossumd8faa362007-04-27 19:54:29 +00001272 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001273 order in which they should be put in the MRO, but it's hard to
1274 diagnose what constraint can't be satisfied.
1275*/
1276
1277static void
1278set_mro_error(PyObject *to_merge, int *remain)
1279{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001280 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001281 char buf[1000];
1282 PyObject *k, *v;
1283 PyObject *set = PyDict_New();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001284 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001285
1286 to_merge_size = PyList_GET_SIZE(to_merge);
1287 for (i = 0; i < to_merge_size; i++) {
1288 PyObject *L = PyList_GET_ITEM(to_merge, i);
1289 if (remain[i] < PyList_GET_SIZE(L)) {
1290 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001291 if (PyDict_SetItem(set, c, Py_None) < 0) {
1292 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001293 return;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001294 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001295 }
1296 }
1297 n = PyDict_Size(set);
1298
Raymond Hettingerf394df42003-04-06 19:13:41 +00001299 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1300consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001301 i = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001302 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001303 PyObject *name = class_name(k);
1304 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001305 name ? PyUnicode_AsString(name) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001306 Py_XDECREF(name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001307 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001308 buf[off++] = ',';
1309 buf[off] = '\0';
1310 }
1311 }
1312 PyErr_SetString(PyExc_TypeError, buf);
1313 Py_DECREF(set);
1314}
1315
Tim Petersea7f75d2002-12-07 21:39:16 +00001316static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001317pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001318 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001319 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001320 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001321
Guido van Rossum1f121312002-11-14 19:49:16 +00001322 to_merge_size = PyList_GET_SIZE(to_merge);
1323
Guido van Rossum98f33732002-11-25 21:36:54 +00001324 /* remain stores an index into each sublist of to_merge.
1325 remain[i] is the index of the next base in to_merge[i]
1326 that is not included in acc.
1327 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001328 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001329 if (remain == NULL)
1330 return -1;
1331 for (i = 0; i < to_merge_size; i++)
1332 remain[i] = 0;
1333
1334 again:
1335 empty_cnt = 0;
1336 for (i = 0; i < to_merge_size; i++) {
1337 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001338
Guido van Rossum1f121312002-11-14 19:49:16 +00001339 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1340
1341 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1342 empty_cnt++;
1343 continue;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001344 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001345
Guido van Rossum98f33732002-11-25 21:36:54 +00001346 /* Choose next candidate for MRO.
1347
1348 The input sequences alone can determine the choice.
1349 If not, choose the class which appears in the MRO
1350 of the earliest direct superclass of the new class.
1351 */
1352
Guido van Rossum1f121312002-11-14 19:49:16 +00001353 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1354 for (j = 0; j < to_merge_size; j++) {
1355 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001356 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001357 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001358 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001359 }
1360 ok = PyList_Append(acc, candidate);
1361 if (ok < 0) {
1362 PyMem_Free(remain);
1363 return -1;
1364 }
1365 for (j = 0; j < to_merge_size; j++) {
1366 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001367 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1368 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001369 remain[j]++;
1370 }
1371 }
1372 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001373 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001374 }
1375
Guido van Rossum98f33732002-11-25 21:36:54 +00001376 if (empty_cnt == to_merge_size) {
1377 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001378 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001379 }
1380 set_mro_error(to_merge, remain);
1381 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001382 return -1;
1383}
1384
Tim Peters6d6c1a32001-08-02 04:15:00 +00001385static PyObject *
1386mro_implementation(PyTypeObject *type)
1387{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001388 Py_ssize_t i, n;
1389 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001390 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001391 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001392
Christian Heimes412dc9c2008-01-27 18:55:54 +00001393 if (type->tp_dict == NULL) {
1394 if (PyType_Ready(type) < 0)
Guido van Rossum63517572002-06-18 16:44:57 +00001395 return NULL;
1396 }
1397
Guido van Rossum98f33732002-11-25 21:36:54 +00001398 /* Find a superclass linearization that honors the constraints
1399 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001400 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001401
1402 to_merge is a list of lists, where each list is a superclass
1403 linearization implied by a base class. The last element of
1404 to_merge is the declared list of bases.
1405 */
1406
Tim Peters6d6c1a32001-08-02 04:15:00 +00001407 bases = type->tp_bases;
1408 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001409
1410 to_merge = PyList_New(n+1);
1411 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001412 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001413
Tim Peters6d6c1a32001-08-02 04:15:00 +00001414 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001415 PyObject *base = PyTuple_GET_ITEM(bases, i);
1416 PyObject *parentMRO;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001417 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001418 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001419 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001420 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001421 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001422
1423 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001424 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001425
1426 bases_aslist = PySequence_List(bases);
1427 if (bases_aslist == NULL) {
1428 Py_DECREF(to_merge);
1429 return NULL;
1430 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001431 /* This is just a basic sanity check. */
1432 if (check_duplicates(bases_aslist) < 0) {
1433 Py_DECREF(to_merge);
1434 Py_DECREF(bases_aslist);
1435 return NULL;
1436 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001437 PyList_SET_ITEM(to_merge, n, bases_aslist);
1438
1439 result = Py_BuildValue("[O]", (PyObject *)type);
1440 if (result == NULL) {
1441 Py_DECREF(to_merge);
1442 return NULL;
1443 }
1444
1445 ok = pmerge(result, to_merge);
1446 Py_DECREF(to_merge);
1447 if (ok < 0) {
1448 Py_DECREF(result);
1449 return NULL;
1450 }
1451
Tim Peters6d6c1a32001-08-02 04:15:00 +00001452 return result;
1453}
1454
1455static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001456mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001457{
1458 PyTypeObject *type = (PyTypeObject *)self;
1459
Tim Peters6d6c1a32001-08-02 04:15:00 +00001460 return mro_implementation(type);
1461}
1462
1463static int
1464mro_internal(PyTypeObject *type)
1465{
1466 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001467 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001468
Christian Heimes90aa7642007-12-19 02:45:37 +00001469 if (Py_TYPE(type) == &PyType_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470 result = mro_implementation(type);
1471 }
1472 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001473 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001474 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001475 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001476 if (mro == NULL)
1477 return -1;
1478 result = PyObject_CallObject(mro, NULL);
1479 Py_DECREF(mro);
1480 }
1481 if (result == NULL)
1482 return -1;
1483 tuple = PySequence_Tuple(result);
1484 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001485 if (tuple == NULL)
1486 return -1;
1487 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001488 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001489 PyObject *cls;
1490 PyTypeObject *solid;
1491
1492 solid = solid_base(type);
1493
1494 len = PyTuple_GET_SIZE(tuple);
1495
1496 for (i = 0; i < len; i++) {
1497 PyTypeObject *t;
1498 cls = PyTuple_GET_ITEM(tuple, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001499 if (!PyType_Check(cls)) {
Armin Rigo037d1e02005-12-29 17:07:39 +00001500 PyErr_Format(PyExc_TypeError,
1501 "mro() returned a non-class ('%.500s')",
Christian Heimes90aa7642007-12-19 02:45:37 +00001502 Py_TYPE(cls)->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001503 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001504 return -1;
1505 }
1506 t = (PyTypeObject*)cls;
1507 if (!PyType_IsSubtype(solid, solid_base(t))) {
1508 PyErr_Format(PyExc_TypeError,
1509 "mro() returned base with unsuitable layout ('%.500s')",
1510 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001511 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001512 return -1;
1513 }
1514 }
1515 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001516 type->tp_mro = tuple;
Christian Heimesa62da1d2008-01-12 19:39:10 +00001517
1518 type_mro_modified(type, type->tp_mro);
1519 /* corner case: the old-style super class might have been hidden
1520 from the custom MRO */
1521 type_mro_modified(type, type->tp_bases);
1522
1523 type_modified(type);
1524
Tim Peters6d6c1a32001-08-02 04:15:00 +00001525 return 0;
1526}
1527
1528
1529/* Calculate the best base amongst multiple base classes.
1530 This is the first one that's on the path to the "solid base". */
1531
1532static PyTypeObject *
1533best_base(PyObject *bases)
1534{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001535 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001536 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001537 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001538
1539 assert(PyTuple_Check(bases));
1540 n = PyTuple_GET_SIZE(bases);
1541 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001542 base = NULL;
1543 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001544 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001545 base_proto = PyTuple_GET_ITEM(bases, i);
Tim Petersa91e9642001-11-14 23:32:33 +00001546 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001547 PyErr_SetString(
1548 PyExc_TypeError,
1549 "bases must be types");
1550 return NULL;
1551 }
Tim Petersa91e9642001-11-14 23:32:33 +00001552 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001553 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001554 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001555 return NULL;
1556 }
1557 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001558 if (winner == NULL) {
1559 winner = candidate;
1560 base = base_i;
1561 }
1562 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001563 ;
1564 else if (PyType_IsSubtype(candidate, winner)) {
1565 winner = candidate;
1566 base = base_i;
1567 }
1568 else {
1569 PyErr_SetString(
1570 PyExc_TypeError,
1571 "multiple bases have "
1572 "instance lay-out conflict");
1573 return NULL;
1574 }
1575 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001576 if (base == NULL)
1577 PyErr_SetString(PyExc_TypeError,
1578 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001579 return base;
1580}
1581
1582static int
1583extra_ivars(PyTypeObject *type, PyTypeObject *base)
1584{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001585 size_t t_size = type->tp_basicsize;
1586 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001587
Guido van Rossum9676b222001-08-17 20:32:36 +00001588 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589 if (type->tp_itemsize || base->tp_itemsize) {
1590 /* If itemsize is involved, stricter rules */
1591 return t_size != b_size ||
1592 type->tp_itemsize != base->tp_itemsize;
1593 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001594 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001595 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1596 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001597 t_size -= sizeof(PyObject *);
1598 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001599 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1600 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001601 t_size -= sizeof(PyObject *);
1602
1603 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001604}
1605
1606static PyTypeObject *
1607solid_base(PyTypeObject *type)
1608{
1609 PyTypeObject *base;
1610
1611 if (type->tp_base)
1612 base = solid_base(type->tp_base);
1613 else
1614 base = &PyBaseObject_Type;
1615 if (extra_ivars(type, base))
1616 return type;
1617 else
1618 return base;
1619}
1620
Jeremy Hylton938ace62002-07-17 16:30:39 +00001621static void object_dealloc(PyObject *);
1622static int object_init(PyObject *, PyObject *, PyObject *);
1623static int update_slot(PyTypeObject *, PyObject *);
1624static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001625
Guido van Rossum360e4b82007-05-14 22:51:27 +00001626/*
1627 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1628 * inherited from various builtin types. The builtin base usually provides
1629 * its own __dict__ descriptor, so we use that when we can.
1630 */
1631static PyTypeObject *
1632get_builtin_base_with_dict(PyTypeObject *type)
1633{
1634 while (type->tp_base != NULL) {
1635 if (type->tp_dictoffset != 0 &&
1636 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1637 return type;
1638 type = type->tp_base;
1639 }
1640 return NULL;
1641}
1642
1643static PyObject *
1644get_dict_descriptor(PyTypeObject *type)
1645{
1646 static PyObject *dict_str;
1647 PyObject *descr;
1648
1649 if (dict_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001650 dict_str = PyUnicode_InternFromString("__dict__");
Guido van Rossum360e4b82007-05-14 22:51:27 +00001651 if (dict_str == NULL)
1652 return NULL;
1653 }
1654 descr = _PyType_Lookup(type, dict_str);
1655 if (descr == NULL || !PyDescr_IsData(descr))
1656 return NULL;
1657
1658 return descr;
1659}
1660
1661static void
1662raise_dict_descr_error(PyObject *obj)
1663{
1664 PyErr_Format(PyExc_TypeError,
1665 "this __dict__ descriptor does not support "
Christian Heimes90aa7642007-12-19 02:45:37 +00001666 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001667}
1668
Tim Peters6d6c1a32001-08-02 04:15:00 +00001669static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001670subtype_dict(PyObject *obj, void *context)
1671{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001672 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001673 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001674 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001675
Christian Heimes90aa7642007-12-19 02:45:37 +00001676 base = get_builtin_base_with_dict(Py_TYPE(obj));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001677 if (base != NULL) {
1678 descrgetfunc func;
1679 PyObject *descr = get_dict_descriptor(base);
1680 if (descr == NULL) {
1681 raise_dict_descr_error(obj);
1682 return NULL;
1683 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001684 func = Py_TYPE(descr)->tp_descr_get;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001685 if (func == NULL) {
1686 raise_dict_descr_error(obj);
1687 return NULL;
1688 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001689 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001690 }
1691
1692 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001693 if (dictptr == NULL) {
1694 PyErr_SetString(PyExc_AttributeError,
1695 "This object has no __dict__");
1696 return NULL;
1697 }
1698 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001699 if (dict == NULL)
1700 *dictptr = dict = PyDict_New();
1701 Py_XINCREF(dict);
1702 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001703}
1704
Guido van Rossum6661be32001-10-26 04:26:12 +00001705static int
1706subtype_setdict(PyObject *obj, PyObject *value, void *context)
1707{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001708 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001709 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001710 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001711
Christian Heimes90aa7642007-12-19 02:45:37 +00001712 base = get_builtin_base_with_dict(Py_TYPE(obj));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001713 if (base != NULL) {
1714 descrsetfunc func;
1715 PyObject *descr = get_dict_descriptor(base);
1716 if (descr == NULL) {
1717 raise_dict_descr_error(obj);
1718 return -1;
1719 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001720 func = Py_TYPE(descr)->tp_descr_set;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001721 if (func == NULL) {
1722 raise_dict_descr_error(obj);
1723 return -1;
1724 }
1725 return func(descr, obj, value);
1726 }
1727
1728 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001729 if (dictptr == NULL) {
1730 PyErr_SetString(PyExc_AttributeError,
1731 "This object has no __dict__");
1732 return -1;
1733 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001734 if (value != NULL && !PyDict_Check(value)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001735 PyErr_Format(PyExc_TypeError,
1736 "__dict__ must be set to a dictionary, "
Christian Heimes90aa7642007-12-19 02:45:37 +00001737 "not a '%.200s'", Py_TYPE(value)->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001738 return -1;
1739 }
1740 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001741 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001742 *dictptr = value;
1743 Py_XDECREF(dict);
1744 return 0;
1745}
1746
Guido van Rossumad47da02002-08-12 19:05:44 +00001747static PyObject *
1748subtype_getweakref(PyObject *obj, void *context)
1749{
1750 PyObject **weaklistptr;
1751 PyObject *result;
1752
Christian Heimes90aa7642007-12-19 02:45:37 +00001753 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001754 PyErr_SetString(PyExc_AttributeError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001755 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001756 return NULL;
1757 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001758 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1759 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1760 (size_t)(Py_TYPE(obj)->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001761 weaklistptr = (PyObject **)
Christian Heimes90aa7642007-12-19 02:45:37 +00001762 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001763 if (*weaklistptr == NULL)
1764 result = Py_None;
1765 else
1766 result = *weaklistptr;
1767 Py_INCREF(result);
1768 return result;
1769}
1770
Guido van Rossum373c7412003-01-07 13:41:37 +00001771/* Three variants on the subtype_getsets list. */
1772
1773static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001774 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001775 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001776 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001777 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001778 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001779};
1780
Guido van Rossum373c7412003-01-07 13:41:37 +00001781static PyGetSetDef subtype_getsets_dict_only[] = {
1782 {"__dict__", subtype_dict, subtype_setdict,
1783 PyDoc_STR("dictionary for instance variables (if defined)")},
1784 {0}
1785};
1786
1787static PyGetSetDef subtype_getsets_weakref_only[] = {
1788 {"__weakref__", subtype_getweakref, NULL,
1789 PyDoc_STR("list of weak references to the object (if defined)")},
1790 {0}
1791};
1792
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001793static int
1794valid_identifier(PyObject *s)
1795{
Martin v. Löwis5b222132007-06-10 09:51:05 +00001796 if (!PyUnicode_Check(s)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001797 PyErr_Format(PyExc_TypeError,
1798 "__slots__ items must be strings, not '%.200s'",
Christian Heimes90aa7642007-12-19 02:45:37 +00001799 Py_TYPE(s)->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001800 return 0;
1801 }
Georg Brandlf4780d02007-08-30 18:29:48 +00001802 if (!PyUnicode_IsIdentifier(s)) {
1803 PyErr_SetString(PyExc_TypeError,
1804 "__slots__ must be identifiers");
1805 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001806 }
1807 return 1;
1808}
1809
Guido van Rossumd8faa362007-04-27 19:54:29 +00001810/* Forward */
1811static int
1812object_init(PyObject *self, PyObject *args, PyObject *kwds);
1813
1814static int
1815type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1816{
1817 int res;
1818
1819 assert(args != NULL && PyTuple_Check(args));
1820 assert(kwds == NULL || PyDict_Check(kwds));
1821
1822 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1823 PyErr_SetString(PyExc_TypeError,
1824 "type.__init__() takes no keyword arguments");
1825 return -1;
1826 }
1827
1828 if (args != NULL && PyTuple_Check(args) &&
1829 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1830 PyErr_SetString(PyExc_TypeError,
1831 "type.__init__() takes 1 or 3 arguments");
1832 return -1;
1833 }
1834
1835 /* Call object.__init__(self) now. */
1836 /* XXX Could call super(type, cls).__init__() but what's the point? */
1837 args = PyTuple_GetSlice(args, 0, 0);
1838 res = object_init(cls, args, NULL);
1839 Py_DECREF(args);
1840 return res;
1841}
1842
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001843static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1845{
1846 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001847 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001848 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001849 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001850 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001851 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001852 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001853 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001854
Tim Peters3abca122001-10-27 19:37:48 +00001855 assert(args != NULL && PyTuple_Check(args));
1856 assert(kwds == NULL || PyDict_Check(kwds));
1857
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001858 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001859 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001860 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1861 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001862
1863 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1864 PyObject *x = PyTuple_GET_ITEM(args, 0);
Christian Heimes90aa7642007-12-19 02:45:37 +00001865 Py_INCREF(Py_TYPE(x));
1866 return (PyObject *) Py_TYPE(x);
Tim Peters3abca122001-10-27 19:37:48 +00001867 }
1868
1869 /* SF bug 475327 -- if that didn't trigger, we need 3
1870 arguments. but PyArg_ParseTupleAndKeywords below may give
1871 a msg saying type() needs exactly 3. */
1872 if (nargs + nkwds != 3) {
1873 PyErr_SetString(PyExc_TypeError,
1874 "type() takes 1 or 3 arguments");
1875 return NULL;
1876 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001877 }
1878
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001879 /* Check arguments: (name, bases, dict) */
Guido van Rossum98297ee2007-11-06 21:34:58 +00001880 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001881 &name,
1882 &PyTuple_Type, &bases,
1883 &PyDict_Type, &dict))
1884 return NULL;
1885
1886 /* Determine the proper metatype to deal with this,
1887 and check for metatype conflicts while we're at it.
1888 Note that if some other metatype wins to contract,
1889 it's possible that its instances are not types. */
1890 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001891 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001892 for (i = 0; i < nbases; i++) {
1893 tmp = PyTuple_GET_ITEM(bases, i);
Christian Heimes90aa7642007-12-19 02:45:37 +00001894 tmptype = Py_TYPE(tmp);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001895 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001896 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001897 if (PyType_IsSubtype(tmptype, winner)) {
1898 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001899 continue;
1900 }
1901 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001902 "metaclass conflict: "
1903 "the metaclass of a derived class "
1904 "must be a (non-strict) subclass "
1905 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001906 return NULL;
1907 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001908 if (winner != metatype) {
1909 if (winner->tp_new != type_new) /* Pass it to the winner */
1910 return winner->tp_new(winner, args, kwds);
1911 metatype = winner;
1912 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001913
1914 /* Adjust for empty tuple bases */
1915 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001916 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001917 if (bases == NULL)
1918 return NULL;
1919 nbases = 1;
1920 }
1921 else
1922 Py_INCREF(bases);
1923
1924 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1925
1926 /* Calculate best base, and check that all bases are type objects */
1927 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001928 if (base == NULL) {
1929 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001930 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001931 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001932 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1933 PyErr_Format(PyExc_TypeError,
1934 "type '%.100s' is not an acceptable base type",
1935 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001936 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001937 return NULL;
1938 }
1939
Tim Peters6d6c1a32001-08-02 04:15:00 +00001940 /* Check for a __slots__ sequence variable in dict, and count it */
1941 slots = PyDict_GetItemString(dict, "__slots__");
1942 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001943 add_dict = 0;
1944 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001945 may_add_dict = base->tp_dictoffset == 0;
1946 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1947 if (slots == NULL) {
1948 if (may_add_dict) {
1949 add_dict++;
1950 }
1951 if (may_add_weak) {
1952 add_weak++;
1953 }
1954 }
1955 else {
1956 /* Have slots */
1957
Tim Peters6d6c1a32001-08-02 04:15:00 +00001958 /* Make it into a tuple */
Neal Norwitz80e7f272007-08-26 06:45:23 +00001959 if (PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001960 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001961 else
1962 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001963 if (slots == NULL) {
1964 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001965 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001966 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001967 assert(PyTuple_Check(slots));
1968
1969 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001970 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001971 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001972 PyErr_Format(PyExc_TypeError,
1973 "nonempty __slots__ "
1974 "not supported for subtype of '%s'",
1975 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001976 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001977 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001978 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001979 return NULL;
1980 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001981
1982 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001983 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001984 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001985 if (!valid_identifier(tmp))
1986 goto bad_slots;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001987 assert(PyUnicode_Check(tmp));
1988 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001989 if (!may_add_dict || add_dict) {
1990 PyErr_SetString(PyExc_TypeError,
1991 "__dict__ slot disallowed: "
1992 "we already got one");
1993 goto bad_slots;
1994 }
1995 add_dict++;
1996 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00001997 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001998 if (!may_add_weak || add_weak) {
1999 PyErr_SetString(PyExc_TypeError,
2000 "__weakref__ slot disallowed: "
2001 "either we already got one, "
2002 "or __itemsize__ != 0");
2003 goto bad_slots;
2004 }
2005 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002006 }
2007 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002008
Guido van Rossumd8faa362007-04-27 19:54:29 +00002009 /* Copy slots into a list, mangle names and sort them.
2010 Sorted names are needed for __class__ assignment.
2011 Convert them back to tuple at the end.
2012 */
2013 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002014 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00002015 goto bad_slots;
2016 for (i = j = 0; i < nslots; i++) {
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002017 tmp = PyTuple_GET_ITEM(slots, i);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002018 if ((add_dict &&
2019 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
2020 (add_weak &&
2021 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
Guido van Rossumad47da02002-08-12 19:05:44 +00002022 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002023 tmp =_Py_Mangle(name, tmp);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002024 if (!tmp)
2025 goto bad_slots;
2026 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00002027 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002028 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002029 assert(j == nslots - add_dict - add_weak);
2030 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002031 Py_DECREF(slots);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002032 if (PyList_Sort(newslots) == -1) {
2033 Py_DECREF(bases);
2034 Py_DECREF(newslots);
2035 return NULL;
2036 }
2037 slots = PyList_AsTuple(newslots);
2038 Py_DECREF(newslots);
2039 if (slots == NULL) {
2040 Py_DECREF(bases);
2041 return NULL;
2042 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002043
Guido van Rossumad47da02002-08-12 19:05:44 +00002044 /* Secondary bases may provide weakrefs or dict */
2045 if (nbases > 1 &&
2046 ((may_add_dict && !add_dict) ||
2047 (may_add_weak && !add_weak))) {
2048 for (i = 0; i < nbases; i++) {
2049 tmp = PyTuple_GET_ITEM(bases, i);
2050 if (tmp == (PyObject *)base)
2051 continue; /* Skip primary base */
Guido van Rossumad47da02002-08-12 19:05:44 +00002052 assert(PyType_Check(tmp));
2053 tmptype = (PyTypeObject *)tmp;
2054 if (may_add_dict && !add_dict &&
2055 tmptype->tp_dictoffset != 0)
2056 add_dict++;
2057 if (may_add_weak && !add_weak &&
2058 tmptype->tp_weaklistoffset != 0)
2059 add_weak++;
2060 if (may_add_dict && !add_dict)
2061 continue;
2062 if (may_add_weak && !add_weak)
2063 continue;
2064 /* Nothing more to check */
2065 break;
2066 }
2067 }
Guido van Rossum9676b222001-08-17 20:32:36 +00002068 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002069
2070 /* XXX From here until type is safely allocated,
2071 "return NULL" may leak slots! */
2072
2073 /* Allocate the type object */
2074 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00002075 if (type == NULL) {
2076 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002077 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002078 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00002079 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002080
2081 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002082 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002083 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002084 et->ht_name = name;
2085 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002086
Guido van Rossumdc91b992001-08-08 22:26:22 +00002087 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002088 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2089 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002090 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2091 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002092
Guido van Rossumdc91b992001-08-08 22:26:22 +00002093 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002094 type->tp_as_number = &et->as_number;
2095 type->tp_as_sequence = &et->as_sequence;
2096 type->tp_as_mapping = &et->as_mapping;
2097 type->tp_as_buffer = &et->as_buffer;
Neal Norwitz80e7f272007-08-26 06:45:23 +00002098 type->tp_name = PyUnicode_AsString(name);
2099 if (!type->tp_name) {
2100 Py_DECREF(type);
2101 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002102 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002103
2104 /* Set tp_base and tp_bases */
2105 type->tp_bases = bases;
2106 Py_INCREF(base);
2107 type->tp_base = base;
2108
Guido van Rossum687ae002001-10-15 22:03:32 +00002109 /* Initialize tp_dict from passed-in dict */
2110 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002111 if (dict == NULL) {
2112 Py_DECREF(type);
2113 return NULL;
2114 }
2115
Guido van Rossumc3542212001-08-16 09:18:56 +00002116 /* Set __module__ in the dict */
2117 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2118 tmp = PyEval_GetGlobals();
2119 if (tmp != NULL) {
2120 tmp = PyDict_GetItemString(tmp, "__name__");
2121 if (tmp != NULL) {
2122 if (PyDict_SetItemString(dict, "__module__",
2123 tmp) < 0)
2124 return NULL;
2125 }
2126 }
2127 }
2128
Tim Peters2f93e282001-10-04 05:27:00 +00002129 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00002130 and is a string. The __doc__ accessor will first look for tp_doc;
2131 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00002132 */
2133 {
2134 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
Neal Norwitz6ea45d32007-08-26 04:19:43 +00002135 if (doc != NULL && PyUnicode_Check(doc)) {
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002136 Py_ssize_t len;
2137 char *doc_str;
Neal Norwitz6ea45d32007-08-26 04:19:43 +00002138 char *tp_doc;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002139
2140 doc_str = PyUnicode_AsStringAndSize(doc, &len);
2141 if (doc_str == NULL) {
Neal Norwitz6ea45d32007-08-26 04:19:43 +00002142 Py_DECREF(type);
2143 return NULL;
Tim Peters2f93e282001-10-04 05:27:00 +00002144 }
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002145 if ((Py_ssize_t)strlen(doc_str) != len) {
2146 PyErr_SetString(PyExc_TypeError,
2147 "__doc__ contains null-bytes");
2148 Py_DECREF(type);
2149 return NULL;
2150 }
2151 tp_doc = (char *)PyObject_MALLOC(len + 1);
Neal Norwitz6ea45d32007-08-26 04:19:43 +00002152 if (tp_doc == NULL) {
2153 Py_DECREF(type);
2154 return NULL;
Neal Norwitza369c5a2007-08-25 07:41:59 +00002155 }
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002156 memcpy(tp_doc, doc_str, len + 1);
Neal Norwitz6ea45d32007-08-26 04:19:43 +00002157 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00002158 }
2159 }
2160
Tim Peters6d6c1a32001-08-02 04:15:00 +00002161 /* Special-case __new__: if it's a plain function,
2162 make it a static function */
2163 tmp = PyDict_GetItemString(dict, "__new__");
2164 if (tmp != NULL && PyFunction_Check(tmp)) {
2165 tmp = PyStaticMethod_New(tmp);
2166 if (tmp == NULL) {
2167 Py_DECREF(type);
2168 return NULL;
2169 }
2170 PyDict_SetItemString(dict, "__new__", tmp);
2171 Py_DECREF(tmp);
2172 }
2173
2174 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002175 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00002176 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002177 if (slots != NULL) {
2178 for (i = 0; i < nslots; i++, mp++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002179 mp->name = PyUnicode_AsString(
Tim Peters6d6c1a32001-08-02 04:15:00 +00002180 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00002181 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002182 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002183
2184 /* __dict__ and __weakref__ are already filtered out */
2185 assert(strcmp(mp->name, "__dict__") != 0);
2186 assert(strcmp(mp->name, "__weakref__") != 0);
2187
Tim Peters6d6c1a32001-08-02 04:15:00 +00002188 slotoffset += sizeof(PyObject *);
2189 }
2190 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002191 if (add_dict) {
2192 if (base->tp_itemsize)
2193 type->tp_dictoffset = -(long)sizeof(PyObject *);
2194 else
2195 type->tp_dictoffset = slotoffset;
2196 slotoffset += sizeof(PyObject *);
2197 }
2198 if (add_weak) {
2199 assert(!base->tp_itemsize);
2200 type->tp_weaklistoffset = slotoffset;
2201 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002202 }
2203 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002204 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002205 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002206
2207 if (type->tp_weaklistoffset && type->tp_dictoffset)
2208 type->tp_getset = subtype_getsets_full;
2209 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2210 type->tp_getset = subtype_getsets_weakref_only;
2211 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2212 type->tp_getset = subtype_getsets_dict_only;
2213 else
2214 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002215
2216 /* Special case some slots */
2217 if (type->tp_dictoffset != 0 || nslots > 0) {
2218 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2219 type->tp_getattro = PyObject_GenericGetAttr;
2220 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2221 type->tp_setattro = PyObject_GenericSetAttr;
2222 }
2223 type->tp_dealloc = subtype_dealloc;
2224
Guido van Rossum9475a232001-10-05 20:51:39 +00002225 /* Enable GC unless there are really no instance variables possible */
2226 if (!(type->tp_basicsize == sizeof(PyObject) &&
2227 type->tp_itemsize == 0))
2228 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2229
Tim Peters6d6c1a32001-08-02 04:15:00 +00002230 /* Always override allocation strategy to use regular heap */
2231 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002232 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002233 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002234 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002235 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002236 }
2237 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002238 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239
2240 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002241 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002242 Py_DECREF(type);
2243 return NULL;
2244 }
2245
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002246 /* Put the proper slots in place */
2247 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002248
Tim Peters6d6c1a32001-08-02 04:15:00 +00002249 return (PyObject *)type;
2250}
2251
2252/* Internal API to look for a name through the MRO.
2253 This returns a borrowed reference, and doesn't set an exception! */
2254PyObject *
2255_PyType_Lookup(PyTypeObject *type, PyObject *name)
2256{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002257 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002258 PyObject *mro, *res, *base, *dict;
Christian Heimesa62da1d2008-01-12 19:39:10 +00002259 unsigned int h;
2260
2261 if (MCACHE_CACHEABLE_NAME(name) &&
Christian Heimes412dc9c2008-01-27 18:55:54 +00002262 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
Christian Heimesa62da1d2008-01-12 19:39:10 +00002263 /* fast path */
2264 h = MCACHE_HASH_METHOD(type, name);
2265 if (method_cache[h].version == type->tp_version_tag &&
2266 method_cache[h].name == name)
2267 return method_cache[h].value;
2268 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002269
Guido van Rossum687ae002001-10-15 22:03:32 +00002270 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002271 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002272
2273 /* If mro is NULL, the type is either not yet initialized
2274 by PyType_Ready(), or already cleared by type_clear().
2275 Either way the safest thing to do is to return NULL. */
2276 if (mro == NULL)
2277 return NULL;
2278
Christian Heimesa62da1d2008-01-12 19:39:10 +00002279 res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002280 assert(PyTuple_Check(mro));
2281 n = PyTuple_GET_SIZE(mro);
2282 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002283 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002284 assert(PyType_Check(base));
2285 dict = ((PyTypeObject *)base)->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002286 assert(dict && PyDict_Check(dict));
2287 res = PyDict_GetItem(dict, name);
2288 if (res != NULL)
Christian Heimesa62da1d2008-01-12 19:39:10 +00002289 break;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002290 }
Christian Heimesa62da1d2008-01-12 19:39:10 +00002291
2292 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2293 h = MCACHE_HASH_METHOD(type, name);
2294 method_cache[h].version = type->tp_version_tag;
2295 method_cache[h].value = res; /* borrowed */
2296 Py_INCREF(name);
2297 Py_DECREF(method_cache[h].name);
2298 method_cache[h].name = name;
2299 }
2300 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002301}
2302
2303/* This is similar to PyObject_GenericGetAttr(),
2304 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2305static PyObject *
2306type_getattro(PyTypeObject *type, PyObject *name)
2307{
Christian Heimes90aa7642007-12-19 02:45:37 +00002308 PyTypeObject *metatype = Py_TYPE(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002309 PyObject *meta_attribute, *attribute;
2310 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002311
2312 /* Initialize this type (we'll assume the metatype is initialized) */
2313 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002314 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002315 return NULL;
2316 }
2317
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002318 /* No readable descriptor found yet */
2319 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002320
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002321 /* Look for the attribute in the metatype */
2322 meta_attribute = _PyType_Lookup(metatype, name);
2323
2324 if (meta_attribute != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002325 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002326
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002327 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2328 /* Data descriptors implement tp_descr_set to intercept
2329 * writes. Assume the attribute is not overridden in
2330 * type's tp_dict (and bases): call the descriptor now.
2331 */
2332 return meta_get(meta_attribute, (PyObject *)type,
2333 (PyObject *)metatype);
2334 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002335 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002336 }
2337
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002338 /* No data descriptor found on metatype. Look in tp_dict of this
2339 * type and its bases */
2340 attribute = _PyType_Lookup(type, name);
2341 if (attribute != NULL) {
2342 /* Implement descriptor functionality, if any */
Christian Heimes90aa7642007-12-19 02:45:37 +00002343 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002344
2345 Py_XDECREF(meta_attribute);
2346
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002347 if (local_get != NULL) {
2348 /* NULL 2nd argument indicates the descriptor was
2349 * found on the target object itself (or a base) */
2350 return local_get(attribute, (PyObject *)NULL,
2351 (PyObject *)type);
2352 }
Tim Peters34592512002-07-11 06:23:50 +00002353
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002354 Py_INCREF(attribute);
2355 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002356 }
2357
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002358 /* No attribute found in local __dict__ (or bases): use the
2359 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002360 if (meta_get != NULL) {
2361 PyObject *res;
2362 res = meta_get(meta_attribute, (PyObject *)type,
2363 (PyObject *)metatype);
2364 Py_DECREF(meta_attribute);
2365 return res;
2366 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002367
2368 /* If an ordinary attribute was found on the metatype, return it now */
2369 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002370 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002371 }
2372
2373 /* Give up */
2374 PyErr_Format(PyExc_AttributeError,
Walter Dörwald75163602007-06-11 15:47:13 +00002375 "type object '%.50s' has no attribute '%U'",
2376 type->tp_name, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002377 return NULL;
2378}
2379
2380static int
2381type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2382{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002383 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2384 PyErr_Format(
2385 PyExc_TypeError,
2386 "can't set attributes of built-in/extension type '%s'",
2387 type->tp_name);
2388 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002389 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002390 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2391 return -1;
2392 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002393}
2394
2395static void
2396type_dealloc(PyTypeObject *type)
2397{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002398 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002399
2400 /* Assert this is a heap-allocated type object */
2401 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002402 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002403 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002404 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002405 Py_XDECREF(type->tp_base);
2406 Py_XDECREF(type->tp_dict);
2407 Py_XDECREF(type->tp_bases);
2408 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002409 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002410 Py_XDECREF(type->tp_subclasses);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002411 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2412 * of most other objects. It's okay to cast it to char *.
2413 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002414 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002415 Py_XDECREF(et->ht_name);
2416 Py_XDECREF(et->ht_slots);
Christian Heimes90aa7642007-12-19 02:45:37 +00002417 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002418}
2419
Guido van Rossum1c450732001-10-08 15:18:27 +00002420static PyObject *
2421type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2422{
2423 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002424 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002425
2426 list = PyList_New(0);
2427 if (list == NULL)
2428 return NULL;
2429 raw = type->tp_subclasses;
2430 if (raw == NULL)
2431 return list;
2432 assert(PyList_Check(raw));
2433 n = PyList_GET_SIZE(raw);
2434 for (i = 0; i < n; i++) {
2435 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002436 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002437 ref = PyWeakref_GET_OBJECT(ref);
2438 if (ref != Py_None) {
2439 if (PyList_Append(list, ref) < 0) {
2440 Py_DECREF(list);
2441 return NULL;
2442 }
2443 }
2444 }
2445 return list;
2446}
2447
Guido van Rossum47374822007-08-02 16:48:17 +00002448static PyObject *
2449type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2450{
2451 return PyDict_New();
2452}
2453
Tim Peters6d6c1a32001-08-02 04:15:00 +00002454static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002455 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002456 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002457 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002458 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Guido van Rossum47374822007-08-02 16:48:17 +00002459 {"__prepare__", (PyCFunction)type_prepare,
2460 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2461 PyDoc_STR("__prepare__() -> dict\n"
2462 "used to create the namespace for the class statement")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002463 {0}
2464};
2465
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002466PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002467"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002468"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002469
Guido van Rossum048eb752001-10-02 21:24:57 +00002470static int
2471type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2472{
Guido van Rossuma3862092002-06-10 15:24:42 +00002473 /* Because of type_is_gc(), the collector only calls this
2474 for heaptypes. */
2475 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002476
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002477 Py_VISIT(type->tp_dict);
2478 Py_VISIT(type->tp_cache);
2479 Py_VISIT(type->tp_mro);
2480 Py_VISIT(type->tp_bases);
2481 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002482
2483 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002484 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002485 in cycles; tp_subclasses is a list of weak references,
2486 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002487
Guido van Rossum048eb752001-10-02 21:24:57 +00002488 return 0;
2489}
2490
2491static int
2492type_clear(PyTypeObject *type)
2493{
Guido van Rossuma3862092002-06-10 15:24:42 +00002494 /* Because of type_is_gc(), the collector only calls this
2495 for heaptypes. */
2496 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002497
Guido van Rossuma3862092002-06-10 15:24:42 +00002498 /* The only field we need to clear is tp_mro, which is part of a
2499 hard cycle (its first element is the class itself) that won't
2500 be broken otherwise (it's a tuple and tuples don't have a
2501 tp_clear handler). None of the other fields need to be
2502 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002503
Guido van Rossuma3862092002-06-10 15:24:42 +00002504 tp_dict:
2505 It is a dict, so the collector will call its tp_clear.
2506
2507 tp_cache:
2508 Not used; if it were, it would be a dict.
2509
2510 tp_bases, tp_base:
2511 If these are involved in a cycle, there must be at least
2512 one other, mutable object in the cycle, e.g. a base
2513 class's dict; the cycle will be broken that way.
2514
2515 tp_subclasses:
2516 A list of weak references can't be part of a cycle; and
2517 lists have their own tp_clear.
2518
Guido van Rossume5c691a2003-03-07 15:13:17 +00002519 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002520 A tuple of strings can't be part of a cycle.
2521 */
2522
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002523 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002524
2525 return 0;
2526}
2527
2528static int
2529type_is_gc(PyTypeObject *type)
2530{
2531 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2532}
2533
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002534PyTypeObject PyType_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002535 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002536 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002537 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002538 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002539 (destructor)type_dealloc, /* tp_dealloc */
2540 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002541 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002542 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002543 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002544 (reprfunc)type_repr, /* tp_repr */
2545 0, /* tp_as_number */
2546 0, /* tp_as_sequence */
2547 0, /* tp_as_mapping */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002548 0, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002549 (ternaryfunc)type_call, /* tp_call */
2550 0, /* tp_str */
2551 (getattrofunc)type_getattro, /* tp_getattro */
2552 (setattrofunc)type_setattro, /* tp_setattro */
2553 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002554 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002555 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002556 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002557 (traverseproc)type_traverse, /* tp_traverse */
2558 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002559 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002560 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002561 0, /* tp_iter */
2562 0, /* tp_iternext */
2563 type_methods, /* tp_methods */
2564 type_members, /* tp_members */
2565 type_getsets, /* tp_getset */
2566 0, /* tp_base */
2567 0, /* tp_dict */
2568 0, /* tp_descr_get */
2569 0, /* tp_descr_set */
2570 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002571 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002572 0, /* tp_alloc */
2573 type_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002574 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002575 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002576};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002577
2578
2579/* The base type of all types (eventually)... except itself. */
2580
Guido van Rossumd8faa362007-04-27 19:54:29 +00002581/* You may wonder why object.__new__() only complains about arguments
2582 when object.__init__() is not overridden, and vice versa.
2583
2584 Consider the use cases:
2585
2586 1. When neither is overridden, we want to hear complaints about
2587 excess (i.e., any) arguments, since their presence could
2588 indicate there's a bug.
2589
2590 2. When defining an Immutable type, we are likely to override only
2591 __new__(), since __init__() is called too late to initialize an
2592 Immutable object. Since __new__() defines the signature for the
2593 type, it would be a pain to have to override __init__() just to
2594 stop it from complaining about excess arguments.
2595
2596 3. When defining a Mutable type, we are likely to override only
2597 __init__(). So here the converse reasoning applies: we don't
2598 want to have to override __new__() just to stop it from
2599 complaining.
2600
2601 4. When __init__() is overridden, and the subclass __init__() calls
2602 object.__init__(), the latter should complain about excess
2603 arguments; ditto for __new__().
2604
2605 Use cases 2 and 3 make it unattractive to unconditionally check for
2606 excess arguments. The best solution that addresses all four use
2607 cases is as follows: __init__() complains about excess arguments
2608 unless __new__() is overridden and __init__() is not overridden
2609 (IOW, if __init__() is overridden or __new__() is not overridden);
2610 symmetrically, __new__() complains about excess arguments unless
2611 __init__() is overridden and __new__() is not overridden
2612 (IOW, if __new__() is overridden or __init__() is not overridden).
2613
2614 However, for backwards compatibility, this breaks too much code.
2615 Therefore, in 2.6, we'll *warn* about excess arguments when both
2616 methods are overridden; for all other cases we'll use the above
2617 rules.
2618
2619*/
2620
2621/* Forward */
2622static PyObject *
2623object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2624
2625static int
2626excess_args(PyObject *args, PyObject *kwds)
2627{
2628 return PyTuple_GET_SIZE(args) ||
2629 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2630}
2631
Tim Peters6d6c1a32001-08-02 04:15:00 +00002632static int
2633object_init(PyObject *self, PyObject *args, PyObject *kwds)
2634{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002635 int err = 0;
2636 if (excess_args(args, kwds)) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002637 PyTypeObject *type = Py_TYPE(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002638 if (type->tp_init != object_init &&
2639 type->tp_new != object_new)
2640 {
2641 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2642 "object.__init__() takes no parameters",
2643 1);
2644 }
2645 else if (type->tp_init != object_init ||
2646 type->tp_new == object_new)
2647 {
2648 PyErr_SetString(PyExc_TypeError,
2649 "object.__init__() takes no parameters");
2650 err = -1;
2651 }
2652 }
2653 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002654}
2655
Guido van Rossum298e4212003-02-13 16:30:16 +00002656static PyObject *
2657object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2658{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002659 int err = 0;
2660 if (excess_args(args, kwds)) {
2661 if (type->tp_new != object_new &&
2662 type->tp_init != object_init)
2663 {
2664 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2665 "object.__new__() takes no parameters",
2666 1);
2667 }
2668 else if (type->tp_new != object_new ||
2669 type->tp_init == object_init)
2670 {
2671 PyErr_SetString(PyExc_TypeError,
2672 "object.__new__() takes no parameters");
2673 err = -1;
2674 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002675 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002676 if (err < 0)
2677 return NULL;
Christian Heimes9e7f1d22008-02-28 12:27:11 +00002678
2679 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2680 static PyObject *comma = NULL;
2681 PyObject *abstract_methods = NULL;
2682 PyObject *builtins;
2683 PyObject *sorted;
2684 PyObject *sorted_methods = NULL;
2685 PyObject *joined = NULL;
2686
2687 /* Compute ", ".join(sorted(type.__abstractmethods__))
2688 into joined. */
2689 abstract_methods = type_abstractmethods(type, NULL);
2690 if (abstract_methods == NULL)
2691 goto error;
2692 builtins = PyEval_GetBuiltins();
2693 if (builtins == NULL)
2694 goto error;
2695 sorted = PyDict_GetItemString(builtins, "sorted");
2696 if (sorted == NULL)
2697 goto error;
2698 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2699 abstract_methods,
2700 NULL);
2701 if (sorted_methods == NULL)
2702 goto error;
2703 if (comma == NULL) {
2704 comma = PyUnicode_InternFromString(", ");
2705 if (comma == NULL)
2706 goto error;
2707 }
2708 joined = PyObject_CallMethod(comma, "join",
2709 "O", sorted_methods);
2710 if (joined == NULL)
2711 goto error;
2712
2713 PyErr_Format(PyExc_TypeError,
2714 "Can't instantiate abstract class %s "
2715 "with abstract methods %U",
2716 type->tp_name,
2717 joined);
2718 error:
2719 Py_XDECREF(joined);
2720 Py_XDECREF(sorted_methods);
2721 Py_XDECREF(abstract_methods);
2722 return NULL;
2723 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002724 return type->tp_alloc(type, 0);
2725}
2726
Tim Peters6d6c1a32001-08-02 04:15:00 +00002727static void
2728object_dealloc(PyObject *self)
2729{
Christian Heimes90aa7642007-12-19 02:45:37 +00002730 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002731}
2732
Guido van Rossum8e248182001-08-12 05:17:56 +00002733static PyObject *
2734object_repr(PyObject *self)
2735{
Guido van Rossum76e69632001-08-16 18:52:43 +00002736 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002737 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002738
Christian Heimes90aa7642007-12-19 02:45:37 +00002739 type = Py_TYPE(self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002740 mod = type_module(type, NULL);
2741 if (mod == NULL)
2742 PyErr_Clear();
Martin v. Löwis5b222132007-06-10 09:51:05 +00002743 else if (!PyUnicode_Check(mod)) {
Guido van Rossum76e69632001-08-16 18:52:43 +00002744 Py_DECREF(mod);
2745 mod = NULL;
2746 }
2747 name = type_name(type, NULL);
2748 if (name == NULL)
2749 return NULL;
Georg Brandl1a3284e2007-12-02 09:40:06 +00002750 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
Walter Dörwald4dbd01b2007-06-11 14:03:45 +00002751 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002752 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00002753 rtn = PyUnicode_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002754 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002755 Py_XDECREF(mod);
2756 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002757 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002758}
2759
Guido van Rossumb8f63662001-08-15 23:57:02 +00002760static PyObject *
2761object_str(PyObject *self)
2762{
2763 unaryfunc f;
2764
Christian Heimes90aa7642007-12-19 02:45:37 +00002765 f = Py_TYPE(self)->tp_repr;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002766 if (f == NULL)
2767 f = object_repr;
2768 return f(self);
2769}
2770
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002771static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002772object_richcompare(PyObject *self, PyObject *other, int op)
2773{
2774 PyObject *res;
2775
2776 switch (op) {
2777
2778 case Py_EQ:
Guido van Rossumab078dd2008-01-06 00:09:11 +00002779 /* Return NotImplemented instead of False, so if two
2780 objects are compared, both get a chance at the
2781 comparison. See issue #1393. */
2782 res = (self == other) ? Py_True : Py_NotImplemented;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002783 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002784 break;
2785
2786 case Py_NE:
Guido van Rossume27dc722007-03-27 22:37:34 +00002787 /* By default, != returns the opposite of ==,
2788 unless the latter returns NotImplemented. */
2789 res = PyObject_RichCompare(self, other, Py_EQ);
2790 if (res != NULL && res != Py_NotImplemented) {
2791 int ok = PyObject_IsTrue(res);
2792 Py_DECREF(res);
2793 if (ok < 0)
2794 res = NULL;
2795 else {
2796 if (ok)
2797 res = Py_False;
2798 else
2799 res = Py_True;
2800 Py_INCREF(res);
2801 }
2802 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002803 break;
2804
2805 default:
2806 res = Py_NotImplemented;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002807 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002808 break;
2809 }
2810
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002811 return res;
2812}
2813
2814static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002815object_get_class(PyObject *self, void *closure)
2816{
Christian Heimes90aa7642007-12-19 02:45:37 +00002817 Py_INCREF(Py_TYPE(self));
2818 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002819}
2820
2821static int
2822equiv_structs(PyTypeObject *a, PyTypeObject *b)
2823{
2824 return a == b ||
2825 (a != NULL &&
2826 b != NULL &&
2827 a->tp_basicsize == b->tp_basicsize &&
2828 a->tp_itemsize == b->tp_itemsize &&
2829 a->tp_dictoffset == b->tp_dictoffset &&
2830 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2831 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2832 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2833}
2834
2835static int
2836same_slots_added(PyTypeObject *a, PyTypeObject *b)
2837{
2838 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002839 Py_ssize_t size;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002840 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002841
2842 if (base != b->tp_base)
2843 return 0;
2844 if (equiv_structs(a, base) && equiv_structs(b, base))
2845 return 1;
2846 size = base->tp_basicsize;
2847 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2848 size += sizeof(PyObject *);
2849 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2850 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002851
2852 /* Check slots compliance */
2853 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2854 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2855 if (slots_a && slots_b) {
2856 if (PyObject_Compare(slots_a, slots_b) != 0)
2857 return 0;
2858 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2859 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002860 return size == a->tp_basicsize && size == b->tp_basicsize;
2861}
2862
2863static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002864compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002865{
2866 PyTypeObject *newbase, *oldbase;
2867
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002868 if (newto->tp_dealloc != oldto->tp_dealloc ||
2869 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002870 {
2871 PyErr_Format(PyExc_TypeError,
2872 "%s assignment: "
2873 "'%s' deallocator differs from '%s'",
2874 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002875 newto->tp_name,
2876 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002877 return 0;
2878 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002879 newbase = newto;
2880 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002881 while (equiv_structs(newbase, newbase->tp_base))
2882 newbase = newbase->tp_base;
2883 while (equiv_structs(oldbase, oldbase->tp_base))
2884 oldbase = oldbase->tp_base;
2885 if (newbase != oldbase &&
2886 (newbase->tp_base != oldbase->tp_base ||
2887 !same_slots_added(newbase, oldbase))) {
2888 PyErr_Format(PyExc_TypeError,
2889 "%s assignment: "
2890 "'%s' object layout differs from '%s'",
2891 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002892 newto->tp_name,
2893 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002894 return 0;
2895 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002896
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002897 return 1;
2898}
2899
2900static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002901object_set_class(PyObject *self, PyObject *value, void *closure)
2902{
Christian Heimes90aa7642007-12-19 02:45:37 +00002903 PyTypeObject *oldto = Py_TYPE(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002904 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002905
Guido van Rossumb6b89422002-04-15 01:03:30 +00002906 if (value == NULL) {
2907 PyErr_SetString(PyExc_TypeError,
2908 "can't delete __class__ attribute");
2909 return -1;
2910 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002911 if (!PyType_Check(value)) {
2912 PyErr_Format(PyExc_TypeError,
2913 "__class__ must be set to new-style class, not '%s' object",
Christian Heimes90aa7642007-12-19 02:45:37 +00002914 Py_TYPE(value)->tp_name);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002915 return -1;
2916 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002917 newto = (PyTypeObject *)value;
2918 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2919 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002920 {
2921 PyErr_Format(PyExc_TypeError,
2922 "__class__ assignment: only for heap types");
2923 return -1;
2924 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002925 if (compatible_for_assignment(newto, oldto, "__class__")) {
2926 Py_INCREF(newto);
Christian Heimes90aa7642007-12-19 02:45:37 +00002927 Py_TYPE(self) = newto;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002928 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002929 return 0;
2930 }
2931 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002932 return -1;
2933 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002934}
2935
2936static PyGetSetDef object_getsets[] = {
2937 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002938 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002939 {0}
2940};
2941
Guido van Rossumc53f0092003-02-18 22:05:12 +00002942
Guido van Rossum036f9992003-02-21 22:02:54 +00002943/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002944 We fall back to helpers in copyreg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00002945 - pickle protocols < 2
2946 - calculating the list of slot names (done only once per class)
2947 - the __newobj__ function (which is used as a token but never called)
2948*/
2949
2950static PyObject *
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002951import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00002952{
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002953 static PyObject *copyreg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002954
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002955 if (!copyreg_str) {
2956 copyreg_str = PyUnicode_InternFromString("copyreg");
2957 if (copyreg_str == NULL)
Guido van Rossum3926a632001-09-25 16:25:58 +00002958 return NULL;
2959 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002960
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002961 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00002962}
2963
2964static PyObject *
2965slotnames(PyObject *cls)
2966{
2967 PyObject *clsdict;
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002968 PyObject *copyreg;
Guido van Rossum036f9992003-02-21 22:02:54 +00002969 PyObject *slotnames;
2970
2971 if (!PyType_Check(cls)) {
2972 Py_INCREF(Py_None);
2973 return Py_None;
2974 }
2975
2976 clsdict = ((PyTypeObject *)cls)->tp_dict;
2977 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002978 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002979 Py_INCREF(slotnames);
2980 return slotnames;
2981 }
2982
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002983 copyreg = import_copyreg();
2984 if (copyreg == NULL)
Guido van Rossum036f9992003-02-21 22:02:54 +00002985 return NULL;
2986
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002987 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
2988 Py_DECREF(copyreg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002989 if (slotnames != NULL &&
2990 slotnames != Py_None &&
2991 !PyList_Check(slotnames))
2992 {
2993 PyErr_SetString(PyExc_TypeError,
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002994 "copyreg._slotnames didn't return a list or None");
Guido van Rossum036f9992003-02-21 22:02:54 +00002995 Py_DECREF(slotnames);
2996 slotnames = NULL;
2997 }
2998
2999 return slotnames;
3000}
3001
3002static PyObject *
3003reduce_2(PyObject *obj)
3004{
3005 PyObject *cls, *getnewargs;
3006 PyObject *args = NULL, *args2 = NULL;
3007 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3008 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003009 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003010 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00003011
3012 cls = PyObject_GetAttrString(obj, "__class__");
3013 if (cls == NULL)
3014 return NULL;
3015
3016 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
3017 if (getnewargs != NULL) {
3018 args = PyObject_CallObject(getnewargs, NULL);
3019 Py_DECREF(getnewargs);
3020 if (args != NULL && !PyTuple_Check(args)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003021 PyErr_Format(PyExc_TypeError,
3022 "__getnewargs__ should return a tuple, "
Christian Heimes90aa7642007-12-19 02:45:37 +00003023 "not '%.200s'", Py_TYPE(args)->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00003024 goto end;
3025 }
3026 }
3027 else {
3028 PyErr_Clear();
3029 args = PyTuple_New(0);
3030 }
3031 if (args == NULL)
3032 goto end;
3033
3034 getstate = PyObject_GetAttrString(obj, "__getstate__");
3035 if (getstate != NULL) {
3036 state = PyObject_CallObject(getstate, NULL);
3037 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00003038 if (state == NULL)
3039 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003040 }
3041 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00003042 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00003043 state = PyObject_GetAttrString(obj, "__dict__");
3044 if (state == NULL) {
3045 PyErr_Clear();
3046 state = Py_None;
3047 Py_INCREF(state);
3048 }
3049 names = slotnames(cls);
3050 if (names == NULL)
3051 goto end;
3052 if (names != Py_None) {
3053 assert(PyList_Check(names));
3054 slots = PyDict_New();
3055 if (slots == NULL)
3056 goto end;
3057 n = 0;
3058 /* Can't pre-compute the list size; the list
3059 is stored on the class so accessible to other
3060 threads, which may be run by DECREF */
3061 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3062 PyObject *name, *value;
3063 name = PyList_GET_ITEM(names, i);
3064 value = PyObject_GetAttr(obj, name);
3065 if (value == NULL)
3066 PyErr_Clear();
3067 else {
3068 int err = PyDict_SetItem(slots, name,
3069 value);
3070 Py_DECREF(value);
3071 if (err)
3072 goto end;
3073 n++;
3074 }
3075 }
3076 if (n) {
3077 state = Py_BuildValue("(NO)", state, slots);
3078 if (state == NULL)
3079 goto end;
3080 }
3081 }
3082 }
3083
3084 if (!PyList_Check(obj)) {
3085 listitems = Py_None;
3086 Py_INCREF(listitems);
3087 }
3088 else {
3089 listitems = PyObject_GetIter(obj);
3090 if (listitems == NULL)
3091 goto end;
3092 }
3093
3094 if (!PyDict_Check(obj)) {
3095 dictitems = Py_None;
3096 Py_INCREF(dictitems);
3097 }
3098 else {
Guido van Rossumcc2b0162007-02-11 06:12:03 +00003099 PyObject *items = PyObject_CallMethod(obj, "items", "");
3100 if (items == NULL)
3101 goto end;
3102 dictitems = PyObject_GetIter(items);
3103 Py_DECREF(items);
Guido van Rossum036f9992003-02-21 22:02:54 +00003104 if (dictitems == NULL)
3105 goto end;
3106 }
3107
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003108 copyreg = import_copyreg();
3109 if (copyreg == NULL)
Guido van Rossum036f9992003-02-21 22:02:54 +00003110 goto end;
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003111 newobj = PyObject_GetAttrString(copyreg, "__newobj__");
Guido van Rossum036f9992003-02-21 22:02:54 +00003112 if (newobj == NULL)
3113 goto end;
3114
3115 n = PyTuple_GET_SIZE(args);
3116 args2 = PyTuple_New(n+1);
3117 if (args2 == NULL)
3118 goto end;
3119 PyTuple_SET_ITEM(args2, 0, cls);
3120 cls = NULL;
3121 for (i = 0; i < n; i++) {
3122 PyObject *v = PyTuple_GET_ITEM(args, i);
3123 Py_INCREF(v);
3124 PyTuple_SET_ITEM(args2, i+1, v);
3125 }
3126
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003127 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003128
3129 end:
3130 Py_XDECREF(cls);
3131 Py_XDECREF(args);
3132 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00003133 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00003134 Py_XDECREF(state);
3135 Py_XDECREF(names);
3136 Py_XDECREF(listitems);
3137 Py_XDECREF(dictitems);
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003138 Py_XDECREF(copyreg);
Guido van Rossum036f9992003-02-21 22:02:54 +00003139 Py_XDECREF(newobj);
3140 return res;
3141}
3142
Guido van Rossumd8faa362007-04-27 19:54:29 +00003143/*
3144 * There were two problems when object.__reduce__ and object.__reduce_ex__
3145 * were implemented in the same function:
3146 * - trying to pickle an object with a custom __reduce__ method that
3147 * fell back to object.__reduce__ in certain circumstances led to
3148 * infinite recursion at Python level and eventual RuntimeError.
3149 * - Pickling objects that lied about their type by overwriting the
3150 * __class__ descriptor could lead to infinite recursion at C level
3151 * and eventual segfault.
3152 *
3153 * Because of backwards compatibility, the two methods still have to
3154 * behave in the same way, even if this is not required by the pickle
3155 * protocol. This common functionality was moved to the _common_reduce
3156 * function.
3157 */
3158static PyObject *
3159_common_reduce(PyObject *self, int proto)
3160{
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003161 PyObject *copyreg, *res;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003162
3163 if (proto >= 2)
3164 return reduce_2(self);
3165
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003166 copyreg = import_copyreg();
3167 if (!copyreg)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003168 return NULL;
3169
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003170 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3171 Py_DECREF(copyreg);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003172
3173 return res;
3174}
3175
3176static PyObject *
3177object_reduce(PyObject *self, PyObject *args)
3178{
3179 int proto = 0;
3180
3181 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3182 return NULL;
3183
3184 return _common_reduce(self, proto);
3185}
3186
Guido van Rossum036f9992003-02-21 22:02:54 +00003187static PyObject *
3188object_reduce_ex(PyObject *self, PyObject *args)
3189{
Guido van Rossumd8faa362007-04-27 19:54:29 +00003190 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003191 int proto = 0;
3192
3193 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3194 return NULL;
3195
3196 reduce = PyObject_GetAttrString(self, "__reduce__");
3197 if (reduce == NULL)
3198 PyErr_Clear();
3199 else {
3200 PyObject *cls, *clsreduce, *objreduce;
3201 int override;
3202 cls = PyObject_GetAttrString(self, "__class__");
3203 if (cls == NULL) {
3204 Py_DECREF(reduce);
3205 return NULL;
3206 }
3207 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3208 Py_DECREF(cls);
3209 if (clsreduce == NULL) {
3210 Py_DECREF(reduce);
3211 return NULL;
3212 }
3213 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3214 "__reduce__");
3215 override = (clsreduce != objreduce);
3216 Py_DECREF(clsreduce);
3217 if (override) {
3218 res = PyObject_CallObject(reduce, NULL);
3219 Py_DECREF(reduce);
3220 return res;
3221 }
3222 else
3223 Py_DECREF(reduce);
3224 }
3225
Guido van Rossumd8faa362007-04-27 19:54:29 +00003226 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003227}
3228
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003229static PyObject *
3230object_subclasshook(PyObject *cls, PyObject *args)
3231{
3232 Py_INCREF(Py_NotImplemented);
3233 return Py_NotImplemented;
3234}
3235
3236PyDoc_STRVAR(object_subclasshook_doc,
3237"Abstract classes can override this to customize issubclass().\n"
3238"\n"
3239"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3240"It should return True, False or NotImplemented. If it returns\n"
3241"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3242"overrides the normal algorithm (and the outcome is cached).\n");
Eric Smith8c663262007-08-25 02:26:07 +00003243
3244/*
3245 from PEP 3101, this code implements:
3246
3247 class object:
3248 def __format__(self, format_spec):
3249 return format(str(self), format_spec)
3250*/
3251static PyObject *
3252object_format(PyObject *self, PyObject *args)
3253{
3254 PyObject *format_spec;
3255 PyObject *self_as_str = NULL;
3256 PyObject *result = NULL;
3257 PyObject *format_meth = NULL;
3258
Eric Smithfc6e8fe2008-01-11 00:17:22 +00003259 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
Eric Smith8c663262007-08-25 02:26:07 +00003260 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +00003261
Thomas Heller519a0422007-11-15 20:48:54 +00003262 self_as_str = PyObject_Str(self);
Eric Smith8c663262007-08-25 02:26:07 +00003263 if (self_as_str != NULL) {
3264 /* find the format function */
3265 format_meth = PyObject_GetAttrString(self_as_str, "__format__");
3266 if (format_meth != NULL) {
3267 /* and call it */
3268 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
3269 }
3270 }
3271
3272 Py_XDECREF(self_as_str);
3273 Py_XDECREF(format_meth);
3274
3275 return result;
3276}
3277
Guido van Rossum3926a632001-09-25 16:25:58 +00003278static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00003279 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3280 PyDoc_STR("helper for pickle")},
Guido van Rossumd8faa362007-04-27 19:54:29 +00003281 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003282 PyDoc_STR("helper for pickle")},
Christian Heimes9e7f1d22008-02-28 12:27:11 +00003283 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3284 object_subclasshook_doc},
Eric Smith8c663262007-08-25 02:26:07 +00003285 {"__format__", object_format, METH_VARARGS,
3286 PyDoc_STR("default object formatter")},
Guido van Rossum3926a632001-09-25 16:25:58 +00003287 {0}
3288};
3289
Guido van Rossum036f9992003-02-21 22:02:54 +00003290
Tim Peters6d6c1a32001-08-02 04:15:00 +00003291PyTypeObject PyBaseObject_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003292 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003293 "object", /* tp_name */
3294 sizeof(PyObject), /* tp_basicsize */
3295 0, /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003296 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003297 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003298 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003299 0, /* tp_setattr */
3300 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003301 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003302 0, /* tp_as_number */
3303 0, /* tp_as_sequence */
3304 0, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003305 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003306 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003307 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003308 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003309 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003310 0, /* tp_as_buffer */
3311 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003312 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003313 0, /* tp_traverse */
3314 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003315 object_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003316 0, /* tp_weaklistoffset */
3317 0, /* tp_iter */
3318 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00003319 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003320 0, /* tp_members */
3321 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003322 0, /* tp_base */
3323 0, /* tp_dict */
3324 0, /* tp_descr_get */
3325 0, /* tp_descr_set */
3326 0, /* tp_dictoffset */
3327 object_init, /* tp_init */
3328 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003329 object_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003330 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003331};
3332
3333
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003334/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003335
3336static int
3337add_methods(PyTypeObject *type, PyMethodDef *meth)
3338{
Guido van Rossum687ae002001-10-15 22:03:32 +00003339 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003340
3341 for (; meth->ml_name != NULL; meth++) {
3342 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003343 if (PyDict_GetItemString(dict, meth->ml_name) &&
3344 !(meth->ml_flags & METH_COEXIST))
3345 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003346 if (meth->ml_flags & METH_CLASS) {
3347 if (meth->ml_flags & METH_STATIC) {
3348 PyErr_SetString(PyExc_ValueError,
3349 "method cannot be both class and static");
3350 return -1;
3351 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003352 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003353 }
3354 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003355 PyObject *cfunc = PyCFunction_New(meth, NULL);
3356 if (cfunc == NULL)
3357 return -1;
3358 descr = PyStaticMethod_New(cfunc);
3359 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003360 }
3361 else {
3362 descr = PyDescr_NewMethod(type, meth);
3363 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003364 if (descr == NULL)
3365 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003366 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003367 return -1;
3368 Py_DECREF(descr);
3369 }
3370 return 0;
3371}
3372
3373static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003374add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003375{
Guido van Rossum687ae002001-10-15 22:03:32 +00003376 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003377
3378 for (; memb->name != NULL; memb++) {
3379 PyObject *descr;
3380 if (PyDict_GetItemString(dict, memb->name))
3381 continue;
3382 descr = PyDescr_NewMember(type, memb);
3383 if (descr == NULL)
3384 return -1;
3385 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3386 return -1;
3387 Py_DECREF(descr);
3388 }
3389 return 0;
3390}
3391
3392static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003393add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003394{
Guido van Rossum687ae002001-10-15 22:03:32 +00003395 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003396
3397 for (; gsp->name != NULL; gsp++) {
3398 PyObject *descr;
3399 if (PyDict_GetItemString(dict, gsp->name))
3400 continue;
3401 descr = PyDescr_NewGetSet(type, gsp);
3402
3403 if (descr == NULL)
3404 return -1;
3405 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3406 return -1;
3407 Py_DECREF(descr);
3408 }
3409 return 0;
3410}
3411
Guido van Rossum13d52f02001-08-10 21:24:08 +00003412static void
3413inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003414{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003415 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003416
Guido van Rossum13d52f02001-08-10 21:24:08 +00003417 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003418 oldsize = base->tp_basicsize;
3419 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3420 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3421 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003422 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003423 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003424 if (type->tp_traverse == NULL)
3425 type->tp_traverse = base->tp_traverse;
3426 if (type->tp_clear == NULL)
3427 type->tp_clear = base->tp_clear;
3428 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003429 {
Guido van Rossumf884b742001-12-17 17:14:22 +00003430 /* The condition below could use some explanation.
3431 It appears that tp_new is not inherited for static types
3432 whose base class is 'object'; this seems to be a precaution
3433 so that old extension types don't suddenly become
3434 callable (object.__new__ wouldn't insure the invariants
3435 that the extension type's own factory function ensures).
3436 Heap types, of course, are under our control, so they do
3437 inherit tp_new; static extension types that specify some
3438 other built-in type as the default are considered
3439 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003440 if (base != &PyBaseObject_Type ||
3441 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3442 if (type->tp_new == NULL)
3443 type->tp_new = base->tp_new;
3444 }
3445 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003446 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003447
3448 /* Copy other non-function slots */
3449
3450#undef COPYVAL
3451#define COPYVAL(SLOT) \
3452 if (type->SLOT == 0) type->SLOT = base->SLOT
3453
3454 COPYVAL(tp_itemsize);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003455 COPYVAL(tp_weaklistoffset);
3456 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003457
3458 /* Setup fast subclass flags */
3459 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3460 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3461 else if (PyType_IsSubtype(base, &PyType_Type))
3462 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3463 else if (PyType_IsSubtype(base, &PyLong_Type))
3464 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3465 else if (PyType_IsSubtype(base, &PyString_Type))
3466 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
3467 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3468 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3469 else if (PyType_IsSubtype(base, &PyTuple_Type))
3470 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3471 else if (PyType_IsSubtype(base, &PyList_Type))
3472 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3473 else if (PyType_IsSubtype(base, &PyDict_Type))
3474 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003475}
3476
Guido van Rossumf5243f02008-01-01 04:06:48 +00003477static char *hash_name_op[] = {
Guido van Rossum38938152006-08-21 23:36:26 +00003478 "__eq__",
Guido van Rossum38938152006-08-21 23:36:26 +00003479 "__cmp__",
3480 "__hash__",
Guido van Rossumf5243f02008-01-01 04:06:48 +00003481 NULL
Guido van Rossum38938152006-08-21 23:36:26 +00003482};
3483
3484static int
Guido van Rossumf5243f02008-01-01 04:06:48 +00003485overrides_hash(PyTypeObject *type)
Guido van Rossum38938152006-08-21 23:36:26 +00003486{
Guido van Rossumf5243f02008-01-01 04:06:48 +00003487 char **p;
Guido van Rossum38938152006-08-21 23:36:26 +00003488 PyObject *dict = type->tp_dict;
3489
3490 assert(dict != NULL);
Guido van Rossumf5243f02008-01-01 04:06:48 +00003491 for (p = hash_name_op; *p; p++) {
3492 if (PyDict_GetItemString(dict, *p) != NULL)
Guido van Rossum38938152006-08-21 23:36:26 +00003493 return 1;
3494 }
3495 return 0;
3496}
3497
Guido van Rossum13d52f02001-08-10 21:24:08 +00003498static void
3499inherit_slots(PyTypeObject *type, PyTypeObject *base)
3500{
3501 PyTypeObject *basebase;
3502
3503#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003504#undef COPYSLOT
3505#undef COPYNUM
3506#undef COPYSEQ
3507#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003508#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003509
3510#define SLOTDEFINED(SLOT) \
3511 (base->SLOT != 0 && \
3512 (basebase == NULL || base->SLOT != basebase->SLOT))
3513
Tim Peters6d6c1a32001-08-02 04:15:00 +00003514#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003515 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003516
3517#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3518#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3519#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003520#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003521
Guido van Rossum13d52f02001-08-10 21:24:08 +00003522 /* This won't inherit indirect slots (from tp_as_number etc.)
3523 if type doesn't provide the space. */
3524
3525 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3526 basebase = base->tp_base;
3527 if (basebase->tp_as_number == NULL)
3528 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003529 COPYNUM(nb_add);
3530 COPYNUM(nb_subtract);
3531 COPYNUM(nb_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003532 COPYNUM(nb_remainder);
3533 COPYNUM(nb_divmod);
3534 COPYNUM(nb_power);
3535 COPYNUM(nb_negative);
3536 COPYNUM(nb_positive);
3537 COPYNUM(nb_absolute);
Jack Diederich4dafcc42006-11-28 19:15:13 +00003538 COPYNUM(nb_bool);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003539 COPYNUM(nb_invert);
3540 COPYNUM(nb_lshift);
3541 COPYNUM(nb_rshift);
3542 COPYNUM(nb_and);
3543 COPYNUM(nb_xor);
3544 COPYNUM(nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003545 COPYNUM(nb_int);
3546 COPYNUM(nb_long);
3547 COPYNUM(nb_float);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003548 COPYNUM(nb_inplace_add);
3549 COPYNUM(nb_inplace_subtract);
3550 COPYNUM(nb_inplace_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003551 COPYNUM(nb_inplace_remainder);
3552 COPYNUM(nb_inplace_power);
3553 COPYNUM(nb_inplace_lshift);
3554 COPYNUM(nb_inplace_rshift);
3555 COPYNUM(nb_inplace_and);
3556 COPYNUM(nb_inplace_xor);
3557 COPYNUM(nb_inplace_or);
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003558 COPYNUM(nb_true_divide);
3559 COPYNUM(nb_floor_divide);
3560 COPYNUM(nb_inplace_true_divide);
3561 COPYNUM(nb_inplace_floor_divide);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003562 COPYNUM(nb_index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003563 }
3564
Guido van Rossum13d52f02001-08-10 21:24:08 +00003565 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3566 basebase = base->tp_base;
3567 if (basebase->tp_as_sequence == NULL)
3568 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003569 COPYSEQ(sq_length);
3570 COPYSEQ(sq_concat);
3571 COPYSEQ(sq_repeat);
3572 COPYSEQ(sq_item);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003573 COPYSEQ(sq_ass_item);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003574 COPYSEQ(sq_contains);
3575 COPYSEQ(sq_inplace_concat);
3576 COPYSEQ(sq_inplace_repeat);
3577 }
3578
Guido van Rossum13d52f02001-08-10 21:24:08 +00003579 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3580 basebase = base->tp_base;
3581 if (basebase->tp_as_mapping == NULL)
3582 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003583 COPYMAP(mp_length);
3584 COPYMAP(mp_subscript);
3585 COPYMAP(mp_ass_subscript);
3586 }
3587
Tim Petersfc57ccb2001-10-12 02:38:24 +00003588 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3589 basebase = base->tp_base;
3590 if (basebase->tp_as_buffer == NULL)
3591 basebase = NULL;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00003592 COPYBUF(bf_getbuffer);
3593 COPYBUF(bf_releasebuffer);
Tim Petersfc57ccb2001-10-12 02:38:24 +00003594 }
3595
Guido van Rossum13d52f02001-08-10 21:24:08 +00003596 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003597
Tim Peters6d6c1a32001-08-02 04:15:00 +00003598 COPYSLOT(tp_dealloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003599 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3600 type->tp_getattr = base->tp_getattr;
3601 type->tp_getattro = base->tp_getattro;
3602 }
3603 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3604 type->tp_setattr = base->tp_setattr;
3605 type->tp_setattro = base->tp_setattro;
3606 }
3607 /* tp_compare see tp_richcompare */
3608 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003609 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003610 COPYSLOT(tp_call);
3611 COPYSLOT(tp_str);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003612 {
Guido van Rossum38938152006-08-21 23:36:26 +00003613 /* Copy comparison-related slots only when
3614 not overriding them anywhere */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003615 if (type->tp_compare == NULL &&
3616 type->tp_richcompare == NULL &&
Guido van Rossum38938152006-08-21 23:36:26 +00003617 type->tp_hash == NULL &&
Guido van Rossumf5243f02008-01-01 04:06:48 +00003618 !overrides_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003619 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003620 type->tp_compare = base->tp_compare;
3621 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003622 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003623 }
3624 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003625 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003626 COPYSLOT(tp_iter);
3627 COPYSLOT(tp_iternext);
3628 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003629 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003630 COPYSLOT(tp_descr_get);
3631 COPYSLOT(tp_descr_set);
3632 COPYSLOT(tp_dictoffset);
3633 COPYSLOT(tp_init);
3634 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003635 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003636 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3637 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3638 /* They agree about gc. */
3639 COPYSLOT(tp_free);
3640 }
3641 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3642 type->tp_free == NULL &&
Neal Norwitz30d1c512007-08-19 22:48:23 +00003643 base->tp_free == PyObject_Free) {
Tim Peters3cfe7542003-05-21 21:29:48 +00003644 /* A bit of magic to plug in the correct default
3645 * tp_free function when a derived class adds gc,
3646 * didn't define tp_free, and the base uses the
3647 * default non-gc tp_free.
3648 */
3649 type->tp_free = PyObject_GC_Del;
3650 }
3651 /* else they didn't agree about gc, and there isn't something
3652 * obvious to be done -- the type is on its own.
3653 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003654 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003655}
3656
Jeremy Hylton938ace62002-07-17 16:30:39 +00003657static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003658
Tim Peters6d6c1a32001-08-02 04:15:00 +00003659int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003660PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003661{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003662 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003663 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003664 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003665
Guido van Rossumcab05802002-06-10 15:29:03 +00003666 if (type->tp_flags & Py_TPFLAGS_READY) {
3667 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003668 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003669 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003670 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003671
3672 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003673
Tim Peters36eb4df2003-03-23 03:33:13 +00003674#ifdef Py_TRACE_REFS
3675 /* PyType_Ready is the closest thing we have to a choke point
3676 * for type objects, so is the best place I can think of to try
3677 * to get type objects into the doubly-linked list of all objects.
3678 * Still, not all type objects go thru PyType_Ready.
3679 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003680 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003681#endif
3682
Tim Peters6d6c1a32001-08-02 04:15:00 +00003683 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3684 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003685 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003686 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003687 Py_INCREF(base);
3688 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003689
Guido van Rossumd8faa362007-04-27 19:54:29 +00003690 /* Now the only way base can still be NULL is if type is
3691 * &PyBaseObject_Type.
3692 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003693
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003694 /* Initialize the base class */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003695 if (base != NULL && base->tp_dict == NULL) {
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003696 if (PyType_Ready(base) < 0)
3697 goto error;
3698 }
3699
Guido van Rossumd8faa362007-04-27 19:54:29 +00003700 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003701 compilable separately on Windows can call PyType_Ready() instead of
3702 initializing the ob_type field of their type objects. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003703 /* The test for base != NULL is really unnecessary, since base is only
3704 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3705 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3706 know that. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003707 if (Py_TYPE(type) == NULL && base != NULL)
3708 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003709
Tim Peters6d6c1a32001-08-02 04:15:00 +00003710 /* Initialize tp_bases */
3711 bases = type->tp_bases;
3712 if (bases == NULL) {
3713 if (base == NULL)
3714 bases = PyTuple_New(0);
3715 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003716 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003717 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003718 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003719 type->tp_bases = bases;
3720 }
3721
Guido van Rossum687ae002001-10-15 22:03:32 +00003722 /* Initialize tp_dict */
3723 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003724 if (dict == NULL) {
3725 dict = PyDict_New();
3726 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003727 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003728 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003729 }
3730
Guido van Rossum687ae002001-10-15 22:03:32 +00003731 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003732 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003733 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003734 if (type->tp_methods != NULL) {
3735 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003736 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003737 }
3738 if (type->tp_members != NULL) {
3739 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003740 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003741 }
3742 if (type->tp_getset != NULL) {
3743 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003744 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003745 }
3746
Tim Peters6d6c1a32001-08-02 04:15:00 +00003747 /* Calculate method resolution order */
3748 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003749 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003750 }
3751
Guido van Rossum13d52f02001-08-10 21:24:08 +00003752 /* Inherit special flags from dominant base */
3753 if (type->tp_base != NULL)
3754 inherit_special(type, type->tp_base);
3755
Tim Peters6d6c1a32001-08-02 04:15:00 +00003756 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003757 bases = type->tp_mro;
3758 assert(bases != NULL);
3759 assert(PyTuple_Check(bases));
3760 n = PyTuple_GET_SIZE(bases);
3761 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003762 PyObject *b = PyTuple_GET_ITEM(bases, i);
3763 if (PyType_Check(b))
3764 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003765 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003766
Tim Peters3cfe7542003-05-21 21:29:48 +00003767 /* Sanity check for tp_free. */
3768 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3769 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003770 /* This base class needs to call tp_free, but doesn't have
3771 * one, or its tp_free is for non-gc'ed objects.
3772 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003773 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3774 "gc and is a base type but has inappropriate "
3775 "tp_free slot",
3776 type->tp_name);
3777 goto error;
3778 }
3779
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003780 /* if the type dictionary doesn't contain a __doc__, set it from
3781 the tp_doc slot.
3782 */
3783 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3784 if (type->tp_doc != NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +00003785 PyObject *doc = PyUnicode_FromString(type->tp_doc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003786 if (doc == NULL)
3787 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003788 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3789 Py_DECREF(doc);
3790 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003791 PyDict_SetItemString(type->tp_dict,
3792 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003793 }
3794 }
3795
Guido van Rossum38938152006-08-21 23:36:26 +00003796 /* Hack for tp_hash and __hash__.
3797 If after all that, tp_hash is still NULL, and __hash__ is not in
3798 tp_dict, set tp_dict['__hash__'] equal to None.
3799 This signals that __hash__ is not inherited.
3800 */
3801 if (type->tp_hash == NULL) {
3802 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3803 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3804 goto error;
3805 }
3806 }
3807
Guido van Rossum13d52f02001-08-10 21:24:08 +00003808 /* Some more special stuff */
3809 base = type->tp_base;
3810 if (base != NULL) {
3811 if (type->tp_as_number == NULL)
3812 type->tp_as_number = base->tp_as_number;
3813 if (type->tp_as_sequence == NULL)
3814 type->tp_as_sequence = base->tp_as_sequence;
3815 if (type->tp_as_mapping == NULL)
3816 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003817 if (type->tp_as_buffer == NULL)
3818 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003819 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003820
Guido van Rossum1c450732001-10-08 15:18:27 +00003821 /* Link into each base class's list of subclasses */
3822 bases = type->tp_bases;
3823 n = PyTuple_GET_SIZE(bases);
3824 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003825 PyObject *b = PyTuple_GET_ITEM(bases, i);
3826 if (PyType_Check(b) &&
3827 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003828 goto error;
3829 }
3830
Guido van Rossum13d52f02001-08-10 21:24:08 +00003831 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003832 assert(type->tp_dict != NULL);
3833 type->tp_flags =
3834 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003835 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003836
3837 error:
3838 type->tp_flags &= ~Py_TPFLAGS_READYING;
3839 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003840}
3841
Guido van Rossum1c450732001-10-08 15:18:27 +00003842static int
3843add_subclass(PyTypeObject *base, PyTypeObject *type)
3844{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003845 Py_ssize_t i;
3846 int result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003847 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003848
3849 list = base->tp_subclasses;
3850 if (list == NULL) {
3851 base->tp_subclasses = list = PyList_New(0);
3852 if (list == NULL)
3853 return -1;
3854 }
3855 assert(PyList_Check(list));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003856 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003857 i = PyList_GET_SIZE(list);
3858 while (--i >= 0) {
3859 ref = PyList_GET_ITEM(list, i);
3860 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003861 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003862 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003863 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003864 result = PyList_Append(list, newobj);
3865 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003866 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003867}
3868
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003869static void
3870remove_subclass(PyTypeObject *base, PyTypeObject *type)
3871{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003872 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003873 PyObject *list, *ref;
3874
3875 list = base->tp_subclasses;
3876 if (list == NULL) {
3877 return;
3878 }
3879 assert(PyList_Check(list));
3880 i = PyList_GET_SIZE(list);
3881 while (--i >= 0) {
3882 ref = PyList_GET_ITEM(list, i);
3883 assert(PyWeakref_CheckRef(ref));
3884 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3885 /* this can't fail, right? */
3886 PySequence_DelItem(list, i);
3887 return;
3888 }
3889 }
3890}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003891
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003892static int
3893check_num_args(PyObject *ob, int n)
3894{
3895 if (!PyTuple_CheckExact(ob)) {
3896 PyErr_SetString(PyExc_SystemError,
3897 "PyArg_UnpackTuple() argument list is not a tuple");
3898 return 0;
3899 }
3900 if (n == PyTuple_GET_SIZE(ob))
3901 return 1;
3902 PyErr_Format(
3903 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003904 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003905 return 0;
3906}
3907
Tim Peters6d6c1a32001-08-02 04:15:00 +00003908/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3909
3910/* There's a wrapper *function* for each distinct function typedef used
Guido van Rossumd8faa362007-04-27 19:54:29 +00003911 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003912 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3913 Most tables have only one entry; the tables for binary operators have two
3914 entries, one regular and one with reversed arguments. */
3915
3916static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003917wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003918{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003919 lenfunc func = (lenfunc)wrapped;
3920 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003921
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003922 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003923 return NULL;
3924 res = (*func)(self);
3925 if (res == -1 && PyErr_Occurred())
3926 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00003927 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003928}
3929
Tim Peters6d6c1a32001-08-02 04:15:00 +00003930static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003931wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3932{
3933 inquiry func = (inquiry)wrapped;
3934 int res;
3935
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003936 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003937 return NULL;
3938 res = (*func)(self);
3939 if (res == -1 && PyErr_Occurred())
3940 return NULL;
3941 return PyBool_FromLong((long)res);
3942}
3943
3944static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003945wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3946{
3947 binaryfunc func = (binaryfunc)wrapped;
3948 PyObject *other;
3949
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003950 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003951 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003952 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003953 return (*func)(self, other);
3954}
3955
3956static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003957wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3958{
3959 binaryfunc func = (binaryfunc)wrapped;
3960 PyObject *other;
3961
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003962 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003963 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003964 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003965 return (*func)(self, other);
3966}
3967
3968static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003969wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3970{
3971 binaryfunc func = (binaryfunc)wrapped;
3972 PyObject *other;
3973
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003974 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003975 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003976 other = PyTuple_GET_ITEM(args, 0);
Christian Heimes90aa7642007-12-19 02:45:37 +00003977 if (!PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003978 Py_INCREF(Py_NotImplemented);
3979 return Py_NotImplemented;
3980 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003981 return (*func)(other, self);
3982}
3983
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003984static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003985wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3986{
3987 ternaryfunc func = (ternaryfunc)wrapped;
3988 PyObject *other;
3989 PyObject *third = Py_None;
3990
3991 /* Note: This wrapper only works for __pow__() */
3992
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003993 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003994 return NULL;
3995 return (*func)(self, other, third);
3996}
3997
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003998static PyObject *
3999wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4000{
4001 ternaryfunc func = (ternaryfunc)wrapped;
4002 PyObject *other;
4003 PyObject *third = Py_None;
4004
4005 /* Note: This wrapper only works for __pow__() */
4006
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004007 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004008 return NULL;
4009 return (*func)(other, self, third);
4010}
4011
Tim Peters6d6c1a32001-08-02 04:15:00 +00004012static PyObject *
4013wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4014{
4015 unaryfunc func = (unaryfunc)wrapped;
4016
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004017 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004018 return NULL;
4019 return (*func)(self);
4020}
4021
Tim Peters6d6c1a32001-08-02 04:15:00 +00004022static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004023wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004024{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004025 ssizeargfunc func = (ssizeargfunc)wrapped;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004026 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004027 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004028
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004029 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4030 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004031 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004032 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004033 return NULL;
4034 return (*func)(self, i);
4035}
4036
Martin v. Löwis18e16552006-02-15 17:27:45 +00004037static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004038getindex(PyObject *self, PyObject *arg)
4039{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004040 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004041
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004042 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004043 if (i == -1 && PyErr_Occurred())
4044 return -1;
4045 if (i < 0) {
Christian Heimes90aa7642007-12-19 02:45:37 +00004046 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004047 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00004048 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004049 if (n < 0)
4050 return -1;
4051 i += n;
4052 }
4053 }
4054 return i;
4055}
4056
4057static PyObject *
4058wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4059{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004060 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004061 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004062 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004063
Guido van Rossumf4593e02001-10-03 12:09:30 +00004064 if (PyTuple_GET_SIZE(args) == 1) {
4065 arg = PyTuple_GET_ITEM(args, 0);
4066 i = getindex(self, arg);
4067 if (i == -1 && PyErr_Occurred())
4068 return NULL;
4069 return (*func)(self, i);
4070 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004071 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004072 assert(PyErr_Occurred());
4073 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004074}
4075
Tim Peters6d6c1a32001-08-02 04:15:00 +00004076static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004077wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004078{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004079 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4080 Py_ssize_t i;
4081 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004082 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004083
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004084 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004085 return NULL;
4086 i = getindex(self, arg);
4087 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004088 return NULL;
4089 res = (*func)(self, i, value);
4090 if (res == -1 && PyErr_Occurred())
4091 return NULL;
4092 Py_INCREF(Py_None);
4093 return Py_None;
4094}
4095
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004096static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004097wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004098{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004099 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4100 Py_ssize_t i;
4101 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004102 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004103
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004104 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004105 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004106 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004107 i = getindex(self, arg);
4108 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004109 return NULL;
4110 res = (*func)(self, i, NULL);
4111 if (res == -1 && PyErr_Occurred())
4112 return NULL;
4113 Py_INCREF(Py_None);
4114 return Py_None;
4115}
4116
Tim Peters6d6c1a32001-08-02 04:15:00 +00004117/* XXX objobjproc is a misnomer; should be objargpred */
4118static PyObject *
4119wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4120{
4121 objobjproc func = (objobjproc)wrapped;
4122 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004123 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004124
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004125 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004126 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004127 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004128 res = (*func)(self, value);
4129 if (res == -1 && PyErr_Occurred())
4130 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004131 else
4132 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004133}
4134
Tim Peters6d6c1a32001-08-02 04:15:00 +00004135static PyObject *
4136wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4137{
4138 objobjargproc func = (objobjargproc)wrapped;
4139 int res;
4140 PyObject *key, *value;
4141
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004142 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004143 return NULL;
4144 res = (*func)(self, key, value);
4145 if (res == -1 && PyErr_Occurred())
4146 return NULL;
4147 Py_INCREF(Py_None);
4148 return Py_None;
4149}
4150
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004151static PyObject *
4152wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4153{
4154 objobjargproc func = (objobjargproc)wrapped;
4155 int res;
4156 PyObject *key;
4157
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004158 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004159 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004160 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004161 res = (*func)(self, key, NULL);
4162 if (res == -1 && PyErr_Occurred())
4163 return NULL;
4164 Py_INCREF(Py_None);
4165 return Py_None;
4166}
4167
Tim Peters6d6c1a32001-08-02 04:15:00 +00004168static PyObject *
4169wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
4170{
4171 cmpfunc func = (cmpfunc)wrapped;
4172 int res;
4173 PyObject *other;
4174
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004175 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004176 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004177 other = PyTuple_GET_ITEM(args, 0);
Christian Heimes90aa7642007-12-19 02:45:37 +00004178 if (Py_TYPE(other)->tp_compare != func &&
4179 !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
Guido van Rossumceccae52001-09-18 20:03:57 +00004180 PyErr_Format(
4181 PyExc_TypeError,
4182 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
Christian Heimes90aa7642007-12-19 02:45:37 +00004183 Py_TYPE(self)->tp_name,
4184 Py_TYPE(self)->tp_name,
4185 Py_TYPE(other)->tp_name);
Guido van Rossumceccae52001-09-18 20:03:57 +00004186 return NULL;
4187 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004188 res = (*func)(self, other);
4189 if (PyErr_Occurred())
4190 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00004191 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004192}
4193
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004194/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004195 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004196static int
4197hackcheck(PyObject *self, setattrofunc func, char *what)
4198{
Christian Heimes90aa7642007-12-19 02:45:37 +00004199 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004200 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4201 type = type->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004202 /* If type is NULL now, this is a really weird type.
4203 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004204 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004205 PyErr_Format(PyExc_TypeError,
4206 "can't apply this %s to %s object",
4207 what,
4208 type->tp_name);
4209 return 0;
4210 }
4211 return 1;
4212}
4213
Tim Peters6d6c1a32001-08-02 04:15:00 +00004214static PyObject *
4215wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4216{
4217 setattrofunc func = (setattrofunc)wrapped;
4218 int res;
4219 PyObject *name, *value;
4220
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004221 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004222 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004223 if (!hackcheck(self, func, "__setattr__"))
4224 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004225 res = (*func)(self, name, value);
4226 if (res < 0)
4227 return NULL;
4228 Py_INCREF(Py_None);
4229 return Py_None;
4230}
4231
4232static PyObject *
4233wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4234{
4235 setattrofunc func = (setattrofunc)wrapped;
4236 int res;
4237 PyObject *name;
4238
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004239 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004240 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004241 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004242 if (!hackcheck(self, func, "__delattr__"))
4243 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004244 res = (*func)(self, name, NULL);
4245 if (res < 0)
4246 return NULL;
4247 Py_INCREF(Py_None);
4248 return Py_None;
4249}
4250
Tim Peters6d6c1a32001-08-02 04:15:00 +00004251static PyObject *
4252wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4253{
4254 hashfunc func = (hashfunc)wrapped;
4255 long res;
4256
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004257 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004258 return NULL;
4259 res = (*func)(self);
4260 if (res == -1 && PyErr_Occurred())
4261 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00004262 return PyLong_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004263}
4264
Tim Peters6d6c1a32001-08-02 04:15:00 +00004265static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004266wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004267{
4268 ternaryfunc func = (ternaryfunc)wrapped;
4269
Guido van Rossumc8e56452001-10-22 00:43:43 +00004270 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004271}
4272
Tim Peters6d6c1a32001-08-02 04:15:00 +00004273static PyObject *
4274wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4275{
4276 richcmpfunc func = (richcmpfunc)wrapped;
4277 PyObject *other;
4278
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004279 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004280 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004281 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004282 return (*func)(self, other, op);
4283}
4284
4285#undef RICHCMP_WRAPPER
4286#define RICHCMP_WRAPPER(NAME, OP) \
4287static PyObject * \
4288richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4289{ \
4290 return wrap_richcmpfunc(self, args, wrapped, OP); \
4291}
4292
Jack Jansen8e938b42001-08-08 15:29:49 +00004293RICHCMP_WRAPPER(lt, Py_LT)
4294RICHCMP_WRAPPER(le, Py_LE)
4295RICHCMP_WRAPPER(eq, Py_EQ)
4296RICHCMP_WRAPPER(ne, Py_NE)
4297RICHCMP_WRAPPER(gt, Py_GT)
4298RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004299
Tim Peters6d6c1a32001-08-02 04:15:00 +00004300static PyObject *
4301wrap_next(PyObject *self, PyObject *args, void *wrapped)
4302{
4303 unaryfunc func = (unaryfunc)wrapped;
4304 PyObject *res;
4305
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004306 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004307 return NULL;
4308 res = (*func)(self);
4309 if (res == NULL && !PyErr_Occurred())
4310 PyErr_SetNone(PyExc_StopIteration);
4311 return res;
4312}
4313
Tim Peters6d6c1a32001-08-02 04:15:00 +00004314static PyObject *
4315wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4316{
4317 descrgetfunc func = (descrgetfunc)wrapped;
4318 PyObject *obj;
4319 PyObject *type = NULL;
4320
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004321 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004322 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004323 if (obj == Py_None)
4324 obj = NULL;
4325 if (type == Py_None)
4326 type = NULL;
4327 if (type == NULL &&obj == NULL) {
4328 PyErr_SetString(PyExc_TypeError,
4329 "__get__(None, None) is invalid");
4330 return NULL;
4331 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004332 return (*func)(self, obj, type);
4333}
4334
Tim Peters6d6c1a32001-08-02 04:15:00 +00004335static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004336wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004337{
4338 descrsetfunc func = (descrsetfunc)wrapped;
4339 PyObject *obj, *value;
4340 int ret;
4341
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004342 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004343 return NULL;
4344 ret = (*func)(self, obj, value);
4345 if (ret < 0)
4346 return NULL;
4347 Py_INCREF(Py_None);
4348 return Py_None;
4349}
Guido van Rossum22b13872002-08-06 21:41:44 +00004350
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004351static PyObject *
4352wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4353{
4354 descrsetfunc func = (descrsetfunc)wrapped;
4355 PyObject *obj;
4356 int ret;
4357
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004358 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004359 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004360 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004361 ret = (*func)(self, obj, NULL);
4362 if (ret < 0)
4363 return NULL;
4364 Py_INCREF(Py_None);
4365 return Py_None;
4366}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004367
Tim Peters6d6c1a32001-08-02 04:15:00 +00004368static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004369wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004370{
4371 initproc func = (initproc)wrapped;
4372
Guido van Rossumc8e56452001-10-22 00:43:43 +00004373 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004374 return NULL;
4375 Py_INCREF(Py_None);
4376 return Py_None;
4377}
4378
Tim Peters6d6c1a32001-08-02 04:15:00 +00004379static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004380tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004381{
Barry Warsaw60f01882001-08-22 19:24:42 +00004382 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004383 PyObject *arg0, *res;
4384
4385 if (self == NULL || !PyType_Check(self))
4386 Py_FatalError("__new__() called with non-type 'self'");
4387 type = (PyTypeObject *)self;
4388 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004389 PyErr_Format(PyExc_TypeError,
4390 "%s.__new__(): not enough arguments",
4391 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004392 return NULL;
4393 }
4394 arg0 = PyTuple_GET_ITEM(args, 0);
4395 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004396 PyErr_Format(PyExc_TypeError,
4397 "%s.__new__(X): X is not a type object (%s)",
4398 type->tp_name,
Christian Heimes90aa7642007-12-19 02:45:37 +00004399 Py_TYPE(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004400 return NULL;
4401 }
4402 subtype = (PyTypeObject *)arg0;
4403 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004404 PyErr_Format(PyExc_TypeError,
4405 "%s.__new__(%s): %s is not a subtype of %s",
4406 type->tp_name,
4407 subtype->tp_name,
4408 subtype->tp_name,
4409 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004410 return NULL;
4411 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004412
4413 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004414 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004415 most derived base that's not a heap type is this type. */
4416 staticbase = subtype;
4417 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4418 staticbase = staticbase->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004419 /* If staticbase is NULL now, it is a really weird type.
4420 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004421 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004422 PyErr_Format(PyExc_TypeError,
4423 "%s.__new__(%s) is not safe, use %s.__new__()",
4424 type->tp_name,
4425 subtype->tp_name,
4426 staticbase == NULL ? "?" : staticbase->tp_name);
4427 return NULL;
4428 }
4429
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004430 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4431 if (args == NULL)
4432 return NULL;
4433 res = type->tp_new(subtype, args, kwds);
4434 Py_DECREF(args);
4435 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004436}
4437
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004438static struct PyMethodDef tp_new_methoddef[] = {
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004439 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004440 PyDoc_STR("T.__new__(S, ...) -> "
Guido van Rossumd8faa362007-04-27 19:54:29 +00004441 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004442 {0}
4443};
4444
4445static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004446add_tp_new_wrapper(PyTypeObject *type)
4447{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004448 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004449
Guido van Rossum687ae002001-10-15 22:03:32 +00004450 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004451 return 0;
4452 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004453 if (func == NULL)
4454 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004455 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004456 Py_DECREF(func);
4457 return -1;
4458 }
4459 Py_DECREF(func);
4460 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004461}
4462
Guido van Rossumf040ede2001-08-07 16:40:56 +00004463/* Slot wrappers that call the corresponding __foo__ slot. See comments
4464 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004465
Guido van Rossumdc91b992001-08-08 22:26:22 +00004466#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004467static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004468FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004469{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004470 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004471 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004472}
4473
Guido van Rossumdc91b992001-08-08 22:26:22 +00004474#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004475static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004476FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004477{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004478 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004479 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004480}
4481
Guido van Rossumcd118802003-01-06 22:57:47 +00004482/* Boolean helper for SLOT1BINFULL().
4483 right.__class__ is a nontrivial subclass of left.__class__. */
4484static int
4485method_is_overloaded(PyObject *left, PyObject *right, char *name)
4486{
4487 PyObject *a, *b;
4488 int ok;
4489
Christian Heimes90aa7642007-12-19 02:45:37 +00004490 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004491 if (b == NULL) {
4492 PyErr_Clear();
4493 /* If right doesn't have it, it's not overloaded */
4494 return 0;
4495 }
4496
Christian Heimes90aa7642007-12-19 02:45:37 +00004497 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004498 if (a == NULL) {
4499 PyErr_Clear();
4500 Py_DECREF(b);
4501 /* If right has it but left doesn't, it's overloaded */
4502 return 1;
4503 }
4504
4505 ok = PyObject_RichCompareBool(a, b, Py_NE);
4506 Py_DECREF(a);
4507 Py_DECREF(b);
4508 if (ok < 0) {
4509 PyErr_Clear();
4510 return 0;
4511 }
4512
4513 return ok;
4514}
4515
Guido van Rossumdc91b992001-08-08 22:26:22 +00004516
4517#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004518static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004519FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004520{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004521 static PyObject *cache_str, *rcache_str; \
Christian Heimes90aa7642007-12-19 02:45:37 +00004522 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4523 Py_TYPE(other)->tp_as_number != NULL && \
4524 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4525 if (Py_TYPE(self)->tp_as_number != NULL && \
4526 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004527 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004528 if (do_other && \
Christian Heimes90aa7642007-12-19 02:45:37 +00004529 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004530 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004531 r = call_maybe( \
4532 other, ROPSTR, &rcache_str, "(O)", self); \
4533 if (r != Py_NotImplemented) \
4534 return r; \
4535 Py_DECREF(r); \
4536 do_other = 0; \
4537 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004538 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004539 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004540 if (r != Py_NotImplemented || \
Christian Heimes90aa7642007-12-19 02:45:37 +00004541 Py_TYPE(other) == Py_TYPE(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004542 return r; \
4543 Py_DECREF(r); \
4544 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004545 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004546 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004547 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004548 } \
4549 Py_INCREF(Py_NotImplemented); \
4550 return Py_NotImplemented; \
4551}
4552
4553#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4554 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4555
4556#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4557static PyObject * \
4558FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4559{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004560 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004561 return call_method(self, OPSTR, &cache_str, \
4562 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004563}
4564
Martin v. Löwis18e16552006-02-15 17:27:45 +00004565static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004566slot_sq_length(PyObject *self)
4567{
Guido van Rossum2730b132001-08-28 18:22:14 +00004568 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004569 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004570 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004571
4572 if (res == NULL)
4573 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00004574 len = PyLong_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004575 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004576 if (len < 0) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00004577 if (!PyErr_Occurred())
4578 PyErr_SetString(PyExc_ValueError,
4579 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004580 return -1;
4581 }
Guido van Rossum26111622001-10-01 16:42:49 +00004582 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004583}
4584
Guido van Rossumf4593e02001-10-03 12:09:30 +00004585/* Super-optimized version of slot_sq_item.
4586 Other slots could do the same... */
4587static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004588slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004589{
4590 static PyObject *getitem_str;
4591 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4592 descrgetfunc f;
4593
4594 if (getitem_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004595 getitem_str = PyUnicode_InternFromString("__getitem__");
Guido van Rossumf4593e02001-10-03 12:09:30 +00004596 if (getitem_str == NULL)
4597 return NULL;
4598 }
Christian Heimes90aa7642007-12-19 02:45:37 +00004599 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004600 if (func != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +00004601 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004602 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004603 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00004604 func = f(func, self, (PyObject *)(Py_TYPE(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004605 if (func == NULL) {
4606 return NULL;
4607 }
4608 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004609 ival = PyLong_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004610 if (ival != NULL) {
4611 args = PyTuple_New(1);
4612 if (args != NULL) {
4613 PyTuple_SET_ITEM(args, 0, ival);
4614 retval = PyObject_Call(func, args, NULL);
4615 Py_XDECREF(args);
4616 Py_XDECREF(func);
4617 return retval;
4618 }
4619 }
4620 }
4621 else {
4622 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4623 }
4624 Py_XDECREF(args);
4625 Py_XDECREF(ival);
4626 Py_XDECREF(func);
4627 return NULL;
4628}
4629
Tim Peters6d6c1a32001-08-02 04:15:00 +00004630static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004631slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004632{
4633 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004634 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004635
4636 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004637 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004638 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004639 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004640 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004641 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004642 if (res == NULL)
4643 return -1;
4644 Py_DECREF(res);
4645 return 0;
4646}
4647
4648static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00004649slot_sq_contains(PyObject *self, PyObject *value)
4650{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004651 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004652 int result = -1;
4653
Guido van Rossum60718732001-08-28 17:47:51 +00004654 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004655
Guido van Rossum55f20992001-10-01 17:18:22 +00004656 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004657 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004658 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004659 if (args == NULL)
4660 res = NULL;
4661 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004662 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004663 Py_DECREF(args);
4664 }
4665 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004666 if (res != NULL) {
4667 result = PyObject_IsTrue(res);
4668 Py_DECREF(res);
4669 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004670 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004671 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004672 /* Possible results: -1 and 1 */
4673 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004674 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004675 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004676 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004677}
4678
Tim Peters6d6c1a32001-08-02 04:15:00 +00004679#define slot_mp_length slot_sq_length
4680
Guido van Rossumdc91b992001-08-08 22:26:22 +00004681SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004682
4683static int
4684slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4685{
4686 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004687 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004688
4689 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004690 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004691 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004692 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004693 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004694 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004695 if (res == NULL)
4696 return -1;
4697 Py_DECREF(res);
4698 return 0;
4699}
4700
Guido van Rossumdc91b992001-08-08 22:26:22 +00004701SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4702SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4703SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004704SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4705SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4706
Jeremy Hylton938ace62002-07-17 16:30:39 +00004707static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004708
4709SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4710 nb_power, "__pow__", "__rpow__")
4711
4712static PyObject *
4713slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4714{
Guido van Rossum2730b132001-08-28 18:22:14 +00004715 static PyObject *pow_str;
4716
Guido van Rossumdc91b992001-08-08 22:26:22 +00004717 if (modulus == Py_None)
4718 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004719 /* Three-arg power doesn't use __rpow__. But ternary_op
4720 can call this when the second argument's type uses
4721 slot_nb_power, so check before calling self.__pow__. */
Christian Heimes90aa7642007-12-19 02:45:37 +00004722 if (Py_TYPE(self)->tp_as_number != NULL &&
4723 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00004724 return call_method(self, "__pow__", &pow_str,
4725 "(OO)", other, modulus);
4726 }
4727 Py_INCREF(Py_NotImplemented);
4728 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004729}
4730
4731SLOT0(slot_nb_negative, "__neg__")
4732SLOT0(slot_nb_positive, "__pos__")
4733SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004734
4735static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004736slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004737{
Tim Petersea7f75d2002-12-07 21:39:16 +00004738 PyObject *func, *args;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004739 static PyObject *bool_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004740 int result = -1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004741 int from_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004742
Jack Diederich4dafcc42006-11-28 19:15:13 +00004743 func = lookup_maybe(self, "__bool__", &bool_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004744 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004745 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004746 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004747 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004748 if (func == NULL)
4749 return PyErr_Occurred() ? -1 : 1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004750 from_len = 1;
Tim Petersea7f75d2002-12-07 21:39:16 +00004751 }
4752 args = PyTuple_New(0);
4753 if (args != NULL) {
4754 PyObject *temp = PyObject_Call(func, args, NULL);
4755 Py_DECREF(args);
4756 if (temp != NULL) {
Jack Diederich4dafcc42006-11-28 19:15:13 +00004757 if (from_len) {
4758 /* enforced by slot_nb_len */
Jeremy Hylton090a3492003-06-27 16:46:45 +00004759 result = PyObject_IsTrue(temp);
Jack Diederich4dafcc42006-11-28 19:15:13 +00004760 }
4761 else if (PyBool_Check(temp)) {
4762 result = PyObject_IsTrue(temp);
4763 }
Jeremy Hylton090a3492003-06-27 16:46:45 +00004764 else {
4765 PyErr_Format(PyExc_TypeError,
Jack Diederich4dafcc42006-11-28 19:15:13 +00004766 "__bool__ should return "
4767 "bool, returned %s",
Christian Heimes90aa7642007-12-19 02:45:37 +00004768 Py_TYPE(temp)->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004769 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004770 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004771 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004772 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004773 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004774 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004775 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004776}
4777
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004778
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004779static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004780slot_nb_index(PyObject *self)
4781{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004782 static PyObject *index_str;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004783 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004784}
4785
4786
Guido van Rossumdc91b992001-08-08 22:26:22 +00004787SLOT0(slot_nb_invert, "__invert__")
4788SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4789SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4790SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4791SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4792SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004793
Guido van Rossumdc91b992001-08-08 22:26:22 +00004794SLOT0(slot_nb_int, "__int__")
4795SLOT0(slot_nb_long, "__long__")
4796SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004797SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4798SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4799SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004800SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004801/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4802static PyObject *
4803slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4804{
4805 static PyObject *cache_str;
4806 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4807}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004808SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4809SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4810SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4811SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4812SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4813SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4814 "__floordiv__", "__rfloordiv__")
4815SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4816SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4817SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004818
4819static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004820half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004821{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004822 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004823 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004824 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004825
Guido van Rossum60718732001-08-28 17:47:51 +00004826 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004827 if (func == NULL) {
4828 PyErr_Clear();
4829 }
4830 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004831 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004832 if (args == NULL)
4833 res = NULL;
4834 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004835 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004836 Py_DECREF(args);
4837 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004838 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004839 if (res != Py_NotImplemented) {
4840 if (res == NULL)
4841 return -2;
Christian Heimes217cfd12007-12-02 14:31:20 +00004842 c = PyLong_AsLong(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004843 Py_DECREF(res);
4844 if (c == -1 && PyErr_Occurred())
4845 return -2;
4846 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4847 }
4848 Py_DECREF(res);
4849 }
4850 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004851}
4852
Guido van Rossumab3b0342001-09-18 20:38:53 +00004853/* This slot is published for the benefit of try_3way_compare in object.c */
4854int
4855_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004856{
4857 int c;
4858
Christian Heimes90aa7642007-12-19 02:45:37 +00004859 if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004860 c = half_compare(self, other);
4861 if (c <= 1)
4862 return c;
4863 }
Christian Heimes90aa7642007-12-19 02:45:37 +00004864 if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004865 c = half_compare(other, self);
4866 if (c < -1)
4867 return -2;
4868 if (c <= 1)
4869 return -c;
4870 }
4871 return (void *)self < (void *)other ? -1 :
4872 (void *)self > (void *)other ? 1 : 0;
4873}
4874
4875static PyObject *
4876slot_tp_repr(PyObject *self)
4877{
4878 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004879 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004880
Guido van Rossum60718732001-08-28 17:47:51 +00004881 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004882 if (func != NULL) {
4883 res = PyEval_CallObject(func, NULL);
4884 Py_DECREF(func);
4885 return res;
4886 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004887 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004888 return PyUnicode_FromFormat("<%s object at %p>",
Christian Heimes90aa7642007-12-19 02:45:37 +00004889 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004890}
4891
4892static PyObject *
4893slot_tp_str(PyObject *self)
4894{
4895 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004896 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004897
Guido van Rossum60718732001-08-28 17:47:51 +00004898 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004899 if (func != NULL) {
4900 res = PyEval_CallObject(func, NULL);
4901 Py_DECREF(func);
4902 return res;
4903 }
4904 else {
Walter Dörwald1ab83302007-05-18 17:15:44 +00004905 PyObject *ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004906 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004907 res = slot_tp_repr(self);
4908 if (!res)
4909 return NULL;
4910 ress = _PyUnicode_AsDefaultEncodedString(res, NULL);
4911 Py_DECREF(res);
4912 return ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004913 }
4914}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004915
4916static long
4917slot_tp_hash(PyObject *self)
4918{
Guido van Rossum4011a242006-08-17 23:09:57 +00004919 PyObject *func, *res;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004920 static PyObject *hash_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004921 long h;
4922
Guido van Rossum60718732001-08-28 17:47:51 +00004923 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004924
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004925 if (func == Py_None) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004926 Py_DECREF(func);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004927 func = NULL;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004928 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004929
4930 if (func == NULL) {
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004931 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
Christian Heimes90aa7642007-12-19 02:45:37 +00004932 Py_TYPE(self)->tp_name);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004933 return -1;
4934 }
4935
Guido van Rossum4011a242006-08-17 23:09:57 +00004936 res = PyEval_CallObject(func, NULL);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004937 Py_DECREF(func);
4938 if (res == NULL)
4939 return -1;
4940 if (PyLong_Check(res))
4941 h = PyLong_Type.tp_hash(res);
4942 else
Christian Heimes217cfd12007-12-02 14:31:20 +00004943 h = PyLong_AsLong(res);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004944 Py_DECREF(res);
4945 if (h == -1 && !PyErr_Occurred())
4946 h = -2;
4947 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004948}
4949
4950static PyObject *
4951slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4952{
Guido van Rossum60718732001-08-28 17:47:51 +00004953 static PyObject *call_str;
4954 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004955 PyObject *res;
4956
4957 if (meth == NULL)
4958 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004959
Tim Peters6d6c1a32001-08-02 04:15:00 +00004960 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004961
Tim Peters6d6c1a32001-08-02 04:15:00 +00004962 Py_DECREF(meth);
4963 return res;
4964}
4965
Guido van Rossum14a6f832001-10-17 13:59:09 +00004966/* There are two slot dispatch functions for tp_getattro.
4967
4968 - slot_tp_getattro() is used when __getattribute__ is overridden
4969 but no __getattr__ hook is present;
4970
4971 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4972
Guido van Rossumc334df52002-04-04 23:44:47 +00004973 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4974 detects the absence of __getattr__ and then installs the simpler slot if
4975 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004976
Tim Peters6d6c1a32001-08-02 04:15:00 +00004977static PyObject *
4978slot_tp_getattro(PyObject *self, PyObject *name)
4979{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004980 static PyObject *getattribute_str = NULL;
4981 return call_method(self, "__getattribute__", &getattribute_str,
4982 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004983}
4984
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004985static PyObject *
4986slot_tp_getattr_hook(PyObject *self, PyObject *name)
4987{
Christian Heimes90aa7642007-12-19 02:45:37 +00004988 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004989 PyObject *getattr, *getattribute, *res;
4990 static PyObject *getattribute_str = NULL;
4991 static PyObject *getattr_str = NULL;
4992
4993 if (getattr_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004994 getattr_str = PyUnicode_InternFromString("__getattr__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004995 if (getattr_str == NULL)
4996 return NULL;
4997 }
4998 if (getattribute_str == NULL) {
4999 getattribute_str =
Martin v. Löwis5b222132007-06-10 09:51:05 +00005000 PyUnicode_InternFromString("__getattribute__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005001 if (getattribute_str == NULL)
5002 return NULL;
5003 }
5004 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005005 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005006 /* No __getattr__ hook: use a simpler dispatcher */
5007 tp->tp_getattro = slot_tp_getattro;
5008 return slot_tp_getattro(self, name);
5009 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005010 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005011 if (getattribute == NULL ||
Christian Heimes90aa7642007-12-19 02:45:37 +00005012 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00005013 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5014 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005015 res = PyObject_GenericGetAttr(self, name);
5016 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00005017 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005018 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005019 PyErr_Clear();
Thomas Wouters477c8d52006-05-27 19:21:47 +00005020 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005021 }
5022 return res;
5023}
5024
Tim Peters6d6c1a32001-08-02 04:15:00 +00005025static int
5026slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5027{
5028 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005029 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005030
5031 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00005032 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005033 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005034 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005035 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005036 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005037 if (res == NULL)
5038 return -1;
5039 Py_DECREF(res);
5040 return 0;
5041}
5042
Guido van Rossumf5243f02008-01-01 04:06:48 +00005043static char *name_op[] = {
5044 "__lt__",
5045 "__le__",
5046 "__eq__",
5047 "__ne__",
5048 "__gt__",
5049 "__ge__",
5050};
5051
Tim Peters6d6c1a32001-08-02 04:15:00 +00005052static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005053half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005054{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005055 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005056 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005057
Guido van Rossum60718732001-08-28 17:47:51 +00005058 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005059 if (func == NULL) {
5060 PyErr_Clear();
5061 Py_INCREF(Py_NotImplemented);
5062 return Py_NotImplemented;
5063 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005064 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005065 if (args == NULL)
5066 res = NULL;
5067 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005068 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005069 Py_DECREF(args);
5070 }
5071 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005072 return res;
5073}
5074
Guido van Rossumb8f63662001-08-15 23:57:02 +00005075static PyObject *
5076slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5077{
5078 PyObject *res;
5079
Christian Heimes90aa7642007-12-19 02:45:37 +00005080 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005081 res = half_richcompare(self, other, op);
5082 if (res != Py_NotImplemented)
5083 return res;
5084 Py_DECREF(res);
5085 }
Christian Heimes90aa7642007-12-19 02:45:37 +00005086 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00005087 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005088 if (res != Py_NotImplemented) {
5089 return res;
5090 }
5091 Py_DECREF(res);
5092 }
5093 Py_INCREF(Py_NotImplemented);
5094 return Py_NotImplemented;
5095}
5096
5097static PyObject *
5098slot_tp_iter(PyObject *self)
5099{
5100 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005101 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005102
Guido van Rossum60718732001-08-28 17:47:51 +00005103 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005104 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00005105 PyObject *args;
5106 args = res = PyTuple_New(0);
5107 if (args != NULL) {
5108 res = PyObject_Call(func, args, NULL);
5109 Py_DECREF(args);
5110 }
5111 Py_DECREF(func);
5112 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005113 }
5114 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005115 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005116 if (func == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005117 PyErr_Format(PyExc_TypeError,
5118 "'%.200s' object is not iterable",
Christian Heimes90aa7642007-12-19 02:45:37 +00005119 Py_TYPE(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005120 return NULL;
5121 }
5122 Py_DECREF(func);
5123 return PySeqIter_New(self);
5124}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005125
5126static PyObject *
5127slot_tp_iternext(PyObject *self)
5128{
Guido van Rossum2730b132001-08-28 18:22:14 +00005129 static PyObject *next_str;
Georg Brandla18af4e2007-04-21 15:47:16 +00005130 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005131}
5132
Guido van Rossum1a493502001-08-17 16:47:50 +00005133static PyObject *
5134slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5135{
Christian Heimes90aa7642007-12-19 02:45:37 +00005136 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00005137 PyObject *get;
5138 static PyObject *get_str = NULL;
5139
5140 if (get_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005141 get_str = PyUnicode_InternFromString("__get__");
Guido van Rossum1a493502001-08-17 16:47:50 +00005142 if (get_str == NULL)
5143 return NULL;
5144 }
5145 get = _PyType_Lookup(tp, get_str);
5146 if (get == NULL) {
5147 /* Avoid further slowdowns */
5148 if (tp->tp_descr_get == slot_tp_descr_get)
5149 tp->tp_descr_get = NULL;
5150 Py_INCREF(self);
5151 return self;
5152 }
Guido van Rossum2c252392001-08-24 10:13:31 +00005153 if (obj == NULL)
5154 obj = Py_None;
5155 if (type == NULL)
5156 type = Py_None;
Thomas Wouters477c8d52006-05-27 19:21:47 +00005157 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005158}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005159
5160static int
5161slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5162{
Guido van Rossum2c252392001-08-24 10:13:31 +00005163 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005164 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005165
5166 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00005167 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005168 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00005169 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005170 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005171 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005172 if (res == NULL)
5173 return -1;
5174 Py_DECREF(res);
5175 return 0;
5176}
5177
5178static int
5179slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5180{
Guido van Rossum60718732001-08-28 17:47:51 +00005181 static PyObject *init_str;
5182 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005183 PyObject *res;
5184
5185 if (meth == NULL)
5186 return -1;
5187 res = PyObject_Call(meth, args, kwds);
5188 Py_DECREF(meth);
5189 if (res == NULL)
5190 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005191 if (res != Py_None) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005192 PyErr_Format(PyExc_TypeError,
5193 "__init__() should return None, not '%.200s'",
Christian Heimes90aa7642007-12-19 02:45:37 +00005194 Py_TYPE(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005195 Py_DECREF(res);
5196 return -1;
5197 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005198 Py_DECREF(res);
5199 return 0;
5200}
5201
5202static PyObject *
5203slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5204{
Guido van Rossum7bed2132002-08-08 21:57:53 +00005205 static PyObject *new_str;
5206 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005207 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005208 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005209
Guido van Rossum7bed2132002-08-08 21:57:53 +00005210 if (new_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005211 new_str = PyUnicode_InternFromString("__new__");
Guido van Rossum7bed2132002-08-08 21:57:53 +00005212 if (new_str == NULL)
5213 return NULL;
5214 }
5215 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005216 if (func == NULL)
5217 return NULL;
5218 assert(PyTuple_Check(args));
5219 n = PyTuple_GET_SIZE(args);
5220 newargs = PyTuple_New(n+1);
5221 if (newargs == NULL)
5222 return NULL;
5223 Py_INCREF(type);
5224 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5225 for (i = 0; i < n; i++) {
5226 x = PyTuple_GET_ITEM(args, i);
5227 Py_INCREF(x);
5228 PyTuple_SET_ITEM(newargs, i+1, x);
5229 }
5230 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005231 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005232 Py_DECREF(func);
5233 return x;
5234}
5235
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005236static void
5237slot_tp_del(PyObject *self)
5238{
5239 static PyObject *del_str = NULL;
5240 PyObject *del, *res;
5241 PyObject *error_type, *error_value, *error_traceback;
5242
5243 /* Temporarily resurrect the object. */
5244 assert(self->ob_refcnt == 0);
5245 self->ob_refcnt = 1;
5246
5247 /* Save the current exception, if any. */
5248 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5249
5250 /* Execute __del__ method, if any. */
5251 del = lookup_maybe(self, "__del__", &del_str);
5252 if (del != NULL) {
5253 res = PyEval_CallObject(del, NULL);
5254 if (res == NULL)
5255 PyErr_WriteUnraisable(del);
5256 else
5257 Py_DECREF(res);
5258 Py_DECREF(del);
5259 }
5260
5261 /* Restore the saved exception. */
5262 PyErr_Restore(error_type, error_value, error_traceback);
5263
5264 /* Undo the temporary resurrection; can't use DECREF here, it would
5265 * cause a recursive call.
5266 */
5267 assert(self->ob_refcnt > 0);
5268 if (--self->ob_refcnt == 0)
5269 return; /* this is the normal path out */
5270
5271 /* __del__ resurrected it! Make it look like the original Py_DECREF
5272 * never happened.
5273 */
5274 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005275 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005276 _Py_NewReference(self);
5277 self->ob_refcnt = refcnt;
5278 }
Christian Heimes90aa7642007-12-19 02:45:37 +00005279 assert(!PyType_IS_GC(Py_TYPE(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005280 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005281 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5282 * we need to undo that. */
5283 _Py_DEC_REFTOTAL;
5284 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5285 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005286 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5287 * _Py_NewReference bumped tp_allocs: both of those need to be
5288 * undone.
5289 */
5290#ifdef COUNT_ALLOCS
Christian Heimes90aa7642007-12-19 02:45:37 +00005291 --Py_TYPE(self)->tp_frees;
5292 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005293#endif
5294}
5295
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005296
5297/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005298 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005299 structure, which incorporates the additional structures used for numbers,
5300 sequences and mappings.
5301 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005302 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005303 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5304 terminated with an all-zero entry. (This table is further initialized and
5305 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005306
Guido van Rossum6d204072001-10-21 00:44:31 +00005307typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005308
5309#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005310#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005311#undef ETSLOT
5312#undef SQSLOT
5313#undef MPSLOT
5314#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005315#undef UNSLOT
5316#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005317#undef BINSLOT
5318#undef RBINSLOT
5319
Guido van Rossum6d204072001-10-21 00:44:31 +00005320#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005321 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5322 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005323#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5324 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005325 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005326#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005327 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005328 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005329#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5330 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5331#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5332 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5333#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5334 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5335#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5336 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5337 "x." NAME "() <==> " DOC)
5338#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5339 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5340 "x." NAME "(y) <==> x" DOC "y")
5341#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5342 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5343 "x." NAME "(y) <==> x" DOC "y")
5344#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5345 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5346 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005347#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5348 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5349 "x." NAME "(y) <==> " DOC)
5350#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5351 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5352 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005353
5354static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005355 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005356 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005357 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5358 The logic in abstract.c always falls back to nb_add/nb_multiply in
5359 this case. Defining both the nb_* and the sq_* slots to call the
5360 user-defined methods has unexpected side-effects, as shown by
5361 test_descr.notimplemented() */
5362 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005363 "x.__add__(y) <==> x+y"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005364 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005365 "x.__mul__(n) <==> x*n"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005366 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005367 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005368 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5369 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005370 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005371 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005372 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005373 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005374 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5375 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005376 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005377 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005378 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005379 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005380
Martin v. Löwis18e16552006-02-15 17:27:45 +00005381 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005382 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005383 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005384 wrap_binaryfunc,
5385 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005386 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005387 wrap_objobjargproc,
5388 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005389 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005390 wrap_delitem,
5391 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005392
Guido van Rossum6d204072001-10-21 00:44:31 +00005393 BINSLOT("__add__", nb_add, slot_nb_add,
5394 "+"),
5395 RBINSLOT("__radd__", nb_add, slot_nb_add,
5396 "+"),
5397 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5398 "-"),
5399 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5400 "-"),
5401 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5402 "*"),
5403 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5404 "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005405 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5406 "%"),
5407 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5408 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005409 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005410 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005411 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005412 "divmod(y, x)"),
5413 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5414 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5415 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5416 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5417 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5418 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5419 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5420 "abs(x)"),
Jack Diederich4dafcc42006-11-28 19:15:13 +00005421 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005422 "x != 0"),
5423 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5424 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5425 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5426 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5427 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5428 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5429 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5430 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5431 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5432 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5433 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005434 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5435 "int(x)"),
5436 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5437 "long(x)"),
5438 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5439 "float(x)"),
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005440 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005441 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005442 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5443 wrap_binaryfunc, "+"),
5444 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5445 wrap_binaryfunc, "-"),
5446 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5447 wrap_binaryfunc, "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005448 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5449 wrap_binaryfunc, "%"),
5450 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005451 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005452 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5453 wrap_binaryfunc, "<<"),
5454 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5455 wrap_binaryfunc, ">>"),
5456 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5457 wrap_binaryfunc, "&"),
5458 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5459 wrap_binaryfunc, "^"),
5460 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5461 wrap_binaryfunc, "|"),
5462 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5463 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5464 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5465 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5466 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5467 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5468 IBSLOT("__itruediv__", nb_inplace_true_divide,
5469 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005470
Guido van Rossum6d204072001-10-21 00:44:31 +00005471 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5472 "x.__str__() <==> str(x)"),
5473 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5474 "x.__repr__() <==> repr(x)"),
5475 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5476 "x.__cmp__(y) <==> cmp(x,y)"),
5477 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5478 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005479 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5480 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005481 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005482 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5483 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5484 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5485 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5486 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5487 "x.__setattr__('name', value) <==> x.name = value"),
5488 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5489 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5490 "x.__delattr__('name') <==> del x.name"),
5491 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5492 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5493 "x.__lt__(y) <==> x<y"),
5494 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5495 "x.__le__(y) <==> x<=y"),
5496 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5497 "x.__eq__(y) <==> x==y"),
5498 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5499 "x.__ne__(y) <==> x!=y"),
5500 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5501 "x.__gt__(y) <==> x>y"),
5502 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5503 "x.__ge__(y) <==> x>=y"),
5504 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5505 "x.__iter__() <==> iter(x)"),
Georg Brandla18af4e2007-04-21 15:47:16 +00005506 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5507 "x.__next__() <==> next(x)"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005508 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5509 "descr.__get__(obj[, type]) -> value"),
5510 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5511 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005512 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5513 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005514 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005515 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005516 "see x.__class__.__doc__ for signature",
5517 PyWrapperFlag_KEYWORDS),
5518 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005519 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005520 {NULL}
5521};
5522
Guido van Rossumc334df52002-04-04 23:44:47 +00005523/* Given a type pointer and an offset gotten from a slotdef entry, return a
Guido van Rossumd8faa362007-04-27 19:54:29 +00005524 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005525 the offset to the type pointer, since it takes care to indirect through the
5526 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5527 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005528static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005529slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005530{
5531 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005532 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005533
Guido van Rossume5c691a2003-03-07 15:13:17 +00005534 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005535 assert(offset >= 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005536 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5537 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5538 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005539 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005540 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005541 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5542 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005543 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005544 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005545 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5546 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005547 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005548 }
5549 else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005550 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005551 }
5552 if (ptr != NULL)
5553 ptr += offset;
5554 return (void **)ptr;
5555}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005556
Guido van Rossumc334df52002-04-04 23:44:47 +00005557/* Length of array of slotdef pointers used to store slots with the
5558 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5559 the same __name__, for any __name__. Since that's a static property, it is
5560 appropriate to declare fixed-size arrays for this. */
5561#define MAX_EQUIV 10
5562
5563/* Return a slot pointer for a given name, but ONLY if the attribute has
5564 exactly one slot function. The name must be an interned string. */
5565static void **
5566resolve_slotdups(PyTypeObject *type, PyObject *name)
5567{
5568 /* XXX Maybe this could be optimized more -- but is it worth it? */
5569
5570 /* pname and ptrs act as a little cache */
5571 static PyObject *pname;
5572 static slotdef *ptrs[MAX_EQUIV];
5573 slotdef *p, **pp;
5574 void **res, **ptr;
5575
5576 if (pname != name) {
5577 /* Collect all slotdefs that match name into ptrs. */
5578 pname = name;
5579 pp = ptrs;
5580 for (p = slotdefs; p->name_strobj; p++) {
5581 if (p->name_strobj == name)
5582 *pp++ = p;
5583 }
5584 *pp = NULL;
5585 }
5586
5587 /* Look in all matching slots of the type; if exactly one of these has
Guido van Rossumd8faa362007-04-27 19:54:29 +00005588 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005589 res = NULL;
5590 for (pp = ptrs; *pp; pp++) {
5591 ptr = slotptr(type, (*pp)->offset);
5592 if (ptr == NULL || *ptr == NULL)
5593 continue;
5594 if (res != NULL)
5595 return NULL;
5596 res = ptr;
5597 }
5598 return res;
5599}
5600
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005601/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005602 does some incredibly complex thinking and then sticks something into the
5603 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5604 interests, and then stores a generic wrapper or a specific function into
5605 the slot.) Return a pointer to the next slotdef with a different offset,
5606 because that's convenient for fixup_slot_dispatchers(). */
5607static slotdef *
5608update_one_slot(PyTypeObject *type, slotdef *p)
5609{
5610 PyObject *descr;
5611 PyWrapperDescrObject *d;
5612 void *generic = NULL, *specific = NULL;
5613 int use_generic = 0;
5614 int offset = p->offset;
5615 void **ptr = slotptr(type, offset);
5616
5617 if (ptr == NULL) {
5618 do {
5619 ++p;
5620 } while (p->offset == offset);
5621 return p;
5622 }
5623 do {
5624 descr = _PyType_Lookup(type, p->name_strobj);
5625 if (descr == NULL)
5626 continue;
Christian Heimes90aa7642007-12-19 02:45:37 +00005627 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00005628 void **tptr = resolve_slotdups(type, p->name_strobj);
5629 if (tptr == NULL || tptr == ptr)
5630 generic = p->function;
5631 d = (PyWrapperDescrObject *)descr;
5632 if (d->d_base->wrapper == p->wrapper &&
5633 PyType_IsSubtype(type, d->d_type))
5634 {
5635 if (specific == NULL ||
5636 specific == d->d_wrapped)
5637 specific = d->d_wrapped;
5638 else
5639 use_generic = 1;
5640 }
5641 }
Christian Heimes90aa7642007-12-19 02:45:37 +00005642 else if (Py_TYPE(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00005643 PyCFunction_GET_FUNCTION(descr) ==
5644 (PyCFunction)tp_new_wrapper &&
5645 strcmp(p->name, "__new__") == 0)
5646 {
5647 /* The __new__ wrapper is not a wrapper descriptor,
5648 so must be special-cased differently.
5649 If we don't do this, creating an instance will
5650 always use slot_tp_new which will look up
5651 __new__ in the MRO which will call tp_new_wrapper
5652 which will look through the base classes looking
5653 for a static base and call its tp_new (usually
5654 PyType_GenericNew), after performing various
5655 sanity checks and constructing a new argument
5656 list. Cut all that nonsense short -- this speeds
5657 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005658 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005659 /* XXX I'm not 100% sure that there isn't a hole
5660 in this reasoning that requires additional
5661 sanity checks. I'll buy the first person to
5662 point out a bug in this reasoning a beer. */
5663 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005664 else {
5665 use_generic = 1;
5666 generic = p->function;
5667 }
5668 } while ((++p)->offset == offset);
5669 if (specific && !use_generic)
5670 *ptr = specific;
5671 else
5672 *ptr = generic;
5673 return p;
5674}
5675
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005676/* In the type, update the slots whose slotdefs are gathered in the pp array.
5677 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005678static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005679update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005680{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005681 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005682
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005683 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005684 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005685 return 0;
5686}
5687
Guido van Rossumc334df52002-04-04 23:44:47 +00005688/* Comparison function for qsort() to compare slotdefs by their offset, and
5689 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005690static int
5691slotdef_cmp(const void *aa, const void *bb)
5692{
5693 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5694 int c = a->offset - b->offset;
5695 if (c != 0)
5696 return c;
5697 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005698 /* Cannot use a-b, as this gives off_t,
5699 which may lose precision when converted to int. */
5700 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005701}
5702
Guido van Rossumc334df52002-04-04 23:44:47 +00005703/* Initialize the slotdefs table by adding interned string objects for the
5704 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005705static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005706init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005707{
5708 slotdef *p;
5709 static int initialized = 0;
5710
5711 if (initialized)
5712 return;
5713 for (p = slotdefs; p->name; p++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005714 p->name_strobj = PyUnicode_InternFromString(p->name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005715 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005716 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005717 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005718 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5719 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005720 initialized = 1;
5721}
5722
Guido van Rossumc334df52002-04-04 23:44:47 +00005723/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005724static int
5725update_slot(PyTypeObject *type, PyObject *name)
5726{
Guido van Rossumc334df52002-04-04 23:44:47 +00005727 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005728 slotdef *p;
5729 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005730 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005731
Christian Heimesa62da1d2008-01-12 19:39:10 +00005732 /* Clear the VALID_VERSION flag of 'type' and all its
5733 subclasses. This could possibly be unified with the
5734 update_subclasses() recursion below, but carefully:
5735 they each have their own conditions on which to stop
5736 recursing into subclasses. */
5737 type_modified(type);
5738
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005739 init_slotdefs();
5740 pp = ptrs;
5741 for (p = slotdefs; p->name; p++) {
5742 /* XXX assume name is interned! */
5743 if (p->name_strobj == name)
5744 *pp++ = p;
5745 }
5746 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005747 for (pp = ptrs; *pp; pp++) {
5748 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005749 offset = p->offset;
5750 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005751 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005752 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005753 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005754 if (ptrs[0] == NULL)
5755 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005756 return update_subclasses(type, name,
5757 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005758}
5759
Guido van Rossumc334df52002-04-04 23:44:47 +00005760/* Store the proper functions in the slot dispatches at class (type)
5761 definition time, based upon which operations the class overrides in its
5762 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005763static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005764fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005765{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005766 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005767
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005768 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005769 for (p = slotdefs; p->name; )
5770 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005771}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005772
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005773static void
5774update_all_slots(PyTypeObject* type)
5775{
5776 slotdef *p;
5777
5778 init_slotdefs();
5779 for (p = slotdefs; p->name; p++) {
5780 /* update_slot returns int but can't actually fail */
5781 update_slot(type, p->name_strobj);
5782 }
5783}
5784
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005785/* recurse_down_subclasses() and update_subclasses() are mutually
5786 recursive functions to call a callback for all subclasses,
5787 but refraining from recursing into subclasses that define 'name'. */
5788
5789static int
5790update_subclasses(PyTypeObject *type, PyObject *name,
5791 update_callback callback, void *data)
5792{
5793 if (callback(type, data) < 0)
5794 return -1;
5795 return recurse_down_subclasses(type, name, callback, data);
5796}
5797
5798static int
5799recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5800 update_callback callback, void *data)
5801{
5802 PyTypeObject *subclass;
5803 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005804 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005805
5806 subclasses = type->tp_subclasses;
5807 if (subclasses == NULL)
5808 return 0;
5809 assert(PyList_Check(subclasses));
5810 n = PyList_GET_SIZE(subclasses);
5811 for (i = 0; i < n; i++) {
5812 ref = PyList_GET_ITEM(subclasses, i);
5813 assert(PyWeakref_CheckRef(ref));
5814 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5815 assert(subclass != NULL);
5816 if ((PyObject *)subclass == Py_None)
5817 continue;
5818 assert(PyType_Check(subclass));
5819 /* Avoid recursing down into unaffected classes */
5820 dict = subclass->tp_dict;
5821 if (dict != NULL && PyDict_Check(dict) &&
5822 PyDict_GetItem(dict, name) != NULL)
5823 continue;
5824 if (update_subclasses(subclass, name, callback, data) < 0)
5825 return -1;
5826 }
5827 return 0;
5828}
5829
Guido van Rossum6d204072001-10-21 00:44:31 +00005830/* This function is called by PyType_Ready() to populate the type's
5831 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005832 function slot (like tp_repr) that's defined in the type, one or more
5833 corresponding descriptors are added in the type's tp_dict dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +00005834 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005835 cause more than one descriptor to be added (for example, the nb_add
5836 slot adds both __add__ and __radd__ descriptors) and some function
5837 slots compete for the same descriptor (for example both sq_item and
5838 mp_subscript generate a __getitem__ descriptor).
5839
Guido van Rossumd8faa362007-04-27 19:54:29 +00005840 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005841 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005842 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005843 between competing slots: the members of PyHeapTypeObject are listed
5844 from most general to least general, so the most general slot is
5845 preferred. In particular, because as_mapping comes before as_sequence,
5846 for a type that defines both mp_subscript and sq_item, mp_subscript
5847 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005848
5849 This only adds new descriptors and doesn't overwrite entries in
5850 tp_dict that were previously defined. The descriptors contain a
5851 reference to the C function they must call, so that it's safe if they
5852 are copied into a subtype's __dict__ and the subtype has a different
5853 C function in its slot -- calling the method defined by the
5854 descriptor will call the C function that was used to create it,
5855 rather than the C function present in the slot when it is called.
5856 (This is important because a subtype may have a C function in the
5857 slot that calls the method from the dictionary, and we want to avoid
5858 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005859
5860static int
5861add_operators(PyTypeObject *type)
5862{
5863 PyObject *dict = type->tp_dict;
5864 slotdef *p;
5865 PyObject *descr;
5866 void **ptr;
5867
5868 init_slotdefs();
5869 for (p = slotdefs; p->name; p++) {
5870 if (p->wrapper == NULL)
5871 continue;
5872 ptr = slotptr(type, p->offset);
5873 if (!ptr || !*ptr)
5874 continue;
5875 if (PyDict_GetItem(dict, p->name_strobj))
5876 continue;
5877 descr = PyDescr_NewWrapper(type, p, *ptr);
5878 if (descr == NULL)
5879 return -1;
5880 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5881 return -1;
5882 Py_DECREF(descr);
5883 }
5884 if (type->tp_new != NULL) {
5885 if (add_tp_new_wrapper(type) < 0)
5886 return -1;
5887 }
5888 return 0;
5889}
5890
Guido van Rossum705f0f52001-08-24 16:47:00 +00005891
5892/* Cooperative 'super' */
5893
5894typedef struct {
5895 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005896 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005897 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005898 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005899} superobject;
5900
Guido van Rossum6f799372001-09-20 20:46:19 +00005901static PyMemberDef super_members[] = {
5902 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5903 "the class invoking super()"},
5904 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5905 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005906 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005907 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005908 {0}
5909};
5910
Guido van Rossum705f0f52001-08-24 16:47:00 +00005911static void
5912super_dealloc(PyObject *self)
5913{
5914 superobject *su = (superobject *)self;
5915
Guido van Rossum048eb752001-10-02 21:24:57 +00005916 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005917 Py_XDECREF(su->obj);
5918 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005919 Py_XDECREF(su->obj_type);
Christian Heimes90aa7642007-12-19 02:45:37 +00005920 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005921}
5922
5923static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005924super_repr(PyObject *self)
5925{
5926 superobject *su = (superobject *)self;
5927
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005928 if (su->obj_type)
Walter Dörwald1ab83302007-05-18 17:15:44 +00005929 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005930 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005931 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005932 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005933 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00005934 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005935 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005936 su->type ? su->type->tp_name : "NULL");
5937}
5938
5939static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005940super_getattro(PyObject *self, PyObject *name)
5941{
5942 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005943 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005944
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005945 if (!skip) {
5946 /* We want __class__ to return the class of the super object
5947 (i.e. super, or a subclass), not the class of su->obj. */
Martin v. Löwis5b222132007-06-10 09:51:05 +00005948 skip = (PyUnicode_Check(name) &&
5949 PyUnicode_GET_SIZE(name) == 9 &&
5950 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005951 }
5952
5953 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005954 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005955 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005956 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005957 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005958
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005959 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005960 mro = starttype->tp_mro;
5961
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005962 if (mro == NULL)
5963 n = 0;
5964 else {
5965 assert(PyTuple_Check(mro));
5966 n = PyTuple_GET_SIZE(mro);
5967 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005968 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005969 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005970 break;
5971 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005972 i++;
5973 res = NULL;
5974 for (; i < n; i++) {
5975 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005976 if (PyType_Check(tmp))
5977 dict = ((PyTypeObject *)tmp)->tp_dict;
Tim Petersa91e9642001-11-14 23:32:33 +00005978 else
5979 continue;
5980 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005981 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005982 Py_INCREF(res);
Christian Heimes90aa7642007-12-19 02:45:37 +00005983 f = Py_TYPE(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005984 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005985 tmp = f(res,
5986 /* Only pass 'obj' param if
5987 this is instance-mode super
5988 (See SF ID #743627)
5989 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005990 (su->obj == (PyObject *)
5991 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005992 ? (PyObject *)NULL
5993 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005994 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005995 Py_DECREF(res);
5996 res = tmp;
5997 }
5998 return res;
5999 }
6000 }
6001 }
6002 return PyObject_GenericGetAttr(self, name);
6003}
6004
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006005static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006006supercheck(PyTypeObject *type, PyObject *obj)
6007{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006008 /* Check that a super() call makes sense. Return a type object.
6009
6010 obj can be a new-style class, or an instance of one:
6011
Guido van Rossumd8faa362007-04-27 19:54:29 +00006012 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006013 used for class methods; the return value is obj.
6014
6015 - If it is an instance, it must be an instance of 'type'. This is
6016 the normal case; the return value is obj.__class__.
6017
6018 But... when obj is an instance, we want to allow for the case where
Christian Heimes90aa7642007-12-19 02:45:37 +00006019 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006020 This will allow using super() with a proxy for obj.
6021 */
6022
Guido van Rossum8e80a722003-02-18 19:22:22 +00006023 /* Check for first bullet above (special case) */
6024 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6025 Py_INCREF(obj);
6026 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006027 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006028
6029 /* Normal case */
Christian Heimes90aa7642007-12-19 02:45:37 +00006030 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6031 Py_INCREF(Py_TYPE(obj));
6032 return Py_TYPE(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006033 }
6034 else {
6035 /* Try the slow way */
6036 static PyObject *class_str = NULL;
6037 PyObject *class_attr;
6038
6039 if (class_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00006040 class_str = PyUnicode_FromString("__class__");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006041 if (class_str == NULL)
6042 return NULL;
6043 }
6044
6045 class_attr = PyObject_GetAttr(obj, class_str);
6046
6047 if (class_attr != NULL &&
6048 PyType_Check(class_attr) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00006049 (PyTypeObject *)class_attr != Py_TYPE(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006050 {
6051 int ok = PyType_IsSubtype(
6052 (PyTypeObject *)class_attr, type);
6053 if (ok)
6054 return (PyTypeObject *)class_attr;
6055 }
6056
6057 if (class_attr == NULL)
6058 PyErr_Clear();
6059 else
6060 Py_DECREF(class_attr);
6061 }
6062
Guido van Rossumd8faa362007-04-27 19:54:29 +00006063 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006064 "super(type, obj): "
6065 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006066 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006067}
6068
Guido van Rossum705f0f52001-08-24 16:47:00 +00006069static PyObject *
6070super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6071{
6072 superobject *su = (superobject *)self;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006073 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006074
6075 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6076 /* Not binding to an object, or already bound */
6077 Py_INCREF(self);
6078 return self;
6079 }
Christian Heimes90aa7642007-12-19 02:45:37 +00006080 if (Py_TYPE(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00006081 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006082 call its type */
Christian Heimes90aa7642007-12-19 02:45:37 +00006083 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
Guido van Rossumd8faa362007-04-27 19:54:29 +00006084 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00006085 else {
6086 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006087 PyTypeObject *obj_type = supercheck(su->type, obj);
6088 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006089 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006090 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006091 NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006092 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006093 return NULL;
6094 Py_INCREF(su->type);
6095 Py_INCREF(obj);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006096 newobj->type = su->type;
6097 newobj->obj = obj;
6098 newobj->obj_type = obj_type;
6099 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006100 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006101}
6102
6103static int
6104super_init(PyObject *self, PyObject *args, PyObject *kwds)
6105{
6106 superobject *su = (superobject *)self;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006107 PyTypeObject *type = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00006108 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006109 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006110
Thomas Wouters89f507f2006-12-13 04:49:30 +00006111 if (!_PyArg_NoKeywords("super", kwds))
6112 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006113 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
Guido van Rossum705f0f52001-08-24 16:47:00 +00006114 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006115
6116 if (type == NULL) {
6117 /* Call super(), without args -- fill in from __class__
6118 and first local variable on the stack. */
6119 PyFrameObject *f = PyThreadState_GET()->frame;
6120 PyCodeObject *co = f->f_code;
6121 int i, n;
6122 if (co == NULL) {
6123 PyErr_SetString(PyExc_SystemError,
6124 "super(): no code object");
6125 return -1;
6126 }
6127 if (co->co_argcount == 0) {
6128 PyErr_SetString(PyExc_SystemError,
6129 "super(): no arguments");
6130 return -1;
6131 }
6132 obj = f->f_localsplus[0];
6133 if (obj == NULL) {
6134 PyErr_SetString(PyExc_SystemError,
6135 "super(): arg[0] deleted");
6136 return -1;
6137 }
6138 if (co->co_freevars == NULL)
6139 n = 0;
6140 else {
6141 assert(PyTuple_Check(co->co_freevars));
6142 n = PyTuple_GET_SIZE(co->co_freevars);
6143 }
6144 for (i = 0; i < n; i++) {
6145 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
6146 assert(PyUnicode_Check(name));
6147 if (!PyUnicode_CompareWithASCIIString(name,
6148 "__class__")) {
6149 PyObject *cell =
6150 f->f_localsplus[co->co_nlocals + i];
6151 if (cell == NULL || !PyCell_Check(cell)) {
6152 PyErr_SetString(PyExc_SystemError,
6153 "super(): bad __class__ cell");
6154 return -1;
6155 }
6156 type = (PyTypeObject *) PyCell_GET(cell);
6157 if (type == NULL) {
6158 PyErr_SetString(PyExc_SystemError,
6159 "super(): empty __class__ cell");
6160 return -1;
6161 }
6162 if (!PyType_Check(type)) {
6163 PyErr_Format(PyExc_SystemError,
6164 "super(): __class__ is not a type (%s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00006165 Py_TYPE(type)->tp_name);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006166 return -1;
6167 }
6168 break;
6169 }
6170 }
6171 if (type == NULL) {
6172 PyErr_SetString(PyExc_SystemError,
6173 "super(): __class__ cell not found");
6174 return -1;
6175 }
6176 }
6177
Guido van Rossum705f0f52001-08-24 16:47:00 +00006178 if (obj == Py_None)
6179 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006180 if (obj != NULL) {
6181 obj_type = supercheck(type, obj);
6182 if (obj_type == NULL)
6183 return -1;
6184 Py_INCREF(obj);
6185 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006186 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006187 su->type = type;
6188 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006189 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006190 return 0;
6191}
6192
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006193PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006194"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006195"super(type) -> unbound super object\n"
6196"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006197"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006198"Typical use to call a cooperative superclass method:\n"
6199"class C(B):\n"
6200" def meth(self, arg):\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006201" super().meth(arg)\n"
6202"This works for class methods too:\n"
6203"class C(B):\n"
6204" @classmethod\n"
6205" def cmeth(cls, arg):\n"
6206" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006207
Guido van Rossum048eb752001-10-02 21:24:57 +00006208static int
6209super_traverse(PyObject *self, visitproc visit, void *arg)
6210{
6211 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006212
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006213 Py_VISIT(su->obj);
6214 Py_VISIT(su->type);
6215 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006216
6217 return 0;
6218}
6219
Guido van Rossum705f0f52001-08-24 16:47:00 +00006220PyTypeObject PySuper_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00006221 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00006222 "super", /* tp_name */
6223 sizeof(superobject), /* tp_basicsize */
6224 0, /* tp_itemsize */
6225 /* methods */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006226 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006227 0, /* tp_print */
6228 0, /* tp_getattr */
6229 0, /* tp_setattr */
6230 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006231 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006232 0, /* tp_as_number */
6233 0, /* tp_as_sequence */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006234 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006235 0, /* tp_hash */
6236 0, /* tp_call */
6237 0, /* tp_str */
6238 super_getattro, /* tp_getattro */
6239 0, /* tp_setattro */
6240 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006241 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6242 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006243 super_doc, /* tp_doc */
6244 super_traverse, /* tp_traverse */
6245 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006246 0, /* tp_richcompare */
6247 0, /* tp_weaklistoffset */
6248 0, /* tp_iter */
6249 0, /* tp_iternext */
6250 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006251 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006252 0, /* tp_getset */
6253 0, /* tp_base */
6254 0, /* tp_dict */
6255 super_descr_get, /* tp_descr_get */
6256 0, /* tp_descr_set */
6257 0, /* tp_dictoffset */
6258 super_init, /* tp_init */
6259 PyType_GenericAlloc, /* tp_alloc */
6260 PyType_GenericNew, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006261 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006262};