blob: d4a70d44f1fa2f98090cc7aab588f272ace4f8fd [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00008
9/* Support type attribute cache */
10
11/* The cache can keep references to the names alive for longer than
12 they normally would. This is why the maximum size is limited to
13 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
14 strings are used as attribute names. */
15#define MCACHE_MAX_ATTR_SIZE 100
16#define MCACHE_SIZE_EXP 10
17#define MCACHE_HASH(version, name_hash) \
18 (((unsigned int)(version) * (unsigned int)(name_hash)) \
19 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
20#define MCACHE_HASH_METHOD(type, name) \
21 MCACHE_HASH((type)->tp_version_tag, \
22 ((PyStringObject *)(name))->ob_shash)
23#define MCACHE_CACHEABLE_NAME(name) \
24 PyString_CheckExact(name) && \
25 PyString_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
26
27struct method_cache_entry {
28 unsigned int version;
29 PyObject *name; /* reference to exactly a str or None */
30 PyObject *value; /* borrowed */
31};
32
33static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
34static unsigned int next_version_tag = 0;
35
36static void
37type_modified(PyTypeObject *type)
38{
39 /* Invalidate any cached data for the specified type and all
40 subclasses. This function is called after the base
41 classes, mro, or attributes of the type are altered.
42
43 Invariants:
44
45 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
46 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
47 objects coming from non-recompiled extension modules)
48
49 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
50 it must first be set on all super types.
51
52 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
53 type (so it must first clear it on all subclasses). The
54 tp_version_tag value is meaningless unless this flag is set.
55 We don't assign new version tags eagerly, but only as
56 needed.
57 */
58 PyObject *raw, *ref;
59 Py_ssize_t i, n;
60
61 if(!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
62 return;
63
64 raw = type->tp_subclasses;
65 if (raw != NULL) {
66 n = PyList_GET_SIZE(raw);
67 for (i = 0; i < n; i++) {
68 ref = PyList_GET_ITEM(raw, i);
69 ref = PyWeakref_GET_OBJECT(ref);
70 if (ref != Py_None) {
71 type_modified((PyTypeObject *)ref);
72 }
73 }
74 }
75 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
76}
77
78static void
79type_mro_modified(PyTypeObject *type, PyObject *bases) {
80 /*
81 Check that all base classes or elements of the mro of type are
82 able to be cached. This function is called after the base
83 classes or mro of the type are altered.
84
85 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
86 inherits from an old-style class, either directly or if it
87 appears in the MRO of a new-style class. No support either for
88 custom MROs that include types that are not officially super
89 types.
90
91 Called from mro_internal, which will subsequently be called on
92 each subclass when their mro is recursively updated.
93 */
94 Py_ssize_t i, n;
95 int clear = 0;
96
97 if(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
98 return;
99
100 n = PyTuple_GET_SIZE(bases);
101 for (i = 0; i < n; i++) {
102 PyObject *b = PyTuple_GET_ITEM(bases, i);
103 PyTypeObject *cls;
104
105 if (!PyType_Check(b) ) {
106 clear = 1;
107 break;
108 }
109
110 cls = (PyTypeObject *)b;
111
112 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
113 !PyType_IsSubtype(type, cls)) {
114 clear = 1;
115 break;
116 }
117 }
118
119 if (clear)
120 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
121 Py_TPFLAGS_VALID_VERSION_TAG);
122}
123
124static int
125assign_version_tag(PyTypeObject *type)
126{
127 /* Ensure that the tp_version_tag is valid and set
128 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
129 must first be done on all super classes. Return 0 if this
130 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
131 */
132 Py_ssize_t i, n;
133 PyObject *bases;
134
135 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
136 return 1;
137 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
138 return 0;
139 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
140 return 0;
141
142 type->tp_version_tag = next_version_tag++;
143 /* for stress-testing: next_version_tag &= 0xFF; */
144
145 if (type->tp_version_tag == 0) {
146 /* wrap-around or just starting Python - clear the whole
147 cache by filling names with references to Py_None.
148 Values are also set to NULL for added protection, as they
149 are borrowed reference */
150 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
151 method_cache[i].value = NULL;
152 Py_XDECREF(method_cache[i].name);
153 method_cache[i].name = Py_None;
154 Py_INCREF(Py_None);
155 }
156 /* mark all version tags as invalid */
157 type_modified(&PyBaseObject_Type);
158 return 1;
159 }
160 bases = type->tp_bases;
161 n = PyTuple_GET_SIZE(bases);
162 for (i = 0; i < n; i++) {
163 PyObject *b = PyTuple_GET_ITEM(bases, i);
164 assert(PyType_Check(b));
165 if (!assign_version_tag((PyTypeObject *)b))
166 return 0;
167 }
168 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
169 return 1;
170}
171
172
Guido van Rossum6f799372001-09-20 20:46:19 +0000173static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000174 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
175 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
176 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +0000177 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000178 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
179 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
180 {"__dictoffset__", T_LONG,
181 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000182 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
183 {0}
184};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000185
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000186static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000187type_name(PyTypeObject *type, void *context)
188{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000189 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000190
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000191 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +0000192 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000193
Georg Brandlc255c7b2006-02-20 22:27:28 +0000194 Py_INCREF(et->ht_name);
195 return et->ht_name;
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000196 }
197 else {
198 s = strrchr(type->tp_name, '.');
199 if (s == NULL)
200 s = type->tp_name;
201 else
202 s++;
203 return PyString_FromString(s);
204 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000205}
206
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000207static int
208type_set_name(PyTypeObject *type, PyObject *value, void *context)
209{
Guido van Rossume5c691a2003-03-07 15:13:17 +0000210 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000211
212 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
213 PyErr_Format(PyExc_TypeError,
214 "can't set %s.__name__", type->tp_name);
215 return -1;
216 }
217 if (!value) {
218 PyErr_Format(PyExc_TypeError,
219 "can't delete %s.__name__", type->tp_name);
220 return -1;
221 }
222 if (!PyString_Check(value)) {
223 PyErr_Format(PyExc_TypeError,
224 "can only assign string to %s.__name__, not '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +0000225 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000226 return -1;
227 }
Tim Petersea7f75d2002-12-07 21:39:16 +0000228 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000229 != (size_t)PyString_GET_SIZE(value)) {
230 PyErr_Format(PyExc_ValueError,
231 "__name__ must not contain null bytes");
232 return -1;
233 }
234
Guido van Rossume5c691a2003-03-07 15:13:17 +0000235 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000236
237 Py_INCREF(value);
238
Georg Brandlc255c7b2006-02-20 22:27:28 +0000239 Py_DECREF(et->ht_name);
240 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000241
242 type->tp_name = PyString_AS_STRING(value);
243
244 return 0;
245}
246
Guido van Rossumc3542212001-08-16 09:18:56 +0000247static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000248type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000249{
Guido van Rossumc3542212001-08-16 09:18:56 +0000250 PyObject *mod;
251 char *s;
252
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000253 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
254 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +0000255 if (!mod) {
256 PyErr_Format(PyExc_AttributeError, "__module__");
257 return 0;
258 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000259 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +0000260 return mod;
261 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000262 else {
263 s = strrchr(type->tp_name, '.');
264 if (s != NULL)
265 return PyString_FromStringAndSize(
Armin Rigo7ccbca92006-10-04 12:17:45 +0000266 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000267 return PyString_FromString("__builtin__");
268 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000269}
270
Guido van Rossum3926a632001-09-25 16:25:58 +0000271static int
272type_set_module(PyTypeObject *type, PyObject *value, void *context)
273{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000274 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000275 PyErr_Format(PyExc_TypeError,
276 "can't set %s.__module__", type->tp_name);
277 return -1;
278 }
279 if (!value) {
280 PyErr_Format(PyExc_TypeError,
281 "can't delete %s.__module__", type->tp_name);
282 return -1;
283 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000284
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000285 type_modified(type);
286
Guido van Rossum3926a632001-09-25 16:25:58 +0000287 return PyDict_SetItemString(type->tp_dict, "__module__", value);
288}
289
Tim Peters6d6c1a32001-08-02 04:15:00 +0000290static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000291type_get_bases(PyTypeObject *type, void *context)
292{
293 Py_INCREF(type->tp_bases);
294 return type->tp_bases;
295}
296
297static PyTypeObject *best_base(PyObject *);
298static int mro_internal(PyTypeObject *);
299static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
300static int add_subclass(PyTypeObject*, PyTypeObject*);
301static void remove_subclass(PyTypeObject *, PyTypeObject *);
302static void update_all_slots(PyTypeObject *);
303
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000304typedef int (*update_callback)(PyTypeObject *, void *);
305static int update_subclasses(PyTypeObject *type, PyObject *name,
306 update_callback callback, void *data);
307static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
308 update_callback callback, void *data);
309
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000310static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000311mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000312{
313 PyTypeObject *subclass;
314 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000315 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000316
317 subclasses = type->tp_subclasses;
318 if (subclasses == NULL)
319 return 0;
320 assert(PyList_Check(subclasses));
321 n = PyList_GET_SIZE(subclasses);
322 for (i = 0; i < n; i++) {
323 ref = PyList_GET_ITEM(subclasses, i);
324 assert(PyWeakref_CheckRef(ref));
325 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
326 assert(subclass != NULL);
327 if ((PyObject *)subclass == Py_None)
328 continue;
329 assert(PyType_Check(subclass));
330 old_mro = subclass->tp_mro;
331 if (mro_internal(subclass) < 0) {
332 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000333 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000334 }
335 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000336 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000337 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000338 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000339 if (!tuple)
340 return -1;
341 if (PyList_Append(temp, tuple) < 0)
342 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000343 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000344 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000345 if (mro_subclasses(subclass, temp) < 0)
346 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000347 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000348 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000349}
350
351static int
352type_set_bases(PyTypeObject *type, PyObject *value, void *context)
353{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000354 Py_ssize_t i;
355 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000356 PyObject *ob, *temp;
Armin Rigoc0ba52d2007-04-19 14:44:48 +0000357 PyTypeObject *new_base, *old_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000358 PyObject *old_bases, *old_mro;
359
360 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
361 PyErr_Format(PyExc_TypeError,
362 "can't set %s.__bases__", type->tp_name);
363 return -1;
364 }
365 if (!value) {
366 PyErr_Format(PyExc_TypeError,
367 "can't delete %s.__bases__", type->tp_name);
368 return -1;
369 }
370 if (!PyTuple_Check(value)) {
371 PyErr_Format(PyExc_TypeError,
372 "can only assign tuple to %s.__bases__, not %s",
Christian Heimese93237d2007-12-19 02:37:44 +0000373 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000374 return -1;
375 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000376 if (PyTuple_GET_SIZE(value) == 0) {
377 PyErr_Format(PyExc_TypeError,
378 "can only assign non-empty tuple to %s.__bases__, not ()",
379 type->tp_name);
380 return -1;
381 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000382 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
383 ob = PyTuple_GET_ITEM(value, i);
384 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
385 PyErr_Format(
386 PyExc_TypeError,
387 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +0000388 type->tp_name, Py_TYPE(ob)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000389 return -1;
390 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000391 if (PyType_Check(ob)) {
392 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
393 PyErr_SetString(PyExc_TypeError,
394 "a __bases__ item causes an inheritance cycle");
395 return -1;
396 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000397 }
398 }
399
400 new_base = best_base(value);
401
402 if (!new_base) {
403 return -1;
404 }
405
406 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
407 return -1;
408
409 Py_INCREF(new_base);
410 Py_INCREF(value);
411
412 old_bases = type->tp_bases;
413 old_base = type->tp_base;
414 old_mro = type->tp_mro;
415
416 type->tp_bases = value;
417 type->tp_base = new_base;
418
419 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000420 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000421 }
422
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000423 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000424 if (!temp)
425 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000426
427 r = mro_subclasses(type, temp);
428
429 if (r < 0) {
430 for (i = 0; i < PyList_Size(temp); i++) {
431 PyTypeObject* cls;
432 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000433 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
434 "", 2, 2, &cls, &mro);
Armin Rigo796fc992007-04-19 14:56:48 +0000435 Py_INCREF(mro);
436 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000437 cls->tp_mro = mro;
Armin Rigo796fc992007-04-19 14:56:48 +0000438 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000439 }
440 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000441 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000442 }
443
444 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000445
446 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000447 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000448 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000449 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000450
451 /* for now, sod that: just remove from all old_bases,
452 add to all new_bases */
453
454 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
455 ob = PyTuple_GET_ITEM(old_bases, i);
456 if (PyType_Check(ob)) {
457 remove_subclass(
458 (PyTypeObject*)ob, type);
459 }
460 }
461
462 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
463 ob = PyTuple_GET_ITEM(value, i);
464 if (PyType_Check(ob)) {
465 if (add_subclass((PyTypeObject*)ob, type) < 0)
466 r = -1;
467 }
468 }
469
470 update_all_slots(type);
471
472 Py_DECREF(old_bases);
473 Py_DECREF(old_base);
474 Py_DECREF(old_mro);
475
476 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000477
478 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000479 Py_DECREF(type->tp_bases);
480 Py_DECREF(type->tp_base);
481 if (type->tp_mro != old_mro) {
482 Py_DECREF(type->tp_mro);
483 }
484
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000485 type->tp_bases = old_bases;
486 type->tp_base = old_base;
487 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000488
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000489 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000490}
491
492static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000493type_dict(PyTypeObject *type, void *context)
494{
495 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496 Py_INCREF(Py_None);
497 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000498 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000499 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000500}
501
Tim Peters24008312002-03-17 18:56:20 +0000502static PyObject *
503type_get_doc(PyTypeObject *type, void *context)
504{
505 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000506 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000507 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000508 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000509 if (result == NULL) {
510 result = Py_None;
511 Py_INCREF(result);
512 }
Christian Heimese93237d2007-12-19 02:37:44 +0000513 else if (Py_TYPE(result)->tp_descr_get) {
514 result = Py_TYPE(result)->tp_descr_get(result, NULL,
Tim Peters2b858972002-04-18 04:12:28 +0000515 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000516 }
517 else {
518 Py_INCREF(result);
519 }
Tim Peters24008312002-03-17 18:56:20 +0000520 return result;
521}
522
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000523static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000524 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
525 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000526 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000527 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000528 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000529 {0}
530};
531
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000532static int
533type_compare(PyObject *v, PyObject *w)
534{
535 /* This is called with type objects only. So we
536 can just compare the addresses. */
537 Py_uintptr_t vv = (Py_uintptr_t)v;
538 Py_uintptr_t ww = (Py_uintptr_t)w;
539 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
540}
541
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000543type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000544{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000545 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000546 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000547
548 mod = type_module(type, NULL);
549 if (mod == NULL)
550 PyErr_Clear();
551 else if (!PyString_Check(mod)) {
552 Py_DECREF(mod);
553 mod = NULL;
554 }
555 name = type_name(type, NULL);
556 if (name == NULL)
557 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000558
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000559 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
560 kind = "class";
561 else
562 kind = "type";
563
Barry Warsaw7ce36942001-08-24 18:34:26 +0000564 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000565 rtn = PyString_FromFormat("<%s '%s.%s'>",
566 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000567 PyString_AS_STRING(mod),
568 PyString_AS_STRING(name));
569 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000570 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000571 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000572
Guido van Rossumc3542212001-08-16 09:18:56 +0000573 Py_XDECREF(mod);
574 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000575 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000576}
577
Tim Peters6d6c1a32001-08-02 04:15:00 +0000578static PyObject *
579type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
580{
581 PyObject *obj;
582
583 if (type->tp_new == NULL) {
584 PyErr_Format(PyExc_TypeError,
585 "cannot create '%.100s' instances",
586 type->tp_name);
587 return NULL;
588 }
589
Tim Peters3f996e72001-09-13 19:18:27 +0000590 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000591 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000592 /* Ugly exception: when the call was type(something),
593 don't call tp_init on the result. */
594 if (type == &PyType_Type &&
595 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
596 (kwds == NULL ||
597 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
598 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000599 /* If the returned object is not an instance of type,
600 it won't be initialized. */
601 if (!PyType_IsSubtype(obj->ob_type, type))
602 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000603 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000604 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
605 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000606 type->tp_init(obj, args, kwds) < 0) {
607 Py_DECREF(obj);
608 obj = NULL;
609 }
610 }
611 return obj;
612}
613
614PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000615PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000616{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000617 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000618 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
619 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000620
621 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000622 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000623 else
Anthony Baxtera6286212006-04-11 07:42:36 +0000624 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000625
Neil Schemenauerc806c882001-08-29 23:54:54 +0000626 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000627 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000628
Neil Schemenauerc806c882001-08-29 23:54:54 +0000629 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000630
Tim Peters6d6c1a32001-08-02 04:15:00 +0000631 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
632 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000633
Tim Peters6d6c1a32001-08-02 04:15:00 +0000634 if (type->tp_itemsize == 0)
635 PyObject_INIT(obj, type);
636 else
637 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000638
Tim Peters6d6c1a32001-08-02 04:15:00 +0000639 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000640 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000641 return obj;
642}
643
644PyObject *
645PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
646{
647 return type->tp_alloc(type, 0);
648}
649
Guido van Rossum9475a232001-10-05 20:51:39 +0000650/* Helpers for subtyping */
651
652static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000653traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
654{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000655 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000656 PyMemberDef *mp;
657
Christian Heimese93237d2007-12-19 02:37:44 +0000658 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000659 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000660 for (i = 0; i < n; i++, mp++) {
661 if (mp->type == T_OBJECT_EX) {
662 char *addr = (char *)self + mp->offset;
663 PyObject *obj = *(PyObject **)addr;
664 if (obj != NULL) {
665 int err = visit(obj, arg);
666 if (err)
667 return err;
668 }
669 }
670 }
671 return 0;
672}
673
674static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000675subtype_traverse(PyObject *self, visitproc visit, void *arg)
676{
677 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000678 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000679
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000680 /* Find the nearest base with a different tp_traverse,
681 and traverse slots while we're at it */
Christian Heimese93237d2007-12-19 02:37:44 +0000682 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000683 base = type;
684 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
Christian Heimese93237d2007-12-19 02:37:44 +0000685 if (Py_SIZE(base)) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000686 int err = traverse_slots(base, self, visit, arg);
687 if (err)
688 return err;
689 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000690 base = base->tp_base;
691 assert(base);
692 }
693
694 if (type->tp_dictoffset != base->tp_dictoffset) {
695 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Woutersc6e55062006-04-15 21:47:09 +0000696 if (dictptr && *dictptr)
697 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000698 }
699
Thomas Woutersc6e55062006-04-15 21:47:09 +0000700 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000701 /* For a heaptype, the instances count as references
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000702 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000703 can find cycles involving this link. */
Thomas Woutersc6e55062006-04-15 21:47:09 +0000704 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000705
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000706 if (basetraverse)
707 return basetraverse(self, visit, arg);
708 return 0;
709}
710
711static void
712clear_slots(PyTypeObject *type, PyObject *self)
713{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000714 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000715 PyMemberDef *mp;
716
Christian Heimese93237d2007-12-19 02:37:44 +0000717 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000718 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000719 for (i = 0; i < n; i++, mp++) {
720 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
721 char *addr = (char *)self + mp->offset;
722 PyObject *obj = *(PyObject **)addr;
723 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000724 *(PyObject **)addr = NULL;
Thomas Woutersedf17d82006-04-15 17:28:34 +0000725 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000726 }
727 }
728 }
729}
730
731static int
732subtype_clear(PyObject *self)
733{
734 PyTypeObject *type, *base;
735 inquiry baseclear;
736
737 /* Find the nearest base with a different tp_clear
738 and clear slots while we're at it */
Christian Heimese93237d2007-12-19 02:37:44 +0000739 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000740 base = type;
741 while ((baseclear = base->tp_clear) == subtype_clear) {
Christian Heimese93237d2007-12-19 02:37:44 +0000742 if (Py_SIZE(base))
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000743 clear_slots(base, self);
744 base = base->tp_base;
745 assert(base);
746 }
747
Guido van Rossuma3862092002-06-10 15:24:42 +0000748 /* There's no need to clear the instance dict (if any);
749 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000750
751 if (baseclear)
752 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000753 return 0;
754}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000755
756static void
757subtype_dealloc(PyObject *self)
758{
Guido van Rossum14227b42001-12-06 02:35:58 +0000759 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000760 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000761
Guido van Rossum22b13872002-08-06 21:41:44 +0000762 /* Extract the type; we expect it to be a heap type */
Christian Heimese93237d2007-12-19 02:37:44 +0000763 type = Py_TYPE(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000764 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000765
Guido van Rossum22b13872002-08-06 21:41:44 +0000766 /* Test whether the type has GC exactly once */
767
768 if (!PyType_IS_GC(type)) {
769 /* It's really rare to find a dynamic type that doesn't have
770 GC; it can only happen when deriving from 'object' and not
771 adding any slots or instance variables. This allows
772 certain simplifications: there's no need to call
773 clear_slots(), or DECREF the dict, or clear weakrefs. */
774
775 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000776 if (type->tp_del) {
777 type->tp_del(self);
778 if (self->ob_refcnt > 0)
779 return;
780 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000781
782 /* Find the nearest base with a different tp_dealloc */
783 base = type;
784 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimese93237d2007-12-19 02:37:44 +0000785 assert(Py_SIZE(base) == 0);
Guido van Rossum22b13872002-08-06 21:41:44 +0000786 base = base->tp_base;
787 assert(base);
788 }
789
790 /* Call the base tp_dealloc() */
791 assert(basedealloc);
792 basedealloc(self);
793
794 /* Can't reference self beyond this point */
795 Py_DECREF(type);
796
797 /* Done */
798 return;
799 }
800
801 /* We get here only if the type has GC */
802
803 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000804 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000805 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000806 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000807 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000808 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000809 /* DO NOT restore GC tracking at this point. weakref callbacks
810 * (if any, and whether directly here or indirectly in something we
811 * call) may trigger GC, and if self is tracked at that point, it
812 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000813 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000814
Guido van Rossum59195fd2003-06-13 20:54:40 +0000815 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000816 base = type;
817 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000818 base = base->tp_base;
819 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000820 }
821
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000822 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000823 the finalizer (__del__), clearing slots, or clearing the instance
824 dict. */
825
Guido van Rossum1987c662003-05-29 14:29:23 +0000826 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
827 PyObject_ClearWeakRefs(self);
828
829 /* Maybe call finalizer; exit early if resurrected */
830 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000831 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000832 type->tp_del(self);
833 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000834 goto endlabel; /* resurrected */
835 else
836 _PyObject_GC_UNTRACK(self);
Brett Cannonf5bee302007-01-23 23:21:22 +0000837 /* New weakrefs could be created during the finalizer call.
838 If this occurs, clear them out without calling their
839 finalizers since they might rely on part of the object
840 being finalized that has already been destroyed. */
841 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
842 /* Modeled after GET_WEAKREFS_LISTPTR() */
843 PyWeakReference **list = (PyWeakReference **) \
844 PyObject_GET_WEAKREFS_LISTPTR(self);
845 while (*list)
846 _PyWeakref_ClearRef(*list);
847 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000848 }
849
Guido van Rossum59195fd2003-06-13 20:54:40 +0000850 /* Clear slots up to the nearest base with a different tp_dealloc */
851 base = type;
852 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimese93237d2007-12-19 02:37:44 +0000853 if (Py_SIZE(base))
Guido van Rossum59195fd2003-06-13 20:54:40 +0000854 clear_slots(base, self);
855 base = base->tp_base;
856 assert(base);
857 }
858
Tim Peters6d6c1a32001-08-02 04:15:00 +0000859 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000860 if (type->tp_dictoffset && !base->tp_dictoffset) {
861 PyObject **dictptr = _PyObject_GetDictPtr(self);
862 if (dictptr != NULL) {
863 PyObject *dict = *dictptr;
864 if (dict != NULL) {
865 Py_DECREF(dict);
866 *dictptr = NULL;
867 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000868 }
869 }
870
Tim Peters0bd743c2003-11-13 22:50:00 +0000871 /* Call the base tp_dealloc(); first retrack self if
872 * basedealloc knows about gc.
873 */
874 if (PyType_IS_GC(base))
875 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000876 assert(basedealloc);
877 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000878
879 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000880 Py_DECREF(type);
881
Guido van Rossum0906e072002-08-07 20:42:09 +0000882 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000883 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000884 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000885 --_PyTrash_delete_nesting;
886
887 /* Explanation of the weirdness around the trashcan macros:
888
889 Q. What do the trashcan macros do?
890
891 A. Read the comment titled "Trashcan mechanism" in object.h.
892 For one, this explains why there must be a call to GC-untrack
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000893 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000894 trashcan code, the answers to the following questions don't make
895 sense.
896
897 Q. Why do we GC-untrack before the trashcan and then immediately
898 GC-track again afterward?
899
900 A. In the case that the base class is GC-aware, the base class
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000901 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000902 UNTRACK macro, this will crash when the object is already
903 untracked. Because we don't know what the base class does, the
904 only safe thing is to make sure the object is tracked when we
905 call the base class dealloc. But... The trashcan begin macro
906 requires that the object is *untracked* before it is called. So
907 the dance becomes:
908
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000909 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000910 trashcan begin
911 GC track
912
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000913 Q. Why did the last question say "immediately GC-track again"?
914 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000915
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000916 A. Because the code *used* to re-track immediately. Bad Idea.
917 self has a refcount of 0, and if gc ever gets its hands on it
918 (which can happen if any weakref callback gets invoked), it
919 looks like trash to gc too, and gc also tries to delete self
920 then. But we're already deleting self. Double dealloction is
921 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +0000922
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000923 Q. Why the bizarre (net-zero) manipulation of
924 _PyTrash_delete_nesting around the trashcan macros?
925
926 A. Some base classes (e.g. list) also use the trashcan mechanism.
927 The following scenario used to be possible:
928
929 - suppose the trashcan level is one below the trashcan limit
930
931 - subtype_dealloc() is called
932
933 - the trashcan limit is not yet reached, so the trashcan level
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000934 is incremented and the code between trashcan begin and end is
935 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000936
937 - this destroys much of the object's contents, including its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000938 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000939
940 - basedealloc() is called; this is really list_dealloc(), or
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000941 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000942
943 - the trashcan limit is now reached, so the object is put on the
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000944 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000945
946 - basedealloc() returns
947
948 - subtype_dealloc() decrefs the object's type
949
950 - subtype_dealloc() returns
951
952 - later, the trashcan code starts deleting the objects from its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000953 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000954
955 - subtype_dealloc() is called *AGAIN* for the same object
956
957 - at the very least (if the destroyed slots and __dict__ don't
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000958 cause problems) the object's type gets decref'ed a second
959 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000960
961 The remedy is to make sure that if the code between trashcan
962 begin and end in subtype_dealloc() is called, the code between
963 trashcan begin and end in basedealloc() will also be called.
964 This is done by decrementing the level after passing into the
965 trashcan block, and incrementing it just before leaving the
966 block.
967
968 But now it's possible that a chain of objects consisting solely
969 of objects whose deallocator is subtype_dealloc() will defeat
970 the trashcan mechanism completely: the decremented level means
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000971 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000972 *increment* the level *before* entering the trashcan block, and
973 matchingly decrement it after leaving. This means the trashcan
974 code will trigger a little early, but that's no big deal.
975
976 Q. Are there any live examples of code in need of all this
977 complexity?
978
979 A. Yes. See SF bug 668433 for code that crashed (when Python was
980 compiled in debug mode) before the trashcan level manipulations
981 were added. For more discussion, see SF patches 581742, 575073
982 and bug 574207.
983 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000984}
985
Jeremy Hylton938ace62002-07-17 16:30:39 +0000986static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000987
Tim Peters6d6c1a32001-08-02 04:15:00 +0000988/* type test with subclassing support */
989
990int
991PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
992{
993 PyObject *mro;
994
Guido van Rossum9478d072001-09-07 18:52:13 +0000995 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
996 return b == a || b == &PyBaseObject_Type;
997
Tim Peters6d6c1a32001-08-02 04:15:00 +0000998 mro = a->tp_mro;
999 if (mro != NULL) {
1000 /* Deal with multiple inheritance without recursion
1001 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001002 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001003 assert(PyTuple_Check(mro));
1004 n = PyTuple_GET_SIZE(mro);
1005 for (i = 0; i < n; i++) {
1006 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1007 return 1;
1008 }
1009 return 0;
1010 }
1011 else {
1012 /* a is not completely initilized yet; follow tp_base */
1013 do {
1014 if (a == b)
1015 return 1;
1016 a = a->tp_base;
1017 } while (a != NULL);
1018 return b == &PyBaseObject_Type;
1019 }
1020}
1021
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001022/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001023 without looking in the instance dictionary
1024 (so we can't use PyObject_GetAttr) but still binding
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001025 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001026 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001027 static variable used to cache the interned Python string.
1028
1029 Two variants:
1030
1031 - lookup_maybe() returns NULL without raising an exception
1032 when the _PyType_Lookup() call fails;
1033
1034 - lookup_method() always raises an exception upon errors.
1035*/
Guido van Rossum60718732001-08-28 17:47:51 +00001036
1037static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001038lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001039{
1040 PyObject *res;
1041
1042 if (*attrobj == NULL) {
1043 *attrobj = PyString_InternFromString(attrstr);
1044 if (*attrobj == NULL)
1045 return NULL;
1046 }
Christian Heimese93237d2007-12-19 02:37:44 +00001047 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001048 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +00001049 descrgetfunc f;
Christian Heimese93237d2007-12-19 02:37:44 +00001050 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
Guido van Rossum60718732001-08-28 17:47:51 +00001051 Py_INCREF(res);
1052 else
Christian Heimese93237d2007-12-19 02:37:44 +00001053 res = f(res, self, (PyObject *)(Py_TYPE(self)));
Guido van Rossum60718732001-08-28 17:47:51 +00001054 }
1055 return res;
1056}
1057
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001058static PyObject *
1059lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1060{
1061 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1062 if (res == NULL && !PyErr_Occurred())
1063 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1064 return res;
1065}
1066
Guido van Rossum2730b132001-08-28 18:22:14 +00001067/* A variation of PyObject_CallMethod that uses lookup_method()
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001068 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001069 as lookup_method to cache the interned name string object. */
1070
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001071static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001072call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1073{
1074 va_list va;
1075 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001076 va_start(va, format);
1077
Guido van Rossumda21c012001-10-03 00:50:18 +00001078 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001079 if (func == NULL) {
1080 va_end(va);
1081 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +00001082 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001083 return NULL;
1084 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001085
1086 if (format && *format)
1087 args = Py_VaBuildValue(format, va);
1088 else
1089 args = PyTuple_New(0);
1090
1091 va_end(va);
1092
1093 if (args == NULL)
1094 return NULL;
1095
1096 assert(PyTuple_Check(args));
1097 retval = PyObject_Call(func, args, NULL);
1098
1099 Py_DECREF(args);
1100 Py_DECREF(func);
1101
1102 return retval;
1103}
1104
1105/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1106
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001107static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001108call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1109{
1110 va_list va;
1111 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001112 va_start(va, format);
1113
Guido van Rossumda21c012001-10-03 00:50:18 +00001114 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +00001115 if (func == NULL) {
1116 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001117 if (!PyErr_Occurred()) {
1118 Py_INCREF(Py_NotImplemented);
1119 return Py_NotImplemented;
1120 }
Guido van Rossum717ce002001-09-14 16:58:08 +00001121 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001122 }
1123
1124 if (format && *format)
1125 args = Py_VaBuildValue(format, va);
1126 else
1127 args = PyTuple_New(0);
1128
1129 va_end(va);
1130
Guido van Rossum717ce002001-09-14 16:58:08 +00001131 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00001132 return NULL;
1133
Guido van Rossum717ce002001-09-14 16:58:08 +00001134 assert(PyTuple_Check(args));
1135 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001136
1137 Py_DECREF(args);
1138 Py_DECREF(func);
1139
1140 return retval;
1141}
1142
Tim Petersa91e9642001-11-14 23:32:33 +00001143static int
1144fill_classic_mro(PyObject *mro, PyObject *cls)
1145{
1146 PyObject *bases, *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001147 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001148
1149 assert(PyList_Check(mro));
1150 assert(PyClass_Check(cls));
1151 i = PySequence_Contains(mro, cls);
1152 if (i < 0)
1153 return -1;
1154 if (!i) {
1155 if (PyList_Append(mro, cls) < 0)
1156 return -1;
1157 }
1158 bases = ((PyClassObject *)cls)->cl_bases;
1159 assert(bases && PyTuple_Check(bases));
1160 n = PyTuple_GET_SIZE(bases);
1161 for (i = 0; i < n; i++) {
1162 base = PyTuple_GET_ITEM(bases, i);
1163 if (fill_classic_mro(mro, base) < 0)
1164 return -1;
1165 }
1166 return 0;
1167}
1168
1169static PyObject *
1170classic_mro(PyObject *cls)
1171{
1172 PyObject *mro;
1173
1174 assert(PyClass_Check(cls));
1175 mro = PyList_New(0);
1176 if (mro != NULL) {
1177 if (fill_classic_mro(mro, cls) == 0)
1178 return mro;
1179 Py_DECREF(mro);
1180 }
1181 return NULL;
1182}
1183
Tim Petersea7f75d2002-12-07 21:39:16 +00001184/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001185 Method resolution order algorithm C3 described in
1186 "A Monotonic Superclass Linearization for Dylan",
1187 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001188 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001189 (OOPSLA 1996)
1190
Guido van Rossum98f33732002-11-25 21:36:54 +00001191 Some notes about the rules implied by C3:
1192
Tim Petersea7f75d2002-12-07 21:39:16 +00001193 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001194 It isn't legal to repeat a class in a list of base classes.
1195
1196 The next three properties are the 3 constraints in "C3".
1197
Tim Petersea7f75d2002-12-07 21:39:16 +00001198 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001199 If A precedes B in C's MRO, then A will precede B in the MRO of all
1200 subclasses of C.
1201
1202 Monotonicity.
1203 The MRO of a class must be an extension without reordering of the
1204 MRO of each of its superclasses.
1205
1206 Extended Precedence Graph (EPG).
1207 Linearization is consistent if there is a path in the EPG from
1208 each class to all its successors in the linearization. See
1209 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001210 */
1211
Tim Petersea7f75d2002-12-07 21:39:16 +00001212static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001213tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001214 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001215 size = PyList_GET_SIZE(list);
1216
1217 for (j = whence+1; j < size; j++) {
1218 if (PyList_GET_ITEM(list, j) == o)
1219 return 1;
1220 }
1221 return 0;
1222}
1223
Guido van Rossum98f33732002-11-25 21:36:54 +00001224static PyObject *
1225class_name(PyObject *cls)
1226{
1227 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1228 if (name == NULL) {
1229 PyErr_Clear();
1230 Py_XDECREF(name);
1231 name = PyObject_Repr(cls);
1232 }
1233 if (name == NULL)
1234 return NULL;
1235 if (!PyString_Check(name)) {
1236 Py_DECREF(name);
1237 return NULL;
1238 }
1239 return name;
1240}
1241
1242static int
1243check_duplicates(PyObject *list)
1244{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001245 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001246 /* Let's use a quadratic time algorithm,
1247 assuming that the bases lists is short.
1248 */
1249 n = PyList_GET_SIZE(list);
1250 for (i = 0; i < n; i++) {
1251 PyObject *o = PyList_GET_ITEM(list, i);
1252 for (j = i + 1; j < n; j++) {
1253 if (PyList_GET_ITEM(list, j) == o) {
1254 o = class_name(o);
1255 PyErr_Format(PyExc_TypeError,
1256 "duplicate base class %s",
1257 o ? PyString_AS_STRING(o) : "?");
1258 Py_XDECREF(o);
1259 return -1;
1260 }
1261 }
1262 }
1263 return 0;
1264}
1265
1266/* Raise a TypeError for an MRO order disagreement.
1267
1268 It's hard to produce a good error message. In the absence of better
1269 insight into error reporting, report the classes that were candidates
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001270 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001271 order in which they should be put in the MRO, but it's hard to
1272 diagnose what constraint can't be satisfied.
1273*/
1274
1275static void
1276set_mro_error(PyObject *to_merge, int *remain)
1277{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001278 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001279 char buf[1000];
1280 PyObject *k, *v;
1281 PyObject *set = PyDict_New();
Georg Brandl5c170fd2006-03-17 19:03:25 +00001282 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001283
1284 to_merge_size = PyList_GET_SIZE(to_merge);
1285 for (i = 0; i < to_merge_size; i++) {
1286 PyObject *L = PyList_GET_ITEM(to_merge, i);
1287 if (remain[i] < PyList_GET_SIZE(L)) {
1288 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Georg Brandl5c170fd2006-03-17 19:03:25 +00001289 if (PyDict_SetItem(set, c, Py_None) < 0) {
1290 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001291 return;
Georg Brandl5c170fd2006-03-17 19:03:25 +00001292 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001293 }
1294 }
1295 n = PyDict_Size(set);
1296
Raymond Hettingerf394df42003-04-06 19:13:41 +00001297 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1298consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001299 i = 0;
Skip Montanaro429433b2006-04-18 00:35:43 +00001300 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001301 PyObject *name = class_name(k);
1302 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1303 name ? PyString_AS_STRING(name) : "?");
1304 Py_XDECREF(name);
Skip Montanaro429433b2006-04-18 00:35:43 +00001305 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001306 buf[off++] = ',';
1307 buf[off] = '\0';
1308 }
1309 }
1310 PyErr_SetString(PyExc_TypeError, buf);
1311 Py_DECREF(set);
1312}
1313
Tim Petersea7f75d2002-12-07 21:39:16 +00001314static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001315pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001316 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001317 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001318 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001319
Guido van Rossum1f121312002-11-14 19:49:16 +00001320 to_merge_size = PyList_GET_SIZE(to_merge);
1321
Guido van Rossum98f33732002-11-25 21:36:54 +00001322 /* remain stores an index into each sublist of to_merge.
1323 remain[i] is the index of the next base in to_merge[i]
1324 that is not included in acc.
1325 */
Anthony Baxtera6286212006-04-11 07:42:36 +00001326 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001327 if (remain == NULL)
1328 return -1;
1329 for (i = 0; i < to_merge_size; i++)
1330 remain[i] = 0;
1331
1332 again:
1333 empty_cnt = 0;
1334 for (i = 0; i < to_merge_size; i++) {
1335 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001336
Guido van Rossum1f121312002-11-14 19:49:16 +00001337 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1338
1339 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1340 empty_cnt++;
1341 continue;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001342 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001343
Guido van Rossum98f33732002-11-25 21:36:54 +00001344 /* Choose next candidate for MRO.
1345
1346 The input sequences alone can determine the choice.
1347 If not, choose the class which appears in the MRO
1348 of the earliest direct superclass of the new class.
1349 */
1350
Guido van Rossum1f121312002-11-14 19:49:16 +00001351 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1352 for (j = 0; j < to_merge_size; j++) {
1353 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001354 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001355 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001356 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001357 }
1358 ok = PyList_Append(acc, candidate);
1359 if (ok < 0) {
1360 PyMem_Free(remain);
1361 return -1;
1362 }
1363 for (j = 0; j < to_merge_size; j++) {
1364 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001365 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1366 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001367 remain[j]++;
1368 }
1369 }
1370 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001371 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001372 }
1373
Guido van Rossum98f33732002-11-25 21:36:54 +00001374 if (empty_cnt == to_merge_size) {
1375 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001376 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001377 }
1378 set_mro_error(to_merge, remain);
1379 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001380 return -1;
1381}
1382
Tim Peters6d6c1a32001-08-02 04:15:00 +00001383static PyObject *
1384mro_implementation(PyTypeObject *type)
1385{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001386 Py_ssize_t i, n;
1387 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001388 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001389 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001390
Guido van Rossum63517572002-06-18 16:44:57 +00001391 if(type->tp_dict == NULL) {
1392 if(PyType_Ready(type) < 0)
1393 return NULL;
1394 }
1395
Guido van Rossum98f33732002-11-25 21:36:54 +00001396 /* Find a superclass linearization that honors the constraints
1397 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001398 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001399
1400 to_merge is a list of lists, where each list is a superclass
1401 linearization implied by a base class. The last element of
1402 to_merge is the declared list of bases.
1403 */
1404
Tim Peters6d6c1a32001-08-02 04:15:00 +00001405 bases = type->tp_bases;
1406 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001407
1408 to_merge = PyList_New(n+1);
1409 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001410 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001411
Tim Peters6d6c1a32001-08-02 04:15:00 +00001412 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001413 PyObject *base = PyTuple_GET_ITEM(bases, i);
1414 PyObject *parentMRO;
1415 if (PyType_Check(base))
1416 parentMRO = PySequence_List(
1417 ((PyTypeObject*)base)->tp_mro);
1418 else
1419 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001420 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001421 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001422 return NULL;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001423 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001424
1425 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001426 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001427
1428 bases_aslist = PySequence_List(bases);
1429 if (bases_aslist == NULL) {
1430 Py_DECREF(to_merge);
1431 return NULL;
1432 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001433 /* This is just a basic sanity check. */
1434 if (check_duplicates(bases_aslist) < 0) {
1435 Py_DECREF(to_merge);
1436 Py_DECREF(bases_aslist);
1437 return NULL;
1438 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001439 PyList_SET_ITEM(to_merge, n, bases_aslist);
1440
1441 result = Py_BuildValue("[O]", (PyObject *)type);
1442 if (result == NULL) {
1443 Py_DECREF(to_merge);
1444 return NULL;
1445 }
1446
1447 ok = pmerge(result, to_merge);
1448 Py_DECREF(to_merge);
1449 if (ok < 0) {
1450 Py_DECREF(result);
1451 return NULL;
1452 }
1453
Tim Peters6d6c1a32001-08-02 04:15:00 +00001454 return result;
1455}
1456
1457static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001458mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001459{
1460 PyTypeObject *type = (PyTypeObject *)self;
1461
Tim Peters6d6c1a32001-08-02 04:15:00 +00001462 return mro_implementation(type);
1463}
1464
1465static int
1466mro_internal(PyTypeObject *type)
1467{
1468 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001469 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470
Christian Heimese93237d2007-12-19 02:37:44 +00001471 if (Py_TYPE(type) == &PyType_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001472 result = mro_implementation(type);
1473 }
1474 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001475 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001476 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001477 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001478 if (mro == NULL)
1479 return -1;
1480 result = PyObject_CallObject(mro, NULL);
1481 Py_DECREF(mro);
1482 }
1483 if (result == NULL)
1484 return -1;
1485 tuple = PySequence_Tuple(result);
1486 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001487 if (tuple == NULL)
1488 return -1;
1489 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001490 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001491 PyObject *cls;
1492 PyTypeObject *solid;
1493
1494 solid = solid_base(type);
1495
1496 len = PyTuple_GET_SIZE(tuple);
1497
1498 for (i = 0; i < len; i++) {
1499 PyTypeObject *t;
1500 cls = PyTuple_GET_ITEM(tuple, i);
1501 if (PyClass_Check(cls))
1502 continue;
1503 else if (!PyType_Check(cls)) {
1504 PyErr_Format(PyExc_TypeError,
1505 "mro() returned a non-class ('%.500s')",
Christian Heimese93237d2007-12-19 02:37:44 +00001506 Py_TYPE(cls)->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001507 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001508 return -1;
1509 }
1510 t = (PyTypeObject*)cls;
1511 if (!PyType_IsSubtype(solid, solid_base(t))) {
1512 PyErr_Format(PyExc_TypeError,
1513 "mro() returned base with unsuitable layout ('%.500s')",
1514 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001515 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001516 return -1;
1517 }
1518 }
1519 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001520 type->tp_mro = tuple;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001521
1522 type_mro_modified(type, type->tp_mro);
1523 /* corner case: the old-style super class might have been hidden
1524 from the custom MRO */
1525 type_mro_modified(type, type->tp_bases);
1526
1527 type_modified(type);
1528
Tim Peters6d6c1a32001-08-02 04:15:00 +00001529 return 0;
1530}
1531
1532
1533/* Calculate the best base amongst multiple base classes.
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001534 This is the first one that's on the path to the "solid base". */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001535
1536static PyTypeObject *
1537best_base(PyObject *bases)
1538{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001539 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001540 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001541 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001542
1543 assert(PyTuple_Check(bases));
1544 n = PyTuple_GET_SIZE(bases);
1545 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001546 base = NULL;
1547 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001548 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001549 base_proto = PyTuple_GET_ITEM(bases, i);
1550 if (PyClass_Check(base_proto))
1551 continue;
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001552 if (!PyType_Check(base_proto)) {
1553 PyErr_SetString(
1554 PyExc_TypeError,
1555 "bases must be types");
1556 return NULL;
1557 }
Tim Petersa91e9642001-11-14 23:32:33 +00001558 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001559 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001560 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001561 return NULL;
1562 }
1563 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001564 if (winner == NULL) {
1565 winner = candidate;
1566 base = base_i;
1567 }
1568 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001569 ;
1570 else if (PyType_IsSubtype(candidate, winner)) {
1571 winner = candidate;
1572 base = base_i;
1573 }
1574 else {
1575 PyErr_SetString(
1576 PyExc_TypeError,
1577 "multiple bases have "
1578 "instance lay-out conflict");
1579 return NULL;
1580 }
1581 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001582 if (base == NULL)
1583 PyErr_SetString(PyExc_TypeError,
1584 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001585 return base;
1586}
1587
1588static int
1589extra_ivars(PyTypeObject *type, PyTypeObject *base)
1590{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001591 size_t t_size = type->tp_basicsize;
1592 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001593
Guido van Rossum9676b222001-08-17 20:32:36 +00001594 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001595 if (type->tp_itemsize || base->tp_itemsize) {
1596 /* If itemsize is involved, stricter rules */
1597 return t_size != b_size ||
1598 type->tp_itemsize != base->tp_itemsize;
1599 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001600 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001601 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1602 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001603 t_size -= sizeof(PyObject *);
1604 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001605 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1606 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001607 t_size -= sizeof(PyObject *);
1608
1609 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001610}
1611
1612static PyTypeObject *
1613solid_base(PyTypeObject *type)
1614{
1615 PyTypeObject *base;
1616
1617 if (type->tp_base)
1618 base = solid_base(type->tp_base);
1619 else
1620 base = &PyBaseObject_Type;
1621 if (extra_ivars(type, base))
1622 return type;
1623 else
1624 return base;
1625}
1626
Jeremy Hylton938ace62002-07-17 16:30:39 +00001627static void object_dealloc(PyObject *);
1628static int object_init(PyObject *, PyObject *, PyObject *);
1629static int update_slot(PyTypeObject *, PyObject *);
1630static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631
Armin Rigo9790a272007-05-02 19:23:31 +00001632/*
1633 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1634 * inherited from various builtin types. The builtin base usually provides
1635 * its own __dict__ descriptor, so we use that when we can.
1636 */
1637static PyTypeObject *
1638get_builtin_base_with_dict(PyTypeObject *type)
1639{
1640 while (type->tp_base != NULL) {
1641 if (type->tp_dictoffset != 0 &&
1642 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1643 return type;
1644 type = type->tp_base;
1645 }
1646 return NULL;
1647}
1648
1649static PyObject *
1650get_dict_descriptor(PyTypeObject *type)
1651{
1652 static PyObject *dict_str;
1653 PyObject *descr;
1654
1655 if (dict_str == NULL) {
1656 dict_str = PyString_InternFromString("__dict__");
1657 if (dict_str == NULL)
1658 return NULL;
1659 }
1660 descr = _PyType_Lookup(type, dict_str);
1661 if (descr == NULL || !PyDescr_IsData(descr))
1662 return NULL;
1663
1664 return descr;
1665}
1666
1667static void
1668raise_dict_descr_error(PyObject *obj)
1669{
1670 PyErr_Format(PyExc_TypeError,
1671 "this __dict__ descriptor does not support "
1672 "'%.200s' objects", obj->ob_type->tp_name);
1673}
1674
Tim Peters6d6c1a32001-08-02 04:15:00 +00001675static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001676subtype_dict(PyObject *obj, void *context)
1677{
Armin Rigo9790a272007-05-02 19:23:31 +00001678 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001679 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001680 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001681
Armin Rigo9790a272007-05-02 19:23:31 +00001682 base = get_builtin_base_with_dict(obj->ob_type);
1683 if (base != NULL) {
1684 descrgetfunc func;
1685 PyObject *descr = get_dict_descriptor(base);
1686 if (descr == NULL) {
1687 raise_dict_descr_error(obj);
1688 return NULL;
1689 }
1690 func = descr->ob_type->tp_descr_get;
1691 if (func == NULL) {
1692 raise_dict_descr_error(obj);
1693 return NULL;
1694 }
1695 return func(descr, obj, (PyObject *)(obj->ob_type));
1696 }
1697
1698 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001699 if (dictptr == NULL) {
1700 PyErr_SetString(PyExc_AttributeError,
1701 "This object has no __dict__");
1702 return NULL;
1703 }
1704 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001705 if (dict == NULL)
1706 *dictptr = dict = PyDict_New();
1707 Py_XINCREF(dict);
1708 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001709}
1710
Guido van Rossum6661be32001-10-26 04:26:12 +00001711static int
1712subtype_setdict(PyObject *obj, PyObject *value, void *context)
1713{
Armin Rigo9790a272007-05-02 19:23:31 +00001714 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001715 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001716 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001717
Armin Rigo9790a272007-05-02 19:23:31 +00001718 base = get_builtin_base_with_dict(obj->ob_type);
1719 if (base != NULL) {
1720 descrsetfunc func;
1721 PyObject *descr = get_dict_descriptor(base);
1722 if (descr == NULL) {
1723 raise_dict_descr_error(obj);
1724 return -1;
1725 }
1726 func = descr->ob_type->tp_descr_set;
1727 if (func == NULL) {
1728 raise_dict_descr_error(obj);
1729 return -1;
1730 }
1731 return func(descr, obj, value);
1732 }
1733
1734 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001735 if (dictptr == NULL) {
1736 PyErr_SetString(PyExc_AttributeError,
1737 "This object has no __dict__");
1738 return -1;
1739 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001740 if (value != NULL && !PyDict_Check(value)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001741 PyErr_Format(PyExc_TypeError,
1742 "__dict__ must be set to a dictionary, "
Christian Heimese93237d2007-12-19 02:37:44 +00001743 "not a '%.200s'", Py_TYPE(value)->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001744 return -1;
1745 }
1746 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001747 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001748 *dictptr = value;
1749 Py_XDECREF(dict);
1750 return 0;
1751}
1752
Guido van Rossumad47da02002-08-12 19:05:44 +00001753static PyObject *
1754subtype_getweakref(PyObject *obj, void *context)
1755{
1756 PyObject **weaklistptr;
1757 PyObject *result;
1758
Christian Heimese93237d2007-12-19 02:37:44 +00001759 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001760 PyErr_SetString(PyExc_AttributeError,
Fred Drake7a36f5f2006-08-04 05:17:21 +00001761 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001762 return NULL;
1763 }
Christian Heimese93237d2007-12-19 02:37:44 +00001764 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1765 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1766 (size_t)(Py_TYPE(obj)->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001767 weaklistptr = (PyObject **)
Christian Heimese93237d2007-12-19 02:37:44 +00001768 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001769 if (*weaklistptr == NULL)
1770 result = Py_None;
1771 else
1772 result = *weaklistptr;
1773 Py_INCREF(result);
1774 return result;
1775}
1776
Guido van Rossum373c7412003-01-07 13:41:37 +00001777/* Three variants on the subtype_getsets list. */
1778
1779static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001780 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001781 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001782 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001783 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001784 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001785};
1786
Guido van Rossum373c7412003-01-07 13:41:37 +00001787static PyGetSetDef subtype_getsets_dict_only[] = {
1788 {"__dict__", subtype_dict, subtype_setdict,
1789 PyDoc_STR("dictionary for instance variables (if defined)")},
1790 {0}
1791};
1792
1793static PyGetSetDef subtype_getsets_weakref_only[] = {
1794 {"__weakref__", subtype_getweakref, NULL,
1795 PyDoc_STR("list of weak references to the object (if defined)")},
1796 {0}
1797};
1798
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001799static int
1800valid_identifier(PyObject *s)
1801{
Guido van Rossum03013a02002-07-16 14:30:28 +00001802 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001803 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001804
1805 if (!PyString_Check(s)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001806 PyErr_Format(PyExc_TypeError,
1807 "__slots__ items must be strings, not '%.200s'",
Christian Heimese93237d2007-12-19 02:37:44 +00001808 Py_TYPE(s)->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001809 return 0;
1810 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001811 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001812 n = PyString_GET_SIZE(s);
1813 /* We must reject an empty name. As a hack, we bump the
1814 length to 1 so that the loop will balk on the trailing \0. */
1815 if (n == 0)
1816 n = 1;
1817 for (i = 0; i < n; i++, p++) {
1818 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1819 PyErr_SetString(PyExc_TypeError,
1820 "__slots__ must be identifiers");
1821 return 0;
1822 }
1823 }
1824 return 1;
1825}
1826
Martin v. Löwisd919a592002-10-14 21:07:28 +00001827#ifdef Py_USING_UNICODE
1828/* Replace Unicode objects in slots. */
1829
1830static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001831_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001832{
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001833 PyObject *tmp = NULL;
1834 PyObject *slot_name, *new_name;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001835 Py_ssize_t i;
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001836
Martin v. Löwisd919a592002-10-14 21:07:28 +00001837 for (i = 0; i < nslots; i++) {
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001838 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1839 if (tmp == NULL) {
1840 tmp = PySequence_List(slots);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001841 if (tmp == NULL)
1842 return NULL;
1843 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001844 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1845 NULL);
1846 if (new_name == NULL) {
Martin v. Löwisd919a592002-10-14 21:07:28 +00001847 Py_DECREF(tmp);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001848 return NULL;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001849 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001850 Py_INCREF(new_name);
1851 PyList_SET_ITEM(tmp, i, new_name);
1852 Py_DECREF(slot_name);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001853 }
1854 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001855 if (tmp != NULL) {
1856 slots = PyList_AsTuple(tmp);
1857 Py_DECREF(tmp);
1858 }
1859 return slots;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001860}
1861#endif
1862
Guido van Rossumf102e242007-03-23 18:53:03 +00001863/* Forward */
1864static int
1865object_init(PyObject *self, PyObject *args, PyObject *kwds);
1866
1867static int
1868type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1869{
1870 int res;
1871
1872 assert(args != NULL && PyTuple_Check(args));
1873 assert(kwds == NULL || PyDict_Check(kwds));
1874
1875 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1876 PyErr_SetString(PyExc_TypeError,
1877 "type.__init__() takes no keyword arguments");
1878 return -1;
1879 }
1880
1881 if (args != NULL && PyTuple_Check(args) &&
1882 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1883 PyErr_SetString(PyExc_TypeError,
1884 "type.__init__() takes 1 or 3 arguments");
1885 return -1;
1886 }
1887
1888 /* Call object.__init__(self) now. */
1889 /* XXX Could call super(type, cls).__init__() but what's the point? */
1890 args = PyTuple_GetSlice(args, 0, 0);
1891 res = object_init(cls, args, NULL);
1892 Py_DECREF(args);
1893 return res;
1894}
1895
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001896static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001897type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1898{
1899 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001900 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001901 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001902 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001903 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001904 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001905 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001906 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001907
Tim Peters3abca122001-10-27 19:37:48 +00001908 assert(args != NULL && PyTuple_Check(args));
1909 assert(kwds == NULL || PyDict_Check(kwds));
1910
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001911 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001912 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001913 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1914 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001915
1916 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1917 PyObject *x = PyTuple_GET_ITEM(args, 0);
Christian Heimese93237d2007-12-19 02:37:44 +00001918 Py_INCREF(Py_TYPE(x));
1919 return (PyObject *) Py_TYPE(x);
Tim Peters3abca122001-10-27 19:37:48 +00001920 }
1921
1922 /* SF bug 475327 -- if that didn't trigger, we need 3
1923 arguments. but PyArg_ParseTupleAndKeywords below may give
1924 a msg saying type() needs exactly 3. */
1925 if (nargs + nkwds != 3) {
1926 PyErr_SetString(PyExc_TypeError,
1927 "type() takes 1 or 3 arguments");
1928 return NULL;
1929 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001930 }
1931
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001932 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001933 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1934 &name,
1935 &PyTuple_Type, &bases,
1936 &PyDict_Type, &dict))
1937 return NULL;
1938
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001939 /* Determine the proper metatype to deal with this,
1940 and check for metatype conflicts while we're at it.
1941 Note that if some other metatype wins to contract,
1942 it's possible that its instances are not types. */
1943 nbases = PyTuple_GET_SIZE(bases);
1944 winner = metatype;
1945 for (i = 0; i < nbases; i++) {
1946 tmp = PyTuple_GET_ITEM(bases, i);
1947 tmptype = tmp->ob_type;
1948 if (tmptype == &PyClass_Type)
1949 continue; /* Special case classic classes */
1950 if (PyType_IsSubtype(winner, tmptype))
1951 continue;
1952 if (PyType_IsSubtype(tmptype, winner)) {
1953 winner = tmptype;
1954 continue;
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001955 }
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001956 PyErr_SetString(PyExc_TypeError,
1957 "metaclass conflict: "
1958 "the metaclass of a derived class "
1959 "must be a (non-strict) subclass "
1960 "of the metaclasses of all its bases");
1961 return NULL;
1962 }
1963 if (winner != metatype) {
1964 if (winner->tp_new != type_new) /* Pass it to the winner */
1965 return winner->tp_new(winner, args, kwds);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001966 metatype = winner;
1967 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001968
1969 /* Adjust for empty tuple bases */
1970 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001971 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001972 if (bases == NULL)
1973 return NULL;
1974 nbases = 1;
1975 }
1976 else
1977 Py_INCREF(bases);
1978
1979 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1980
1981 /* Calculate best base, and check that all bases are type objects */
1982 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001983 if (base == NULL) {
1984 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001985 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001986 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1988 PyErr_Format(PyExc_TypeError,
1989 "type '%.100s' is not an acceptable base type",
1990 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001991 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001992 return NULL;
1993 }
1994
Tim Peters6d6c1a32001-08-02 04:15:00 +00001995 /* Check for a __slots__ sequence variable in dict, and count it */
1996 slots = PyDict_GetItemString(dict, "__slots__");
1997 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001998 add_dict = 0;
1999 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00002000 may_add_dict = base->tp_dictoffset == 0;
2001 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2002 if (slots == NULL) {
2003 if (may_add_dict) {
2004 add_dict++;
2005 }
2006 if (may_add_weak) {
2007 add_weak++;
2008 }
2009 }
2010 else {
2011 /* Have slots */
2012
Tim Peters6d6c1a32001-08-02 04:15:00 +00002013 /* Make it into a tuple */
Neal Norwitzcbd9ee62007-04-14 05:25:50 +00002014 if (PyString_Check(slots) || PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002015 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002016 else
2017 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002018 if (slots == NULL) {
2019 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002021 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002022 assert(PyTuple_Check(slots));
2023
2024 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00002026 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00002027 PyErr_Format(PyExc_TypeError,
2028 "nonempty __slots__ "
2029 "not supported for subtype of '%s'",
2030 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00002031 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002032 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00002033 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00002034 return NULL;
2035 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002036
Martin v. Löwisd919a592002-10-14 21:07:28 +00002037#ifdef Py_USING_UNICODE
2038 tmp = _unicode_to_string(slots, nslots);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00002039 if (tmp == NULL)
2040 goto bad_slots;
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00002041 if (tmp != slots) {
2042 Py_DECREF(slots);
2043 slots = tmp;
2044 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00002045#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00002046 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002047 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00002048 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2049 char *s;
2050 if (!valid_identifier(tmp))
2051 goto bad_slots;
2052 assert(PyString_Check(tmp));
2053 s = PyString_AS_STRING(tmp);
2054 if (strcmp(s, "__dict__") == 0) {
2055 if (!may_add_dict || add_dict) {
2056 PyErr_SetString(PyExc_TypeError,
2057 "__dict__ slot disallowed: "
2058 "we already got one");
2059 goto bad_slots;
2060 }
2061 add_dict++;
2062 }
2063 if (strcmp(s, "__weakref__") == 0) {
2064 if (!may_add_weak || add_weak) {
2065 PyErr_SetString(PyExc_TypeError,
2066 "__weakref__ slot disallowed: "
2067 "either we already got one, "
2068 "or __itemsize__ != 0");
2069 goto bad_slots;
2070 }
2071 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002072 }
2073 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002074
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002075 /* Copy slots into a list, mangle names and sort them.
2076 Sorted names are needed for __class__ assignment.
2077 Convert them back to tuple at the end.
2078 */
2079 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002080 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00002081 goto bad_slots;
2082 for (i = j = 0; i < nslots; i++) {
2083 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002084 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00002085 s = PyString_AS_STRING(tmp);
2086 if ((add_dict && strcmp(s, "__dict__") == 0) ||
2087 (add_weak && strcmp(s, "__weakref__") == 0))
2088 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089 tmp =_Py_Mangle(name, tmp);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002090 if (!tmp)
2091 goto bad_slots;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002092 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00002093 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002094 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002095 assert(j == nslots - add_dict - add_weak);
2096 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002097 Py_DECREF(slots);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002098 if (PyList_Sort(newslots) == -1) {
2099 Py_DECREF(bases);
2100 Py_DECREF(newslots);
2101 return NULL;
2102 }
2103 slots = PyList_AsTuple(newslots);
2104 Py_DECREF(newslots);
2105 if (slots == NULL) {
2106 Py_DECREF(bases);
2107 return NULL;
2108 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002109
Guido van Rossumad47da02002-08-12 19:05:44 +00002110 /* Secondary bases may provide weakrefs or dict */
2111 if (nbases > 1 &&
2112 ((may_add_dict && !add_dict) ||
2113 (may_add_weak && !add_weak))) {
2114 for (i = 0; i < nbases; i++) {
2115 tmp = PyTuple_GET_ITEM(bases, i);
2116 if (tmp == (PyObject *)base)
2117 continue; /* Skip primary base */
2118 if (PyClass_Check(tmp)) {
2119 /* Classic base class provides both */
2120 if (may_add_dict && !add_dict)
2121 add_dict++;
2122 if (may_add_weak && !add_weak)
2123 add_weak++;
2124 break;
2125 }
2126 assert(PyType_Check(tmp));
2127 tmptype = (PyTypeObject *)tmp;
2128 if (may_add_dict && !add_dict &&
2129 tmptype->tp_dictoffset != 0)
2130 add_dict++;
2131 if (may_add_weak && !add_weak &&
2132 tmptype->tp_weaklistoffset != 0)
2133 add_weak++;
2134 if (may_add_dict && !add_dict)
2135 continue;
2136 if (may_add_weak && !add_weak)
2137 continue;
2138 /* Nothing more to check */
2139 break;
2140 }
2141 }
Guido van Rossum9676b222001-08-17 20:32:36 +00002142 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002143
2144 /* XXX From here until type is safely allocated,
2145 "return NULL" may leak slots! */
2146
2147 /* Allocate the type object */
2148 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00002149 if (type == NULL) {
2150 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002151 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002152 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00002153 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002154
2155 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002156 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002157 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002158 et->ht_name = name;
2159 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002160
Guido van Rossumdc91b992001-08-08 22:26:22 +00002161 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002162 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2163 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002164 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2165 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002166
2167 /* It's a new-style number unless it specifically inherits any
2168 old-style numeric behavior */
2169 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
2170 (base->tp_as_number == NULL))
2171 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
2172
2173 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002174 type->tp_as_number = &et->as_number;
2175 type->tp_as_sequence = &et->as_sequence;
2176 type->tp_as_mapping = &et->as_mapping;
2177 type->tp_as_buffer = &et->as_buffer;
2178 type->tp_name = PyString_AS_STRING(name);
2179
2180 /* Set tp_base and tp_bases */
2181 type->tp_bases = bases;
2182 Py_INCREF(base);
2183 type->tp_base = base;
2184
Guido van Rossum687ae002001-10-15 22:03:32 +00002185 /* Initialize tp_dict from passed-in dict */
2186 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002187 if (dict == NULL) {
2188 Py_DECREF(type);
2189 return NULL;
2190 }
2191
Guido van Rossumc3542212001-08-16 09:18:56 +00002192 /* Set __module__ in the dict */
2193 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2194 tmp = PyEval_GetGlobals();
2195 if (tmp != NULL) {
2196 tmp = PyDict_GetItemString(tmp, "__name__");
2197 if (tmp != NULL) {
2198 if (PyDict_SetItemString(dict, "__module__",
2199 tmp) < 0)
2200 return NULL;
2201 }
2202 }
2203 }
2204
Tim Peters2f93e282001-10-04 05:27:00 +00002205 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00002206 and is a string. The __doc__ accessor will first look for tp_doc;
2207 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00002208 */
2209 {
2210 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2211 if (doc != NULL && PyString_Check(doc)) {
2212 const size_t n = (size_t)PyString_GET_SIZE(doc);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002213 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002214 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00002215 Py_DECREF(type);
2216 return NULL;
2217 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002218 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002219 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00002220 }
2221 }
2222
Tim Peters6d6c1a32001-08-02 04:15:00 +00002223 /* Special-case __new__: if it's a plain function,
2224 make it a static function */
2225 tmp = PyDict_GetItemString(dict, "__new__");
2226 if (tmp != NULL && PyFunction_Check(tmp)) {
2227 tmp = PyStaticMethod_New(tmp);
2228 if (tmp == NULL) {
2229 Py_DECREF(type);
2230 return NULL;
2231 }
2232 PyDict_SetItemString(dict, "__new__", tmp);
2233 Py_DECREF(tmp);
2234 }
2235
2236 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002237 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00002238 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239 if (slots != NULL) {
2240 for (i = 0; i < nslots; i++, mp++) {
2241 mp->name = PyString_AS_STRING(
2242 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00002243 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002244 mp->offset = slotoffset;
Žiga Seilnacht89032082007-03-11 15:54:54 +00002245
2246 /* __dict__ and __weakref__ are already filtered out */
2247 assert(strcmp(mp->name, "__dict__") != 0);
2248 assert(strcmp(mp->name, "__weakref__") != 0);
2249
Tim Peters6d6c1a32001-08-02 04:15:00 +00002250 slotoffset += sizeof(PyObject *);
2251 }
2252 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002253 if (add_dict) {
2254 if (base->tp_itemsize)
2255 type->tp_dictoffset = -(long)sizeof(PyObject *);
2256 else
2257 type->tp_dictoffset = slotoffset;
2258 slotoffset += sizeof(PyObject *);
2259 }
2260 if (add_weak) {
2261 assert(!base->tp_itemsize);
2262 type->tp_weaklistoffset = slotoffset;
2263 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002264 }
2265 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002266 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002267 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002268
2269 if (type->tp_weaklistoffset && type->tp_dictoffset)
2270 type->tp_getset = subtype_getsets_full;
2271 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2272 type->tp_getset = subtype_getsets_weakref_only;
2273 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2274 type->tp_getset = subtype_getsets_dict_only;
2275 else
2276 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002277
2278 /* Special case some slots */
2279 if (type->tp_dictoffset != 0 || nslots > 0) {
2280 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2281 type->tp_getattro = PyObject_GenericGetAttr;
2282 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2283 type->tp_setattro = PyObject_GenericSetAttr;
2284 }
2285 type->tp_dealloc = subtype_dealloc;
2286
Guido van Rossum9475a232001-10-05 20:51:39 +00002287 /* Enable GC unless there are really no instance variables possible */
2288 if (!(type->tp_basicsize == sizeof(PyObject) &&
2289 type->tp_itemsize == 0))
2290 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2291
Tim Peters6d6c1a32001-08-02 04:15:00 +00002292 /* Always override allocation strategy to use regular heap */
2293 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002294 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002295 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002296 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002297 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002298 }
2299 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002300 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002301
2302 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002303 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002304 Py_DECREF(type);
2305 return NULL;
2306 }
2307
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002308 /* Put the proper slots in place */
2309 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002310
Tim Peters6d6c1a32001-08-02 04:15:00 +00002311 return (PyObject *)type;
2312}
2313
2314/* Internal API to look for a name through the MRO.
2315 This returns a borrowed reference, and doesn't set an exception! */
2316PyObject *
2317_PyType_Lookup(PyTypeObject *type, PyObject *name)
2318{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002319 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002320 PyObject *mro, *res, *base, *dict;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002321 unsigned int h;
2322
2323 if (MCACHE_CACHEABLE_NAME(name) &&
2324 PyType_HasFeature(type,Py_TPFLAGS_VALID_VERSION_TAG)) {
2325 /* fast path */
2326 h = MCACHE_HASH_METHOD(type, name);
2327 if (method_cache[h].version == type->tp_version_tag &&
2328 method_cache[h].name == name)
2329 return method_cache[h].value;
2330 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002331
Guido van Rossum687ae002001-10-15 22:03:32 +00002332 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002333 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002334
2335 /* If mro is NULL, the type is either not yet initialized
2336 by PyType_Ready(), or already cleared by type_clear().
2337 Either way the safest thing to do is to return NULL. */
2338 if (mro == NULL)
2339 return NULL;
2340
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002341 res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002342 assert(PyTuple_Check(mro));
2343 n = PyTuple_GET_SIZE(mro);
2344 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002345 base = PyTuple_GET_ITEM(mro, i);
2346 if (PyClass_Check(base))
2347 dict = ((PyClassObject *)base)->cl_dict;
2348 else {
2349 assert(PyType_Check(base));
2350 dict = ((PyTypeObject *)base)->tp_dict;
2351 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002352 assert(dict && PyDict_Check(dict));
2353 res = PyDict_GetItem(dict, name);
2354 if (res != NULL)
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002355 break;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002356 }
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002357
2358 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2359 h = MCACHE_HASH_METHOD(type, name);
2360 method_cache[h].version = type->tp_version_tag;
2361 method_cache[h].value = res; /* borrowed */
2362 Py_INCREF(name);
2363 Py_DECREF(method_cache[h].name);
2364 method_cache[h].name = name;
2365 }
2366 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002367}
2368
2369/* This is similar to PyObject_GenericGetAttr(),
2370 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2371static PyObject *
2372type_getattro(PyTypeObject *type, PyObject *name)
2373{
Christian Heimese93237d2007-12-19 02:37:44 +00002374 PyTypeObject *metatype = Py_TYPE(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002375 PyObject *meta_attribute, *attribute;
2376 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002377
2378 /* Initialize this type (we'll assume the metatype is initialized) */
2379 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002380 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002381 return NULL;
2382 }
2383
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002384 /* No readable descriptor found yet */
2385 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002386
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002387 /* Look for the attribute in the metatype */
2388 meta_attribute = _PyType_Lookup(metatype, name);
2389
2390 if (meta_attribute != NULL) {
Christian Heimese93237d2007-12-19 02:37:44 +00002391 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002392
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002393 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2394 /* Data descriptors implement tp_descr_set to intercept
2395 * writes. Assume the attribute is not overridden in
2396 * type's tp_dict (and bases): call the descriptor now.
2397 */
2398 return meta_get(meta_attribute, (PyObject *)type,
2399 (PyObject *)metatype);
2400 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002401 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002402 }
2403
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002404 /* No data descriptor found on metatype. Look in tp_dict of this
2405 * type and its bases */
2406 attribute = _PyType_Lookup(type, name);
2407 if (attribute != NULL) {
2408 /* Implement descriptor functionality, if any */
Christian Heimese93237d2007-12-19 02:37:44 +00002409 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002410
2411 Py_XDECREF(meta_attribute);
2412
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002413 if (local_get != NULL) {
2414 /* NULL 2nd argument indicates the descriptor was
2415 * found on the target object itself (or a base) */
2416 return local_get(attribute, (PyObject *)NULL,
2417 (PyObject *)type);
2418 }
Tim Peters34592512002-07-11 06:23:50 +00002419
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002420 Py_INCREF(attribute);
2421 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002422 }
2423
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002424 /* No attribute found in local __dict__ (or bases): use the
2425 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002426 if (meta_get != NULL) {
2427 PyObject *res;
2428 res = meta_get(meta_attribute, (PyObject *)type,
2429 (PyObject *)metatype);
2430 Py_DECREF(meta_attribute);
2431 return res;
2432 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002433
2434 /* If an ordinary attribute was found on the metatype, return it now */
2435 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002436 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002437 }
2438
2439 /* Give up */
2440 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002441 "type object '%.50s' has no attribute '%.400s'",
2442 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002443 return NULL;
2444}
2445
2446static int
2447type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2448{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002449 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2450 PyErr_Format(
2451 PyExc_TypeError,
2452 "can't set attributes of built-in/extension type '%s'",
2453 type->tp_name);
2454 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002455 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002456 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2457 return -1;
2458 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002459}
2460
2461static void
2462type_dealloc(PyTypeObject *type)
2463{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002464 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002465
2466 /* Assert this is a heap-allocated type object */
2467 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002468 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002469 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002470 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002471 Py_XDECREF(type->tp_base);
2472 Py_XDECREF(type->tp_dict);
2473 Py_XDECREF(type->tp_bases);
2474 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002475 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002476 Py_XDECREF(type->tp_subclasses);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002477 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2478 * of most other objects. It's okay to cast it to char *.
2479 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002480 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002481 Py_XDECREF(et->ht_name);
2482 Py_XDECREF(et->ht_slots);
Christian Heimese93237d2007-12-19 02:37:44 +00002483 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002484}
2485
Guido van Rossum1c450732001-10-08 15:18:27 +00002486static PyObject *
2487type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2488{
2489 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002490 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002491
2492 list = PyList_New(0);
2493 if (list == NULL)
2494 return NULL;
2495 raw = type->tp_subclasses;
2496 if (raw == NULL)
2497 return list;
2498 assert(PyList_Check(raw));
2499 n = PyList_GET_SIZE(raw);
2500 for (i = 0; i < n; i++) {
2501 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002502 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002503 ref = PyWeakref_GET_OBJECT(ref);
2504 if (ref != Py_None) {
2505 if (PyList_Append(list, ref) < 0) {
2506 Py_DECREF(list);
2507 return NULL;
2508 }
2509 }
2510 }
2511 return list;
2512}
2513
Tim Peters6d6c1a32001-08-02 04:15:00 +00002514static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002515 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002516 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002517 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002518 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002519 {0}
2520};
2521
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002522PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002523"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002524"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002525
Guido van Rossum048eb752001-10-02 21:24:57 +00002526static int
2527type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2528{
Guido van Rossuma3862092002-06-10 15:24:42 +00002529 /* Because of type_is_gc(), the collector only calls this
2530 for heaptypes. */
2531 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002532
Thomas Woutersc6e55062006-04-15 21:47:09 +00002533 Py_VISIT(type->tp_dict);
2534 Py_VISIT(type->tp_cache);
2535 Py_VISIT(type->tp_mro);
2536 Py_VISIT(type->tp_bases);
2537 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002538
2539 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002540 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002541 in cycles; tp_subclasses is a list of weak references,
2542 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002543
Guido van Rossum048eb752001-10-02 21:24:57 +00002544 return 0;
2545}
2546
2547static int
2548type_clear(PyTypeObject *type)
2549{
Guido van Rossuma3862092002-06-10 15:24:42 +00002550 /* Because of type_is_gc(), the collector only calls this
2551 for heaptypes. */
2552 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002553
Guido van Rossuma3862092002-06-10 15:24:42 +00002554 /* The only field we need to clear is tp_mro, which is part of a
2555 hard cycle (its first element is the class itself) that won't
2556 be broken otherwise (it's a tuple and tuples don't have a
2557 tp_clear handler). None of the other fields need to be
2558 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002559
Guido van Rossuma3862092002-06-10 15:24:42 +00002560 tp_dict:
2561 It is a dict, so the collector will call its tp_clear.
2562
2563 tp_cache:
2564 Not used; if it were, it would be a dict.
2565
2566 tp_bases, tp_base:
2567 If these are involved in a cycle, there must be at least
2568 one other, mutable object in the cycle, e.g. a base
2569 class's dict; the cycle will be broken that way.
2570
2571 tp_subclasses:
2572 A list of weak references can't be part of a cycle; and
2573 lists have their own tp_clear.
2574
Guido van Rossume5c691a2003-03-07 15:13:17 +00002575 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002576 A tuple of strings can't be part of a cycle.
2577 */
2578
Thomas Woutersedf17d82006-04-15 17:28:34 +00002579 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002580
2581 return 0;
2582}
2583
2584static int
2585type_is_gc(PyTypeObject *type)
2586{
2587 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2588}
2589
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002590PyTypeObject PyType_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002591 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002592 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002593 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002594 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002595 (destructor)type_dealloc, /* tp_dealloc */
2596 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002597 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002598 0, /* tp_setattr */
2599 type_compare, /* tp_compare */
2600 (reprfunc)type_repr, /* tp_repr */
2601 0, /* tp_as_number */
2602 0, /* tp_as_sequence */
2603 0, /* tp_as_mapping */
2604 (hashfunc)_Py_HashPointer, /* tp_hash */
2605 (ternaryfunc)type_call, /* tp_call */
2606 0, /* tp_str */
2607 (getattrofunc)type_getattro, /* tp_getattro */
2608 (setattrofunc)type_setattro, /* tp_setattro */
2609 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002610 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002611 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002612 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002613 (traverseproc)type_traverse, /* tp_traverse */
2614 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002615 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002616 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002617 0, /* tp_iter */
2618 0, /* tp_iternext */
2619 type_methods, /* tp_methods */
2620 type_members, /* tp_members */
2621 type_getsets, /* tp_getset */
2622 0, /* tp_base */
2623 0, /* tp_dict */
2624 0, /* tp_descr_get */
2625 0, /* tp_descr_set */
2626 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumf102e242007-03-23 18:53:03 +00002627 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002628 0, /* tp_alloc */
2629 type_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002630 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002631 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002632};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002633
2634
2635/* The base type of all types (eventually)... except itself. */
2636
Guido van Rossum143b5642007-03-23 04:58:42 +00002637/* You may wonder why object.__new__() only complains about arguments
2638 when object.__init__() is not overridden, and vice versa.
2639
2640 Consider the use cases:
2641
2642 1. When neither is overridden, we want to hear complaints about
2643 excess (i.e., any) arguments, since their presence could
2644 indicate there's a bug.
2645
2646 2. When defining an Immutable type, we are likely to override only
2647 __new__(), since __init__() is called too late to initialize an
2648 Immutable object. Since __new__() defines the signature for the
2649 type, it would be a pain to have to override __init__() just to
2650 stop it from complaining about excess arguments.
2651
2652 3. When defining a Mutable type, we are likely to override only
2653 __init__(). So here the converse reasoning applies: we don't
2654 want to have to override __new__() just to stop it from
2655 complaining.
2656
2657 4. When __init__() is overridden, and the subclass __init__() calls
2658 object.__init__(), the latter should complain about excess
2659 arguments; ditto for __new__().
2660
2661 Use cases 2 and 3 make it unattractive to unconditionally check for
2662 excess arguments. The best solution that addresses all four use
2663 cases is as follows: __init__() complains about excess arguments
2664 unless __new__() is overridden and __init__() is not overridden
2665 (IOW, if __init__() is overridden or __new__() is not overridden);
2666 symmetrically, __new__() complains about excess arguments unless
2667 __init__() is overridden and __new__() is not overridden
2668 (IOW, if __new__() is overridden or __init__() is not overridden).
2669
2670 However, for backwards compatibility, this breaks too much code.
2671 Therefore, in 2.6, we'll *warn* about excess arguments when both
2672 methods are overridden; for all other cases we'll use the above
2673 rules.
2674
2675*/
2676
2677/* Forward */
2678static PyObject *
2679object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2680
2681static int
2682excess_args(PyObject *args, PyObject *kwds)
2683{
2684 return PyTuple_GET_SIZE(args) ||
2685 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2686}
2687
Tim Peters6d6c1a32001-08-02 04:15:00 +00002688static int
2689object_init(PyObject *self, PyObject *args, PyObject *kwds)
2690{
Guido van Rossum143b5642007-03-23 04:58:42 +00002691 int err = 0;
2692 if (excess_args(args, kwds)) {
Christian Heimese93237d2007-12-19 02:37:44 +00002693 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum143b5642007-03-23 04:58:42 +00002694 if (type->tp_init != object_init &&
2695 type->tp_new != object_new)
2696 {
2697 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2698 "object.__init__() takes no parameters",
2699 1);
2700 }
2701 else if (type->tp_init != object_init ||
2702 type->tp_new == object_new)
2703 {
2704 PyErr_SetString(PyExc_TypeError,
2705 "object.__init__() takes no parameters");
2706 err = -1;
2707 }
2708 }
2709 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002710}
2711
Guido van Rossum298e4212003-02-13 16:30:16 +00002712static PyObject *
2713object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2714{
Guido van Rossum143b5642007-03-23 04:58:42 +00002715 int err = 0;
2716 if (excess_args(args, kwds)) {
2717 if (type->tp_new != object_new &&
2718 type->tp_init != object_init)
2719 {
2720 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2721 "object.__new__() takes no parameters",
2722 1);
2723 }
2724 else if (type->tp_new != object_new ||
2725 type->tp_init == object_init)
2726 {
2727 PyErr_SetString(PyExc_TypeError,
2728 "object.__new__() takes no parameters");
2729 err = -1;
2730 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002731 }
Guido van Rossum143b5642007-03-23 04:58:42 +00002732 if (err < 0)
2733 return NULL;
Guido van Rossum298e4212003-02-13 16:30:16 +00002734 return type->tp_alloc(type, 0);
2735}
2736
Tim Peters6d6c1a32001-08-02 04:15:00 +00002737static void
2738object_dealloc(PyObject *self)
2739{
Christian Heimese93237d2007-12-19 02:37:44 +00002740 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002741}
2742
Guido van Rossum8e248182001-08-12 05:17:56 +00002743static PyObject *
2744object_repr(PyObject *self)
2745{
Guido van Rossum76e69632001-08-16 18:52:43 +00002746 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002747 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002748
Christian Heimese93237d2007-12-19 02:37:44 +00002749 type = Py_TYPE(self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002750 mod = type_module(type, NULL);
2751 if (mod == NULL)
2752 PyErr_Clear();
2753 else if (!PyString_Check(mod)) {
2754 Py_DECREF(mod);
2755 mod = NULL;
2756 }
2757 name = type_name(type, NULL);
2758 if (name == NULL)
2759 return NULL;
2760 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002761 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002762 PyString_AS_STRING(mod),
2763 PyString_AS_STRING(name),
2764 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002765 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002766 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002767 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002768 Py_XDECREF(mod);
2769 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002770 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002771}
2772
Guido van Rossumb8f63662001-08-15 23:57:02 +00002773static PyObject *
2774object_str(PyObject *self)
2775{
2776 unaryfunc f;
2777
Christian Heimese93237d2007-12-19 02:37:44 +00002778 f = Py_TYPE(self)->tp_repr;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002779 if (f == NULL)
2780 f = object_repr;
2781 return f(self);
2782}
2783
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002784static PyObject *
2785object_get_class(PyObject *self, void *closure)
2786{
Christian Heimese93237d2007-12-19 02:37:44 +00002787 Py_INCREF(Py_TYPE(self));
2788 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002789}
2790
2791static int
2792equiv_structs(PyTypeObject *a, PyTypeObject *b)
2793{
2794 return a == b ||
2795 (a != NULL &&
2796 b != NULL &&
2797 a->tp_basicsize == b->tp_basicsize &&
2798 a->tp_itemsize == b->tp_itemsize &&
2799 a->tp_dictoffset == b->tp_dictoffset &&
2800 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2801 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2802 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2803}
2804
2805static int
2806same_slots_added(PyTypeObject *a, PyTypeObject *b)
2807{
2808 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002809 Py_ssize_t size;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002810 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002811
2812 if (base != b->tp_base)
2813 return 0;
2814 if (equiv_structs(a, base) && equiv_structs(b, base))
2815 return 1;
2816 size = base->tp_basicsize;
2817 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2818 size += sizeof(PyObject *);
2819 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2820 size += sizeof(PyObject *);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002821
2822 /* Check slots compliance */
2823 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2824 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2825 if (slots_a && slots_b) {
2826 if (PyObject_Compare(slots_a, slots_b) != 0)
2827 return 0;
2828 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2829 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002830 return size == a->tp_basicsize && size == b->tp_basicsize;
2831}
2832
2833static int
Anthony Baxtera6286212006-04-11 07:42:36 +00002834compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002835{
2836 PyTypeObject *newbase, *oldbase;
2837
Anthony Baxtera6286212006-04-11 07:42:36 +00002838 if (newto->tp_dealloc != oldto->tp_dealloc ||
2839 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002840 {
2841 PyErr_Format(PyExc_TypeError,
2842 "%s assignment: "
2843 "'%s' deallocator differs from '%s'",
2844 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002845 newto->tp_name,
2846 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002847 return 0;
2848 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002849 newbase = newto;
2850 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002851 while (equiv_structs(newbase, newbase->tp_base))
2852 newbase = newbase->tp_base;
2853 while (equiv_structs(oldbase, oldbase->tp_base))
2854 oldbase = oldbase->tp_base;
2855 if (newbase != oldbase &&
2856 (newbase->tp_base != oldbase->tp_base ||
2857 !same_slots_added(newbase, oldbase))) {
2858 PyErr_Format(PyExc_TypeError,
2859 "%s assignment: "
2860 "'%s' object layout differs from '%s'",
2861 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002862 newto->tp_name,
2863 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002864 return 0;
2865 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002866
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002867 return 1;
2868}
2869
2870static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002871object_set_class(PyObject *self, PyObject *value, void *closure)
2872{
Christian Heimese93237d2007-12-19 02:37:44 +00002873 PyTypeObject *oldto = Py_TYPE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00002874 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002875
Guido van Rossumb6b89422002-04-15 01:03:30 +00002876 if (value == NULL) {
2877 PyErr_SetString(PyExc_TypeError,
2878 "can't delete __class__ attribute");
2879 return -1;
2880 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002881 if (!PyType_Check(value)) {
2882 PyErr_Format(PyExc_TypeError,
2883 "__class__ must be set to new-style class, not '%s' object",
Christian Heimese93237d2007-12-19 02:37:44 +00002884 Py_TYPE(value)->tp_name);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002885 return -1;
2886 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002887 newto = (PyTypeObject *)value;
2888 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2889 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002890 {
2891 PyErr_Format(PyExc_TypeError,
2892 "__class__ assignment: only for heap types");
2893 return -1;
2894 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002895 if (compatible_for_assignment(newto, oldto, "__class__")) {
2896 Py_INCREF(newto);
Christian Heimese93237d2007-12-19 02:37:44 +00002897 Py_TYPE(self) = newto;
Anthony Baxtera6286212006-04-11 07:42:36 +00002898 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002899 return 0;
2900 }
2901 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002902 return -1;
2903 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002904}
2905
2906static PyGetSetDef object_getsets[] = {
2907 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002908 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002909 {0}
2910};
2911
Guido van Rossumc53f0092003-02-18 22:05:12 +00002912
Guido van Rossum036f9992003-02-21 22:02:54 +00002913/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2914 We fall back to helpers in copy_reg for:
2915 - pickle protocols < 2
2916 - calculating the list of slot names (done only once per class)
2917 - the __newobj__ function (which is used as a token but never called)
2918*/
2919
2920static PyObject *
2921import_copy_reg(void)
2922{
2923 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002924
2925 if (!copy_reg_str) {
2926 copy_reg_str = PyString_InternFromString("copy_reg");
2927 if (copy_reg_str == NULL)
2928 return NULL;
2929 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002930
2931 return PyImport_Import(copy_reg_str);
2932}
2933
2934static PyObject *
2935slotnames(PyObject *cls)
2936{
2937 PyObject *clsdict;
2938 PyObject *copy_reg;
2939 PyObject *slotnames;
2940
2941 if (!PyType_Check(cls)) {
2942 Py_INCREF(Py_None);
2943 return Py_None;
2944 }
2945
2946 clsdict = ((PyTypeObject *)cls)->tp_dict;
2947 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002948 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002949 Py_INCREF(slotnames);
2950 return slotnames;
2951 }
2952
2953 copy_reg = import_copy_reg();
2954 if (copy_reg == NULL)
2955 return NULL;
2956
2957 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2958 Py_DECREF(copy_reg);
2959 if (slotnames != NULL &&
2960 slotnames != Py_None &&
2961 !PyList_Check(slotnames))
2962 {
2963 PyErr_SetString(PyExc_TypeError,
2964 "copy_reg._slotnames didn't return a list or None");
2965 Py_DECREF(slotnames);
2966 slotnames = NULL;
2967 }
2968
2969 return slotnames;
2970}
2971
2972static PyObject *
2973reduce_2(PyObject *obj)
2974{
2975 PyObject *cls, *getnewargs;
2976 PyObject *args = NULL, *args2 = NULL;
2977 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2978 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2979 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002980 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002981
2982 cls = PyObject_GetAttrString(obj, "__class__");
2983 if (cls == NULL)
2984 return NULL;
2985
2986 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2987 if (getnewargs != NULL) {
2988 args = PyObject_CallObject(getnewargs, NULL);
2989 Py_DECREF(getnewargs);
2990 if (args != NULL && !PyTuple_Check(args)) {
Georg Brandlccff7852006-06-18 22:17:29 +00002991 PyErr_Format(PyExc_TypeError,
2992 "__getnewargs__ should return a tuple, "
Christian Heimese93237d2007-12-19 02:37:44 +00002993 "not '%.200s'", Py_TYPE(args)->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002994 goto end;
2995 }
2996 }
2997 else {
2998 PyErr_Clear();
2999 args = PyTuple_New(0);
3000 }
3001 if (args == NULL)
3002 goto end;
3003
3004 getstate = PyObject_GetAttrString(obj, "__getstate__");
3005 if (getstate != NULL) {
3006 state = PyObject_CallObject(getstate, NULL);
3007 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00003008 if (state == NULL)
3009 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003010 }
3011 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00003012 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00003013 state = PyObject_GetAttrString(obj, "__dict__");
3014 if (state == NULL) {
3015 PyErr_Clear();
3016 state = Py_None;
3017 Py_INCREF(state);
3018 }
3019 names = slotnames(cls);
3020 if (names == NULL)
3021 goto end;
3022 if (names != Py_None) {
3023 assert(PyList_Check(names));
3024 slots = PyDict_New();
3025 if (slots == NULL)
3026 goto end;
3027 n = 0;
3028 /* Can't pre-compute the list size; the list
3029 is stored on the class so accessible to other
3030 threads, which may be run by DECREF */
3031 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3032 PyObject *name, *value;
3033 name = PyList_GET_ITEM(names, i);
3034 value = PyObject_GetAttr(obj, name);
3035 if (value == NULL)
3036 PyErr_Clear();
3037 else {
3038 int err = PyDict_SetItem(slots, name,
3039 value);
3040 Py_DECREF(value);
3041 if (err)
3042 goto end;
3043 n++;
3044 }
3045 }
3046 if (n) {
3047 state = Py_BuildValue("(NO)", state, slots);
3048 if (state == NULL)
3049 goto end;
3050 }
3051 }
3052 }
3053
3054 if (!PyList_Check(obj)) {
3055 listitems = Py_None;
3056 Py_INCREF(listitems);
3057 }
3058 else {
3059 listitems = PyObject_GetIter(obj);
3060 if (listitems == NULL)
3061 goto end;
3062 }
3063
3064 if (!PyDict_Check(obj)) {
3065 dictitems = Py_None;
3066 Py_INCREF(dictitems);
3067 }
3068 else {
3069 dictitems = PyObject_CallMethod(obj, "iteritems", "");
3070 if (dictitems == NULL)
3071 goto end;
3072 }
3073
3074 copy_reg = import_copy_reg();
3075 if (copy_reg == NULL)
3076 goto end;
3077 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
3078 if (newobj == NULL)
3079 goto end;
3080
3081 n = PyTuple_GET_SIZE(args);
3082 args2 = PyTuple_New(n+1);
3083 if (args2 == NULL)
3084 goto end;
3085 PyTuple_SET_ITEM(args2, 0, cls);
3086 cls = NULL;
3087 for (i = 0; i < n; i++) {
3088 PyObject *v = PyTuple_GET_ITEM(args, i);
3089 Py_INCREF(v);
3090 PyTuple_SET_ITEM(args2, i+1, v);
3091 }
3092
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003093 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003094
3095 end:
3096 Py_XDECREF(cls);
3097 Py_XDECREF(args);
3098 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00003099 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00003100 Py_XDECREF(state);
3101 Py_XDECREF(names);
3102 Py_XDECREF(listitems);
3103 Py_XDECREF(dictitems);
3104 Py_XDECREF(copy_reg);
3105 Py_XDECREF(newobj);
3106 return res;
3107}
3108
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003109/*
3110 * There were two problems when object.__reduce__ and object.__reduce_ex__
3111 * were implemented in the same function:
3112 * - trying to pickle an object with a custom __reduce__ method that
3113 * fell back to object.__reduce__ in certain circumstances led to
3114 * infinite recursion at Python level and eventual RuntimeError.
3115 * - Pickling objects that lied about their type by overwriting the
3116 * __class__ descriptor could lead to infinite recursion at C level
3117 * and eventual segfault.
3118 *
3119 * Because of backwards compatibility, the two methods still have to
3120 * behave in the same way, even if this is not required by the pickle
3121 * protocol. This common functionality was moved to the _common_reduce
3122 * function.
3123 */
3124static PyObject *
3125_common_reduce(PyObject *self, int proto)
3126{
3127 PyObject *copy_reg, *res;
3128
3129 if (proto >= 2)
3130 return reduce_2(self);
3131
3132 copy_reg = import_copy_reg();
3133 if (!copy_reg)
3134 return NULL;
3135
3136 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
3137 Py_DECREF(copy_reg);
3138
3139 return res;
3140}
3141
3142static PyObject *
3143object_reduce(PyObject *self, PyObject *args)
3144{
3145 int proto = 0;
3146
3147 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3148 return NULL;
3149
3150 return _common_reduce(self, proto);
3151}
3152
Guido van Rossum036f9992003-02-21 22:02:54 +00003153static PyObject *
3154object_reduce_ex(PyObject *self, PyObject *args)
3155{
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003156 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003157 int proto = 0;
3158
3159 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3160 return NULL;
3161
3162 reduce = PyObject_GetAttrString(self, "__reduce__");
3163 if (reduce == NULL)
3164 PyErr_Clear();
3165 else {
3166 PyObject *cls, *clsreduce, *objreduce;
3167 int override;
3168 cls = PyObject_GetAttrString(self, "__class__");
3169 if (cls == NULL) {
3170 Py_DECREF(reduce);
3171 return NULL;
3172 }
3173 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3174 Py_DECREF(cls);
3175 if (clsreduce == NULL) {
3176 Py_DECREF(reduce);
3177 return NULL;
3178 }
3179 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3180 "__reduce__");
3181 override = (clsreduce != objreduce);
3182 Py_DECREF(clsreduce);
3183 if (override) {
3184 res = PyObject_CallObject(reduce, NULL);
3185 Py_DECREF(reduce);
3186 return res;
3187 }
3188 else
3189 Py_DECREF(reduce);
3190 }
3191
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003192 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003193}
3194
3195static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00003196 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3197 PyDoc_STR("helper for pickle")},
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003198 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003199 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00003200 {0}
3201};
3202
Guido van Rossum036f9992003-02-21 22:02:54 +00003203
Tim Peters6d6c1a32001-08-02 04:15:00 +00003204PyTypeObject PyBaseObject_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00003205 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003206 "object", /* tp_name */
3207 sizeof(PyObject), /* tp_basicsize */
3208 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003209 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003210 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003211 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003212 0, /* tp_setattr */
3213 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003214 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003215 0, /* tp_as_number */
3216 0, /* tp_as_sequence */
3217 0, /* tp_as_mapping */
Guido van Rossum64c06e32007-11-22 00:55:51 +00003218 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003219 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003220 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003221 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003222 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003223 0, /* tp_as_buffer */
3224 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003225 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003226 0, /* tp_traverse */
3227 0, /* tp_clear */
3228 0, /* tp_richcompare */
3229 0, /* tp_weaklistoffset */
3230 0, /* tp_iter */
3231 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00003232 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003233 0, /* tp_members */
3234 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003235 0, /* tp_base */
3236 0, /* tp_dict */
3237 0, /* tp_descr_get */
3238 0, /* tp_descr_set */
3239 0, /* tp_dictoffset */
3240 object_init, /* tp_init */
3241 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003242 object_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003243 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003244};
3245
3246
3247/* Initialize the __dict__ in a type object */
3248
3249static int
3250add_methods(PyTypeObject *type, PyMethodDef *meth)
3251{
Guido van Rossum687ae002001-10-15 22:03:32 +00003252 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003253
3254 for (; meth->ml_name != NULL; meth++) {
3255 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003256 if (PyDict_GetItemString(dict, meth->ml_name) &&
3257 !(meth->ml_flags & METH_COEXIST))
3258 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003259 if (meth->ml_flags & METH_CLASS) {
3260 if (meth->ml_flags & METH_STATIC) {
3261 PyErr_SetString(PyExc_ValueError,
3262 "method cannot be both class and static");
3263 return -1;
3264 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003265 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003266 }
3267 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003268 PyObject *cfunc = PyCFunction_New(meth, NULL);
3269 if (cfunc == NULL)
3270 return -1;
3271 descr = PyStaticMethod_New(cfunc);
3272 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003273 }
3274 else {
3275 descr = PyDescr_NewMethod(type, meth);
3276 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003277 if (descr == NULL)
3278 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003279 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003280 return -1;
3281 Py_DECREF(descr);
3282 }
3283 return 0;
3284}
3285
3286static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003287add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003288{
Guido van Rossum687ae002001-10-15 22:03:32 +00003289 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003290
3291 for (; memb->name != NULL; memb++) {
3292 PyObject *descr;
3293 if (PyDict_GetItemString(dict, memb->name))
3294 continue;
3295 descr = PyDescr_NewMember(type, memb);
3296 if (descr == NULL)
3297 return -1;
3298 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3299 return -1;
3300 Py_DECREF(descr);
3301 }
3302 return 0;
3303}
3304
3305static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003306add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003307{
Guido van Rossum687ae002001-10-15 22:03:32 +00003308 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003309
3310 for (; gsp->name != NULL; gsp++) {
3311 PyObject *descr;
3312 if (PyDict_GetItemString(dict, gsp->name))
3313 continue;
3314 descr = PyDescr_NewGetSet(type, gsp);
3315
3316 if (descr == NULL)
3317 return -1;
3318 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3319 return -1;
3320 Py_DECREF(descr);
3321 }
3322 return 0;
3323}
3324
Guido van Rossum13d52f02001-08-10 21:24:08 +00003325static void
3326inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003327{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003328 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003329
Guido van Rossum13d52f02001-08-10 21:24:08 +00003330 /* Special flag magic */
3331 if (!type->tp_as_buffer && base->tp_as_buffer) {
3332 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
3333 type->tp_flags |=
3334 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
3335 }
3336 if (!type->tp_as_sequence && base->tp_as_sequence) {
3337 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3338 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3339 }
3340 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3341 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3342 if ((!type->tp_as_number && base->tp_as_number) ||
3343 (!type->tp_as_sequence && base->tp_as_sequence)) {
3344 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3345 if (!type->tp_as_number && !type->tp_as_sequence) {
3346 type->tp_flags |= base->tp_flags &
3347 Py_TPFLAGS_HAVE_INPLACEOPS;
3348 }
3349 }
3350 /* Wow */
3351 }
3352 if (!type->tp_as_number && base->tp_as_number) {
3353 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3354 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3355 }
3356
3357 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003358 oldsize = base->tp_basicsize;
3359 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3360 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3361 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003362 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3363 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003364 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003365 if (type->tp_traverse == NULL)
3366 type->tp_traverse = base->tp_traverse;
3367 if (type->tp_clear == NULL)
3368 type->tp_clear = base->tp_clear;
3369 }
3370 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00003371 /* The condition below could use some explanation.
3372 It appears that tp_new is not inherited for static types
3373 whose base class is 'object'; this seems to be a precaution
3374 so that old extension types don't suddenly become
3375 callable (object.__new__ wouldn't insure the invariants
3376 that the extension type's own factory function ensures).
3377 Heap types, of course, are under our control, so they do
3378 inherit tp_new; static extension types that specify some
3379 other built-in type as the default are considered
3380 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003381 if (base != &PyBaseObject_Type ||
3382 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3383 if (type->tp_new == NULL)
3384 type->tp_new = base->tp_new;
3385 }
3386 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003387 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003388
3389 /* Copy other non-function slots */
3390
3391#undef COPYVAL
3392#define COPYVAL(SLOT) \
3393 if (type->SLOT == 0) type->SLOT = base->SLOT
3394
3395 COPYVAL(tp_itemsize);
3396 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3397 COPYVAL(tp_weaklistoffset);
3398 }
3399 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3400 COPYVAL(tp_dictoffset);
3401 }
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003402
3403 /* Setup fast subclass flags */
3404 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3405 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3406 else if (PyType_IsSubtype(base, &PyType_Type))
3407 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3408 else if (PyType_IsSubtype(base, &PyInt_Type))
3409 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3410 else if (PyType_IsSubtype(base, &PyLong_Type))
3411 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3412 else if (PyType_IsSubtype(base, &PyString_Type))
3413 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003414#ifdef Py_USING_UNICODE
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003415 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3416 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003417#endif
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003418 else if (PyType_IsSubtype(base, &PyTuple_Type))
3419 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3420 else if (PyType_IsSubtype(base, &PyList_Type))
3421 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3422 else if (PyType_IsSubtype(base, &PyDict_Type))
3423 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003424}
3425
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003426static char *hash_name_op[] = {
3427 "__eq__",
3428 "__cmp__",
3429 "__hash__",
3430 NULL
Guido van Rossum64c06e32007-11-22 00:55:51 +00003431};
3432
3433static int
3434overrides_hash(PyTypeObject *type)
3435{
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003436 char **p;
Guido van Rossum64c06e32007-11-22 00:55:51 +00003437 PyObject *dict = type->tp_dict;
3438
3439 assert(dict != NULL);
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003440 for (p = hash_name_op; *p; p++) {
3441 if (PyDict_GetItemString(dict, *p) != NULL)
Guido van Rossum64c06e32007-11-22 00:55:51 +00003442 return 1;
3443 }
3444 return 0;
3445}
3446
Guido van Rossum13d52f02001-08-10 21:24:08 +00003447static void
3448inherit_slots(PyTypeObject *type, PyTypeObject *base)
3449{
3450 PyTypeObject *basebase;
3451
3452#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003453#undef COPYSLOT
3454#undef COPYNUM
3455#undef COPYSEQ
3456#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003457#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003458
3459#define SLOTDEFINED(SLOT) \
3460 (base->SLOT != 0 && \
3461 (basebase == NULL || base->SLOT != basebase->SLOT))
3462
Tim Peters6d6c1a32001-08-02 04:15:00 +00003463#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003464 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003465
3466#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3467#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3468#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003469#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003470
Guido van Rossum13d52f02001-08-10 21:24:08 +00003471 /* This won't inherit indirect slots (from tp_as_number etc.)
3472 if type doesn't provide the space. */
3473
3474 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3475 basebase = base->tp_base;
3476 if (basebase->tp_as_number == NULL)
3477 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003478 COPYNUM(nb_add);
3479 COPYNUM(nb_subtract);
3480 COPYNUM(nb_multiply);
3481 COPYNUM(nb_divide);
3482 COPYNUM(nb_remainder);
3483 COPYNUM(nb_divmod);
3484 COPYNUM(nb_power);
3485 COPYNUM(nb_negative);
3486 COPYNUM(nb_positive);
3487 COPYNUM(nb_absolute);
3488 COPYNUM(nb_nonzero);
3489 COPYNUM(nb_invert);
3490 COPYNUM(nb_lshift);
3491 COPYNUM(nb_rshift);
3492 COPYNUM(nb_and);
3493 COPYNUM(nb_xor);
3494 COPYNUM(nb_or);
3495 COPYNUM(nb_coerce);
3496 COPYNUM(nb_int);
3497 COPYNUM(nb_long);
3498 COPYNUM(nb_float);
3499 COPYNUM(nb_oct);
3500 COPYNUM(nb_hex);
3501 COPYNUM(nb_inplace_add);
3502 COPYNUM(nb_inplace_subtract);
3503 COPYNUM(nb_inplace_multiply);
3504 COPYNUM(nb_inplace_divide);
3505 COPYNUM(nb_inplace_remainder);
3506 COPYNUM(nb_inplace_power);
3507 COPYNUM(nb_inplace_lshift);
3508 COPYNUM(nb_inplace_rshift);
3509 COPYNUM(nb_inplace_and);
3510 COPYNUM(nb_inplace_xor);
3511 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003512 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3513 COPYNUM(nb_true_divide);
3514 COPYNUM(nb_floor_divide);
3515 COPYNUM(nb_inplace_true_divide);
3516 COPYNUM(nb_inplace_floor_divide);
3517 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003518 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3519 COPYNUM(nb_index);
3520 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003521 }
3522
Guido van Rossum13d52f02001-08-10 21:24:08 +00003523 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3524 basebase = base->tp_base;
3525 if (basebase->tp_as_sequence == NULL)
3526 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003527 COPYSEQ(sq_length);
3528 COPYSEQ(sq_concat);
3529 COPYSEQ(sq_repeat);
3530 COPYSEQ(sq_item);
3531 COPYSEQ(sq_slice);
3532 COPYSEQ(sq_ass_item);
3533 COPYSEQ(sq_ass_slice);
3534 COPYSEQ(sq_contains);
3535 COPYSEQ(sq_inplace_concat);
3536 COPYSEQ(sq_inplace_repeat);
3537 }
3538
Guido van Rossum13d52f02001-08-10 21:24:08 +00003539 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3540 basebase = base->tp_base;
3541 if (basebase->tp_as_mapping == NULL)
3542 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003543 COPYMAP(mp_length);
3544 COPYMAP(mp_subscript);
3545 COPYMAP(mp_ass_subscript);
3546 }
3547
Tim Petersfc57ccb2001-10-12 02:38:24 +00003548 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3549 basebase = base->tp_base;
3550 if (basebase->tp_as_buffer == NULL)
3551 basebase = NULL;
3552 COPYBUF(bf_getreadbuffer);
3553 COPYBUF(bf_getwritebuffer);
3554 COPYBUF(bf_getsegcount);
3555 COPYBUF(bf_getcharbuffer);
3556 }
3557
Guido van Rossum13d52f02001-08-10 21:24:08 +00003558 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003559
Tim Peters6d6c1a32001-08-02 04:15:00 +00003560 COPYSLOT(tp_dealloc);
3561 COPYSLOT(tp_print);
3562 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3563 type->tp_getattr = base->tp_getattr;
3564 type->tp_getattro = base->tp_getattro;
3565 }
3566 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3567 type->tp_setattr = base->tp_setattr;
3568 type->tp_setattro = base->tp_setattro;
3569 }
3570 /* tp_compare see tp_richcompare */
3571 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003572 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003573 COPYSLOT(tp_call);
3574 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003575 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003576 if (type->tp_compare == NULL &&
3577 type->tp_richcompare == NULL &&
Guido van Rossum64c06e32007-11-22 00:55:51 +00003578 type->tp_hash == NULL &&
3579 !overrides_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003580 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003581 type->tp_compare = base->tp_compare;
3582 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003583 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003584 }
3585 }
3586 else {
3587 COPYSLOT(tp_compare);
3588 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003589 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3590 COPYSLOT(tp_iter);
3591 COPYSLOT(tp_iternext);
3592 }
3593 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3594 COPYSLOT(tp_descr_get);
3595 COPYSLOT(tp_descr_set);
3596 COPYSLOT(tp_dictoffset);
3597 COPYSLOT(tp_init);
3598 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003599 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003600 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3601 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3602 /* They agree about gc. */
3603 COPYSLOT(tp_free);
3604 }
3605 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3606 type->tp_free == NULL &&
3607 base->tp_free == _PyObject_Del) {
3608 /* A bit of magic to plug in the correct default
3609 * tp_free function when a derived class adds gc,
3610 * didn't define tp_free, and the base uses the
3611 * default non-gc tp_free.
3612 */
3613 type->tp_free = PyObject_GC_Del;
3614 }
3615 /* else they didn't agree about gc, and there isn't something
3616 * obvious to be done -- the type is on its own.
3617 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003618 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003619}
3620
Jeremy Hylton938ace62002-07-17 16:30:39 +00003621static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003622
Tim Peters6d6c1a32001-08-02 04:15:00 +00003623int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003624PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003625{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003626 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003627 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003628 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003629
Guido van Rossumcab05802002-06-10 15:29:03 +00003630 if (type->tp_flags & Py_TPFLAGS_READY) {
3631 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003632 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003633 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003634 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003635
3636 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003637
Tim Peters36eb4df2003-03-23 03:33:13 +00003638#ifdef Py_TRACE_REFS
3639 /* PyType_Ready is the closest thing we have to a choke point
3640 * for type objects, so is the best place I can think of to try
3641 * to get type objects into the doubly-linked list of all objects.
3642 * Still, not all type objects go thru PyType_Ready.
3643 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003644 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003645#endif
3646
Tim Peters6d6c1a32001-08-02 04:15:00 +00003647 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3648 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003649 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003650 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003651 Py_INCREF(base);
3652 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003653
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003654 /* Now the only way base can still be NULL is if type is
3655 * &PyBaseObject_Type.
3656 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003657
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003658 /* Initialize the base class */
3659 if (base && base->tp_dict == NULL) {
3660 if (PyType_Ready(base) < 0)
3661 goto error;
3662 }
3663
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003664 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003665 compilable separately on Windows can call PyType_Ready() instead of
3666 initializing the ob_type field of their type objects. */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003667 /* The test for base != NULL is really unnecessary, since base is only
3668 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3669 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3670 know that. */
Christian Heimese93237d2007-12-19 02:37:44 +00003671 if (Py_TYPE(type) == NULL && base != NULL)
3672 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003673
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674 /* Initialize tp_bases */
3675 bases = type->tp_bases;
3676 if (bases == NULL) {
3677 if (base == NULL)
3678 bases = PyTuple_New(0);
3679 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003680 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003681 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003682 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003683 type->tp_bases = bases;
3684 }
3685
Guido van Rossum687ae002001-10-15 22:03:32 +00003686 /* Initialize tp_dict */
3687 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003688 if (dict == NULL) {
3689 dict = PyDict_New();
3690 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003691 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003692 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693 }
3694
Guido van Rossum687ae002001-10-15 22:03:32 +00003695 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003696 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003697 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003698 if (type->tp_methods != NULL) {
3699 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003700 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003701 }
3702 if (type->tp_members != NULL) {
3703 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003704 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003705 }
3706 if (type->tp_getset != NULL) {
3707 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003708 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003709 }
3710
Tim Peters6d6c1a32001-08-02 04:15:00 +00003711 /* Calculate method resolution order */
3712 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003713 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003714 }
3715
Guido van Rossum13d52f02001-08-10 21:24:08 +00003716 /* Inherit special flags from dominant base */
3717 if (type->tp_base != NULL)
3718 inherit_special(type, type->tp_base);
3719
Tim Peters6d6c1a32001-08-02 04:15:00 +00003720 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003721 bases = type->tp_mro;
3722 assert(bases != NULL);
3723 assert(PyTuple_Check(bases));
3724 n = PyTuple_GET_SIZE(bases);
3725 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003726 PyObject *b = PyTuple_GET_ITEM(bases, i);
3727 if (PyType_Check(b))
3728 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003729 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003730
Tim Peters3cfe7542003-05-21 21:29:48 +00003731 /* Sanity check for tp_free. */
3732 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3733 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003734 /* This base class needs to call tp_free, but doesn't have
3735 * one, or its tp_free is for non-gc'ed objects.
3736 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003737 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3738 "gc and is a base type but has inappropriate "
3739 "tp_free slot",
3740 type->tp_name);
3741 goto error;
3742 }
3743
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003744 /* if the type dictionary doesn't contain a __doc__, set it from
3745 the tp_doc slot.
3746 */
3747 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3748 if (type->tp_doc != NULL) {
3749 PyObject *doc = PyString_FromString(type->tp_doc);
Neal Norwitze1fdb322006-07-21 05:32:28 +00003750 if (doc == NULL)
3751 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003752 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3753 Py_DECREF(doc);
3754 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003755 PyDict_SetItemString(type->tp_dict,
3756 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003757 }
3758 }
3759
Guido van Rossum64c06e32007-11-22 00:55:51 +00003760 /* Hack for tp_hash and __hash__.
3761 If after all that, tp_hash is still NULL, and __hash__ is not in
3762 tp_dict, set tp_dict['__hash__'] equal to None.
3763 This signals that __hash__ is not inherited.
3764 */
3765 if (type->tp_hash == NULL &&
3766 PyDict_GetItemString(type->tp_dict, "__hash__") == NULL &&
3767 PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3768 {
3769 goto error;
3770 }
3771
Guido van Rossum13d52f02001-08-10 21:24:08 +00003772 /* Some more special stuff */
3773 base = type->tp_base;
3774 if (base != NULL) {
3775 if (type->tp_as_number == NULL)
3776 type->tp_as_number = base->tp_as_number;
3777 if (type->tp_as_sequence == NULL)
3778 type->tp_as_sequence = base->tp_as_sequence;
3779 if (type->tp_as_mapping == NULL)
3780 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003781 if (type->tp_as_buffer == NULL)
3782 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003783 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003784
Guido van Rossum1c450732001-10-08 15:18:27 +00003785 /* Link into each base class's list of subclasses */
3786 bases = type->tp_bases;
3787 n = PyTuple_GET_SIZE(bases);
3788 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003789 PyObject *b = PyTuple_GET_ITEM(bases, i);
3790 if (PyType_Check(b) &&
3791 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003792 goto error;
3793 }
3794
Guido van Rossum13d52f02001-08-10 21:24:08 +00003795 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003796 assert(type->tp_dict != NULL);
3797 type->tp_flags =
3798 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003799 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003800
3801 error:
3802 type->tp_flags &= ~Py_TPFLAGS_READYING;
3803 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003804}
3805
Guido van Rossum1c450732001-10-08 15:18:27 +00003806static int
3807add_subclass(PyTypeObject *base, PyTypeObject *type)
3808{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003809 Py_ssize_t i;
3810 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00003811 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003812
3813 list = base->tp_subclasses;
3814 if (list == NULL) {
3815 base->tp_subclasses = list = PyList_New(0);
3816 if (list == NULL)
3817 return -1;
3818 }
3819 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00003820 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003821 i = PyList_GET_SIZE(list);
3822 while (--i >= 0) {
3823 ref = PyList_GET_ITEM(list, i);
3824 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003825 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00003826 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003827 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003828 result = PyList_Append(list, newobj);
3829 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003830 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003831}
3832
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003833static void
3834remove_subclass(PyTypeObject *base, PyTypeObject *type)
3835{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003836 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003837 PyObject *list, *ref;
3838
3839 list = base->tp_subclasses;
3840 if (list == NULL) {
3841 return;
3842 }
3843 assert(PyList_Check(list));
3844 i = PyList_GET_SIZE(list);
3845 while (--i >= 0) {
3846 ref = PyList_GET_ITEM(list, i);
3847 assert(PyWeakref_CheckRef(ref));
3848 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3849 /* this can't fail, right? */
3850 PySequence_DelItem(list, i);
3851 return;
3852 }
3853 }
3854}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003855
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003856static int
3857check_num_args(PyObject *ob, int n)
3858{
3859 if (!PyTuple_CheckExact(ob)) {
3860 PyErr_SetString(PyExc_SystemError,
3861 "PyArg_UnpackTuple() argument list is not a tuple");
3862 return 0;
3863 }
3864 if (n == PyTuple_GET_SIZE(ob))
3865 return 1;
3866 PyErr_Format(
3867 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003868 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003869 return 0;
3870}
3871
Tim Peters6d6c1a32001-08-02 04:15:00 +00003872/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3873
3874/* There's a wrapper *function* for each distinct function typedef used
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003875 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003876 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3877 Most tables have only one entry; the tables for binary operators have two
3878 entries, one regular and one with reversed arguments. */
3879
3880static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003881wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003882{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003883 lenfunc func = (lenfunc)wrapped;
3884 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003885
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003886 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003887 return NULL;
3888 res = (*func)(self);
3889 if (res == -1 && PyErr_Occurred())
3890 return NULL;
3891 return PyInt_FromLong((long)res);
3892}
3893
Tim Peters6d6c1a32001-08-02 04:15:00 +00003894static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003895wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3896{
3897 inquiry func = (inquiry)wrapped;
3898 int res;
3899
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003900 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003901 return NULL;
3902 res = (*func)(self);
3903 if (res == -1 && PyErr_Occurred())
3904 return NULL;
3905 return PyBool_FromLong((long)res);
3906}
3907
3908static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003909wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3910{
3911 binaryfunc func = (binaryfunc)wrapped;
3912 PyObject *other;
3913
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003914 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003915 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003916 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003917 return (*func)(self, other);
3918}
3919
3920static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003921wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3922{
3923 binaryfunc func = (binaryfunc)wrapped;
3924 PyObject *other;
3925
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003926 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003927 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003928 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003929 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003930 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003931 Py_INCREF(Py_NotImplemented);
3932 return Py_NotImplemented;
3933 }
3934 return (*func)(self, other);
3935}
3936
3937static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003938wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3939{
3940 binaryfunc func = (binaryfunc)wrapped;
3941 PyObject *other;
3942
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003943 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003944 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003945 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003946 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003947 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003948 Py_INCREF(Py_NotImplemented);
3949 return Py_NotImplemented;
3950 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003951 return (*func)(other, self);
3952}
3953
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003954static PyObject *
3955wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3956{
3957 coercion func = (coercion)wrapped;
3958 PyObject *other, *res;
3959 int ok;
3960
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003961 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003962 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003963 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003964 ok = func(&self, &other);
3965 if (ok < 0)
3966 return NULL;
3967 if (ok > 0) {
3968 Py_INCREF(Py_NotImplemented);
3969 return Py_NotImplemented;
3970 }
3971 res = PyTuple_New(2);
3972 if (res == NULL) {
3973 Py_DECREF(self);
3974 Py_DECREF(other);
3975 return NULL;
3976 }
3977 PyTuple_SET_ITEM(res, 0, self);
3978 PyTuple_SET_ITEM(res, 1, other);
3979 return res;
3980}
3981
Tim Peters6d6c1a32001-08-02 04:15:00 +00003982static PyObject *
3983wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3984{
3985 ternaryfunc func = (ternaryfunc)wrapped;
3986 PyObject *other;
3987 PyObject *third = Py_None;
3988
3989 /* Note: This wrapper only works for __pow__() */
3990
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003991 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003992 return NULL;
3993 return (*func)(self, other, third);
3994}
3995
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003996static PyObject *
3997wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3998{
3999 ternaryfunc func = (ternaryfunc)wrapped;
4000 PyObject *other;
4001 PyObject *third = Py_None;
4002
4003 /* Note: This wrapper only works for __pow__() */
4004
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004005 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004006 return NULL;
4007 return (*func)(other, self, third);
4008}
4009
Tim Peters6d6c1a32001-08-02 04:15:00 +00004010static PyObject *
4011wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4012{
4013 unaryfunc func = (unaryfunc)wrapped;
4014
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004015 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004016 return NULL;
4017 return (*func)(self);
4018}
4019
Tim Peters6d6c1a32001-08-02 04:15:00 +00004020static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00004021wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004022{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004023 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00004024 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004025 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004026
Armin Rigo314861c2006-03-30 14:04:02 +00004027 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4028 return NULL;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004029 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Armin Rigo314861c2006-03-30 14:04:02 +00004030 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004031 return NULL;
4032 return (*func)(self, i);
4033}
4034
Martin v. Löwis18e16552006-02-15 17:27:45 +00004035static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004036getindex(PyObject *self, PyObject *arg)
4037{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004038 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004039
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004040 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004041 if (i == -1 && PyErr_Occurred())
4042 return -1;
4043 if (i < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00004044 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004045 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00004046 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004047 if (n < 0)
4048 return -1;
4049 i += n;
4050 }
4051 }
4052 return i;
4053}
4054
4055static PyObject *
4056wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4057{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004058 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004059 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004060 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004061
Guido van Rossumf4593e02001-10-03 12:09:30 +00004062 if (PyTuple_GET_SIZE(args) == 1) {
4063 arg = PyTuple_GET_ITEM(args, 0);
4064 i = getindex(self, arg);
4065 if (i == -1 && PyErr_Occurred())
4066 return NULL;
4067 return (*func)(self, i);
4068 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004069 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004070 assert(PyErr_Occurred());
4071 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004072}
4073
Tim Peters6d6c1a32001-08-02 04:15:00 +00004074static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004075wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004076{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004077 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
4078 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004079
Martin v. Löwis18e16552006-02-15 17:27:45 +00004080 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004081 return NULL;
4082 return (*func)(self, i, j);
4083}
4084
Tim Peters6d6c1a32001-08-02 04:15:00 +00004085static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004086wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004087{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004088 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4089 Py_ssize_t i;
4090 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004091 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004092
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004093 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004094 return NULL;
4095 i = getindex(self, arg);
4096 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004097 return NULL;
4098 res = (*func)(self, i, value);
4099 if (res == -1 && PyErr_Occurred())
4100 return NULL;
4101 Py_INCREF(Py_None);
4102 return Py_None;
4103}
4104
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004105static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004106wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004107{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004108 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4109 Py_ssize_t i;
4110 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004111 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004112
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004113 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004114 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004115 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004116 i = getindex(self, arg);
4117 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004118 return NULL;
4119 res = (*func)(self, i, NULL);
4120 if (res == -1 && PyErr_Occurred())
4121 return NULL;
4122 Py_INCREF(Py_None);
4123 return Py_None;
4124}
4125
Tim Peters6d6c1a32001-08-02 04:15:00 +00004126static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004127wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004128{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004129 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4130 Py_ssize_t i, j;
4131 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004132 PyObject *value;
4133
Martin v. Löwis18e16552006-02-15 17:27:45 +00004134 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004135 return NULL;
4136 res = (*func)(self, i, j, value);
4137 if (res == -1 && PyErr_Occurred())
4138 return NULL;
4139 Py_INCREF(Py_None);
4140 return Py_None;
4141}
4142
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004143static PyObject *
4144wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
4145{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004146 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4147 Py_ssize_t i, j;
4148 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004149
Martin v. Löwis18e16552006-02-15 17:27:45 +00004150 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004151 return NULL;
4152 res = (*func)(self, i, j, NULL);
4153 if (res == -1 && PyErr_Occurred())
4154 return NULL;
4155 Py_INCREF(Py_None);
4156 return Py_None;
4157}
4158
Tim Peters6d6c1a32001-08-02 04:15:00 +00004159/* XXX objobjproc is a misnomer; should be objargpred */
4160static PyObject *
4161wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4162{
4163 objobjproc func = (objobjproc)wrapped;
4164 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004165 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004166
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004167 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004168 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004169 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004170 res = (*func)(self, value);
4171 if (res == -1 && PyErr_Occurred())
4172 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004173 else
4174 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004175}
4176
Tim Peters6d6c1a32001-08-02 04:15:00 +00004177static PyObject *
4178wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4179{
4180 objobjargproc func = (objobjargproc)wrapped;
4181 int res;
4182 PyObject *key, *value;
4183
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004184 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004185 return NULL;
4186 res = (*func)(self, key, value);
4187 if (res == -1 && PyErr_Occurred())
4188 return NULL;
4189 Py_INCREF(Py_None);
4190 return Py_None;
4191}
4192
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004193static PyObject *
4194wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4195{
4196 objobjargproc func = (objobjargproc)wrapped;
4197 int res;
4198 PyObject *key;
4199
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004200 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004201 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004202 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004203 res = (*func)(self, key, NULL);
4204 if (res == -1 && PyErr_Occurred())
4205 return NULL;
4206 Py_INCREF(Py_None);
4207 return Py_None;
4208}
4209
Tim Peters6d6c1a32001-08-02 04:15:00 +00004210static PyObject *
4211wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
4212{
4213 cmpfunc func = (cmpfunc)wrapped;
4214 int res;
4215 PyObject *other;
4216
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004217 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004218 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004219 other = PyTuple_GET_ITEM(args, 0);
Christian Heimese93237d2007-12-19 02:37:44 +00004220 if (Py_TYPE(other)->tp_compare != func &&
4221 !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
Guido van Rossumceccae52001-09-18 20:03:57 +00004222 PyErr_Format(
4223 PyExc_TypeError,
4224 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +00004225 Py_TYPE(self)->tp_name,
4226 Py_TYPE(self)->tp_name,
4227 Py_TYPE(other)->tp_name);
Guido van Rossumceccae52001-09-18 20:03:57 +00004228 return NULL;
4229 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004230 res = (*func)(self, other);
4231 if (PyErr_Occurred())
4232 return NULL;
4233 return PyInt_FromLong((long)res);
4234}
4235
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004236/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004237 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004238static int
4239hackcheck(PyObject *self, setattrofunc func, char *what)
4240{
Christian Heimese93237d2007-12-19 02:37:44 +00004241 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004242 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4243 type = type->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004244 /* If type is NULL now, this is a really weird type.
4245 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004246 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004247 PyErr_Format(PyExc_TypeError,
4248 "can't apply this %s to %s object",
4249 what,
4250 type->tp_name);
4251 return 0;
4252 }
4253 return 1;
4254}
4255
Tim Peters6d6c1a32001-08-02 04:15:00 +00004256static PyObject *
4257wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4258{
4259 setattrofunc func = (setattrofunc)wrapped;
4260 int res;
4261 PyObject *name, *value;
4262
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004263 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004264 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004265 if (!hackcheck(self, func, "__setattr__"))
4266 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004267 res = (*func)(self, name, value);
4268 if (res < 0)
4269 return NULL;
4270 Py_INCREF(Py_None);
4271 return Py_None;
4272}
4273
4274static PyObject *
4275wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4276{
4277 setattrofunc func = (setattrofunc)wrapped;
4278 int res;
4279 PyObject *name;
4280
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004281 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004282 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004283 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004284 if (!hackcheck(self, func, "__delattr__"))
4285 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004286 res = (*func)(self, name, NULL);
4287 if (res < 0)
4288 return NULL;
4289 Py_INCREF(Py_None);
4290 return Py_None;
4291}
4292
Tim Peters6d6c1a32001-08-02 04:15:00 +00004293static PyObject *
4294wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4295{
4296 hashfunc func = (hashfunc)wrapped;
4297 long res;
4298
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004299 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004300 return NULL;
4301 res = (*func)(self);
4302 if (res == -1 && PyErr_Occurred())
4303 return NULL;
4304 return PyInt_FromLong(res);
4305}
4306
Tim Peters6d6c1a32001-08-02 04:15:00 +00004307static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004308wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004309{
4310 ternaryfunc func = (ternaryfunc)wrapped;
4311
Guido van Rossumc8e56452001-10-22 00:43:43 +00004312 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004313}
4314
Tim Peters6d6c1a32001-08-02 04:15:00 +00004315static PyObject *
4316wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4317{
4318 richcmpfunc func = (richcmpfunc)wrapped;
4319 PyObject *other;
4320
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004321 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004322 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004323 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004324 return (*func)(self, other, op);
4325}
4326
4327#undef RICHCMP_WRAPPER
4328#define RICHCMP_WRAPPER(NAME, OP) \
4329static PyObject * \
4330richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4331{ \
4332 return wrap_richcmpfunc(self, args, wrapped, OP); \
4333}
4334
Jack Jansen8e938b42001-08-08 15:29:49 +00004335RICHCMP_WRAPPER(lt, Py_LT)
4336RICHCMP_WRAPPER(le, Py_LE)
4337RICHCMP_WRAPPER(eq, Py_EQ)
4338RICHCMP_WRAPPER(ne, Py_NE)
4339RICHCMP_WRAPPER(gt, Py_GT)
4340RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004341
Tim Peters6d6c1a32001-08-02 04:15:00 +00004342static PyObject *
4343wrap_next(PyObject *self, PyObject *args, void *wrapped)
4344{
4345 unaryfunc func = (unaryfunc)wrapped;
4346 PyObject *res;
4347
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004348 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004349 return NULL;
4350 res = (*func)(self);
4351 if (res == NULL && !PyErr_Occurred())
4352 PyErr_SetNone(PyExc_StopIteration);
4353 return res;
4354}
4355
Tim Peters6d6c1a32001-08-02 04:15:00 +00004356static PyObject *
4357wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4358{
4359 descrgetfunc func = (descrgetfunc)wrapped;
4360 PyObject *obj;
4361 PyObject *type = NULL;
4362
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004363 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004364 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004365 if (obj == Py_None)
4366 obj = NULL;
4367 if (type == Py_None)
4368 type = NULL;
4369 if (type == NULL &&obj == NULL) {
4370 PyErr_SetString(PyExc_TypeError,
4371 "__get__(None, None) is invalid");
4372 return NULL;
4373 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004374 return (*func)(self, obj, type);
4375}
4376
Tim Peters6d6c1a32001-08-02 04:15:00 +00004377static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004378wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004379{
4380 descrsetfunc func = (descrsetfunc)wrapped;
4381 PyObject *obj, *value;
4382 int ret;
4383
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004384 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004385 return NULL;
4386 ret = (*func)(self, obj, value);
4387 if (ret < 0)
4388 return NULL;
4389 Py_INCREF(Py_None);
4390 return Py_None;
4391}
Guido van Rossum22b13872002-08-06 21:41:44 +00004392
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004393static PyObject *
4394wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4395{
4396 descrsetfunc func = (descrsetfunc)wrapped;
4397 PyObject *obj;
4398 int ret;
4399
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004400 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004401 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004402 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004403 ret = (*func)(self, obj, NULL);
4404 if (ret < 0)
4405 return NULL;
4406 Py_INCREF(Py_None);
4407 return Py_None;
4408}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004409
Tim Peters6d6c1a32001-08-02 04:15:00 +00004410static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004411wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004412{
4413 initproc func = (initproc)wrapped;
4414
Guido van Rossumc8e56452001-10-22 00:43:43 +00004415 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004416 return NULL;
4417 Py_INCREF(Py_None);
4418 return Py_None;
4419}
4420
Tim Peters6d6c1a32001-08-02 04:15:00 +00004421static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004422tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004423{
Barry Warsaw60f01882001-08-22 19:24:42 +00004424 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004425 PyObject *arg0, *res;
4426
4427 if (self == NULL || !PyType_Check(self))
4428 Py_FatalError("__new__() called with non-type 'self'");
4429 type = (PyTypeObject *)self;
4430 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004431 PyErr_Format(PyExc_TypeError,
4432 "%s.__new__(): not enough arguments",
4433 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004434 return NULL;
4435 }
4436 arg0 = PyTuple_GET_ITEM(args, 0);
4437 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004438 PyErr_Format(PyExc_TypeError,
4439 "%s.__new__(X): X is not a type object (%s)",
4440 type->tp_name,
Christian Heimese93237d2007-12-19 02:37:44 +00004441 Py_TYPE(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004442 return NULL;
4443 }
4444 subtype = (PyTypeObject *)arg0;
4445 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004446 PyErr_Format(PyExc_TypeError,
4447 "%s.__new__(%s): %s is not a subtype of %s",
4448 type->tp_name,
4449 subtype->tp_name,
4450 subtype->tp_name,
4451 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004452 return NULL;
4453 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004454
4455 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004456 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004457 most derived base that's not a heap type is this type. */
4458 staticbase = subtype;
4459 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4460 staticbase = staticbase->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004461 /* If staticbase is NULL now, it is a really weird type.
4462 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004463 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004464 PyErr_Format(PyExc_TypeError,
4465 "%s.__new__(%s) is not safe, use %s.__new__()",
4466 type->tp_name,
4467 subtype->tp_name,
4468 staticbase == NULL ? "?" : staticbase->tp_name);
4469 return NULL;
4470 }
4471
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004472 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4473 if (args == NULL)
4474 return NULL;
4475 res = type->tp_new(subtype, args, kwds);
4476 Py_DECREF(args);
4477 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004478}
4479
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004480static struct PyMethodDef tp_new_methoddef[] = {
Neal Norwitza84dcd72007-05-22 07:16:44 +00004481 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004482 PyDoc_STR("T.__new__(S, ...) -> "
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004483 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004484 {0}
4485};
4486
4487static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004488add_tp_new_wrapper(PyTypeObject *type)
4489{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004490 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004491
Guido van Rossum687ae002001-10-15 22:03:32 +00004492 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004493 return 0;
4494 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004495 if (func == NULL)
4496 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004497 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004498 Py_DECREF(func);
4499 return -1;
4500 }
4501 Py_DECREF(func);
4502 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004503}
4504
Guido van Rossumf040ede2001-08-07 16:40:56 +00004505/* Slot wrappers that call the corresponding __foo__ slot. See comments
4506 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004507
Guido van Rossumdc91b992001-08-08 22:26:22 +00004508#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004509static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004510FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004511{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004512 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004513 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004514}
4515
Guido van Rossumdc91b992001-08-08 22:26:22 +00004516#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004517static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004518FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004519{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004520 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004521 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004522}
4523
Guido van Rossumcd118802003-01-06 22:57:47 +00004524/* Boolean helper for SLOT1BINFULL().
4525 right.__class__ is a nontrivial subclass of left.__class__. */
4526static int
4527method_is_overloaded(PyObject *left, PyObject *right, char *name)
4528{
4529 PyObject *a, *b;
4530 int ok;
4531
Christian Heimese93237d2007-12-19 02:37:44 +00004532 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004533 if (b == NULL) {
4534 PyErr_Clear();
4535 /* If right doesn't have it, it's not overloaded */
4536 return 0;
4537 }
4538
Christian Heimese93237d2007-12-19 02:37:44 +00004539 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004540 if (a == NULL) {
4541 PyErr_Clear();
4542 Py_DECREF(b);
4543 /* If right has it but left doesn't, it's overloaded */
4544 return 1;
4545 }
4546
4547 ok = PyObject_RichCompareBool(a, b, Py_NE);
4548 Py_DECREF(a);
4549 Py_DECREF(b);
4550 if (ok < 0) {
4551 PyErr_Clear();
4552 return 0;
4553 }
4554
4555 return ok;
4556}
4557
Guido van Rossumdc91b992001-08-08 22:26:22 +00004558
4559#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004560static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004561FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004562{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004563 static PyObject *cache_str, *rcache_str; \
Christian Heimese93237d2007-12-19 02:37:44 +00004564 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4565 Py_TYPE(other)->tp_as_number != NULL && \
4566 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4567 if (Py_TYPE(self)->tp_as_number != NULL && \
4568 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004569 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004570 if (do_other && \
Christian Heimese93237d2007-12-19 02:37:44 +00004571 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004572 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004573 r = call_maybe( \
4574 other, ROPSTR, &rcache_str, "(O)", self); \
4575 if (r != Py_NotImplemented) \
4576 return r; \
4577 Py_DECREF(r); \
4578 do_other = 0; \
4579 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004580 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004581 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004582 if (r != Py_NotImplemented || \
Christian Heimese93237d2007-12-19 02:37:44 +00004583 Py_TYPE(other) == Py_TYPE(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004584 return r; \
4585 Py_DECREF(r); \
4586 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004587 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004588 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004589 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004590 } \
4591 Py_INCREF(Py_NotImplemented); \
4592 return Py_NotImplemented; \
4593}
4594
4595#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4596 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4597
4598#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4599static PyObject * \
4600FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4601{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004602 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004603 return call_method(self, OPSTR, &cache_str, \
4604 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004605}
4606
Martin v. Löwis18e16552006-02-15 17:27:45 +00004607static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004608slot_sq_length(PyObject *self)
4609{
Guido van Rossum2730b132001-08-28 18:22:14 +00004610 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004611 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004612 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004613
4614 if (res == NULL)
4615 return -1;
Neal Norwitz1872b1c2006-08-12 18:44:06 +00004616 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004617 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004618 if (len < 0) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00004619 if (!PyErr_Occurred())
4620 PyErr_SetString(PyExc_ValueError,
4621 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004622 return -1;
4623 }
Guido van Rossum26111622001-10-01 16:42:49 +00004624 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004625}
4626
Guido van Rossumf4593e02001-10-03 12:09:30 +00004627/* Super-optimized version of slot_sq_item.
4628 Other slots could do the same... */
4629static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004630slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004631{
4632 static PyObject *getitem_str;
4633 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4634 descrgetfunc f;
4635
4636 if (getitem_str == NULL) {
4637 getitem_str = PyString_InternFromString("__getitem__");
4638 if (getitem_str == NULL)
4639 return NULL;
4640 }
Christian Heimese93237d2007-12-19 02:37:44 +00004641 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004642 if (func != NULL) {
Christian Heimese93237d2007-12-19 02:37:44 +00004643 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004644 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004645 else {
Christian Heimese93237d2007-12-19 02:37:44 +00004646 func = f(func, self, (PyObject *)(Py_TYPE(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004647 if (func == NULL) {
4648 return NULL;
4649 }
4650 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004651 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004652 if (ival != NULL) {
4653 args = PyTuple_New(1);
4654 if (args != NULL) {
4655 PyTuple_SET_ITEM(args, 0, ival);
4656 retval = PyObject_Call(func, args, NULL);
4657 Py_XDECREF(args);
4658 Py_XDECREF(func);
4659 return retval;
4660 }
4661 }
4662 }
4663 else {
4664 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4665 }
4666 Py_XDECREF(args);
4667 Py_XDECREF(ival);
4668 Py_XDECREF(func);
4669 return NULL;
4670}
4671
Martin v. Löwis18e16552006-02-15 17:27:45 +00004672SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004673
4674static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004675slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004676{
4677 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004678 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004679
4680 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004681 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004682 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004683 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004684 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004685 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004686 if (res == NULL)
4687 return -1;
4688 Py_DECREF(res);
4689 return 0;
4690}
4691
4692static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004693slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004694{
4695 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004696 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004697
4698 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004699 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004700 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004701 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004702 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004703 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004704 if (res == NULL)
4705 return -1;
4706 Py_DECREF(res);
4707 return 0;
4708}
4709
4710static int
4711slot_sq_contains(PyObject *self, PyObject *value)
4712{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004713 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004714 int result = -1;
4715
Guido van Rossum60718732001-08-28 17:47:51 +00004716 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004717
Guido van Rossum55f20992001-10-01 17:18:22 +00004718 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004719 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004720 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004721 if (args == NULL)
4722 res = NULL;
4723 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004724 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004725 Py_DECREF(args);
4726 }
4727 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004728 if (res != NULL) {
4729 result = PyObject_IsTrue(res);
4730 Py_DECREF(res);
4731 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004732 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004733 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004734 /* Possible results: -1 and 1 */
4735 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004736 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004737 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004738 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004739}
4740
Tim Peters6d6c1a32001-08-02 04:15:00 +00004741#define slot_mp_length slot_sq_length
4742
Guido van Rossumdc91b992001-08-08 22:26:22 +00004743SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004744
4745static int
4746slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4747{
4748 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004749 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004750
4751 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004752 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004753 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004754 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004755 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004756 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004757 if (res == NULL)
4758 return -1;
4759 Py_DECREF(res);
4760 return 0;
4761}
4762
Guido van Rossumdc91b992001-08-08 22:26:22 +00004763SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4764SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4765SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4766SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4767SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4768SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4769
Jeremy Hylton938ace62002-07-17 16:30:39 +00004770static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004771
4772SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4773 nb_power, "__pow__", "__rpow__")
4774
4775static PyObject *
4776slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4777{
Guido van Rossum2730b132001-08-28 18:22:14 +00004778 static PyObject *pow_str;
4779
Guido van Rossumdc91b992001-08-08 22:26:22 +00004780 if (modulus == Py_None)
4781 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004782 /* Three-arg power doesn't use __rpow__. But ternary_op
4783 can call this when the second argument's type uses
4784 slot_nb_power, so check before calling self.__pow__. */
Christian Heimese93237d2007-12-19 02:37:44 +00004785 if (Py_TYPE(self)->tp_as_number != NULL &&
4786 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00004787 return call_method(self, "__pow__", &pow_str,
4788 "(OO)", other, modulus);
4789 }
4790 Py_INCREF(Py_NotImplemented);
4791 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004792}
4793
4794SLOT0(slot_nb_negative, "__neg__")
4795SLOT0(slot_nb_positive, "__pos__")
4796SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004797
4798static int
4799slot_nb_nonzero(PyObject *self)
4800{
Tim Petersea7f75d2002-12-07 21:39:16 +00004801 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004802 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004803 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004804
Guido van Rossum55f20992001-10-01 17:18:22 +00004805 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004806 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004807 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004808 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004809 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004810 if (func == NULL)
4811 return PyErr_Occurred() ? -1 : 1;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004812 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004813 args = PyTuple_New(0);
4814 if (args != NULL) {
4815 PyObject *temp = PyObject_Call(func, args, NULL);
4816 Py_DECREF(args);
4817 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004818 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004819 result = PyObject_IsTrue(temp);
4820 else {
4821 PyErr_Format(PyExc_TypeError,
4822 "__nonzero__ should return "
4823 "bool or int, returned %s",
4824 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004825 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004826 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004827 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004828 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004829 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004830 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004831 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004832}
4833
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004834
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004835static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004836slot_nb_index(PyObject *self)
4837{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004838 static PyObject *index_str;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004839 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004840}
4841
4842
Guido van Rossumdc91b992001-08-08 22:26:22 +00004843SLOT0(slot_nb_invert, "__invert__")
4844SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4845SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4846SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4847SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4848SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004849
4850static int
4851slot_nb_coerce(PyObject **a, PyObject **b)
4852{
4853 static PyObject *coerce_str;
4854 PyObject *self = *a, *other = *b;
4855
4856 if (self->ob_type->tp_as_number != NULL &&
4857 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4858 PyObject *r;
4859 r = call_maybe(
4860 self, "__coerce__", &coerce_str, "(O)", other);
4861 if (r == NULL)
4862 return -1;
4863 if (r == Py_NotImplemented) {
4864 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004865 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004866 else {
4867 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4868 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004869 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004870 Py_DECREF(r);
4871 return -1;
4872 }
4873 *a = PyTuple_GET_ITEM(r, 0);
4874 Py_INCREF(*a);
4875 *b = PyTuple_GET_ITEM(r, 1);
4876 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004877 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004878 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004879 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004880 }
4881 if (other->ob_type->tp_as_number != NULL &&
4882 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4883 PyObject *r;
4884 r = call_maybe(
4885 other, "__coerce__", &coerce_str, "(O)", self);
4886 if (r == NULL)
4887 return -1;
4888 if (r == Py_NotImplemented) {
4889 Py_DECREF(r);
4890 return 1;
4891 }
4892 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4893 PyErr_SetString(PyExc_TypeError,
4894 "__coerce__ didn't return a 2-tuple");
4895 Py_DECREF(r);
4896 return -1;
4897 }
4898 *a = PyTuple_GET_ITEM(r, 1);
4899 Py_INCREF(*a);
4900 *b = PyTuple_GET_ITEM(r, 0);
4901 Py_INCREF(*b);
4902 Py_DECREF(r);
4903 return 0;
4904 }
4905 return 1;
4906}
4907
Guido van Rossumdc91b992001-08-08 22:26:22 +00004908SLOT0(slot_nb_int, "__int__")
4909SLOT0(slot_nb_long, "__long__")
4910SLOT0(slot_nb_float, "__float__")
4911SLOT0(slot_nb_oct, "__oct__")
4912SLOT0(slot_nb_hex, "__hex__")
4913SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4914SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4915SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4916SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4917SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Martin v. Löwisfd963262007-02-09 12:19:32 +00004918/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4919static PyObject *
4920slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4921{
4922 static PyObject *cache_str;
4923 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4924}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004925SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4926SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4927SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4928SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4929SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4930SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4931 "__floordiv__", "__rfloordiv__")
4932SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4933SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4934SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004935
4936static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004937half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004938{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004939 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004940 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004941 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004942
Guido van Rossum60718732001-08-28 17:47:51 +00004943 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004944 if (func == NULL) {
4945 PyErr_Clear();
4946 }
4947 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004948 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004949 if (args == NULL)
4950 res = NULL;
4951 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004952 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004953 Py_DECREF(args);
4954 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004955 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004956 if (res != Py_NotImplemented) {
4957 if (res == NULL)
4958 return -2;
4959 c = PyInt_AsLong(res);
4960 Py_DECREF(res);
4961 if (c == -1 && PyErr_Occurred())
4962 return -2;
4963 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4964 }
4965 Py_DECREF(res);
4966 }
4967 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004968}
4969
Guido van Rossumab3b0342001-09-18 20:38:53 +00004970/* This slot is published for the benefit of try_3way_compare in object.c */
4971int
4972_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004973{
4974 int c;
4975
Christian Heimese93237d2007-12-19 02:37:44 +00004976 if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004977 c = half_compare(self, other);
4978 if (c <= 1)
4979 return c;
4980 }
Christian Heimese93237d2007-12-19 02:37:44 +00004981 if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004982 c = half_compare(other, self);
4983 if (c < -1)
4984 return -2;
4985 if (c <= 1)
4986 return -c;
4987 }
4988 return (void *)self < (void *)other ? -1 :
4989 (void *)self > (void *)other ? 1 : 0;
4990}
4991
4992static PyObject *
4993slot_tp_repr(PyObject *self)
4994{
4995 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004996 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004997
Guido van Rossum60718732001-08-28 17:47:51 +00004998 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004999 if (func != NULL) {
5000 res = PyEval_CallObject(func, NULL);
5001 Py_DECREF(func);
5002 return res;
5003 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00005004 PyErr_Clear();
5005 return PyString_FromFormat("<%s object at %p>",
Christian Heimese93237d2007-12-19 02:37:44 +00005006 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005007}
5008
5009static PyObject *
5010slot_tp_str(PyObject *self)
5011{
5012 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005013 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005014
Guido van Rossum60718732001-08-28 17:47:51 +00005015 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005016 if (func != NULL) {
5017 res = PyEval_CallObject(func, NULL);
5018 Py_DECREF(func);
5019 return res;
5020 }
5021 else {
5022 PyErr_Clear();
5023 return slot_tp_repr(self);
5024 }
5025}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005026
5027static long
5028slot_tp_hash(PyObject *self)
5029{
Tim Peters61ce0a92002-12-06 23:38:02 +00005030 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00005031 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005032 long h;
5033
Guido van Rossum60718732001-08-28 17:47:51 +00005034 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005035
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005036 if (func != NULL && func != Py_None) {
Tim Peters61ce0a92002-12-06 23:38:02 +00005037 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005038 Py_DECREF(func);
5039 if (res == NULL)
5040 return -1;
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00005041 if (PyLong_Check(res))
Armin Rigo51fc8c42006-08-09 14:55:26 +00005042 h = PyLong_Type.tp_hash(res);
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00005043 else
5044 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00005045 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005046 }
5047 else {
Georg Brandl30b78042007-12-20 21:03:02 +00005048 Py_XDECREF(func); /* may be None */
Guido van Rossumb8f63662001-08-15 23:57:02 +00005049 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005050 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005051 if (func == NULL) {
5052 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005053 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005054 }
5055 if (func != NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00005056 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
5057 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005058 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005059 return -1;
5060 }
5061 PyErr_Clear();
5062 h = _Py_HashPointer((void *)self);
5063 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005064 if (h == -1 && !PyErr_Occurred())
5065 h = -2;
5066 return h;
5067}
5068
5069static PyObject *
5070slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5071{
Guido van Rossum60718732001-08-28 17:47:51 +00005072 static PyObject *call_str;
5073 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005074 PyObject *res;
5075
5076 if (meth == NULL)
5077 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00005078
Tim Peters6d6c1a32001-08-02 04:15:00 +00005079 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00005080
Tim Peters6d6c1a32001-08-02 04:15:00 +00005081 Py_DECREF(meth);
5082 return res;
5083}
5084
Guido van Rossum14a6f832001-10-17 13:59:09 +00005085/* There are two slot dispatch functions for tp_getattro.
5086
5087 - slot_tp_getattro() is used when __getattribute__ is overridden
5088 but no __getattr__ hook is present;
5089
5090 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5091
Guido van Rossumc334df52002-04-04 23:44:47 +00005092 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5093 detects the absence of __getattr__ and then installs the simpler slot if
5094 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005095
Tim Peters6d6c1a32001-08-02 04:15:00 +00005096static PyObject *
5097slot_tp_getattro(PyObject *self, PyObject *name)
5098{
Guido van Rossum14a6f832001-10-17 13:59:09 +00005099 static PyObject *getattribute_str = NULL;
5100 return call_method(self, "__getattribute__", &getattribute_str,
5101 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005102}
5103
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005104static PyObject *
5105slot_tp_getattr_hook(PyObject *self, PyObject *name)
5106{
Christian Heimese93237d2007-12-19 02:37:44 +00005107 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005108 PyObject *getattr, *getattribute, *res;
5109 static PyObject *getattribute_str = NULL;
5110 static PyObject *getattr_str = NULL;
5111
5112 if (getattr_str == NULL) {
5113 getattr_str = PyString_InternFromString("__getattr__");
5114 if (getattr_str == NULL)
5115 return NULL;
5116 }
5117 if (getattribute_str == NULL) {
5118 getattribute_str =
5119 PyString_InternFromString("__getattribute__");
5120 if (getattribute_str == NULL)
5121 return NULL;
5122 }
5123 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005124 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005125 /* No __getattr__ hook: use a simpler dispatcher */
5126 tp->tp_getattro = slot_tp_getattro;
5127 return slot_tp_getattro(self, name);
5128 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005129 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005130 if (getattribute == NULL ||
Christian Heimese93237d2007-12-19 02:37:44 +00005131 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00005132 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5133 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005134 res = PyObject_GenericGetAttr(self, name);
5135 else
Georg Brandl684fd0c2006-05-25 19:15:31 +00005136 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005137 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005138 PyErr_Clear();
Georg Brandl684fd0c2006-05-25 19:15:31 +00005139 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005140 }
5141 return res;
5142}
5143
Tim Peters6d6c1a32001-08-02 04:15:00 +00005144static int
5145slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5146{
5147 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005148 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005149
5150 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00005151 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005152 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005153 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005154 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005155 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005156 if (res == NULL)
5157 return -1;
5158 Py_DECREF(res);
5159 return 0;
5160}
5161
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005162static char *name_op[] = {
5163 "__lt__",
5164 "__le__",
5165 "__eq__",
5166 "__ne__",
5167 "__gt__",
5168 "__ge__",
5169};
5170
Tim Peters6d6c1a32001-08-02 04:15:00 +00005171static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005172half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005173{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005174 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005175 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005176
Guido van Rossum60718732001-08-28 17:47:51 +00005177 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005178 if (func == NULL) {
5179 PyErr_Clear();
5180 Py_INCREF(Py_NotImplemented);
5181 return Py_NotImplemented;
5182 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005183 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005184 if (args == NULL)
5185 res = NULL;
5186 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005187 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005188 Py_DECREF(args);
5189 }
5190 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005191 return res;
5192}
5193
Guido van Rossumb8f63662001-08-15 23:57:02 +00005194static PyObject *
5195slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5196{
5197 PyObject *res;
5198
Christian Heimese93237d2007-12-19 02:37:44 +00005199 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005200 res = half_richcompare(self, other, op);
5201 if (res != Py_NotImplemented)
5202 return res;
5203 Py_DECREF(res);
5204 }
Christian Heimese93237d2007-12-19 02:37:44 +00005205 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00005206 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005207 if (res != Py_NotImplemented) {
5208 return res;
5209 }
5210 Py_DECREF(res);
5211 }
5212 Py_INCREF(Py_NotImplemented);
5213 return Py_NotImplemented;
5214}
5215
5216static PyObject *
5217slot_tp_iter(PyObject *self)
5218{
5219 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005220 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005221
Guido van Rossum60718732001-08-28 17:47:51 +00005222 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005223 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00005224 PyObject *args;
5225 args = res = PyTuple_New(0);
5226 if (args != NULL) {
5227 res = PyObject_Call(func, args, NULL);
5228 Py_DECREF(args);
5229 }
5230 Py_DECREF(func);
5231 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005232 }
5233 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005234 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005235 if (func == NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00005236 PyErr_Format(PyExc_TypeError,
5237 "'%.200s' object is not iterable",
Christian Heimese93237d2007-12-19 02:37:44 +00005238 Py_TYPE(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005239 return NULL;
5240 }
5241 Py_DECREF(func);
5242 return PySeqIter_New(self);
5243}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005244
5245static PyObject *
5246slot_tp_iternext(PyObject *self)
5247{
Guido van Rossum2730b132001-08-28 18:22:14 +00005248 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00005249 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005250}
5251
Guido van Rossum1a493502001-08-17 16:47:50 +00005252static PyObject *
5253slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5254{
Christian Heimese93237d2007-12-19 02:37:44 +00005255 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00005256 PyObject *get;
5257 static PyObject *get_str = NULL;
5258
5259 if (get_str == NULL) {
5260 get_str = PyString_InternFromString("__get__");
5261 if (get_str == NULL)
5262 return NULL;
5263 }
5264 get = _PyType_Lookup(tp, get_str);
5265 if (get == NULL) {
5266 /* Avoid further slowdowns */
5267 if (tp->tp_descr_get == slot_tp_descr_get)
5268 tp->tp_descr_get = NULL;
5269 Py_INCREF(self);
5270 return self;
5271 }
Guido van Rossum2c252392001-08-24 10:13:31 +00005272 if (obj == NULL)
5273 obj = Py_None;
5274 if (type == NULL)
5275 type = Py_None;
Georg Brandl684fd0c2006-05-25 19:15:31 +00005276 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005277}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005278
5279static int
5280slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5281{
Guido van Rossum2c252392001-08-24 10:13:31 +00005282 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005283 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005284
5285 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00005286 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005287 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00005288 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005289 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005290 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005291 if (res == NULL)
5292 return -1;
5293 Py_DECREF(res);
5294 return 0;
5295}
5296
5297static int
5298slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5299{
Guido van Rossum60718732001-08-28 17:47:51 +00005300 static PyObject *init_str;
5301 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005302 PyObject *res;
5303
5304 if (meth == NULL)
5305 return -1;
5306 res = PyObject_Call(meth, args, kwds);
5307 Py_DECREF(meth);
5308 if (res == NULL)
5309 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005310 if (res != Py_None) {
Georg Brandlccff7852006-06-18 22:17:29 +00005311 PyErr_Format(PyExc_TypeError,
5312 "__init__() should return None, not '%.200s'",
Christian Heimese93237d2007-12-19 02:37:44 +00005313 Py_TYPE(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005314 Py_DECREF(res);
5315 return -1;
5316 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005317 Py_DECREF(res);
5318 return 0;
5319}
5320
5321static PyObject *
5322slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5323{
Guido van Rossum7bed2132002-08-08 21:57:53 +00005324 static PyObject *new_str;
5325 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005326 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005327 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005328
Guido van Rossum7bed2132002-08-08 21:57:53 +00005329 if (new_str == NULL) {
5330 new_str = PyString_InternFromString("__new__");
5331 if (new_str == NULL)
5332 return NULL;
5333 }
5334 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005335 if (func == NULL)
5336 return NULL;
5337 assert(PyTuple_Check(args));
5338 n = PyTuple_GET_SIZE(args);
5339 newargs = PyTuple_New(n+1);
5340 if (newargs == NULL)
5341 return NULL;
5342 Py_INCREF(type);
5343 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5344 for (i = 0; i < n; i++) {
5345 x = PyTuple_GET_ITEM(args, i);
5346 Py_INCREF(x);
5347 PyTuple_SET_ITEM(newargs, i+1, x);
5348 }
5349 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005350 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005351 Py_DECREF(func);
5352 return x;
5353}
5354
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005355static void
5356slot_tp_del(PyObject *self)
5357{
5358 static PyObject *del_str = NULL;
5359 PyObject *del, *res;
5360 PyObject *error_type, *error_value, *error_traceback;
5361
5362 /* Temporarily resurrect the object. */
5363 assert(self->ob_refcnt == 0);
5364 self->ob_refcnt = 1;
5365
5366 /* Save the current exception, if any. */
5367 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5368
5369 /* Execute __del__ method, if any. */
5370 del = lookup_maybe(self, "__del__", &del_str);
5371 if (del != NULL) {
5372 res = PyEval_CallObject(del, NULL);
5373 if (res == NULL)
5374 PyErr_WriteUnraisable(del);
5375 else
5376 Py_DECREF(res);
5377 Py_DECREF(del);
5378 }
5379
5380 /* Restore the saved exception. */
5381 PyErr_Restore(error_type, error_value, error_traceback);
5382
5383 /* Undo the temporary resurrection; can't use DECREF here, it would
5384 * cause a recursive call.
5385 */
5386 assert(self->ob_refcnt > 0);
5387 if (--self->ob_refcnt == 0)
5388 return; /* this is the normal path out */
5389
5390 /* __del__ resurrected it! Make it look like the original Py_DECREF
5391 * never happened.
5392 */
5393 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005394 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005395 _Py_NewReference(self);
5396 self->ob_refcnt = refcnt;
5397 }
Christian Heimese93237d2007-12-19 02:37:44 +00005398 assert(!PyType_IS_GC(Py_TYPE(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005399 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005400 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5401 * we need to undo that. */
5402 _Py_DEC_REFTOTAL;
5403 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5404 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005405 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5406 * _Py_NewReference bumped tp_allocs: both of those need to be
5407 * undone.
5408 */
5409#ifdef COUNT_ALLOCS
Christian Heimese93237d2007-12-19 02:37:44 +00005410 --Py_TYPE(self)->tp_frees;
5411 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005412#endif
5413}
5414
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005415
5416/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005417 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005418 structure, which incorporates the additional structures used for numbers,
5419 sequences and mappings.
5420 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005421 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005422 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5423 terminated with an all-zero entry. (This table is further initialized and
5424 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005425
Guido van Rossum6d204072001-10-21 00:44:31 +00005426typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005427
5428#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005429#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005430#undef ETSLOT
5431#undef SQSLOT
5432#undef MPSLOT
5433#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005434#undef UNSLOT
5435#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005436#undef BINSLOT
5437#undef RBINSLOT
5438
Guido van Rossum6d204072001-10-21 00:44:31 +00005439#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005440 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5441 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005442#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5443 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005444 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005445#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005446 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005447 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005448#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5449 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5450#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5451 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5452#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5453 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5454#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5455 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5456 "x." NAME "() <==> " DOC)
5457#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5458 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5459 "x." NAME "(y) <==> x" DOC "y")
5460#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5461 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5462 "x." NAME "(y) <==> x" DOC "y")
5463#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5464 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5465 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005466#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5467 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5468 "x." NAME "(y) <==> " DOC)
5469#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5470 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5471 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005472
5473static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005474 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005475 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005476 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5477 The logic in abstract.c always falls back to nb_add/nb_multiply in
5478 this case. Defining both the nb_* and the sq_* slots to call the
5479 user-defined methods has unexpected side-effects, as shown by
5480 test_descr.notimplemented() */
5481 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005482 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00005483 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005484 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005485 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005486 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005487 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5488 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005489 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005490 "x.__getslice__(i, j) <==> x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005491 \n\
5492 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005493 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005494 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005495 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005496 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005497 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005498 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005499 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005500 \n\
5501 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005502 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005503 "x.__delslice__(i, j) <==> del x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005504 \n\
5505 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005506 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5507 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005508 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005509 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005510 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005511 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005512
Martin v. Löwis18e16552006-02-15 17:27:45 +00005513 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005514 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005515 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005516 wrap_binaryfunc,
5517 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005518 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005519 wrap_objobjargproc,
5520 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005521 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005522 wrap_delitem,
5523 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005524
Guido van Rossum6d204072001-10-21 00:44:31 +00005525 BINSLOT("__add__", nb_add, slot_nb_add,
5526 "+"),
5527 RBINSLOT("__radd__", nb_add, slot_nb_add,
5528 "+"),
5529 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5530 "-"),
5531 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5532 "-"),
5533 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5534 "*"),
5535 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5536 "*"),
5537 BINSLOT("__div__", nb_divide, slot_nb_divide,
5538 "/"),
5539 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5540 "/"),
5541 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5542 "%"),
5543 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5544 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005545 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005546 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005547 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005548 "divmod(y, x)"),
5549 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5550 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5551 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5552 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5553 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5554 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5555 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5556 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005557 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005558 "x != 0"),
5559 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5560 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5561 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5562 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5563 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5564 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5565 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5566 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5567 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5568 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5569 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5570 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5571 "x.__coerce__(y) <==> coerce(x, y)"),
5572 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5573 "int(x)"),
5574 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5575 "long(x)"),
5576 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5577 "float(x)"),
5578 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5579 "oct(x)"),
5580 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5581 "hex(x)"),
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005582 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005583 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005584 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5585 wrap_binaryfunc, "+"),
5586 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5587 wrap_binaryfunc, "-"),
5588 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5589 wrap_binaryfunc, "*"),
5590 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5591 wrap_binaryfunc, "/"),
5592 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5593 wrap_binaryfunc, "%"),
5594 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005595 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005596 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5597 wrap_binaryfunc, "<<"),
5598 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5599 wrap_binaryfunc, ">>"),
5600 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5601 wrap_binaryfunc, "&"),
5602 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5603 wrap_binaryfunc, "^"),
5604 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5605 wrap_binaryfunc, "|"),
5606 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5607 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5608 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5609 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5610 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5611 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5612 IBSLOT("__itruediv__", nb_inplace_true_divide,
5613 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005614
Guido van Rossum6d204072001-10-21 00:44:31 +00005615 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5616 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005617 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005618 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5619 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005620 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005621 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5622 "x.__cmp__(y) <==> cmp(x,y)"),
5623 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5624 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005625 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5626 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005627 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005628 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5629 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5630 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5631 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5632 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5633 "x.__setattr__('name', value) <==> x.name = value"),
5634 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5635 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5636 "x.__delattr__('name') <==> del x.name"),
5637 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5638 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5639 "x.__lt__(y) <==> x<y"),
5640 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5641 "x.__le__(y) <==> x<=y"),
5642 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5643 "x.__eq__(y) <==> x==y"),
5644 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5645 "x.__ne__(y) <==> x!=y"),
5646 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5647 "x.__gt__(y) <==> x>y"),
5648 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5649 "x.__ge__(y) <==> x>=y"),
5650 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5651 "x.__iter__() <==> iter(x)"),
5652 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5653 "x.next() -> the next value, or raise StopIteration"),
5654 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5655 "descr.__get__(obj[, type]) -> value"),
5656 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5657 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005658 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5659 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005660 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005661 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005662 "see x.__class__.__doc__ for signature",
5663 PyWrapperFlag_KEYWORDS),
5664 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005665 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005666 {NULL}
5667};
5668
Guido van Rossumc334df52002-04-04 23:44:47 +00005669/* Given a type pointer and an offset gotten from a slotdef entry, return a
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005670 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005671 the offset to the type pointer, since it takes care to indirect through the
5672 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5673 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005674static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005675slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005676{
5677 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005678 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005679
Guido van Rossume5c691a2003-03-07 15:13:17 +00005680 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005681 assert(offset >= 0);
Skip Montanaro429433b2006-04-18 00:35:43 +00005682 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5683 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005684 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005685 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005686 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005687 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005688 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005689 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005690 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005691 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005692 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005693 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005694 }
5695 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005696 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005697 }
5698 if (ptr != NULL)
5699 ptr += offset;
5700 return (void **)ptr;
5701}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005702
Guido van Rossumc334df52002-04-04 23:44:47 +00005703/* Length of array of slotdef pointers used to store slots with the
5704 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5705 the same __name__, for any __name__. Since that's a static property, it is
5706 appropriate to declare fixed-size arrays for this. */
5707#define MAX_EQUIV 10
5708
5709/* Return a slot pointer for a given name, but ONLY if the attribute has
5710 exactly one slot function. The name must be an interned string. */
5711static void **
5712resolve_slotdups(PyTypeObject *type, PyObject *name)
5713{
5714 /* XXX Maybe this could be optimized more -- but is it worth it? */
5715
5716 /* pname and ptrs act as a little cache */
5717 static PyObject *pname;
5718 static slotdef *ptrs[MAX_EQUIV];
5719 slotdef *p, **pp;
5720 void **res, **ptr;
5721
5722 if (pname != name) {
5723 /* Collect all slotdefs that match name into ptrs. */
5724 pname = name;
5725 pp = ptrs;
5726 for (p = slotdefs; p->name_strobj; p++) {
5727 if (p->name_strobj == name)
5728 *pp++ = p;
5729 }
5730 *pp = NULL;
5731 }
5732
5733 /* Look in all matching slots of the type; if exactly one of these has
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005734 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005735 res = NULL;
5736 for (pp = ptrs; *pp; pp++) {
5737 ptr = slotptr(type, (*pp)->offset);
5738 if (ptr == NULL || *ptr == NULL)
5739 continue;
5740 if (res != NULL)
5741 return NULL;
5742 res = ptr;
5743 }
5744 return res;
5745}
5746
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005747/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005748 does some incredibly complex thinking and then sticks something into the
5749 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5750 interests, and then stores a generic wrapper or a specific function into
5751 the slot.) Return a pointer to the next slotdef with a different offset,
5752 because that's convenient for fixup_slot_dispatchers(). */
5753static slotdef *
5754update_one_slot(PyTypeObject *type, slotdef *p)
5755{
5756 PyObject *descr;
5757 PyWrapperDescrObject *d;
5758 void *generic = NULL, *specific = NULL;
5759 int use_generic = 0;
5760 int offset = p->offset;
5761 void **ptr = slotptr(type, offset);
5762
5763 if (ptr == NULL) {
5764 do {
5765 ++p;
5766 } while (p->offset == offset);
5767 return p;
5768 }
5769 do {
5770 descr = _PyType_Lookup(type, p->name_strobj);
5771 if (descr == NULL)
5772 continue;
Christian Heimese93237d2007-12-19 02:37:44 +00005773 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00005774 void **tptr = resolve_slotdups(type, p->name_strobj);
5775 if (tptr == NULL || tptr == ptr)
5776 generic = p->function;
5777 d = (PyWrapperDescrObject *)descr;
5778 if (d->d_base->wrapper == p->wrapper &&
5779 PyType_IsSubtype(type, d->d_type))
5780 {
5781 if (specific == NULL ||
5782 specific == d->d_wrapped)
5783 specific = d->d_wrapped;
5784 else
5785 use_generic = 1;
5786 }
5787 }
Christian Heimese93237d2007-12-19 02:37:44 +00005788 else if (Py_TYPE(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00005789 PyCFunction_GET_FUNCTION(descr) ==
5790 (PyCFunction)tp_new_wrapper &&
5791 strcmp(p->name, "__new__") == 0)
5792 {
5793 /* The __new__ wrapper is not a wrapper descriptor,
5794 so must be special-cased differently.
5795 If we don't do this, creating an instance will
5796 always use slot_tp_new which will look up
5797 __new__ in the MRO which will call tp_new_wrapper
5798 which will look through the base classes looking
5799 for a static base and call its tp_new (usually
5800 PyType_GenericNew), after performing various
5801 sanity checks and constructing a new argument
5802 list. Cut all that nonsense short -- this speeds
5803 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005804 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005805 /* XXX I'm not 100% sure that there isn't a hole
5806 in this reasoning that requires additional
5807 sanity checks. I'll buy the first person to
5808 point out a bug in this reasoning a beer. */
5809 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005810 else {
5811 use_generic = 1;
5812 generic = p->function;
5813 }
5814 } while ((++p)->offset == offset);
5815 if (specific && !use_generic)
5816 *ptr = specific;
5817 else
5818 *ptr = generic;
5819 return p;
5820}
5821
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005822/* In the type, update the slots whose slotdefs are gathered in the pp array.
5823 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005824static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005825update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005826{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005827 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005828
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005829 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005830 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005831 return 0;
5832}
5833
Guido van Rossumc334df52002-04-04 23:44:47 +00005834/* Comparison function for qsort() to compare slotdefs by their offset, and
5835 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005836static int
5837slotdef_cmp(const void *aa, const void *bb)
5838{
5839 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5840 int c = a->offset - b->offset;
5841 if (c != 0)
5842 return c;
5843 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005844 /* Cannot use a-b, as this gives off_t,
5845 which may lose precision when converted to int. */
5846 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005847}
5848
Guido van Rossumc334df52002-04-04 23:44:47 +00005849/* Initialize the slotdefs table by adding interned string objects for the
5850 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005851static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005852init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005853{
5854 slotdef *p;
5855 static int initialized = 0;
5856
5857 if (initialized)
5858 return;
5859 for (p = slotdefs; p->name; p++) {
5860 p->name_strobj = PyString_InternFromString(p->name);
5861 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005862 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005863 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005864 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5865 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005866 initialized = 1;
5867}
5868
Guido van Rossumc334df52002-04-04 23:44:47 +00005869/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005870static int
5871update_slot(PyTypeObject *type, PyObject *name)
5872{
Guido van Rossumc334df52002-04-04 23:44:47 +00005873 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005874 slotdef *p;
5875 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005876 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005877
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00005878 /* Clear the VALID_VERSION flag of 'type' and all its
5879 subclasses. This could possibly be unified with the
5880 update_subclasses() recursion below, but carefully:
5881 they each have their own conditions on which to stop
5882 recursing into subclasses. */
5883 type_modified(type);
5884
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005885 init_slotdefs();
5886 pp = ptrs;
5887 for (p = slotdefs; p->name; p++) {
5888 /* XXX assume name is interned! */
5889 if (p->name_strobj == name)
5890 *pp++ = p;
5891 }
5892 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005893 for (pp = ptrs; *pp; pp++) {
5894 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005895 offset = p->offset;
5896 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005897 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005898 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005899 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005900 if (ptrs[0] == NULL)
5901 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005902 return update_subclasses(type, name,
5903 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005904}
5905
Guido van Rossumc334df52002-04-04 23:44:47 +00005906/* Store the proper functions in the slot dispatches at class (type)
5907 definition time, based upon which operations the class overrides in its
5908 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005909static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005910fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005911{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005912 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005913
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005914 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005915 for (p = slotdefs; p->name; )
5916 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005917}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005918
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005919static void
5920update_all_slots(PyTypeObject* type)
5921{
5922 slotdef *p;
5923
5924 init_slotdefs();
5925 for (p = slotdefs; p->name; p++) {
5926 /* update_slot returns int but can't actually fail */
5927 update_slot(type, p->name_strobj);
5928 }
5929}
5930
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005931/* recurse_down_subclasses() and update_subclasses() are mutually
5932 recursive functions to call a callback for all subclasses,
5933 but refraining from recursing into subclasses that define 'name'. */
5934
5935static int
5936update_subclasses(PyTypeObject *type, PyObject *name,
5937 update_callback callback, void *data)
5938{
5939 if (callback(type, data) < 0)
5940 return -1;
5941 return recurse_down_subclasses(type, name, callback, data);
5942}
5943
5944static int
5945recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5946 update_callback callback, void *data)
5947{
5948 PyTypeObject *subclass;
5949 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005950 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005951
5952 subclasses = type->tp_subclasses;
5953 if (subclasses == NULL)
5954 return 0;
5955 assert(PyList_Check(subclasses));
5956 n = PyList_GET_SIZE(subclasses);
5957 for (i = 0; i < n; i++) {
5958 ref = PyList_GET_ITEM(subclasses, i);
5959 assert(PyWeakref_CheckRef(ref));
5960 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5961 assert(subclass != NULL);
5962 if ((PyObject *)subclass == Py_None)
5963 continue;
5964 assert(PyType_Check(subclass));
5965 /* Avoid recursing down into unaffected classes */
5966 dict = subclass->tp_dict;
5967 if (dict != NULL && PyDict_Check(dict) &&
5968 PyDict_GetItem(dict, name) != NULL)
5969 continue;
5970 if (update_subclasses(subclass, name, callback, data) < 0)
5971 return -1;
5972 }
5973 return 0;
5974}
5975
Guido van Rossum6d204072001-10-21 00:44:31 +00005976/* This function is called by PyType_Ready() to populate the type's
5977 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005978 function slot (like tp_repr) that's defined in the type, one or more
5979 corresponding descriptors are added in the type's tp_dict dictionary
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005980 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005981 cause more than one descriptor to be added (for example, the nb_add
5982 slot adds both __add__ and __radd__ descriptors) and some function
5983 slots compete for the same descriptor (for example both sq_item and
5984 mp_subscript generate a __getitem__ descriptor).
5985
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005986 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005987 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005988 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005989 between competing slots: the members of PyHeapTypeObject are listed
5990 from most general to least general, so the most general slot is
5991 preferred. In particular, because as_mapping comes before as_sequence,
5992 for a type that defines both mp_subscript and sq_item, mp_subscript
5993 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005994
5995 This only adds new descriptors and doesn't overwrite entries in
5996 tp_dict that were previously defined. The descriptors contain a
5997 reference to the C function they must call, so that it's safe if they
5998 are copied into a subtype's __dict__ and the subtype has a different
5999 C function in its slot -- calling the method defined by the
6000 descriptor will call the C function that was used to create it,
6001 rather than the C function present in the slot when it is called.
6002 (This is important because a subtype may have a C function in the
6003 slot that calls the method from the dictionary, and we want to avoid
6004 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006005
6006static int
6007add_operators(PyTypeObject *type)
6008{
6009 PyObject *dict = type->tp_dict;
6010 slotdef *p;
6011 PyObject *descr;
6012 void **ptr;
6013
6014 init_slotdefs();
6015 for (p = slotdefs; p->name; p++) {
6016 if (p->wrapper == NULL)
6017 continue;
6018 ptr = slotptr(type, p->offset);
6019 if (!ptr || !*ptr)
6020 continue;
6021 if (PyDict_GetItem(dict, p->name_strobj))
6022 continue;
6023 descr = PyDescr_NewWrapper(type, p, *ptr);
6024 if (descr == NULL)
6025 return -1;
6026 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6027 return -1;
6028 Py_DECREF(descr);
6029 }
6030 if (type->tp_new != NULL) {
6031 if (add_tp_new_wrapper(type) < 0)
6032 return -1;
6033 }
6034 return 0;
6035}
6036
Guido van Rossum705f0f52001-08-24 16:47:00 +00006037
6038/* Cooperative 'super' */
6039
6040typedef struct {
6041 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00006042 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006043 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006044 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006045} superobject;
6046
Guido van Rossum6f799372001-09-20 20:46:19 +00006047static PyMemberDef super_members[] = {
6048 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6049 "the class invoking super()"},
6050 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6051 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006052 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00006053 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006054 {0}
6055};
6056
Guido van Rossum705f0f52001-08-24 16:47:00 +00006057static void
6058super_dealloc(PyObject *self)
6059{
6060 superobject *su = (superobject *)self;
6061
Guido van Rossum048eb752001-10-02 21:24:57 +00006062 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006063 Py_XDECREF(su->obj);
6064 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006065 Py_XDECREF(su->obj_type);
Christian Heimese93237d2007-12-19 02:37:44 +00006066 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006067}
6068
6069static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006070super_repr(PyObject *self)
6071{
6072 superobject *su = (superobject *)self;
6073
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006074 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006075 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00006076 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006077 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006078 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006079 else
6080 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00006081 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006082 su->type ? su->type->tp_name : "NULL");
6083}
6084
6085static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006086super_getattro(PyObject *self, PyObject *name)
6087{
6088 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006089 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006090
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006091 if (!skip) {
6092 /* We want __class__ to return the class of the super object
6093 (i.e. super, or a subclass), not the class of su->obj. */
6094 skip = (PyString_Check(name) &&
6095 PyString_GET_SIZE(name) == 9 &&
6096 strcmp(PyString_AS_STRING(name), "__class__") == 0);
6097 }
6098
6099 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00006100 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006101 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006102 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006103 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006104
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006105 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006106 mro = starttype->tp_mro;
6107
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006108 if (mro == NULL)
6109 n = 0;
6110 else {
6111 assert(PyTuple_Check(mro));
6112 n = PyTuple_GET_SIZE(mro);
6113 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006114 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00006115 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00006116 break;
6117 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006118 i++;
6119 res = NULL;
6120 for (; i < n; i++) {
6121 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00006122 if (PyType_Check(tmp))
6123 dict = ((PyTypeObject *)tmp)->tp_dict;
6124 else if (PyClass_Check(tmp))
6125 dict = ((PyClassObject *)tmp)->cl_dict;
6126 else
6127 continue;
6128 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00006129 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00006130 Py_INCREF(res);
Christian Heimese93237d2007-12-19 02:37:44 +00006131 f = Py_TYPE(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006132 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006133 tmp = f(res,
6134 /* Only pass 'obj' param if
6135 this is instance-mode super
6136 (See SF ID #743627)
6137 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00006138 (su->obj == (PyObject *)
6139 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006140 ? (PyObject *)NULL
6141 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00006142 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006143 Py_DECREF(res);
6144 res = tmp;
6145 }
6146 return res;
6147 }
6148 }
6149 }
6150 return PyObject_GenericGetAttr(self, name);
6151}
6152
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006153static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006154supercheck(PyTypeObject *type, PyObject *obj)
6155{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006156 /* Check that a super() call makes sense. Return a type object.
6157
6158 obj can be a new-style class, or an instance of one:
6159
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006160 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006161 used for class methods; the return value is obj.
6162
6163 - If it is an instance, it must be an instance of 'type'. This is
6164 the normal case; the return value is obj.__class__.
6165
6166 But... when obj is an instance, we want to allow for the case where
Christian Heimese93237d2007-12-19 02:37:44 +00006167 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006168 This will allow using super() with a proxy for obj.
6169 */
6170
Guido van Rossum8e80a722003-02-18 19:22:22 +00006171 /* Check for first bullet above (special case) */
6172 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6173 Py_INCREF(obj);
6174 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006175 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006176
6177 /* Normal case */
Christian Heimese93237d2007-12-19 02:37:44 +00006178 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6179 Py_INCREF(Py_TYPE(obj));
6180 return Py_TYPE(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006181 }
6182 else {
6183 /* Try the slow way */
6184 static PyObject *class_str = NULL;
6185 PyObject *class_attr;
6186
6187 if (class_str == NULL) {
6188 class_str = PyString_FromString("__class__");
6189 if (class_str == NULL)
6190 return NULL;
6191 }
6192
6193 class_attr = PyObject_GetAttr(obj, class_str);
6194
6195 if (class_attr != NULL &&
6196 PyType_Check(class_attr) &&
Christian Heimese93237d2007-12-19 02:37:44 +00006197 (PyTypeObject *)class_attr != Py_TYPE(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006198 {
6199 int ok = PyType_IsSubtype(
6200 (PyTypeObject *)class_attr, type);
6201 if (ok)
6202 return (PyTypeObject *)class_attr;
6203 }
6204
6205 if (class_attr == NULL)
6206 PyErr_Clear();
6207 else
6208 Py_DECREF(class_attr);
6209 }
6210
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006211 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006212 "super(type, obj): "
6213 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006214 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006215}
6216
Guido van Rossum705f0f52001-08-24 16:47:00 +00006217static PyObject *
6218super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6219{
6220 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00006221 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006222
6223 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6224 /* Not binding to an object, or already bound */
6225 Py_INCREF(self);
6226 return self;
6227 }
Christian Heimese93237d2007-12-19 02:37:44 +00006228 if (Py_TYPE(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00006229 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006230 call its type */
Christian Heimese93237d2007-12-19 02:37:44 +00006231 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006232 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00006233 else {
6234 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006235 PyTypeObject *obj_type = supercheck(su->type, obj);
6236 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006237 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00006238 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006239 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00006240 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006241 return NULL;
6242 Py_INCREF(su->type);
6243 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00006244 newobj->type = su->type;
6245 newobj->obj = obj;
6246 newobj->obj_type = obj_type;
6247 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006248 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006249}
6250
6251static int
6252super_init(PyObject *self, PyObject *args, PyObject *kwds)
6253{
6254 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00006255 PyTypeObject *type;
6256 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006257 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006258
Georg Brandl5d59c092006-09-30 08:43:30 +00006259 if (!_PyArg_NoKeywords("super", kwds))
6260 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006261 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
6262 return -1;
6263 if (obj == Py_None)
6264 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006265 if (obj != NULL) {
6266 obj_type = supercheck(type, obj);
6267 if (obj_type == NULL)
6268 return -1;
6269 Py_INCREF(obj);
6270 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006271 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006272 su->type = type;
6273 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006274 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006275 return 0;
6276}
6277
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006278PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00006279"super(type) -> unbound super object\n"
6280"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006281"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006282"Typical use to call a cooperative superclass method:\n"
6283"class C(B):\n"
6284" def meth(self, arg):\n"
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006285" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006286
Guido van Rossum048eb752001-10-02 21:24:57 +00006287static int
6288super_traverse(PyObject *self, visitproc visit, void *arg)
6289{
6290 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006291
Thomas Woutersc6e55062006-04-15 21:47:09 +00006292 Py_VISIT(su->obj);
6293 Py_VISIT(su->type);
6294 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006295
6296 return 0;
6297}
6298
Guido van Rossum705f0f52001-08-24 16:47:00 +00006299PyTypeObject PySuper_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00006300 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00006301 "super", /* tp_name */
6302 sizeof(superobject), /* tp_basicsize */
6303 0, /* tp_itemsize */
6304 /* methods */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006305 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006306 0, /* tp_print */
6307 0, /* tp_getattr */
6308 0, /* tp_setattr */
6309 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006310 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006311 0, /* tp_as_number */
6312 0, /* tp_as_sequence */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006313 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006314 0, /* tp_hash */
6315 0, /* tp_call */
6316 0, /* tp_str */
6317 super_getattro, /* tp_getattro */
6318 0, /* tp_setattro */
6319 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006320 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6321 Py_TPFLAGS_BASETYPE, /* tp_flags */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006322 super_doc, /* tp_doc */
6323 super_traverse, /* tp_traverse */
6324 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006325 0, /* tp_richcompare */
6326 0, /* tp_weaklistoffset */
6327 0, /* tp_iter */
6328 0, /* tp_iternext */
6329 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006330 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006331 0, /* tp_getset */
6332 0, /* tp_base */
6333 0, /* tp_dict */
6334 super_descr_get, /* tp_descr_get */
6335 0, /* tp_descr_set */
6336 0, /* tp_dictoffset */
6337 super_init, /* tp_init */
6338 PyType_GenericAlloc, /* tp_alloc */
6339 PyType_GenericNew, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006340 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006341};