blob: cf5e2a9a8306fbb4b1447e238dcb4370ba64cb7f [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, \
Gregory P. Smithdd96db62008-06-09 04:58:54 +000022 ((PyStringObject *)(name))->ob_shash)
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000023#define MCACHE_CACHEABLE_NAME(name) \
Gregory P. Smithdd96db62008-06-09 04:58:54 +000024 PyString_CheckExact(name) && \
25 PyString_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000026
27struct method_cache_entry {
28 unsigned int version;
29 PyObject *name; /* reference to exactly a str or None */
30 PyObject *value; /* borrowed */
31};
32
33static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
34static unsigned int next_version_tag = 0;
Christian Heimes908caac2008-01-27 23:34:59 +000035
36unsigned int
37PyType_ClearCache(void)
38{
39 Py_ssize_t i;
40 unsigned int cur_version_tag = next_version_tag - 1;
41
42 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
43 method_cache[i].version = 0;
44 Py_CLEAR(method_cache[i].name);
45 method_cache[i].value = NULL;
46 }
47 next_version_tag = 0;
48 /* mark all version tags as invalid */
Georg Brandl74a1dea2008-05-28 11:21:39 +000049 PyType_Modified(&PyBaseObject_Type);
Christian Heimes908caac2008-01-27 23:34:59 +000050 return cur_version_tag;
51}
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000052
Georg Brandl74a1dea2008-05-28 11:21:39 +000053void
54PyType_Modified(PyTypeObject *type)
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000055{
56 /* Invalidate any cached data for the specified type and all
57 subclasses. This function is called after the base
58 classes, mro, or attributes of the type are altered.
59
60 Invariants:
61
62 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
63 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
64 objects coming from non-recompiled extension modules)
65
66 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
67 it must first be set on all super types.
68
69 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
70 type (so it must first clear it on all subclasses). The
71 tp_version_tag value is meaningless unless this flag is set.
72 We don't assign new version tags eagerly, but only as
73 needed.
74 */
75 PyObject *raw, *ref;
76 Py_ssize_t i, n;
77
Neal Norwitze7bb9182008-01-27 17:10:14 +000078 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000079 return;
80
81 raw = type->tp_subclasses;
82 if (raw != NULL) {
83 n = PyList_GET_SIZE(raw);
84 for (i = 0; i < n; i++) {
85 ref = PyList_GET_ITEM(raw, i);
86 ref = PyWeakref_GET_OBJECT(ref);
87 if (ref != Py_None) {
Georg Brandl74a1dea2008-05-28 11:21:39 +000088 PyType_Modified((PyTypeObject *)ref);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000089 }
90 }
91 }
92 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
93}
94
95static void
96type_mro_modified(PyTypeObject *type, PyObject *bases) {
97 /*
98 Check that all base classes or elements of the mro of type are
99 able to be cached. This function is called after the base
100 classes or mro of the type are altered.
101
102 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
103 inherits from an old-style class, either directly or if it
104 appears in the MRO of a new-style class. No support either for
105 custom MROs that include types that are not officially super
106 types.
107
108 Called from mro_internal, which will subsequently be called on
109 each subclass when their mro is recursively updated.
110 */
111 Py_ssize_t i, n;
112 int clear = 0;
113
Neal Norwitze7bb9182008-01-27 17:10:14 +0000114 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000115 return;
116
117 n = PyTuple_GET_SIZE(bases);
118 for (i = 0; i < n; i++) {
119 PyObject *b = PyTuple_GET_ITEM(bases, i);
120 PyTypeObject *cls;
121
122 if (!PyType_Check(b) ) {
123 clear = 1;
124 break;
125 }
126
127 cls = (PyTypeObject *)b;
128
129 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
130 !PyType_IsSubtype(type, cls)) {
131 clear = 1;
132 break;
133 }
134 }
135
136 if (clear)
137 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
138 Py_TPFLAGS_VALID_VERSION_TAG);
139}
140
141static int
142assign_version_tag(PyTypeObject *type)
143{
144 /* Ensure that the tp_version_tag is valid and set
145 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
146 must first be done on all super classes. Return 0 if this
147 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
148 */
149 Py_ssize_t i, n;
Georg Brandlf18a7072008-05-29 14:35:39 +0000150 PyObject *bases;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000151
152 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
153 return 1;
154 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
155 return 0;
156 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
157 return 0;
158
159 type->tp_version_tag = next_version_tag++;
160 /* for stress-testing: next_version_tag &= 0xFF; */
161
162 if (type->tp_version_tag == 0) {
163 /* wrap-around or just starting Python - clear the whole
164 cache by filling names with references to Py_None.
165 Values are also set to NULL for added protection, as they
166 are borrowed reference */
167 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
168 method_cache[i].value = NULL;
Georg Brandlf18a7072008-05-29 14:35:39 +0000169 Py_XDECREF(method_cache[i].name);
Georg Brandl5ec330c2008-05-28 15:41:36 +0000170 method_cache[i].name = Py_None;
Georg Brandlf18a7072008-05-29 14:35:39 +0000171 Py_INCREF(Py_None);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000172 }
173 /* mark all version tags as invalid */
Georg Brandl74a1dea2008-05-28 11:21:39 +0000174 PyType_Modified(&PyBaseObject_Type);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000175 return 1;
176 }
177 bases = type->tp_bases;
178 n = PyTuple_GET_SIZE(bases);
179 for (i = 0; i < n; i++) {
180 PyObject *b = PyTuple_GET_ITEM(bases, i);
181 assert(PyType_Check(b));
182 if (!assign_version_tag((PyTypeObject *)b))
183 return 0;
184 }
185 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
186 return 1;
187}
188
189
Guido van Rossum6f799372001-09-20 20:46:19 +0000190static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000191 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
192 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
193 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +0000194 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000195 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
196 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
197 {"__dictoffset__", T_LONG,
198 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000199 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
200 {0}
201};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000202
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000203static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000204type_name(PyTypeObject *type, void *context)
205{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000206 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000207
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000208 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +0000209 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000210
Georg Brandlc255c7b2006-02-20 22:27:28 +0000211 Py_INCREF(et->ht_name);
212 return et->ht_name;
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000213 }
214 else {
215 s = strrchr(type->tp_name, '.');
216 if (s == NULL)
217 s = type->tp_name;
218 else
219 s++;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000220 return PyString_FromString(s);
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000221 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000222}
223
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000224static int
225type_set_name(PyTypeObject *type, PyObject *value, void *context)
226{
Guido van Rossume5c691a2003-03-07 15:13:17 +0000227 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000228
229 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
230 PyErr_Format(PyExc_TypeError,
231 "can't set %s.__name__", type->tp_name);
232 return -1;
233 }
234 if (!value) {
235 PyErr_Format(PyExc_TypeError,
236 "can't delete %s.__name__", type->tp_name);
237 return -1;
238 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000239 if (!PyString_Check(value)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000240 PyErr_Format(PyExc_TypeError,
241 "can only assign string to %s.__name__, not '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +0000242 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000243 return -1;
244 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000245 if (strlen(PyString_AS_STRING(value))
246 != (size_t)PyString_GET_SIZE(value)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000247 PyErr_Format(PyExc_ValueError,
248 "__name__ must not contain null bytes");
249 return -1;
250 }
251
Guido van Rossume5c691a2003-03-07 15:13:17 +0000252 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000253
254 Py_INCREF(value);
255
Georg Brandlc255c7b2006-02-20 22:27:28 +0000256 Py_DECREF(et->ht_name);
257 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000258
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000259 type->tp_name = PyString_AS_STRING(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000260
261 return 0;
262}
263
Guido van Rossumc3542212001-08-16 09:18:56 +0000264static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000265type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000266{
Guido van Rossumc3542212001-08-16 09:18:56 +0000267 PyObject *mod;
268 char *s;
269
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000270 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
271 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +0000272 if (!mod) {
273 PyErr_Format(PyExc_AttributeError, "__module__");
274 return 0;
275 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000276 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +0000277 return mod;
278 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000279 else {
280 s = strrchr(type->tp_name, '.');
281 if (s != NULL)
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000282 return PyString_FromStringAndSize(
Armin Rigo7ccbca92006-10-04 12:17:45 +0000283 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000284 return PyString_FromString("__builtin__");
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000285 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000286}
287
Guido van Rossum3926a632001-09-25 16:25:58 +0000288static int
289type_set_module(PyTypeObject *type, PyObject *value, void *context)
290{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000291 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000292 PyErr_Format(PyExc_TypeError,
293 "can't set %s.__module__", type->tp_name);
294 return -1;
295 }
296 if (!value) {
297 PyErr_Format(PyExc_TypeError,
298 "can't delete %s.__module__", type->tp_name);
299 return -1;
300 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000301
Georg Brandl74a1dea2008-05-28 11:21:39 +0000302 PyType_Modified(type);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000303
Guido van Rossum3926a632001-09-25 16:25:58 +0000304 return PyDict_SetItemString(type->tp_dict, "__module__", value);
305}
306
Tim Peters6d6c1a32001-08-02 04:15:00 +0000307static PyObject *
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +0000308type_abstractmethods(PyTypeObject *type, void *context)
309{
310 PyObject *mod = PyDict_GetItemString(type->tp_dict,
311 "__abstractmethods__");
312 if (!mod) {
313 PyErr_Format(PyExc_AttributeError, "__abstractmethods__");
314 return NULL;
315 }
316 Py_XINCREF(mod);
317 return mod;
318}
319
320static int
321type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
322{
323 /* __abstractmethods__ should only be set once on a type, in
324 abc.ABCMeta.__new__, so this function doesn't do anything
325 special to update subclasses.
326 */
327 int res = PyDict_SetItemString(type->tp_dict,
328 "__abstractmethods__", value);
329 if (res == 0) {
Georg Brandl74a1dea2008-05-28 11:21:39 +0000330 PyType_Modified(type);
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +0000331 if (value && PyObject_IsTrue(value)) {
332 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
333 }
334 else {
335 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
336 }
337 }
338 return res;
339}
340
341static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000342type_get_bases(PyTypeObject *type, void *context)
343{
344 Py_INCREF(type->tp_bases);
345 return type->tp_bases;
346}
347
348static PyTypeObject *best_base(PyObject *);
349static int mro_internal(PyTypeObject *);
350static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
351static int add_subclass(PyTypeObject*, PyTypeObject*);
352static void remove_subclass(PyTypeObject *, PyTypeObject *);
353static void update_all_slots(PyTypeObject *);
354
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000355typedef int (*update_callback)(PyTypeObject *, void *);
356static int update_subclasses(PyTypeObject *type, PyObject *name,
357 update_callback callback, void *data);
358static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
359 update_callback callback, void *data);
360
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000361static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000362mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000363{
364 PyTypeObject *subclass;
365 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000366 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000367
368 subclasses = type->tp_subclasses;
369 if (subclasses == NULL)
370 return 0;
371 assert(PyList_Check(subclasses));
372 n = PyList_GET_SIZE(subclasses);
373 for (i = 0; i < n; i++) {
374 ref = PyList_GET_ITEM(subclasses, i);
375 assert(PyWeakref_CheckRef(ref));
376 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
377 assert(subclass != NULL);
378 if ((PyObject *)subclass == Py_None)
379 continue;
380 assert(PyType_Check(subclass));
381 old_mro = subclass->tp_mro;
382 if (mro_internal(subclass) < 0) {
383 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000384 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000385 }
386 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000387 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000388 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000389 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000390 if (!tuple)
391 return -1;
392 if (PyList_Append(temp, tuple) < 0)
393 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000394 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000395 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000396 if (mro_subclasses(subclass, temp) < 0)
397 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000398 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000399 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000400}
401
402static int
403type_set_bases(PyTypeObject *type, PyObject *value, void *context)
404{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000405 Py_ssize_t i;
406 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000407 PyObject *ob, *temp;
Armin Rigoc0ba52d2007-04-19 14:44:48 +0000408 PyTypeObject *new_base, *old_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000409 PyObject *old_bases, *old_mro;
410
411 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
412 PyErr_Format(PyExc_TypeError,
413 "can't set %s.__bases__", type->tp_name);
414 return -1;
415 }
416 if (!value) {
417 PyErr_Format(PyExc_TypeError,
418 "can't delete %s.__bases__", type->tp_name);
419 return -1;
420 }
421 if (!PyTuple_Check(value)) {
422 PyErr_Format(PyExc_TypeError,
423 "can only assign tuple to %s.__bases__, not %s",
Christian Heimese93237d2007-12-19 02:37:44 +0000424 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000425 return -1;
426 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000427 if (PyTuple_GET_SIZE(value) == 0) {
428 PyErr_Format(PyExc_TypeError,
429 "can only assign non-empty tuple to %s.__bases__, not ()",
430 type->tp_name);
431 return -1;
432 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000433 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
434 ob = PyTuple_GET_ITEM(value, i);
435 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
436 PyErr_Format(
437 PyExc_TypeError,
438 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +0000439 type->tp_name, Py_TYPE(ob)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000440 return -1;
441 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000442 if (PyType_Check(ob)) {
443 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
444 PyErr_SetString(PyExc_TypeError,
445 "a __bases__ item causes an inheritance cycle");
446 return -1;
447 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000448 }
449 }
450
451 new_base = best_base(value);
452
453 if (!new_base) {
454 return -1;
455 }
456
457 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
458 return -1;
459
460 Py_INCREF(new_base);
461 Py_INCREF(value);
462
463 old_bases = type->tp_bases;
464 old_base = type->tp_base;
465 old_mro = type->tp_mro;
466
467 type->tp_bases = value;
468 type->tp_base = new_base;
469
470 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000471 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000472 }
473
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000474 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000475 if (!temp)
476 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000477
478 r = mro_subclasses(type, temp);
479
480 if (r < 0) {
481 for (i = 0; i < PyList_Size(temp); i++) {
482 PyTypeObject* cls;
483 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000484 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
485 "", 2, 2, &cls, &mro);
Armin Rigo796fc992007-04-19 14:56:48 +0000486 Py_INCREF(mro);
487 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000488 cls->tp_mro = mro;
Armin Rigo796fc992007-04-19 14:56:48 +0000489 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000490 }
491 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000492 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000493 }
494
495 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000496
497 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000498 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000499 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000500 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000501
502 /* for now, sod that: just remove from all old_bases,
503 add to all new_bases */
504
505 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
506 ob = PyTuple_GET_ITEM(old_bases, i);
507 if (PyType_Check(ob)) {
508 remove_subclass(
509 (PyTypeObject*)ob, type);
510 }
511 }
512
513 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
514 ob = PyTuple_GET_ITEM(value, i);
515 if (PyType_Check(ob)) {
516 if (add_subclass((PyTypeObject*)ob, type) < 0)
517 r = -1;
518 }
519 }
520
521 update_all_slots(type);
522
523 Py_DECREF(old_bases);
524 Py_DECREF(old_base);
525 Py_DECREF(old_mro);
526
527 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000528
529 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000530 Py_DECREF(type->tp_bases);
531 Py_DECREF(type->tp_base);
532 if (type->tp_mro != old_mro) {
533 Py_DECREF(type->tp_mro);
534 }
535
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000536 type->tp_bases = old_bases;
537 type->tp_base = old_base;
538 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000539
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000540 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000541}
542
543static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000544type_dict(PyTypeObject *type, void *context)
545{
546 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000547 Py_INCREF(Py_None);
548 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000549 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000550 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000551}
552
Tim Peters24008312002-03-17 18:56:20 +0000553static PyObject *
554type_get_doc(PyTypeObject *type, void *context)
555{
556 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000557 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000558 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000559 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000560 if (result == NULL) {
561 result = Py_None;
562 Py_INCREF(result);
563 }
Christian Heimese93237d2007-12-19 02:37:44 +0000564 else if (Py_TYPE(result)->tp_descr_get) {
565 result = Py_TYPE(result)->tp_descr_get(result, NULL,
Tim Peters2b858972002-04-18 04:12:28 +0000566 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000567 }
568 else {
569 Py_INCREF(result);
570 }
Tim Peters24008312002-03-17 18:56:20 +0000571 return result;
572}
573
Antoine Pitrou0668c622008-08-26 22:42:08 +0000574static PyObject *
575type___instancecheck__(PyObject *type, PyObject *inst)
576{
577 switch (_PyObject_RealIsInstance(inst, type)) {
578 case -1:
579 return NULL;
580 case 0:
581 Py_RETURN_FALSE;
582 default:
583 Py_RETURN_TRUE;
584 }
585}
586
587
588static PyObject *
589type_get_instancecheck(PyObject *type, void *context)
590{
591 static PyMethodDef ml = {"__instancecheck__",
592 type___instancecheck__, METH_O };
593 return PyCFunction_New(&ml, type);
594}
595
596static PyObject *
597type___subclasscheck__(PyObject *type, PyObject *inst)
598{
599 switch (_PyObject_RealIsSubclass(inst, type)) {
600 case -1:
601 return NULL;
602 case 0:
603 Py_RETURN_FALSE;
604 default:
605 Py_RETURN_TRUE;
606 }
607}
608
609static PyObject *
610type_get_subclasscheck(PyObject *type, void *context)
611{
612 static PyMethodDef ml = {"__subclasscheck__",
613 type___subclasscheck__, METH_O };
614 return PyCFunction_New(&ml, type);
615}
616
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000617static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000618 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
619 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000620 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +0000621 {"__abstractmethods__", (getter)type_abstractmethods,
622 (setter)type_set_abstractmethods, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000623 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000624 {"__doc__", (getter)type_get_doc, NULL, NULL},
Antoine Pitrou0668c622008-08-26 22:42:08 +0000625 {"__instancecheck__", (getter)type_get_instancecheck, NULL, NULL},
626 {"__subclasscheck__", (getter)type_get_subclasscheck, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000627 {0}
628};
629
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000630static int
631type_compare(PyObject *v, PyObject *w)
632{
633 /* This is called with type objects only. So we
634 can just compare the addresses. */
635 Py_uintptr_t vv = (Py_uintptr_t)v;
636 Py_uintptr_t ww = (Py_uintptr_t)w;
637 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
638}
639
Steven Bethardae42f332008-03-18 17:26:10 +0000640static PyObject*
641type_richcompare(PyObject *v, PyObject *w, int op)
642{
643 PyObject *result;
644 Py_uintptr_t vv, ww;
645 int c;
646
647 /* Make sure both arguments are types. */
648 if (!PyType_Check(v) || !PyType_Check(w)) {
649 result = Py_NotImplemented;
650 goto out;
651 }
652
653 /* Py3K warning if comparison isn't == or != */
654 if (Py_Py3kWarningFlag && op != Py_EQ && op != Py_NE &&
Benjamin Peterson9f4f4812008-04-27 03:01:45 +0000655 PyErr_WarnEx(PyExc_DeprecationWarning,
Georg Brandld5b635f2008-03-25 08:29:14 +0000656 "type inequality comparisons not supported "
Benjamin Peterson9f4f4812008-04-27 03:01:45 +0000657 "in 3.x", 1) < 0) {
Steven Bethardae42f332008-03-18 17:26:10 +0000658 return NULL;
659 }
660
661 /* Compare addresses */
662 vv = (Py_uintptr_t)v;
663 ww = (Py_uintptr_t)w;
664 switch (op) {
665 case Py_LT: c = vv < ww; break;
666 case Py_LE: c = vv <= ww; break;
667 case Py_EQ: c = vv == ww; break;
668 case Py_NE: c = vv != ww; break;
669 case Py_GT: c = vv > ww; break;
670 case Py_GE: c = vv >= ww; break;
671 default:
672 result = Py_NotImplemented;
673 goto out;
674 }
675 result = c ? Py_True : Py_False;
676
677 /* incref and return */
678 out:
679 Py_INCREF(result);
680 return result;
681}
682
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000683static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000684type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000685{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000686 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000687 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000688
689 mod = type_module(type, NULL);
690 if (mod == NULL)
691 PyErr_Clear();
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000692 else if (!PyString_Check(mod)) {
Guido van Rossumc3542212001-08-16 09:18:56 +0000693 Py_DECREF(mod);
694 mod = NULL;
695 }
696 name = type_name(type, NULL);
697 if (name == NULL)
698 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000699
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000700 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
701 kind = "class";
702 else
703 kind = "type";
704
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000705 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
706 rtn = PyString_FromFormat("<%s '%s.%s'>",
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000707 kind,
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000708 PyString_AS_STRING(mod),
709 PyString_AS_STRING(name));
Barry Warsaw7ce36942001-08-24 18:34:26 +0000710 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000711 else
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000712 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000713
Guido van Rossumc3542212001-08-16 09:18:56 +0000714 Py_XDECREF(mod);
715 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000716 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000717}
718
Tim Peters6d6c1a32001-08-02 04:15:00 +0000719static PyObject *
720type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
721{
722 PyObject *obj;
723
724 if (type->tp_new == NULL) {
725 PyErr_Format(PyExc_TypeError,
726 "cannot create '%.100s' instances",
727 type->tp_name);
728 return NULL;
729 }
730
Tim Peters3f996e72001-09-13 19:18:27 +0000731 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000732 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000733 /* Ugly exception: when the call was type(something),
734 don't call tp_init on the result. */
735 if (type == &PyType_Type &&
736 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
737 (kwds == NULL ||
738 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
739 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000740 /* If the returned object is not an instance of type,
741 it won't be initialized. */
742 if (!PyType_IsSubtype(obj->ob_type, type))
743 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000744 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000745 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
746 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000747 type->tp_init(obj, args, kwds) < 0) {
748 Py_DECREF(obj);
749 obj = NULL;
750 }
751 }
752 return obj;
753}
754
755PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000756PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000757{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000758 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000759 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
760 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000761
762 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000763 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000764 else
Anthony Baxtera6286212006-04-11 07:42:36 +0000765 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000766
Neil Schemenauerc806c882001-08-29 23:54:54 +0000767 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000768 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000769
Neil Schemenauerc806c882001-08-29 23:54:54 +0000770 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000771
Tim Peters6d6c1a32001-08-02 04:15:00 +0000772 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
773 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000774
Tim Peters6d6c1a32001-08-02 04:15:00 +0000775 if (type->tp_itemsize == 0)
776 PyObject_INIT(obj, type);
777 else
778 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000779
Tim Peters6d6c1a32001-08-02 04:15:00 +0000780 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000781 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000782 return obj;
783}
784
785PyObject *
786PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
787{
788 return type->tp_alloc(type, 0);
789}
790
Guido van Rossum9475a232001-10-05 20:51:39 +0000791/* Helpers for subtyping */
792
793static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000794traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
795{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000796 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000797 PyMemberDef *mp;
798
Christian Heimese93237d2007-12-19 02:37:44 +0000799 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000800 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000801 for (i = 0; i < n; i++, mp++) {
802 if (mp->type == T_OBJECT_EX) {
803 char *addr = (char *)self + mp->offset;
804 PyObject *obj = *(PyObject **)addr;
805 if (obj != NULL) {
806 int err = visit(obj, arg);
807 if (err)
808 return err;
809 }
810 }
811 }
812 return 0;
813}
814
815static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000816subtype_traverse(PyObject *self, visitproc visit, void *arg)
817{
818 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000819 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000820
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000821 /* Find the nearest base with a different tp_traverse,
822 and traverse slots while we're at it */
Christian Heimese93237d2007-12-19 02:37:44 +0000823 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000824 base = type;
825 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
Christian Heimese93237d2007-12-19 02:37:44 +0000826 if (Py_SIZE(base)) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000827 int err = traverse_slots(base, self, visit, arg);
828 if (err)
829 return err;
830 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000831 base = base->tp_base;
832 assert(base);
833 }
834
835 if (type->tp_dictoffset != base->tp_dictoffset) {
836 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Woutersc6e55062006-04-15 21:47:09 +0000837 if (dictptr && *dictptr)
838 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000839 }
840
Thomas Woutersc6e55062006-04-15 21:47:09 +0000841 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000842 /* For a heaptype, the instances count as references
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000843 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000844 can find cycles involving this link. */
Thomas Woutersc6e55062006-04-15 21:47:09 +0000845 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000846
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000847 if (basetraverse)
848 return basetraverse(self, visit, arg);
849 return 0;
850}
851
852static void
853clear_slots(PyTypeObject *type, PyObject *self)
854{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000855 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000856 PyMemberDef *mp;
857
Christian Heimese93237d2007-12-19 02:37:44 +0000858 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000859 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000860 for (i = 0; i < n; i++, mp++) {
861 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
862 char *addr = (char *)self + mp->offset;
863 PyObject *obj = *(PyObject **)addr;
864 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000865 *(PyObject **)addr = NULL;
Thomas Woutersedf17d82006-04-15 17:28:34 +0000866 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000867 }
868 }
869 }
870}
871
872static int
873subtype_clear(PyObject *self)
874{
875 PyTypeObject *type, *base;
876 inquiry baseclear;
877
878 /* Find the nearest base with a different tp_clear
879 and clear slots while we're at it */
Christian Heimese93237d2007-12-19 02:37:44 +0000880 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000881 base = type;
882 while ((baseclear = base->tp_clear) == subtype_clear) {
Christian Heimese93237d2007-12-19 02:37:44 +0000883 if (Py_SIZE(base))
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000884 clear_slots(base, self);
885 base = base->tp_base;
886 assert(base);
887 }
888
Guido van Rossuma3862092002-06-10 15:24:42 +0000889 /* There's no need to clear the instance dict (if any);
890 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000891
892 if (baseclear)
893 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000894 return 0;
895}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000896
897static void
898subtype_dealloc(PyObject *self)
899{
Guido van Rossum14227b42001-12-06 02:35:58 +0000900 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000901 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000902
Guido van Rossum22b13872002-08-06 21:41:44 +0000903 /* Extract the type; we expect it to be a heap type */
Christian Heimese93237d2007-12-19 02:37:44 +0000904 type = Py_TYPE(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000905 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000906
Guido van Rossum22b13872002-08-06 21:41:44 +0000907 /* Test whether the type has GC exactly once */
908
909 if (!PyType_IS_GC(type)) {
910 /* It's really rare to find a dynamic type that doesn't have
911 GC; it can only happen when deriving from 'object' and not
912 adding any slots or instance variables. This allows
913 certain simplifications: there's no need to call
914 clear_slots(), or DECREF the dict, or clear weakrefs. */
915
916 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000917 if (type->tp_del) {
918 type->tp_del(self);
919 if (self->ob_refcnt > 0)
920 return;
921 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000922
923 /* Find the nearest base with a different tp_dealloc */
924 base = type;
925 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimese93237d2007-12-19 02:37:44 +0000926 assert(Py_SIZE(base) == 0);
Guido van Rossum22b13872002-08-06 21:41:44 +0000927 base = base->tp_base;
928 assert(base);
929 }
930
931 /* Call the base tp_dealloc() */
932 assert(basedealloc);
933 basedealloc(self);
934
935 /* Can't reference self beyond this point */
936 Py_DECREF(type);
937
938 /* Done */
939 return;
940 }
941
942 /* We get here only if the type has GC */
943
944 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000945 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000946 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000947 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000948 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000949 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000950 /* DO NOT restore GC tracking at this point. weakref callbacks
951 * (if any, and whether directly here or indirectly in something we
952 * call) may trigger GC, and if self is tracked at that point, it
953 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000954 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000955
Guido van Rossum59195fd2003-06-13 20:54:40 +0000956 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000957 base = type;
958 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000959 base = base->tp_base;
960 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000961 }
962
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000963 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000964 the finalizer (__del__), clearing slots, or clearing the instance
965 dict. */
966
Guido van Rossum1987c662003-05-29 14:29:23 +0000967 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
968 PyObject_ClearWeakRefs(self);
969
970 /* Maybe call finalizer; exit early if resurrected */
971 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000972 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000973 type->tp_del(self);
974 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000975 goto endlabel; /* resurrected */
976 else
977 _PyObject_GC_UNTRACK(self);
Brett Cannonf5bee302007-01-23 23:21:22 +0000978 /* New weakrefs could be created during the finalizer call.
979 If this occurs, clear them out without calling their
980 finalizers since they might rely on part of the object
981 being finalized that has already been destroyed. */
982 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
983 /* Modeled after GET_WEAKREFS_LISTPTR() */
984 PyWeakReference **list = (PyWeakReference **) \
985 PyObject_GET_WEAKREFS_LISTPTR(self);
986 while (*list)
987 _PyWeakref_ClearRef(*list);
988 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000989 }
990
Guido van Rossum59195fd2003-06-13 20:54:40 +0000991 /* Clear slots up to the nearest base with a different tp_dealloc */
992 base = type;
993 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimese93237d2007-12-19 02:37:44 +0000994 if (Py_SIZE(base))
Guido van Rossum59195fd2003-06-13 20:54:40 +0000995 clear_slots(base, self);
996 base = base->tp_base;
997 assert(base);
998 }
999
Tim Peters6d6c1a32001-08-02 04:15:00 +00001000 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001001 if (type->tp_dictoffset && !base->tp_dictoffset) {
1002 PyObject **dictptr = _PyObject_GetDictPtr(self);
1003 if (dictptr != NULL) {
1004 PyObject *dict = *dictptr;
1005 if (dict != NULL) {
1006 Py_DECREF(dict);
1007 *dictptr = NULL;
1008 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001009 }
1010 }
1011
Tim Peters0bd743c2003-11-13 22:50:00 +00001012 /* Call the base tp_dealloc(); first retrack self if
1013 * basedealloc knows about gc.
1014 */
1015 if (PyType_IS_GC(base))
1016 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001017 assert(basedealloc);
1018 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001019
1020 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +00001021 Py_DECREF(type);
1022
Guido van Rossum0906e072002-08-07 20:42:09 +00001023 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001024 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +00001025 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001026 --_PyTrash_delete_nesting;
1027
1028 /* Explanation of the weirdness around the trashcan macros:
1029
1030 Q. What do the trashcan macros do?
1031
1032 A. Read the comment titled "Trashcan mechanism" in object.h.
1033 For one, this explains why there must be a call to GC-untrack
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001034 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001035 trashcan code, the answers to the following questions don't make
1036 sense.
1037
1038 Q. Why do we GC-untrack before the trashcan and then immediately
1039 GC-track again afterward?
1040
1041 A. In the case that the base class is GC-aware, the base class
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001042 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001043 UNTRACK macro, this will crash when the object is already
1044 untracked. Because we don't know what the base class does, the
1045 only safe thing is to make sure the object is tracked when we
1046 call the base class dealloc. But... The trashcan begin macro
1047 requires that the object is *untracked* before it is called. So
1048 the dance becomes:
1049
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001050 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001051 trashcan begin
1052 GC track
1053
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001054 Q. Why did the last question say "immediately GC-track again"?
1055 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001056
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001057 A. Because the code *used* to re-track immediately. Bad Idea.
1058 self has a refcount of 0, and if gc ever gets its hands on it
1059 (which can happen if any weakref callback gets invoked), it
1060 looks like trash to gc too, and gc also tries to delete self
1061 then. But we're already deleting self. Double dealloction is
1062 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001063
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001064 Q. Why the bizarre (net-zero) manipulation of
1065 _PyTrash_delete_nesting around the trashcan macros?
1066
1067 A. Some base classes (e.g. list) also use the trashcan mechanism.
1068 The following scenario used to be possible:
1069
1070 - suppose the trashcan level is one below the trashcan limit
1071
1072 - subtype_dealloc() is called
1073
1074 - the trashcan limit is not yet reached, so the trashcan level
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001075 is incremented and the code between trashcan begin and end is
1076 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001077
1078 - this destroys much of the object's contents, including its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001079 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001080
1081 - basedealloc() is called; this is really list_dealloc(), or
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001082 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001083
1084 - the trashcan limit is now reached, so the object is put on the
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001085 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001086
1087 - basedealloc() returns
1088
1089 - subtype_dealloc() decrefs the object's type
1090
1091 - subtype_dealloc() returns
1092
1093 - later, the trashcan code starts deleting the objects from its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001094 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001095
1096 - subtype_dealloc() is called *AGAIN* for the same object
1097
1098 - at the very least (if the destroyed slots and __dict__ don't
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001099 cause problems) the object's type gets decref'ed a second
1100 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001101
1102 The remedy is to make sure that if the code between trashcan
1103 begin and end in subtype_dealloc() is called, the code between
1104 trashcan begin and end in basedealloc() will also be called.
1105 This is done by decrementing the level after passing into the
1106 trashcan block, and incrementing it just before leaving the
1107 block.
1108
1109 But now it's possible that a chain of objects consisting solely
1110 of objects whose deallocator is subtype_dealloc() will defeat
1111 the trashcan mechanism completely: the decremented level means
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001112 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001113 *increment* the level *before* entering the trashcan block, and
1114 matchingly decrement it after leaving. This means the trashcan
1115 code will trigger a little early, but that's no big deal.
1116
1117 Q. Are there any live examples of code in need of all this
1118 complexity?
1119
1120 A. Yes. See SF bug 668433 for code that crashed (when Python was
1121 compiled in debug mode) before the trashcan level manipulations
1122 were added. For more discussion, see SF patches 581742, 575073
1123 and bug 574207.
1124 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001125}
1126
Jeremy Hylton938ace62002-07-17 16:30:39 +00001127static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001128
Tim Peters6d6c1a32001-08-02 04:15:00 +00001129/* type test with subclassing support */
1130
1131int
1132PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1133{
1134 PyObject *mro;
1135
Guido van Rossum9478d072001-09-07 18:52:13 +00001136 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1137 return b == a || b == &PyBaseObject_Type;
1138
Tim Peters6d6c1a32001-08-02 04:15:00 +00001139 mro = a->tp_mro;
1140 if (mro != NULL) {
1141 /* Deal with multiple inheritance without recursion
1142 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001143 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001144 assert(PyTuple_Check(mro));
1145 n = PyTuple_GET_SIZE(mro);
1146 for (i = 0; i < n; i++) {
1147 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1148 return 1;
1149 }
1150 return 0;
1151 }
1152 else {
1153 /* a is not completely initilized yet; follow tp_base */
1154 do {
1155 if (a == b)
1156 return 1;
1157 a = a->tp_base;
1158 } while (a != NULL);
1159 return b == &PyBaseObject_Type;
1160 }
1161}
1162
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001163/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001164 without looking in the instance dictionary
1165 (so we can't use PyObject_GetAttr) but still binding
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001166 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001167 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001168 static variable used to cache the interned Python string.
1169
1170 Two variants:
1171
1172 - lookup_maybe() returns NULL without raising an exception
1173 when the _PyType_Lookup() call fails;
1174
1175 - lookup_method() always raises an exception upon errors.
1176*/
Guido van Rossum60718732001-08-28 17:47:51 +00001177
1178static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001179lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001180{
1181 PyObject *res;
1182
1183 if (*attrobj == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001184 *attrobj = PyString_InternFromString(attrstr);
Guido van Rossum60718732001-08-28 17:47:51 +00001185 if (*attrobj == NULL)
1186 return NULL;
1187 }
Christian Heimese93237d2007-12-19 02:37:44 +00001188 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001189 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +00001190 descrgetfunc f;
Christian Heimese93237d2007-12-19 02:37:44 +00001191 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
Guido van Rossum60718732001-08-28 17:47:51 +00001192 Py_INCREF(res);
1193 else
Christian Heimese93237d2007-12-19 02:37:44 +00001194 res = f(res, self, (PyObject *)(Py_TYPE(self)));
Guido van Rossum60718732001-08-28 17:47:51 +00001195 }
1196 return res;
1197}
1198
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001199static PyObject *
1200lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1201{
1202 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1203 if (res == NULL && !PyErr_Occurred())
1204 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1205 return res;
1206}
1207
Guido van Rossum2730b132001-08-28 18:22:14 +00001208/* A variation of PyObject_CallMethod that uses lookup_method()
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001209 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001210 as lookup_method to cache the interned name string object. */
1211
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001212static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001213call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1214{
1215 va_list va;
1216 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001217 va_start(va, format);
1218
Guido van Rossumda21c012001-10-03 00:50:18 +00001219 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001220 if (func == NULL) {
1221 va_end(va);
1222 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +00001223 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001224 return NULL;
1225 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001226
1227 if (format && *format)
1228 args = Py_VaBuildValue(format, va);
1229 else
1230 args = PyTuple_New(0);
1231
1232 va_end(va);
1233
1234 if (args == NULL)
1235 return NULL;
1236
1237 assert(PyTuple_Check(args));
1238 retval = PyObject_Call(func, args, NULL);
1239
1240 Py_DECREF(args);
1241 Py_DECREF(func);
1242
1243 return retval;
1244}
1245
1246/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1247
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001248static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001249call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1250{
1251 va_list va;
1252 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001253 va_start(va, format);
1254
Guido van Rossumda21c012001-10-03 00:50:18 +00001255 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +00001256 if (func == NULL) {
1257 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001258 if (!PyErr_Occurred()) {
1259 Py_INCREF(Py_NotImplemented);
1260 return Py_NotImplemented;
1261 }
Guido van Rossum717ce002001-09-14 16:58:08 +00001262 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001263 }
1264
1265 if (format && *format)
1266 args = Py_VaBuildValue(format, va);
1267 else
1268 args = PyTuple_New(0);
1269
1270 va_end(va);
1271
Guido van Rossum717ce002001-09-14 16:58:08 +00001272 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00001273 return NULL;
1274
Guido van Rossum717ce002001-09-14 16:58:08 +00001275 assert(PyTuple_Check(args));
1276 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001277
1278 Py_DECREF(args);
1279 Py_DECREF(func);
1280
1281 return retval;
1282}
1283
Tim Petersa91e9642001-11-14 23:32:33 +00001284static int
1285fill_classic_mro(PyObject *mro, PyObject *cls)
1286{
1287 PyObject *bases, *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001288 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001289
1290 assert(PyList_Check(mro));
1291 assert(PyClass_Check(cls));
1292 i = PySequence_Contains(mro, cls);
1293 if (i < 0)
1294 return -1;
1295 if (!i) {
1296 if (PyList_Append(mro, cls) < 0)
1297 return -1;
1298 }
1299 bases = ((PyClassObject *)cls)->cl_bases;
1300 assert(bases && PyTuple_Check(bases));
1301 n = PyTuple_GET_SIZE(bases);
1302 for (i = 0; i < n; i++) {
1303 base = PyTuple_GET_ITEM(bases, i);
1304 if (fill_classic_mro(mro, base) < 0)
1305 return -1;
1306 }
1307 return 0;
1308}
1309
1310static PyObject *
1311classic_mro(PyObject *cls)
1312{
1313 PyObject *mro;
1314
1315 assert(PyClass_Check(cls));
1316 mro = PyList_New(0);
1317 if (mro != NULL) {
1318 if (fill_classic_mro(mro, cls) == 0)
1319 return mro;
1320 Py_DECREF(mro);
1321 }
1322 return NULL;
1323}
1324
Tim Petersea7f75d2002-12-07 21:39:16 +00001325/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001326 Method resolution order algorithm C3 described in
1327 "A Monotonic Superclass Linearization for Dylan",
1328 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001329 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001330 (OOPSLA 1996)
1331
Guido van Rossum98f33732002-11-25 21:36:54 +00001332 Some notes about the rules implied by C3:
1333
Tim Petersea7f75d2002-12-07 21:39:16 +00001334 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001335 It isn't legal to repeat a class in a list of base classes.
1336
1337 The next three properties are the 3 constraints in "C3".
1338
Tim Petersea7f75d2002-12-07 21:39:16 +00001339 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001340 If A precedes B in C's MRO, then A will precede B in the MRO of all
1341 subclasses of C.
1342
1343 Monotonicity.
1344 The MRO of a class must be an extension without reordering of the
1345 MRO of each of its superclasses.
1346
1347 Extended Precedence Graph (EPG).
1348 Linearization is consistent if there is a path in the EPG from
1349 each class to all its successors in the linearization. See
1350 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001351 */
1352
Tim Petersea7f75d2002-12-07 21:39:16 +00001353static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001354tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001355 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001356 size = PyList_GET_SIZE(list);
1357
1358 for (j = whence+1; j < size; j++) {
1359 if (PyList_GET_ITEM(list, j) == o)
1360 return 1;
1361 }
1362 return 0;
1363}
1364
Guido van Rossum98f33732002-11-25 21:36:54 +00001365static PyObject *
1366class_name(PyObject *cls)
1367{
1368 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1369 if (name == NULL) {
1370 PyErr_Clear();
1371 Py_XDECREF(name);
1372 name = PyObject_Repr(cls);
1373 }
1374 if (name == NULL)
1375 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001376 if (!PyString_Check(name)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001377 Py_DECREF(name);
1378 return NULL;
1379 }
1380 return name;
1381}
1382
1383static int
1384check_duplicates(PyObject *list)
1385{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001386 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001387 /* Let's use a quadratic time algorithm,
1388 assuming that the bases lists is short.
1389 */
1390 n = PyList_GET_SIZE(list);
1391 for (i = 0; i < n; i++) {
1392 PyObject *o = PyList_GET_ITEM(list, i);
1393 for (j = i + 1; j < n; j++) {
1394 if (PyList_GET_ITEM(list, j) == o) {
1395 o = class_name(o);
1396 PyErr_Format(PyExc_TypeError,
1397 "duplicate base class %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001398 o ? PyString_AS_STRING(o) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001399 Py_XDECREF(o);
1400 return -1;
1401 }
1402 }
1403 }
1404 return 0;
1405}
1406
1407/* Raise a TypeError for an MRO order disagreement.
1408
1409 It's hard to produce a good error message. In the absence of better
1410 insight into error reporting, report the classes that were candidates
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001411 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001412 order in which they should be put in the MRO, but it's hard to
1413 diagnose what constraint can't be satisfied.
1414*/
1415
1416static void
1417set_mro_error(PyObject *to_merge, int *remain)
1418{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001419 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001420 char buf[1000];
1421 PyObject *k, *v;
1422 PyObject *set = PyDict_New();
Georg Brandl5c170fd2006-03-17 19:03:25 +00001423 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001424
1425 to_merge_size = PyList_GET_SIZE(to_merge);
1426 for (i = 0; i < to_merge_size; i++) {
1427 PyObject *L = PyList_GET_ITEM(to_merge, i);
1428 if (remain[i] < PyList_GET_SIZE(L)) {
1429 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Georg Brandl5c170fd2006-03-17 19:03:25 +00001430 if (PyDict_SetItem(set, c, Py_None) < 0) {
1431 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001432 return;
Georg Brandl5c170fd2006-03-17 19:03:25 +00001433 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001434 }
1435 }
1436 n = PyDict_Size(set);
1437
Raymond Hettingerf394df42003-04-06 19:13:41 +00001438 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1439consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001440 i = 0;
Skip Montanaro429433b2006-04-18 00:35:43 +00001441 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001442 PyObject *name = class_name(k);
1443 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001444 name ? PyString_AS_STRING(name) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001445 Py_XDECREF(name);
Skip Montanaro429433b2006-04-18 00:35:43 +00001446 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001447 buf[off++] = ',';
1448 buf[off] = '\0';
1449 }
1450 }
1451 PyErr_SetString(PyExc_TypeError, buf);
1452 Py_DECREF(set);
1453}
1454
Tim Petersea7f75d2002-12-07 21:39:16 +00001455static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001456pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001457 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001458 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001459 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001460
Guido van Rossum1f121312002-11-14 19:49:16 +00001461 to_merge_size = PyList_GET_SIZE(to_merge);
1462
Guido van Rossum98f33732002-11-25 21:36:54 +00001463 /* remain stores an index into each sublist of to_merge.
1464 remain[i] is the index of the next base in to_merge[i]
1465 that is not included in acc.
1466 */
Anthony Baxtera6286212006-04-11 07:42:36 +00001467 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001468 if (remain == NULL)
1469 return -1;
1470 for (i = 0; i < to_merge_size; i++)
1471 remain[i] = 0;
1472
1473 again:
1474 empty_cnt = 0;
1475 for (i = 0; i < to_merge_size; i++) {
1476 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001477
Guido van Rossum1f121312002-11-14 19:49:16 +00001478 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1479
1480 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1481 empty_cnt++;
1482 continue;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001483 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001484
Guido van Rossum98f33732002-11-25 21:36:54 +00001485 /* Choose next candidate for MRO.
1486
1487 The input sequences alone can determine the choice.
1488 If not, choose the class which appears in the MRO
1489 of the earliest direct superclass of the new class.
1490 */
1491
Guido van Rossum1f121312002-11-14 19:49:16 +00001492 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1493 for (j = 0; j < to_merge_size; j++) {
1494 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001495 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001496 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001497 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001498 }
1499 ok = PyList_Append(acc, candidate);
1500 if (ok < 0) {
1501 PyMem_Free(remain);
1502 return -1;
1503 }
1504 for (j = 0; j < to_merge_size; j++) {
1505 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001506 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1507 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001508 remain[j]++;
1509 }
1510 }
1511 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001512 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001513 }
1514
Guido van Rossum98f33732002-11-25 21:36:54 +00001515 if (empty_cnt == to_merge_size) {
1516 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001517 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001518 }
1519 set_mro_error(to_merge, remain);
1520 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001521 return -1;
1522}
1523
Tim Peters6d6c1a32001-08-02 04:15:00 +00001524static PyObject *
1525mro_implementation(PyTypeObject *type)
1526{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001527 Py_ssize_t i, n;
1528 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001529 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001530 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001531
Neal Norwitze7bb9182008-01-27 17:10:14 +00001532 if (type->tp_dict == NULL) {
1533 if (PyType_Ready(type) < 0)
Guido van Rossum63517572002-06-18 16:44:57 +00001534 return NULL;
1535 }
1536
Guido van Rossum98f33732002-11-25 21:36:54 +00001537 /* Find a superclass linearization that honors the constraints
1538 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001539 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001540
1541 to_merge is a list of lists, where each list is a superclass
1542 linearization implied by a base class. The last element of
1543 to_merge is the declared list of bases.
1544 */
1545
Tim Peters6d6c1a32001-08-02 04:15:00 +00001546 bases = type->tp_bases;
1547 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001548
1549 to_merge = PyList_New(n+1);
1550 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001551 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001552
Tim Peters6d6c1a32001-08-02 04:15:00 +00001553 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001554 PyObject *base = PyTuple_GET_ITEM(bases, i);
1555 PyObject *parentMRO;
1556 if (PyType_Check(base))
1557 parentMRO = PySequence_List(
1558 ((PyTypeObject*)base)->tp_mro);
1559 else
1560 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001561 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001562 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001563 return NULL;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001564 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001565
1566 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001567 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001568
1569 bases_aslist = PySequence_List(bases);
1570 if (bases_aslist == NULL) {
1571 Py_DECREF(to_merge);
1572 return NULL;
1573 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001574 /* This is just a basic sanity check. */
1575 if (check_duplicates(bases_aslist) < 0) {
1576 Py_DECREF(to_merge);
1577 Py_DECREF(bases_aslist);
1578 return NULL;
1579 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001580 PyList_SET_ITEM(to_merge, n, bases_aslist);
1581
1582 result = Py_BuildValue("[O]", (PyObject *)type);
1583 if (result == NULL) {
1584 Py_DECREF(to_merge);
1585 return NULL;
1586 }
1587
1588 ok = pmerge(result, to_merge);
1589 Py_DECREF(to_merge);
1590 if (ok < 0) {
1591 Py_DECREF(result);
1592 return NULL;
1593 }
1594
Tim Peters6d6c1a32001-08-02 04:15:00 +00001595 return result;
1596}
1597
1598static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001599mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001600{
1601 PyTypeObject *type = (PyTypeObject *)self;
1602
Tim Peters6d6c1a32001-08-02 04:15:00 +00001603 return mro_implementation(type);
1604}
1605
1606static int
1607mro_internal(PyTypeObject *type)
1608{
1609 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001610 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001611
Christian Heimese93237d2007-12-19 02:37:44 +00001612 if (Py_TYPE(type) == &PyType_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001613 result = mro_implementation(type);
1614 }
1615 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001616 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001617 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001618 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001619 if (mro == NULL)
1620 return -1;
1621 result = PyObject_CallObject(mro, NULL);
1622 Py_DECREF(mro);
1623 }
1624 if (result == NULL)
1625 return -1;
1626 tuple = PySequence_Tuple(result);
1627 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001628 if (tuple == NULL)
1629 return -1;
1630 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001631 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001632 PyObject *cls;
1633 PyTypeObject *solid;
1634
1635 solid = solid_base(type);
1636
1637 len = PyTuple_GET_SIZE(tuple);
1638
1639 for (i = 0; i < len; i++) {
1640 PyTypeObject *t;
1641 cls = PyTuple_GET_ITEM(tuple, i);
1642 if (PyClass_Check(cls))
1643 continue;
1644 else if (!PyType_Check(cls)) {
1645 PyErr_Format(PyExc_TypeError,
1646 "mro() returned a non-class ('%.500s')",
Christian Heimese93237d2007-12-19 02:37:44 +00001647 Py_TYPE(cls)->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001648 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001649 return -1;
1650 }
1651 t = (PyTypeObject*)cls;
1652 if (!PyType_IsSubtype(solid, solid_base(t))) {
1653 PyErr_Format(PyExc_TypeError,
1654 "mro() returned base with unsuitable layout ('%.500s')",
1655 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001656 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001657 return -1;
1658 }
1659 }
1660 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001661 type->tp_mro = tuple;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001662
1663 type_mro_modified(type, type->tp_mro);
1664 /* corner case: the old-style super class might have been hidden
1665 from the custom MRO */
1666 type_mro_modified(type, type->tp_bases);
1667
Georg Brandl74a1dea2008-05-28 11:21:39 +00001668 PyType_Modified(type);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001669
Tim Peters6d6c1a32001-08-02 04:15:00 +00001670 return 0;
1671}
1672
1673
1674/* Calculate the best base amongst multiple base classes.
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001675 This is the first one that's on the path to the "solid base". */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001676
1677static PyTypeObject *
1678best_base(PyObject *bases)
1679{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001680 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001682 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001683
1684 assert(PyTuple_Check(bases));
1685 n = PyTuple_GET_SIZE(bases);
1686 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001687 base = NULL;
1688 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001689 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001690 base_proto = PyTuple_GET_ITEM(bases, i);
1691 if (PyClass_Check(base_proto))
1692 continue;
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001693 if (!PyType_Check(base_proto)) {
1694 PyErr_SetString(
1695 PyExc_TypeError,
1696 "bases must be types");
1697 return NULL;
1698 }
Tim Petersa91e9642001-11-14 23:32:33 +00001699 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001700 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001701 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001702 return NULL;
1703 }
1704 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001705 if (winner == NULL) {
1706 winner = candidate;
1707 base = base_i;
1708 }
1709 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001710 ;
1711 else if (PyType_IsSubtype(candidate, winner)) {
1712 winner = candidate;
1713 base = base_i;
1714 }
1715 else {
1716 PyErr_SetString(
1717 PyExc_TypeError,
1718 "multiple bases have "
1719 "instance lay-out conflict");
1720 return NULL;
1721 }
1722 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001723 if (base == NULL)
1724 PyErr_SetString(PyExc_TypeError,
1725 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001726 return base;
1727}
1728
1729static int
1730extra_ivars(PyTypeObject *type, PyTypeObject *base)
1731{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001732 size_t t_size = type->tp_basicsize;
1733 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001734
Guido van Rossum9676b222001-08-17 20:32:36 +00001735 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001736 if (type->tp_itemsize || base->tp_itemsize) {
1737 /* If itemsize is involved, stricter rules */
1738 return t_size != b_size ||
1739 type->tp_itemsize != base->tp_itemsize;
1740 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001741 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001742 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1743 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001744 t_size -= sizeof(PyObject *);
1745 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001746 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1747 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001748 t_size -= sizeof(PyObject *);
1749
1750 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001751}
1752
1753static PyTypeObject *
1754solid_base(PyTypeObject *type)
1755{
1756 PyTypeObject *base;
1757
1758 if (type->tp_base)
1759 base = solid_base(type->tp_base);
1760 else
1761 base = &PyBaseObject_Type;
1762 if (extra_ivars(type, base))
1763 return type;
1764 else
1765 return base;
1766}
1767
Jeremy Hylton938ace62002-07-17 16:30:39 +00001768static void object_dealloc(PyObject *);
1769static int object_init(PyObject *, PyObject *, PyObject *);
1770static int update_slot(PyTypeObject *, PyObject *);
1771static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001772
Armin Rigo9790a272007-05-02 19:23:31 +00001773/*
1774 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1775 * inherited from various builtin types. The builtin base usually provides
1776 * its own __dict__ descriptor, so we use that when we can.
1777 */
1778static PyTypeObject *
1779get_builtin_base_with_dict(PyTypeObject *type)
1780{
1781 while (type->tp_base != NULL) {
1782 if (type->tp_dictoffset != 0 &&
1783 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1784 return type;
1785 type = type->tp_base;
1786 }
1787 return NULL;
1788}
1789
1790static PyObject *
1791get_dict_descriptor(PyTypeObject *type)
1792{
1793 static PyObject *dict_str;
1794 PyObject *descr;
1795
1796 if (dict_str == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001797 dict_str = PyString_InternFromString("__dict__");
Armin Rigo9790a272007-05-02 19:23:31 +00001798 if (dict_str == NULL)
1799 return NULL;
1800 }
1801 descr = _PyType_Lookup(type, dict_str);
1802 if (descr == NULL || !PyDescr_IsData(descr))
1803 return NULL;
1804
1805 return descr;
1806}
1807
1808static void
1809raise_dict_descr_error(PyObject *obj)
1810{
1811 PyErr_Format(PyExc_TypeError,
1812 "this __dict__ descriptor does not support "
1813 "'%.200s' objects", obj->ob_type->tp_name);
1814}
1815
Tim Peters6d6c1a32001-08-02 04:15:00 +00001816static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001817subtype_dict(PyObject *obj, void *context)
1818{
Armin Rigo9790a272007-05-02 19:23:31 +00001819 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001820 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001821 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001822
Armin Rigo9790a272007-05-02 19:23:31 +00001823 base = get_builtin_base_with_dict(obj->ob_type);
1824 if (base != NULL) {
1825 descrgetfunc func;
1826 PyObject *descr = get_dict_descriptor(base);
1827 if (descr == NULL) {
1828 raise_dict_descr_error(obj);
1829 return NULL;
1830 }
1831 func = descr->ob_type->tp_descr_get;
1832 if (func == NULL) {
1833 raise_dict_descr_error(obj);
1834 return NULL;
1835 }
1836 return func(descr, obj, (PyObject *)(obj->ob_type));
1837 }
1838
1839 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001840 if (dictptr == NULL) {
1841 PyErr_SetString(PyExc_AttributeError,
1842 "This object has no __dict__");
1843 return NULL;
1844 }
1845 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001846 if (dict == NULL)
1847 *dictptr = dict = PyDict_New();
1848 Py_XINCREF(dict);
1849 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001850}
1851
Guido van Rossum6661be32001-10-26 04:26:12 +00001852static int
1853subtype_setdict(PyObject *obj, PyObject *value, void *context)
1854{
Armin Rigo9790a272007-05-02 19:23:31 +00001855 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001856 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001857 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001858
Armin Rigo9790a272007-05-02 19:23:31 +00001859 base = get_builtin_base_with_dict(obj->ob_type);
1860 if (base != NULL) {
1861 descrsetfunc func;
1862 PyObject *descr = get_dict_descriptor(base);
1863 if (descr == NULL) {
1864 raise_dict_descr_error(obj);
1865 return -1;
1866 }
1867 func = descr->ob_type->tp_descr_set;
1868 if (func == NULL) {
1869 raise_dict_descr_error(obj);
1870 return -1;
1871 }
1872 return func(descr, obj, value);
1873 }
1874
1875 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001876 if (dictptr == NULL) {
1877 PyErr_SetString(PyExc_AttributeError,
1878 "This object has no __dict__");
1879 return -1;
1880 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001881 if (value != NULL && !PyDict_Check(value)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001882 PyErr_Format(PyExc_TypeError,
1883 "__dict__ must be set to a dictionary, "
Christian Heimese93237d2007-12-19 02:37:44 +00001884 "not a '%.200s'", Py_TYPE(value)->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001885 return -1;
1886 }
1887 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001888 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001889 *dictptr = value;
1890 Py_XDECREF(dict);
1891 return 0;
1892}
1893
Guido van Rossumad47da02002-08-12 19:05:44 +00001894static PyObject *
1895subtype_getweakref(PyObject *obj, void *context)
1896{
1897 PyObject **weaklistptr;
1898 PyObject *result;
1899
Christian Heimese93237d2007-12-19 02:37:44 +00001900 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001901 PyErr_SetString(PyExc_AttributeError,
Fred Drake7a36f5f2006-08-04 05:17:21 +00001902 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001903 return NULL;
1904 }
Christian Heimese93237d2007-12-19 02:37:44 +00001905 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1906 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1907 (size_t)(Py_TYPE(obj)->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001908 weaklistptr = (PyObject **)
Christian Heimese93237d2007-12-19 02:37:44 +00001909 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001910 if (*weaklistptr == NULL)
1911 result = Py_None;
1912 else
1913 result = *weaklistptr;
1914 Py_INCREF(result);
1915 return result;
1916}
1917
Guido van Rossum373c7412003-01-07 13:41:37 +00001918/* Three variants on the subtype_getsets list. */
1919
1920static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001921 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001922 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001923 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001924 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001925 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001926};
1927
Guido van Rossum373c7412003-01-07 13:41:37 +00001928static PyGetSetDef subtype_getsets_dict_only[] = {
1929 {"__dict__", subtype_dict, subtype_setdict,
1930 PyDoc_STR("dictionary for instance variables (if defined)")},
1931 {0}
1932};
1933
1934static PyGetSetDef subtype_getsets_weakref_only[] = {
1935 {"__weakref__", subtype_getweakref, NULL,
1936 PyDoc_STR("list of weak references to the object (if defined)")},
1937 {0}
1938};
1939
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001940static int
1941valid_identifier(PyObject *s)
1942{
Guido van Rossum03013a02002-07-16 14:30:28 +00001943 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001944 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001945
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001946 if (!PyString_Check(s)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001947 PyErr_Format(PyExc_TypeError,
1948 "__slots__ items must be strings, not '%.200s'",
Christian Heimese93237d2007-12-19 02:37:44 +00001949 Py_TYPE(s)->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001950 return 0;
1951 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001952 p = (unsigned char *) PyString_AS_STRING(s);
1953 n = PyString_GET_SIZE(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001954 /* We must reject an empty name. As a hack, we bump the
1955 length to 1 so that the loop will balk on the trailing \0. */
1956 if (n == 0)
1957 n = 1;
1958 for (i = 0; i < n; i++, p++) {
1959 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1960 PyErr_SetString(PyExc_TypeError,
1961 "__slots__ must be identifiers");
1962 return 0;
1963 }
1964 }
1965 return 1;
1966}
1967
Martin v. Löwisd919a592002-10-14 21:07:28 +00001968#ifdef Py_USING_UNICODE
1969/* Replace Unicode objects in slots. */
1970
1971static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001972_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001973{
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001974 PyObject *tmp = NULL;
1975 PyObject *slot_name, *new_name;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001976 Py_ssize_t i;
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001977
Martin v. Löwisd919a592002-10-14 21:07:28 +00001978 for (i = 0; i < nslots; i++) {
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001979 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1980 if (tmp == NULL) {
1981 tmp = PySequence_List(slots);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001982 if (tmp == NULL)
1983 return NULL;
1984 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001985 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1986 NULL);
1987 if (new_name == NULL) {
Martin v. Löwisd919a592002-10-14 21:07:28 +00001988 Py_DECREF(tmp);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001989 return NULL;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001990 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001991 Py_INCREF(new_name);
1992 PyList_SET_ITEM(tmp, i, new_name);
1993 Py_DECREF(slot_name);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001994 }
1995 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001996 if (tmp != NULL) {
1997 slots = PyList_AsTuple(tmp);
1998 Py_DECREF(tmp);
1999 }
2000 return slots;
Martin v. Löwisd919a592002-10-14 21:07:28 +00002001}
2002#endif
2003
Guido van Rossumf102e242007-03-23 18:53:03 +00002004/* Forward */
2005static int
2006object_init(PyObject *self, PyObject *args, PyObject *kwds);
2007
2008static int
2009type_init(PyObject *cls, PyObject *args, PyObject *kwds)
2010{
2011 int res;
2012
2013 assert(args != NULL && PyTuple_Check(args));
2014 assert(kwds == NULL || PyDict_Check(kwds));
2015
2016 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
2017 PyErr_SetString(PyExc_TypeError,
2018 "type.__init__() takes no keyword arguments");
2019 return -1;
2020 }
2021
2022 if (args != NULL && PyTuple_Check(args) &&
2023 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
2024 PyErr_SetString(PyExc_TypeError,
2025 "type.__init__() takes 1 or 3 arguments");
2026 return -1;
2027 }
2028
2029 /* Call object.__init__(self) now. */
2030 /* XXX Could call super(type, cls).__init__() but what's the point? */
2031 args = PyTuple_GetSlice(args, 0, 0);
2032 res = object_init(cls, args, NULL);
2033 Py_DECREF(args);
2034 return res;
2035}
2036
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002037static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2039{
2040 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002041 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002042 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00002043 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002044 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00002045 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002046 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00002047 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002048
Tim Peters3abca122001-10-27 19:37:48 +00002049 assert(args != NULL && PyTuple_Check(args));
2050 assert(kwds == NULL || PyDict_Check(kwds));
2051
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00002052 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00002053 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002054 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2055 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002056
2057 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2058 PyObject *x = PyTuple_GET_ITEM(args, 0);
Christian Heimese93237d2007-12-19 02:37:44 +00002059 Py_INCREF(Py_TYPE(x));
2060 return (PyObject *) Py_TYPE(x);
Tim Peters3abca122001-10-27 19:37:48 +00002061 }
2062
2063 /* SF bug 475327 -- if that didn't trigger, we need 3
2064 arguments. but PyArg_ParseTupleAndKeywords below may give
2065 a msg saying type() needs exactly 3. */
2066 if (nargs + nkwds != 3) {
2067 PyErr_SetString(PyExc_TypeError,
2068 "type() takes 1 or 3 arguments");
2069 return NULL;
2070 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002071 }
2072
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00002073 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002074 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
2075 &name,
2076 &PyTuple_Type, &bases,
2077 &PyDict_Type, &dict))
2078 return NULL;
2079
Armin Rigoc0ba52d2007-04-19 14:44:48 +00002080 /* Determine the proper metatype to deal with this,
2081 and check for metatype conflicts while we're at it.
2082 Note that if some other metatype wins to contract,
2083 it's possible that its instances are not types. */
2084 nbases = PyTuple_GET_SIZE(bases);
2085 winner = metatype;
2086 for (i = 0; i < nbases; i++) {
2087 tmp = PyTuple_GET_ITEM(bases, i);
2088 tmptype = tmp->ob_type;
2089 if (tmptype == &PyClass_Type)
2090 continue; /* Special case classic classes */
2091 if (PyType_IsSubtype(winner, tmptype))
2092 continue;
2093 if (PyType_IsSubtype(tmptype, winner)) {
2094 winner = tmptype;
2095 continue;
Jeremy Hyltonfa955692007-02-27 18:29:45 +00002096 }
Armin Rigoc0ba52d2007-04-19 14:44:48 +00002097 PyErr_SetString(PyExc_TypeError,
2098 "metaclass conflict: "
2099 "the metaclass of a derived class "
2100 "must be a (non-strict) subclass "
2101 "of the metaclasses of all its bases");
2102 return NULL;
2103 }
2104 if (winner != metatype) {
2105 if (winner->tp_new != type_new) /* Pass it to the winner */
2106 return winner->tp_new(winner, args, kwds);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00002107 metatype = winner;
2108 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002109
2110 /* Adjust for empty tuple bases */
2111 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002112 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002113 if (bases == NULL)
2114 return NULL;
2115 nbases = 1;
2116 }
2117 else
2118 Py_INCREF(bases);
2119
2120 /* XXX From here until type is allocated, "return NULL" leaks bases! */
2121
2122 /* Calculate best base, and check that all bases are type objects */
2123 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002124 if (base == NULL) {
2125 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002126 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002127 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002128 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2129 PyErr_Format(PyExc_TypeError,
2130 "type '%.100s' is not an acceptable base type",
2131 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002132 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002133 return NULL;
2134 }
2135
Tim Peters6d6c1a32001-08-02 04:15:00 +00002136 /* Check for a __slots__ sequence variable in dict, and count it */
2137 slots = PyDict_GetItemString(dict, "__slots__");
2138 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00002139 add_dict = 0;
2140 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00002141 may_add_dict = base->tp_dictoffset == 0;
2142 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2143 if (slots == NULL) {
2144 if (may_add_dict) {
2145 add_dict++;
2146 }
2147 if (may_add_weak) {
2148 add_weak++;
2149 }
2150 }
2151 else {
2152 /* Have slots */
2153
Tim Peters6d6c1a32001-08-02 04:15:00 +00002154 /* Make it into a tuple */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002155 if (PyString_Check(slots) || PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002156 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002157 else
2158 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002159 if (slots == NULL) {
2160 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002161 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002162 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002163 assert(PyTuple_Check(slots));
2164
2165 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00002167 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00002168 PyErr_Format(PyExc_TypeError,
2169 "nonempty __slots__ "
2170 "not supported for subtype of '%s'",
2171 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00002172 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002173 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00002174 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00002175 return NULL;
2176 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002177
Martin v. Löwisd919a592002-10-14 21:07:28 +00002178#ifdef Py_USING_UNICODE
2179 tmp = _unicode_to_string(slots, nslots);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00002180 if (tmp == NULL)
2181 goto bad_slots;
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00002182 if (tmp != slots) {
2183 Py_DECREF(slots);
2184 slots = tmp;
2185 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00002186#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00002187 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002188 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00002189 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2190 char *s;
2191 if (!valid_identifier(tmp))
2192 goto bad_slots;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002193 assert(PyString_Check(tmp));
2194 s = PyString_AS_STRING(tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00002195 if (strcmp(s, "__dict__") == 0) {
2196 if (!may_add_dict || add_dict) {
2197 PyErr_SetString(PyExc_TypeError,
2198 "__dict__ slot disallowed: "
2199 "we already got one");
2200 goto bad_slots;
2201 }
2202 add_dict++;
2203 }
2204 if (strcmp(s, "__weakref__") == 0) {
2205 if (!may_add_weak || add_weak) {
2206 PyErr_SetString(PyExc_TypeError,
2207 "__weakref__ slot disallowed: "
2208 "either we already got one, "
2209 "or __itemsize__ != 0");
2210 goto bad_slots;
2211 }
2212 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002213 }
2214 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002215
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002216 /* Copy slots into a list, mangle names and sort them.
2217 Sorted names are needed for __class__ assignment.
2218 Convert them back to tuple at the end.
2219 */
2220 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002221 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00002222 goto bad_slots;
2223 for (i = j = 0; i < nslots; i++) {
2224 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002225 tmp = PyTuple_GET_ITEM(slots, i);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002226 s = PyString_AS_STRING(tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00002227 if ((add_dict && strcmp(s, "__dict__") == 0) ||
2228 (add_weak && strcmp(s, "__weakref__") == 0))
2229 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002230 tmp =_Py_Mangle(name, tmp);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002231 if (!tmp)
2232 goto bad_slots;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002233 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00002234 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002235 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002236 assert(j == nslots - add_dict - add_weak);
2237 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002238 Py_DECREF(slots);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002239 if (PyList_Sort(newslots) == -1) {
2240 Py_DECREF(bases);
2241 Py_DECREF(newslots);
2242 return NULL;
2243 }
2244 slots = PyList_AsTuple(newslots);
2245 Py_DECREF(newslots);
2246 if (slots == NULL) {
2247 Py_DECREF(bases);
2248 return NULL;
2249 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002250
Guido van Rossumad47da02002-08-12 19:05:44 +00002251 /* Secondary bases may provide weakrefs or dict */
2252 if (nbases > 1 &&
2253 ((may_add_dict && !add_dict) ||
2254 (may_add_weak && !add_weak))) {
2255 for (i = 0; i < nbases; i++) {
2256 tmp = PyTuple_GET_ITEM(bases, i);
2257 if (tmp == (PyObject *)base)
2258 continue; /* Skip primary base */
2259 if (PyClass_Check(tmp)) {
2260 /* Classic base class provides both */
2261 if (may_add_dict && !add_dict)
2262 add_dict++;
2263 if (may_add_weak && !add_weak)
2264 add_weak++;
2265 break;
2266 }
2267 assert(PyType_Check(tmp));
2268 tmptype = (PyTypeObject *)tmp;
2269 if (may_add_dict && !add_dict &&
2270 tmptype->tp_dictoffset != 0)
2271 add_dict++;
2272 if (may_add_weak && !add_weak &&
2273 tmptype->tp_weaklistoffset != 0)
2274 add_weak++;
2275 if (may_add_dict && !add_dict)
2276 continue;
2277 if (may_add_weak && !add_weak)
2278 continue;
2279 /* Nothing more to check */
2280 break;
2281 }
2282 }
Guido van Rossum9676b222001-08-17 20:32:36 +00002283 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002284
2285 /* XXX From here until type is safely allocated,
2286 "return NULL" may leak slots! */
2287
2288 /* Allocate the type object */
2289 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00002290 if (type == NULL) {
2291 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002292 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002293 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00002294 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002295
2296 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002297 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002298 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002299 et->ht_name = name;
2300 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002301
Guido van Rossumdc91b992001-08-08 22:26:22 +00002302 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002303 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2304 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002305 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2306 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Antoine Pitrou789be0c2009-04-02 21:18:34 +00002307 if (base->tp_flags & Py_TPFLAGS_HAVE_NEWBUFFER)
2308 type->tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002309
2310 /* It's a new-style number unless it specifically inherits any
2311 old-style numeric behavior */
2312 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
2313 (base->tp_as_number == NULL))
2314 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
2315
2316 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002317 type->tp_as_number = &et->as_number;
2318 type->tp_as_sequence = &et->as_sequence;
2319 type->tp_as_mapping = &et->as_mapping;
2320 type->tp_as_buffer = &et->as_buffer;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002321 type->tp_name = PyString_AS_STRING(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002322
2323 /* Set tp_base and tp_bases */
2324 type->tp_bases = bases;
2325 Py_INCREF(base);
2326 type->tp_base = base;
2327
Guido van Rossum687ae002001-10-15 22:03:32 +00002328 /* Initialize tp_dict from passed-in dict */
2329 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002330 if (dict == NULL) {
2331 Py_DECREF(type);
2332 return NULL;
2333 }
2334
Guido van Rossumc3542212001-08-16 09:18:56 +00002335 /* Set __module__ in the dict */
2336 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2337 tmp = PyEval_GetGlobals();
2338 if (tmp != NULL) {
2339 tmp = PyDict_GetItemString(tmp, "__name__");
2340 if (tmp != NULL) {
2341 if (PyDict_SetItemString(dict, "__module__",
2342 tmp) < 0)
2343 return NULL;
2344 }
2345 }
2346 }
2347
Tim Peters2f93e282001-10-04 05:27:00 +00002348 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00002349 and is a string. The __doc__ accessor will first look for tp_doc;
2350 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00002351 */
2352 {
2353 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002354 if (doc != NULL && PyString_Check(doc)) {
2355 const size_t n = (size_t)PyString_GET_SIZE(doc);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002356 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002357 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00002358 Py_DECREF(type);
2359 return NULL;
2360 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002361 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002362 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00002363 }
2364 }
2365
Tim Peters6d6c1a32001-08-02 04:15:00 +00002366 /* Special-case __new__: if it's a plain function,
2367 make it a static function */
2368 tmp = PyDict_GetItemString(dict, "__new__");
2369 if (tmp != NULL && PyFunction_Check(tmp)) {
2370 tmp = PyStaticMethod_New(tmp);
2371 if (tmp == NULL) {
2372 Py_DECREF(type);
2373 return NULL;
2374 }
2375 PyDict_SetItemString(dict, "__new__", tmp);
2376 Py_DECREF(tmp);
2377 }
2378
2379 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002380 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00002381 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002382 if (slots != NULL) {
2383 for (i = 0; i < nslots; i++, mp++) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002384 mp->name = PyString_AS_STRING(
Tim Peters6d6c1a32001-08-02 04:15:00 +00002385 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00002386 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002387 mp->offset = slotoffset;
Žiga Seilnacht89032082007-03-11 15:54:54 +00002388
2389 /* __dict__ and __weakref__ are already filtered out */
2390 assert(strcmp(mp->name, "__dict__") != 0);
2391 assert(strcmp(mp->name, "__weakref__") != 0);
2392
Tim Peters6d6c1a32001-08-02 04:15:00 +00002393 slotoffset += sizeof(PyObject *);
2394 }
2395 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002396 if (add_dict) {
2397 if (base->tp_itemsize)
2398 type->tp_dictoffset = -(long)sizeof(PyObject *);
2399 else
2400 type->tp_dictoffset = slotoffset;
2401 slotoffset += sizeof(PyObject *);
2402 }
2403 if (add_weak) {
2404 assert(!base->tp_itemsize);
2405 type->tp_weaklistoffset = slotoffset;
2406 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002407 }
2408 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002409 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002410 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002411
2412 if (type->tp_weaklistoffset && type->tp_dictoffset)
2413 type->tp_getset = subtype_getsets_full;
2414 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2415 type->tp_getset = subtype_getsets_weakref_only;
2416 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2417 type->tp_getset = subtype_getsets_dict_only;
2418 else
2419 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002420
2421 /* Special case some slots */
2422 if (type->tp_dictoffset != 0 || nslots > 0) {
2423 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2424 type->tp_getattro = PyObject_GenericGetAttr;
2425 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2426 type->tp_setattro = PyObject_GenericSetAttr;
2427 }
2428 type->tp_dealloc = subtype_dealloc;
2429
Guido van Rossum9475a232001-10-05 20:51:39 +00002430 /* Enable GC unless there are really no instance variables possible */
2431 if (!(type->tp_basicsize == sizeof(PyObject) &&
2432 type->tp_itemsize == 0))
2433 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2434
Tim Peters6d6c1a32001-08-02 04:15:00 +00002435 /* Always override allocation strategy to use regular heap */
2436 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002437 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002438 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002439 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002440 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002441 }
2442 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002443 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002444
2445 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002446 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002447 Py_DECREF(type);
2448 return NULL;
2449 }
2450
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002451 /* Put the proper slots in place */
2452 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002453
Tim Peters6d6c1a32001-08-02 04:15:00 +00002454 return (PyObject *)type;
2455}
2456
2457/* Internal API to look for a name through the MRO.
2458 This returns a borrowed reference, and doesn't set an exception! */
2459PyObject *
2460_PyType_Lookup(PyTypeObject *type, PyObject *name)
2461{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002462 Py_ssize_t i, n;
Georg Brandlf18a7072008-05-29 14:35:39 +00002463 PyObject *mro, *res, *base, *dict;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002464 unsigned int h;
2465
2466 if (MCACHE_CACHEABLE_NAME(name) &&
Neal Norwitze7bb9182008-01-27 17:10:14 +00002467 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002468 /* fast path */
2469 h = MCACHE_HASH_METHOD(type, name);
2470 if (method_cache[h].version == type->tp_version_tag &&
2471 method_cache[h].name == name)
2472 return method_cache[h].value;
2473 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002474
Guido van Rossum687ae002001-10-15 22:03:32 +00002475 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002476 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002477
2478 /* If mro is NULL, the type is either not yet initialized
2479 by PyType_Ready(), or already cleared by type_clear().
2480 Either way the safest thing to do is to return NULL. */
2481 if (mro == NULL)
2482 return NULL;
2483
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002484 res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002485 assert(PyTuple_Check(mro));
2486 n = PyTuple_GET_SIZE(mro);
2487 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002488 base = PyTuple_GET_ITEM(mro, i);
2489 if (PyClass_Check(base))
2490 dict = ((PyClassObject *)base)->cl_dict;
2491 else {
2492 assert(PyType_Check(base));
2493 dict = ((PyTypeObject *)base)->tp_dict;
2494 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002495 assert(dict && PyDict_Check(dict));
2496 res = PyDict_GetItem(dict, name);
2497 if (res != NULL)
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002498 break;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002499 }
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002500
2501 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2502 h = MCACHE_HASH_METHOD(type, name);
2503 method_cache[h].version = type->tp_version_tag;
2504 method_cache[h].value = res; /* borrowed */
2505 Py_INCREF(name);
Georg Brandlf18a7072008-05-29 14:35:39 +00002506 Py_DECREF(method_cache[h].name);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002507 method_cache[h].name = name;
2508 }
2509 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002510}
2511
2512/* This is similar to PyObject_GenericGetAttr(),
2513 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2514static PyObject *
2515type_getattro(PyTypeObject *type, PyObject *name)
2516{
Christian Heimese93237d2007-12-19 02:37:44 +00002517 PyTypeObject *metatype = Py_TYPE(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002518 PyObject *meta_attribute, *attribute;
2519 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002520
2521 /* Initialize this type (we'll assume the metatype is initialized) */
2522 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002523 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002524 return NULL;
2525 }
2526
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002527 /* No readable descriptor found yet */
2528 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002529
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002530 /* Look for the attribute in the metatype */
2531 meta_attribute = _PyType_Lookup(metatype, name);
2532
2533 if (meta_attribute != NULL) {
Christian Heimese93237d2007-12-19 02:37:44 +00002534 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002535
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002536 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2537 /* Data descriptors implement tp_descr_set to intercept
2538 * writes. Assume the attribute is not overridden in
2539 * type's tp_dict (and bases): call the descriptor now.
2540 */
2541 return meta_get(meta_attribute, (PyObject *)type,
2542 (PyObject *)metatype);
2543 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002544 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002545 }
2546
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002547 /* No data descriptor found on metatype. Look in tp_dict of this
2548 * type and its bases */
2549 attribute = _PyType_Lookup(type, name);
2550 if (attribute != NULL) {
2551 /* Implement descriptor functionality, if any */
Christian Heimese93237d2007-12-19 02:37:44 +00002552 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002553
2554 Py_XDECREF(meta_attribute);
2555
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002556 if (local_get != NULL) {
2557 /* NULL 2nd argument indicates the descriptor was
2558 * found on the target object itself (or a base) */
2559 return local_get(attribute, (PyObject *)NULL,
2560 (PyObject *)type);
2561 }
Tim Peters34592512002-07-11 06:23:50 +00002562
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002563 Py_INCREF(attribute);
2564 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002565 }
2566
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002567 /* No attribute found in local __dict__ (or bases): use the
2568 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002569 if (meta_get != NULL) {
2570 PyObject *res;
2571 res = meta_get(meta_attribute, (PyObject *)type,
2572 (PyObject *)metatype);
2573 Py_DECREF(meta_attribute);
2574 return res;
2575 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002576
2577 /* If an ordinary attribute was found on the metatype, return it now */
2578 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002579 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002580 }
2581
2582 /* Give up */
2583 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002584 "type object '%.50s' has no attribute '%.400s'",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002585 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002586 return NULL;
2587}
2588
2589static int
2590type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2591{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002592 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2593 PyErr_Format(
2594 PyExc_TypeError,
2595 "can't set attributes of built-in/extension type '%s'",
2596 type->tp_name);
2597 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002598 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002599 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2600 return -1;
2601 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002602}
2603
2604static void
2605type_dealloc(PyTypeObject *type)
2606{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002607 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002608
2609 /* Assert this is a heap-allocated type object */
2610 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002611 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002612 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002613 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002614 Py_XDECREF(type->tp_base);
2615 Py_XDECREF(type->tp_dict);
2616 Py_XDECREF(type->tp_bases);
2617 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002618 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002619 Py_XDECREF(type->tp_subclasses);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002620 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2621 * of most other objects. It's okay to cast it to char *.
2622 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002623 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002624 Py_XDECREF(et->ht_name);
2625 Py_XDECREF(et->ht_slots);
Christian Heimese93237d2007-12-19 02:37:44 +00002626 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002627}
2628
Guido van Rossum1c450732001-10-08 15:18:27 +00002629static PyObject *
2630type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2631{
2632 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002633 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002634
2635 list = PyList_New(0);
2636 if (list == NULL)
2637 return NULL;
2638 raw = type->tp_subclasses;
2639 if (raw == NULL)
2640 return list;
2641 assert(PyList_Check(raw));
2642 n = PyList_GET_SIZE(raw);
2643 for (i = 0; i < n; i++) {
2644 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002645 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002646 ref = PyWeakref_GET_OBJECT(ref);
2647 if (ref != Py_None) {
2648 if (PyList_Append(list, ref) < 0) {
2649 Py_DECREF(list);
2650 return NULL;
2651 }
2652 }
2653 }
2654 return list;
2655}
2656
Tim Peters6d6c1a32001-08-02 04:15:00 +00002657static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002658 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002659 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002660 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002661 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002662 {0}
2663};
2664
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002665PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002666"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002667"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002668
Guido van Rossum048eb752001-10-02 21:24:57 +00002669static int
2670type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2671{
Guido van Rossuma3862092002-06-10 15:24:42 +00002672 /* Because of type_is_gc(), the collector only calls this
2673 for heaptypes. */
2674 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002675
Thomas Woutersc6e55062006-04-15 21:47:09 +00002676 Py_VISIT(type->tp_dict);
2677 Py_VISIT(type->tp_cache);
2678 Py_VISIT(type->tp_mro);
2679 Py_VISIT(type->tp_bases);
2680 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002681
2682 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002683 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002684 in cycles; tp_subclasses is a list of weak references,
2685 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002686
Guido van Rossum048eb752001-10-02 21:24:57 +00002687 return 0;
2688}
2689
2690static int
2691type_clear(PyTypeObject *type)
2692{
Guido van Rossuma3862092002-06-10 15:24:42 +00002693 /* Because of type_is_gc(), the collector only calls this
2694 for heaptypes. */
2695 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002696
Guido van Rossuma3862092002-06-10 15:24:42 +00002697 /* The only field we need to clear is tp_mro, which is part of a
2698 hard cycle (its first element is the class itself) that won't
2699 be broken otherwise (it's a tuple and tuples don't have a
2700 tp_clear handler). None of the other fields need to be
2701 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002702
Guido van Rossuma3862092002-06-10 15:24:42 +00002703 tp_dict:
2704 It is a dict, so the collector will call its tp_clear.
2705
2706 tp_cache:
2707 Not used; if it were, it would be a dict.
2708
2709 tp_bases, tp_base:
2710 If these are involved in a cycle, there must be at least
2711 one other, mutable object in the cycle, e.g. a base
2712 class's dict; the cycle will be broken that way.
2713
2714 tp_subclasses:
2715 A list of weak references can't be part of a cycle; and
2716 lists have their own tp_clear.
2717
Guido van Rossume5c691a2003-03-07 15:13:17 +00002718 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002719 A tuple of strings can't be part of a cycle.
2720 */
2721
Thomas Woutersedf17d82006-04-15 17:28:34 +00002722 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002723
2724 return 0;
2725}
2726
2727static int
2728type_is_gc(PyTypeObject *type)
2729{
2730 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2731}
2732
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002733PyTypeObject PyType_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002734 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002735 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002736 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002737 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002738 (destructor)type_dealloc, /* tp_dealloc */
2739 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002740 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002741 0, /* tp_setattr */
2742 type_compare, /* tp_compare */
2743 (reprfunc)type_repr, /* tp_repr */
2744 0, /* tp_as_number */
2745 0, /* tp_as_sequence */
2746 0, /* tp_as_mapping */
2747 (hashfunc)_Py_HashPointer, /* tp_hash */
2748 (ternaryfunc)type_call, /* tp_call */
2749 0, /* tp_str */
2750 (getattrofunc)type_getattro, /* tp_getattro */
2751 (setattrofunc)type_setattro, /* tp_setattro */
2752 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002753 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002754 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002755 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002756 (traverseproc)type_traverse, /* tp_traverse */
2757 (inquiry)type_clear, /* tp_clear */
Steven Bethardae42f332008-03-18 17:26:10 +00002758 type_richcompare, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002759 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002760 0, /* tp_iter */
2761 0, /* tp_iternext */
2762 type_methods, /* tp_methods */
2763 type_members, /* tp_members */
2764 type_getsets, /* tp_getset */
2765 0, /* tp_base */
2766 0, /* tp_dict */
2767 0, /* tp_descr_get */
2768 0, /* tp_descr_set */
2769 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumf102e242007-03-23 18:53:03 +00002770 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771 0, /* tp_alloc */
2772 type_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002773 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002774 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002775};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002776
2777
2778/* The base type of all types (eventually)... except itself. */
2779
Guido van Rossum143b5642007-03-23 04:58:42 +00002780/* You may wonder why object.__new__() only complains about arguments
2781 when object.__init__() is not overridden, and vice versa.
2782
2783 Consider the use cases:
2784
2785 1. When neither is overridden, we want to hear complaints about
2786 excess (i.e., any) arguments, since their presence could
2787 indicate there's a bug.
2788
2789 2. When defining an Immutable type, we are likely to override only
2790 __new__(), since __init__() is called too late to initialize an
2791 Immutable object. Since __new__() defines the signature for the
2792 type, it would be a pain to have to override __init__() just to
2793 stop it from complaining about excess arguments.
2794
2795 3. When defining a Mutable type, we are likely to override only
2796 __init__(). So here the converse reasoning applies: we don't
2797 want to have to override __new__() just to stop it from
2798 complaining.
2799
2800 4. When __init__() is overridden, and the subclass __init__() calls
2801 object.__init__(), the latter should complain about excess
2802 arguments; ditto for __new__().
2803
2804 Use cases 2 and 3 make it unattractive to unconditionally check for
2805 excess arguments. The best solution that addresses all four use
2806 cases is as follows: __init__() complains about excess arguments
2807 unless __new__() is overridden and __init__() is not overridden
2808 (IOW, if __init__() is overridden or __new__() is not overridden);
2809 symmetrically, __new__() complains about excess arguments unless
2810 __init__() is overridden and __new__() is not overridden
2811 (IOW, if __new__() is overridden or __init__() is not overridden).
2812
2813 However, for backwards compatibility, this breaks too much code.
2814 Therefore, in 2.6, we'll *warn* about excess arguments when both
2815 methods are overridden; for all other cases we'll use the above
2816 rules.
2817
2818*/
2819
2820/* Forward */
2821static PyObject *
2822object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2823
2824static int
2825excess_args(PyObject *args, PyObject *kwds)
2826{
2827 return PyTuple_GET_SIZE(args) ||
2828 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2829}
2830
Tim Peters6d6c1a32001-08-02 04:15:00 +00002831static int
2832object_init(PyObject *self, PyObject *args, PyObject *kwds)
2833{
Guido van Rossum143b5642007-03-23 04:58:42 +00002834 int err = 0;
2835 if (excess_args(args, kwds)) {
Christian Heimese93237d2007-12-19 02:37:44 +00002836 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum143b5642007-03-23 04:58:42 +00002837 if (type->tp_init != object_init &&
2838 type->tp_new != object_new)
2839 {
2840 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2841 "object.__init__() takes no parameters",
2842 1);
2843 }
2844 else if (type->tp_init != object_init ||
2845 type->tp_new == object_new)
2846 {
2847 PyErr_SetString(PyExc_TypeError,
2848 "object.__init__() takes no parameters");
2849 err = -1;
2850 }
2851 }
2852 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002853}
2854
Guido van Rossum298e4212003-02-13 16:30:16 +00002855static PyObject *
2856object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2857{
Guido van Rossum143b5642007-03-23 04:58:42 +00002858 int err = 0;
2859 if (excess_args(args, kwds)) {
2860 if (type->tp_new != object_new &&
2861 type->tp_init != object_init)
2862 {
2863 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2864 "object.__new__() takes no parameters",
2865 1);
2866 }
2867 else if (type->tp_new != object_new ||
2868 type->tp_init == object_init)
2869 {
2870 PyErr_SetString(PyExc_TypeError,
2871 "object.__new__() takes no parameters");
2872 err = -1;
2873 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002874 }
Guido van Rossum143b5642007-03-23 04:58:42 +00002875 if (err < 0)
2876 return NULL;
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00002877
2878 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2879 static PyObject *comma = NULL;
2880 PyObject *abstract_methods = NULL;
2881 PyObject *builtins;
2882 PyObject *sorted;
2883 PyObject *sorted_methods = NULL;
2884 PyObject *joined = NULL;
2885 const char *joined_str;
2886
2887 /* Compute ", ".join(sorted(type.__abstractmethods__))
2888 into joined. */
2889 abstract_methods = type_abstractmethods(type, NULL);
2890 if (abstract_methods == NULL)
2891 goto error;
2892 builtins = PyEval_GetBuiltins();
2893 if (builtins == NULL)
2894 goto error;
2895 sorted = PyDict_GetItemString(builtins, "sorted");
2896 if (sorted == NULL)
2897 goto error;
2898 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2899 abstract_methods,
2900 NULL);
2901 if (sorted_methods == NULL)
2902 goto error;
2903 if (comma == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002904 comma = PyString_InternFromString(", ");
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00002905 if (comma == NULL)
2906 goto error;
2907 }
2908 joined = PyObject_CallMethod(comma, "join",
2909 "O", sorted_methods);
2910 if (joined == NULL)
2911 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002912 joined_str = PyString_AsString(joined);
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00002913 if (joined_str == NULL)
2914 goto error;
2915
2916 PyErr_Format(PyExc_TypeError,
2917 "Can't instantiate abstract class %s "
2918 "with abstract methods %s",
2919 type->tp_name,
2920 joined_str);
2921 error:
2922 Py_XDECREF(joined);
2923 Py_XDECREF(sorted_methods);
2924 Py_XDECREF(abstract_methods);
2925 return NULL;
2926 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002927 return type->tp_alloc(type, 0);
2928}
2929
Tim Peters6d6c1a32001-08-02 04:15:00 +00002930static void
2931object_dealloc(PyObject *self)
2932{
Christian Heimese93237d2007-12-19 02:37:44 +00002933 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002934}
2935
Guido van Rossum8e248182001-08-12 05:17:56 +00002936static PyObject *
2937object_repr(PyObject *self)
2938{
Guido van Rossum76e69632001-08-16 18:52:43 +00002939 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002940 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002941
Christian Heimese93237d2007-12-19 02:37:44 +00002942 type = Py_TYPE(self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002943 mod = type_module(type, NULL);
2944 if (mod == NULL)
2945 PyErr_Clear();
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002946 else if (!PyString_Check(mod)) {
Guido van Rossum76e69632001-08-16 18:52:43 +00002947 Py_DECREF(mod);
2948 mod = NULL;
2949 }
2950 name = type_name(type, NULL);
2951 if (name == NULL)
2952 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002953 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
2954 rtn = PyString_FromFormat("<%s.%s object at %p>",
2955 PyString_AS_STRING(mod),
2956 PyString_AS_STRING(name),
Barry Warsaw7ce36942001-08-24 18:34:26 +00002957 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002958 else
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002959 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002960 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002961 Py_XDECREF(mod);
2962 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002963 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002964}
2965
Guido van Rossumb8f63662001-08-15 23:57:02 +00002966static PyObject *
2967object_str(PyObject *self)
2968{
2969 unaryfunc f;
2970
Christian Heimese93237d2007-12-19 02:37:44 +00002971 f = Py_TYPE(self)->tp_repr;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002972 if (f == NULL)
2973 f = object_repr;
2974 return f(self);
2975}
2976
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002977static PyObject *
2978object_get_class(PyObject *self, void *closure)
2979{
Christian Heimese93237d2007-12-19 02:37:44 +00002980 Py_INCREF(Py_TYPE(self));
2981 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002982}
2983
2984static int
2985equiv_structs(PyTypeObject *a, PyTypeObject *b)
2986{
2987 return a == b ||
2988 (a != NULL &&
2989 b != NULL &&
2990 a->tp_basicsize == b->tp_basicsize &&
2991 a->tp_itemsize == b->tp_itemsize &&
2992 a->tp_dictoffset == b->tp_dictoffset &&
2993 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2994 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2995 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2996}
2997
2998static int
2999same_slots_added(PyTypeObject *a, PyTypeObject *b)
3000{
3001 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003002 Py_ssize_t size;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00003003 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003004
3005 if (base != b->tp_base)
3006 return 0;
3007 if (equiv_structs(a, base) && equiv_structs(b, base))
3008 return 1;
3009 size = base->tp_basicsize;
3010 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3011 size += sizeof(PyObject *);
3012 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3013 size += sizeof(PyObject *);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00003014
3015 /* Check slots compliance */
3016 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3017 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3018 if (slots_a && slots_b) {
3019 if (PyObject_Compare(slots_a, slots_b) != 0)
3020 return 0;
3021 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3022 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003023 return size == a->tp_basicsize && size == b->tp_basicsize;
3024}
3025
3026static int
Anthony Baxtera6286212006-04-11 07:42:36 +00003027compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003028{
3029 PyTypeObject *newbase, *oldbase;
3030
Anthony Baxtera6286212006-04-11 07:42:36 +00003031 if (newto->tp_dealloc != oldto->tp_dealloc ||
3032 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003033 {
3034 PyErr_Format(PyExc_TypeError,
3035 "%s assignment: "
3036 "'%s' deallocator differs from '%s'",
3037 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00003038 newto->tp_name,
3039 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003040 return 0;
3041 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003042 newbase = newto;
3043 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003044 while (equiv_structs(newbase, newbase->tp_base))
3045 newbase = newbase->tp_base;
3046 while (equiv_structs(oldbase, oldbase->tp_base))
3047 oldbase = oldbase->tp_base;
3048 if (newbase != oldbase &&
3049 (newbase->tp_base != oldbase->tp_base ||
3050 !same_slots_added(newbase, oldbase))) {
3051 PyErr_Format(PyExc_TypeError,
3052 "%s assignment: "
3053 "'%s' object layout differs from '%s'",
3054 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00003055 newto->tp_name,
3056 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003057 return 0;
3058 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003059
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003060 return 1;
3061}
3062
3063static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003064object_set_class(PyObject *self, PyObject *value, void *closure)
3065{
Christian Heimese93237d2007-12-19 02:37:44 +00003066 PyTypeObject *oldto = Py_TYPE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00003067 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003068
Guido van Rossumb6b89422002-04-15 01:03:30 +00003069 if (value == NULL) {
3070 PyErr_SetString(PyExc_TypeError,
3071 "can't delete __class__ attribute");
3072 return -1;
3073 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003074 if (!PyType_Check(value)) {
3075 PyErr_Format(PyExc_TypeError,
3076 "__class__ must be set to new-style class, not '%s' object",
Christian Heimese93237d2007-12-19 02:37:44 +00003077 Py_TYPE(value)->tp_name);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003078 return -1;
3079 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003080 newto = (PyTypeObject *)value;
3081 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3082 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00003083 {
3084 PyErr_Format(PyExc_TypeError,
3085 "__class__ assignment: only for heap types");
3086 return -1;
3087 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003088 if (compatible_for_assignment(newto, oldto, "__class__")) {
3089 Py_INCREF(newto);
Christian Heimese93237d2007-12-19 02:37:44 +00003090 Py_TYPE(self) = newto;
Anthony Baxtera6286212006-04-11 07:42:36 +00003091 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003092 return 0;
3093 }
3094 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00003095 return -1;
3096 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003097}
3098
3099static PyGetSetDef object_getsets[] = {
3100 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00003101 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003102 {0}
3103};
3104
Guido van Rossumc53f0092003-02-18 22:05:12 +00003105
Guido van Rossum036f9992003-02-21 22:02:54 +00003106/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Georg Brandldffbf5f2008-05-20 07:49:57 +00003107 We fall back to helpers in copy_reg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003108 - pickle protocols < 2
3109 - calculating the list of slot names (done only once per class)
3110 - the __newobj__ function (which is used as a token but never called)
3111*/
3112
3113static PyObject *
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003114import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003115{
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003116 static PyObject *copyreg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00003117
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003118 if (!copyreg_str) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003119 copyreg_str = PyString_InternFromString("copy_reg");
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003120 if (copyreg_str == NULL)
Guido van Rossum3926a632001-09-25 16:25:58 +00003121 return NULL;
3122 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003123
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003124 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003125}
3126
3127static PyObject *
3128slotnames(PyObject *cls)
3129{
3130 PyObject *clsdict;
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003131 PyObject *copyreg;
Guido van Rossum036f9992003-02-21 22:02:54 +00003132 PyObject *slotnames;
3133
3134 if (!PyType_Check(cls)) {
3135 Py_INCREF(Py_None);
3136 return Py_None;
3137 }
3138
3139 clsdict = ((PyTypeObject *)cls)->tp_dict;
3140 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00003141 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00003142 Py_INCREF(slotnames);
3143 return slotnames;
3144 }
3145
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003146 copyreg = import_copyreg();
3147 if (copyreg == NULL)
Guido van Rossum036f9992003-02-21 22:02:54 +00003148 return NULL;
3149
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003150 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
3151 Py_DECREF(copyreg);
Guido van Rossum036f9992003-02-21 22:02:54 +00003152 if (slotnames != NULL &&
3153 slotnames != Py_None &&
3154 !PyList_Check(slotnames))
3155 {
3156 PyErr_SetString(PyExc_TypeError,
Georg Brandldffbf5f2008-05-20 07:49:57 +00003157 "copy_reg._slotnames didn't return a list or None");
Guido van Rossum036f9992003-02-21 22:02:54 +00003158 Py_DECREF(slotnames);
3159 slotnames = NULL;
3160 }
3161
3162 return slotnames;
3163}
3164
3165static PyObject *
3166reduce_2(PyObject *obj)
3167{
3168 PyObject *cls, *getnewargs;
3169 PyObject *args = NULL, *args2 = NULL;
3170 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3171 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003172 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003173 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00003174
3175 cls = PyObject_GetAttrString(obj, "__class__");
3176 if (cls == NULL)
3177 return NULL;
3178
3179 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
3180 if (getnewargs != NULL) {
3181 args = PyObject_CallObject(getnewargs, NULL);
3182 Py_DECREF(getnewargs);
3183 if (args != NULL && !PyTuple_Check(args)) {
Georg Brandlccff7852006-06-18 22:17:29 +00003184 PyErr_Format(PyExc_TypeError,
3185 "__getnewargs__ should return a tuple, "
Christian Heimese93237d2007-12-19 02:37:44 +00003186 "not '%.200s'", Py_TYPE(args)->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00003187 goto end;
3188 }
3189 }
3190 else {
3191 PyErr_Clear();
3192 args = PyTuple_New(0);
3193 }
3194 if (args == NULL)
3195 goto end;
3196
3197 getstate = PyObject_GetAttrString(obj, "__getstate__");
3198 if (getstate != NULL) {
3199 state = PyObject_CallObject(getstate, NULL);
3200 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00003201 if (state == NULL)
3202 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003203 }
3204 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00003205 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00003206 state = PyObject_GetAttrString(obj, "__dict__");
3207 if (state == NULL) {
3208 PyErr_Clear();
3209 state = Py_None;
3210 Py_INCREF(state);
3211 }
3212 names = slotnames(cls);
3213 if (names == NULL)
3214 goto end;
3215 if (names != Py_None) {
3216 assert(PyList_Check(names));
3217 slots = PyDict_New();
3218 if (slots == NULL)
3219 goto end;
3220 n = 0;
3221 /* Can't pre-compute the list size; the list
3222 is stored on the class so accessible to other
3223 threads, which may be run by DECREF */
3224 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3225 PyObject *name, *value;
3226 name = PyList_GET_ITEM(names, i);
3227 value = PyObject_GetAttr(obj, name);
3228 if (value == NULL)
3229 PyErr_Clear();
3230 else {
3231 int err = PyDict_SetItem(slots, name,
3232 value);
3233 Py_DECREF(value);
3234 if (err)
3235 goto end;
3236 n++;
3237 }
3238 }
3239 if (n) {
3240 state = Py_BuildValue("(NO)", state, slots);
3241 if (state == NULL)
3242 goto end;
3243 }
3244 }
3245 }
3246
3247 if (!PyList_Check(obj)) {
3248 listitems = Py_None;
3249 Py_INCREF(listitems);
3250 }
3251 else {
3252 listitems = PyObject_GetIter(obj);
3253 if (listitems == NULL)
3254 goto end;
3255 }
3256
3257 if (!PyDict_Check(obj)) {
3258 dictitems = Py_None;
3259 Py_INCREF(dictitems);
3260 }
3261 else {
3262 dictitems = PyObject_CallMethod(obj, "iteritems", "");
3263 if (dictitems == NULL)
3264 goto end;
3265 }
3266
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003267 copyreg = import_copyreg();
3268 if (copyreg == NULL)
Guido van Rossum036f9992003-02-21 22:02:54 +00003269 goto end;
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003270 newobj = PyObject_GetAttrString(copyreg, "__newobj__");
Guido van Rossum036f9992003-02-21 22:02:54 +00003271 if (newobj == NULL)
3272 goto end;
3273
3274 n = PyTuple_GET_SIZE(args);
3275 args2 = PyTuple_New(n+1);
3276 if (args2 == NULL)
3277 goto end;
3278 PyTuple_SET_ITEM(args2, 0, cls);
3279 cls = NULL;
3280 for (i = 0; i < n; i++) {
3281 PyObject *v = PyTuple_GET_ITEM(args, i);
3282 Py_INCREF(v);
3283 PyTuple_SET_ITEM(args2, i+1, v);
3284 }
3285
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003286 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003287
3288 end:
3289 Py_XDECREF(cls);
3290 Py_XDECREF(args);
3291 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00003292 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00003293 Py_XDECREF(state);
3294 Py_XDECREF(names);
3295 Py_XDECREF(listitems);
3296 Py_XDECREF(dictitems);
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003297 Py_XDECREF(copyreg);
Guido van Rossum036f9992003-02-21 22:02:54 +00003298 Py_XDECREF(newobj);
3299 return res;
3300}
3301
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003302/*
3303 * There were two problems when object.__reduce__ and object.__reduce_ex__
3304 * were implemented in the same function:
3305 * - trying to pickle an object with a custom __reduce__ method that
3306 * fell back to object.__reduce__ in certain circumstances led to
3307 * infinite recursion at Python level and eventual RuntimeError.
3308 * - Pickling objects that lied about their type by overwriting the
3309 * __class__ descriptor could lead to infinite recursion at C level
3310 * and eventual segfault.
3311 *
3312 * Because of backwards compatibility, the two methods still have to
3313 * behave in the same way, even if this is not required by the pickle
3314 * protocol. This common functionality was moved to the _common_reduce
3315 * function.
3316 */
3317static PyObject *
3318_common_reduce(PyObject *self, int proto)
3319{
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003320 PyObject *copyreg, *res;
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003321
3322 if (proto >= 2)
3323 return reduce_2(self);
3324
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003325 copyreg = import_copyreg();
3326 if (!copyreg)
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003327 return NULL;
3328
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003329 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3330 Py_DECREF(copyreg);
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003331
3332 return res;
3333}
3334
3335static PyObject *
3336object_reduce(PyObject *self, PyObject *args)
3337{
3338 int proto = 0;
3339
3340 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3341 return NULL;
3342
3343 return _common_reduce(self, proto);
3344}
3345
Guido van Rossum036f9992003-02-21 22:02:54 +00003346static PyObject *
3347object_reduce_ex(PyObject *self, PyObject *args)
3348{
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003349 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003350 int proto = 0;
3351
3352 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3353 return NULL;
3354
3355 reduce = PyObject_GetAttrString(self, "__reduce__");
3356 if (reduce == NULL)
3357 PyErr_Clear();
3358 else {
3359 PyObject *cls, *clsreduce, *objreduce;
3360 int override;
3361 cls = PyObject_GetAttrString(self, "__class__");
3362 if (cls == NULL) {
3363 Py_DECREF(reduce);
3364 return NULL;
3365 }
3366 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3367 Py_DECREF(cls);
3368 if (clsreduce == NULL) {
3369 Py_DECREF(reduce);
3370 return NULL;
3371 }
3372 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3373 "__reduce__");
3374 override = (clsreduce != objreduce);
3375 Py_DECREF(clsreduce);
3376 if (override) {
3377 res = PyObject_CallObject(reduce, NULL);
3378 Py_DECREF(reduce);
3379 return res;
3380 }
3381 else
3382 Py_DECREF(reduce);
3383 }
3384
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003385 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003386}
3387
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00003388static PyObject *
3389object_subclasshook(PyObject *cls, PyObject *args)
3390{
3391 Py_INCREF(Py_NotImplemented);
3392 return Py_NotImplemented;
3393}
3394
3395PyDoc_STRVAR(object_subclasshook_doc,
3396"Abstract classes can override this to customize issubclass().\n"
3397"\n"
3398"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3399"It should return True, False or NotImplemented. If it returns\n"
3400"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3401"overrides the normal algorithm (and the outcome is cached).\n");
3402
Eric Smitha9f7d622008-02-17 19:46:49 +00003403/*
3404 from PEP 3101, this code implements:
3405
3406 class object:
3407 def __format__(self, format_spec):
3408 if isinstance(format_spec, str):
3409 return format(str(self), format_spec)
3410 elif isinstance(format_spec, unicode):
3411 return format(unicode(self), format_spec)
3412*/
3413static PyObject *
3414object_format(PyObject *self, PyObject *args)
3415{
3416 PyObject *format_spec;
3417 PyObject *self_as_str = NULL;
3418 PyObject *result = NULL;
3419 PyObject *format_meth = NULL;
3420
3421 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3422 return NULL;
Benjamin Peterson78821dd2009-01-25 17:15:10 +00003423#ifdef Py_USING_UNICODE
Eric Smitha9f7d622008-02-17 19:46:49 +00003424 if (PyUnicode_Check(format_spec)) {
3425 self_as_str = PyObject_Unicode(self);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003426 } else if (PyString_Check(format_spec)) {
Benjamin Peterson78821dd2009-01-25 17:15:10 +00003427#else
3428 if (PyString_Check(format_spec)) {
3429#endif
Eric Smitha9f7d622008-02-17 19:46:49 +00003430 self_as_str = PyObject_Str(self);
3431 } else {
3432 PyErr_SetString(PyExc_TypeError, "argument to __format__ must be unicode or str");
3433 return NULL;
3434 }
3435
3436 if (self_as_str != NULL) {
3437 /* find the format function */
3438 format_meth = PyObject_GetAttrString(self_as_str, "__format__");
3439 if (format_meth != NULL) {
3440 /* and call it */
3441 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
3442 }
3443 }
3444
3445 Py_XDECREF(self_as_str);
3446 Py_XDECREF(format_meth);
3447
3448 return result;
3449}
3450
Robert Schuppenies51df0642008-06-01 16:16:17 +00003451static PyObject *
3452object_sizeof(PyObject *self, PyObject *args)
3453{
3454 Py_ssize_t res, isize;
3455
3456 res = 0;
3457 isize = self->ob_type->tp_itemsize;
3458 if (isize > 0)
3459 res = self->ob_type->ob_size * isize;
3460 res += self->ob_type->tp_basicsize;
3461
3462 return PyInt_FromSsize_t(res);
3463}
3464
Guido van Rossum3926a632001-09-25 16:25:58 +00003465static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00003466 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3467 PyDoc_STR("helper for pickle")},
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003468 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003469 PyDoc_STR("helper for pickle")},
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00003470 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3471 object_subclasshook_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00003472 {"__format__", object_format, METH_VARARGS,
3473 PyDoc_STR("default object formatter")},
Robert Schuppenies51df0642008-06-01 16:16:17 +00003474 {"__sizeof__", object_sizeof, METH_NOARGS,
Georg Brandl7a6de8b2008-06-01 16:42:16 +00003475 PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")},
Guido van Rossum3926a632001-09-25 16:25:58 +00003476 {0}
3477};
3478
Guido van Rossum036f9992003-02-21 22:02:54 +00003479
Tim Peters6d6c1a32001-08-02 04:15:00 +00003480PyTypeObject PyBaseObject_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00003481 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003482 "object", /* tp_name */
3483 sizeof(PyObject), /* tp_basicsize */
3484 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003485 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003486 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003487 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003488 0, /* tp_setattr */
3489 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003490 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003491 0, /* tp_as_number */
3492 0, /* tp_as_sequence */
3493 0, /* tp_as_mapping */
Guido van Rossum64c06e32007-11-22 00:55:51 +00003494 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003495 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003496 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003497 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003498 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003499 0, /* tp_as_buffer */
3500 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003501 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003502 0, /* tp_traverse */
3503 0, /* tp_clear */
3504 0, /* tp_richcompare */
3505 0, /* tp_weaklistoffset */
3506 0, /* tp_iter */
3507 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00003508 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003509 0, /* tp_members */
3510 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003511 0, /* tp_base */
3512 0, /* tp_dict */
3513 0, /* tp_descr_get */
3514 0, /* tp_descr_set */
3515 0, /* tp_dictoffset */
3516 object_init, /* tp_init */
3517 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003518 object_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003519 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003520};
3521
3522
3523/* Initialize the __dict__ in a type object */
3524
3525static int
3526add_methods(PyTypeObject *type, PyMethodDef *meth)
3527{
Guido van Rossum687ae002001-10-15 22:03:32 +00003528 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003529
3530 for (; meth->ml_name != NULL; meth++) {
3531 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003532 if (PyDict_GetItemString(dict, meth->ml_name) &&
3533 !(meth->ml_flags & METH_COEXIST))
3534 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003535 if (meth->ml_flags & METH_CLASS) {
3536 if (meth->ml_flags & METH_STATIC) {
3537 PyErr_SetString(PyExc_ValueError,
3538 "method cannot be both class and static");
3539 return -1;
3540 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003541 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003542 }
3543 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003544 PyObject *cfunc = PyCFunction_New(meth, NULL);
3545 if (cfunc == NULL)
3546 return -1;
3547 descr = PyStaticMethod_New(cfunc);
3548 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003549 }
3550 else {
3551 descr = PyDescr_NewMethod(type, meth);
3552 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003553 if (descr == NULL)
3554 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003555 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003556 return -1;
3557 Py_DECREF(descr);
3558 }
3559 return 0;
3560}
3561
3562static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003563add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003564{
Guido van Rossum687ae002001-10-15 22:03:32 +00003565 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003566
3567 for (; memb->name != NULL; memb++) {
3568 PyObject *descr;
3569 if (PyDict_GetItemString(dict, memb->name))
3570 continue;
3571 descr = PyDescr_NewMember(type, memb);
3572 if (descr == NULL)
3573 return -1;
3574 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3575 return -1;
3576 Py_DECREF(descr);
3577 }
3578 return 0;
3579}
3580
3581static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003582add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003583{
Guido van Rossum687ae002001-10-15 22:03:32 +00003584 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003585
3586 for (; gsp->name != NULL; gsp++) {
3587 PyObject *descr;
3588 if (PyDict_GetItemString(dict, gsp->name))
3589 continue;
3590 descr = PyDescr_NewGetSet(type, gsp);
3591
3592 if (descr == NULL)
3593 return -1;
3594 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3595 return -1;
3596 Py_DECREF(descr);
3597 }
3598 return 0;
3599}
3600
Antoine Pitrou789be0c2009-04-02 21:18:34 +00003601#define BUFFER_FLAGS (Py_TPFLAGS_HAVE_GETCHARBUFFER | Py_TPFLAGS_HAVE_NEWBUFFER)
3602
Guido van Rossum13d52f02001-08-10 21:24:08 +00003603static void
3604inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003605{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003606 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003607
Guido van Rossum13d52f02001-08-10 21:24:08 +00003608 /* Special flag magic */
3609 if (!type->tp_as_buffer && base->tp_as_buffer) {
Antoine Pitrou789be0c2009-04-02 21:18:34 +00003610 type->tp_flags &= ~BUFFER_FLAGS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003611 type->tp_flags |=
Antoine Pitrou789be0c2009-04-02 21:18:34 +00003612 base->tp_flags & BUFFER_FLAGS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003613 }
3614 if (!type->tp_as_sequence && base->tp_as_sequence) {
3615 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3616 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3617 }
3618 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3619 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3620 if ((!type->tp_as_number && base->tp_as_number) ||
3621 (!type->tp_as_sequence && base->tp_as_sequence)) {
3622 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3623 if (!type->tp_as_number && !type->tp_as_sequence) {
3624 type->tp_flags |= base->tp_flags &
3625 Py_TPFLAGS_HAVE_INPLACEOPS;
3626 }
3627 }
3628 /* Wow */
3629 }
3630 if (!type->tp_as_number && base->tp_as_number) {
3631 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3632 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3633 }
3634
3635 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003636 oldsize = base->tp_basicsize;
3637 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3638 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3639 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003640 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3641 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003642 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003643 if (type->tp_traverse == NULL)
3644 type->tp_traverse = base->tp_traverse;
3645 if (type->tp_clear == NULL)
3646 type->tp_clear = base->tp_clear;
3647 }
3648 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00003649 /* The condition below could use some explanation.
3650 It appears that tp_new is not inherited for static types
3651 whose base class is 'object'; this seems to be a precaution
3652 so that old extension types don't suddenly become
3653 callable (object.__new__ wouldn't insure the invariants
3654 that the extension type's own factory function ensures).
3655 Heap types, of course, are under our control, so they do
3656 inherit tp_new; static extension types that specify some
3657 other built-in type as the default are considered
3658 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003659 if (base != &PyBaseObject_Type ||
3660 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3661 if (type->tp_new == NULL)
3662 type->tp_new = base->tp_new;
3663 }
3664 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003665 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003666
3667 /* Copy other non-function slots */
3668
3669#undef COPYVAL
3670#define COPYVAL(SLOT) \
3671 if (type->SLOT == 0) type->SLOT = base->SLOT
3672
3673 COPYVAL(tp_itemsize);
3674 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3675 COPYVAL(tp_weaklistoffset);
3676 }
3677 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3678 COPYVAL(tp_dictoffset);
3679 }
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003680
3681 /* Setup fast subclass flags */
3682 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3683 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3684 else if (PyType_IsSubtype(base, &PyType_Type))
3685 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3686 else if (PyType_IsSubtype(base, &PyInt_Type))
3687 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3688 else if (PyType_IsSubtype(base, &PyLong_Type))
3689 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003690 else if (PyType_IsSubtype(base, &PyString_Type))
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003691 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003692#ifdef Py_USING_UNICODE
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003693 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3694 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003695#endif
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003696 else if (PyType_IsSubtype(base, &PyTuple_Type))
3697 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3698 else if (PyType_IsSubtype(base, &PyList_Type))
3699 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3700 else if (PyType_IsSubtype(base, &PyDict_Type))
3701 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003702}
3703
Nick Coghlan48361f52008-08-11 15:45:58 +00003704static int
3705overrides_name(PyTypeObject *type, char *name)
3706{
3707 PyObject *dict = type->tp_dict;
3708
3709 assert(dict != NULL);
3710 if (PyDict_GetItemString(dict, name) != NULL) {
3711 return 1;
3712 }
3713 return 0;
3714}
3715
3716#define OVERRIDES_HASH(x) overrides_name(x, "__hash__")
3717#define OVERRIDES_CMP(x) overrides_name(x, "__cmp__")
3718#define OVERRIDES_EQ(x) overrides_name(x, "__eq__")
3719
Guido van Rossum13d52f02001-08-10 21:24:08 +00003720static void
3721inherit_slots(PyTypeObject *type, PyTypeObject *base)
3722{
3723 PyTypeObject *basebase;
3724
3725#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003726#undef COPYSLOT
3727#undef COPYNUM
3728#undef COPYSEQ
3729#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003730#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003731
3732#define SLOTDEFINED(SLOT) \
3733 (base->SLOT != 0 && \
3734 (basebase == NULL || base->SLOT != basebase->SLOT))
3735
Tim Peters6d6c1a32001-08-02 04:15:00 +00003736#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003737 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003738
3739#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3740#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3741#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003742#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003743
Guido van Rossum13d52f02001-08-10 21:24:08 +00003744 /* This won't inherit indirect slots (from tp_as_number etc.)
3745 if type doesn't provide the space. */
3746
3747 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3748 basebase = base->tp_base;
3749 if (basebase->tp_as_number == NULL)
3750 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003751 COPYNUM(nb_add);
3752 COPYNUM(nb_subtract);
3753 COPYNUM(nb_multiply);
3754 COPYNUM(nb_divide);
3755 COPYNUM(nb_remainder);
3756 COPYNUM(nb_divmod);
3757 COPYNUM(nb_power);
3758 COPYNUM(nb_negative);
3759 COPYNUM(nb_positive);
3760 COPYNUM(nb_absolute);
3761 COPYNUM(nb_nonzero);
3762 COPYNUM(nb_invert);
3763 COPYNUM(nb_lshift);
3764 COPYNUM(nb_rshift);
3765 COPYNUM(nb_and);
3766 COPYNUM(nb_xor);
3767 COPYNUM(nb_or);
3768 COPYNUM(nb_coerce);
3769 COPYNUM(nb_int);
3770 COPYNUM(nb_long);
3771 COPYNUM(nb_float);
3772 COPYNUM(nb_oct);
3773 COPYNUM(nb_hex);
3774 COPYNUM(nb_inplace_add);
3775 COPYNUM(nb_inplace_subtract);
3776 COPYNUM(nb_inplace_multiply);
3777 COPYNUM(nb_inplace_divide);
3778 COPYNUM(nb_inplace_remainder);
3779 COPYNUM(nb_inplace_power);
3780 COPYNUM(nb_inplace_lshift);
3781 COPYNUM(nb_inplace_rshift);
3782 COPYNUM(nb_inplace_and);
3783 COPYNUM(nb_inplace_xor);
3784 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003785 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3786 COPYNUM(nb_true_divide);
3787 COPYNUM(nb_floor_divide);
3788 COPYNUM(nb_inplace_true_divide);
3789 COPYNUM(nb_inplace_floor_divide);
3790 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003791 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3792 COPYNUM(nb_index);
3793 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003794 }
3795
Guido van Rossum13d52f02001-08-10 21:24:08 +00003796 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3797 basebase = base->tp_base;
3798 if (basebase->tp_as_sequence == NULL)
3799 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003800 COPYSEQ(sq_length);
3801 COPYSEQ(sq_concat);
3802 COPYSEQ(sq_repeat);
3803 COPYSEQ(sq_item);
3804 COPYSEQ(sq_slice);
3805 COPYSEQ(sq_ass_item);
3806 COPYSEQ(sq_ass_slice);
3807 COPYSEQ(sq_contains);
3808 COPYSEQ(sq_inplace_concat);
3809 COPYSEQ(sq_inplace_repeat);
3810 }
3811
Guido van Rossum13d52f02001-08-10 21:24:08 +00003812 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3813 basebase = base->tp_base;
3814 if (basebase->tp_as_mapping == NULL)
3815 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003816 COPYMAP(mp_length);
3817 COPYMAP(mp_subscript);
3818 COPYMAP(mp_ass_subscript);
3819 }
3820
Tim Petersfc57ccb2001-10-12 02:38:24 +00003821 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3822 basebase = base->tp_base;
3823 if (basebase->tp_as_buffer == NULL)
3824 basebase = NULL;
3825 COPYBUF(bf_getreadbuffer);
3826 COPYBUF(bf_getwritebuffer);
3827 COPYBUF(bf_getsegcount);
3828 COPYBUF(bf_getcharbuffer);
Christian Heimes1a6387e2008-03-26 12:49:49 +00003829 COPYBUF(bf_getbuffer);
3830 COPYBUF(bf_releasebuffer);
Tim Petersfc57ccb2001-10-12 02:38:24 +00003831 }
3832
Guido van Rossum13d52f02001-08-10 21:24:08 +00003833 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003834
Tim Peters6d6c1a32001-08-02 04:15:00 +00003835 COPYSLOT(tp_dealloc);
3836 COPYSLOT(tp_print);
3837 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3838 type->tp_getattr = base->tp_getattr;
3839 type->tp_getattro = base->tp_getattro;
3840 }
3841 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3842 type->tp_setattr = base->tp_setattr;
3843 type->tp_setattro = base->tp_setattro;
3844 }
3845 /* tp_compare see tp_richcompare */
3846 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003847 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003848 COPYSLOT(tp_call);
3849 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003850 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003851 if (type->tp_compare == NULL &&
3852 type->tp_richcompare == NULL &&
Nick Coghlan53663a62008-07-15 14:27:37 +00003853 type->tp_hash == NULL)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003854 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003855 type->tp_compare = base->tp_compare;
3856 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003857 type->tp_hash = base->tp_hash;
Nick Coghlan48361f52008-08-11 15:45:58 +00003858 /* Check for changes to inherited methods in Py3k*/
3859 if (Py_Py3kWarningFlag) {
3860 if (base->tp_hash &&
3861 (base->tp_hash != PyObject_HashNotImplemented) &&
3862 !OVERRIDES_HASH(type)) {
3863 if (OVERRIDES_CMP(type)) {
3864 PyErr_WarnPy3k("Overriding "
3865 "__cmp__ blocks inheritance "
3866 "of __hash__ in 3.x",
3867 1);
3868 }
3869 if (OVERRIDES_EQ(type)) {
3870 PyErr_WarnPy3k("Overriding "
3871 "__eq__ blocks inheritance "
3872 "of __hash__ in 3.x",
3873 1);
3874 }
3875 }
3876 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003877 }
3878 }
3879 else {
3880 COPYSLOT(tp_compare);
3881 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003882 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3883 COPYSLOT(tp_iter);
3884 COPYSLOT(tp_iternext);
3885 }
3886 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3887 COPYSLOT(tp_descr_get);
3888 COPYSLOT(tp_descr_set);
3889 COPYSLOT(tp_dictoffset);
3890 COPYSLOT(tp_init);
3891 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003892 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003893 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3894 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3895 /* They agree about gc. */
3896 COPYSLOT(tp_free);
3897 }
3898 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3899 type->tp_free == NULL &&
3900 base->tp_free == _PyObject_Del) {
3901 /* A bit of magic to plug in the correct default
3902 * tp_free function when a derived class adds gc,
3903 * didn't define tp_free, and the base uses the
3904 * default non-gc tp_free.
3905 */
3906 type->tp_free = PyObject_GC_Del;
3907 }
3908 /* else they didn't agree about gc, and there isn't something
3909 * obvious to be done -- the type is on its own.
3910 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003911 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003912}
3913
Jeremy Hylton938ace62002-07-17 16:30:39 +00003914static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003915
Tim Peters6d6c1a32001-08-02 04:15:00 +00003916int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003917PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003918{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003919 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003920 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003921 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003922
Guido van Rossumcab05802002-06-10 15:29:03 +00003923 if (type->tp_flags & Py_TPFLAGS_READY) {
3924 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003925 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003926 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003927 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003928
3929 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003930
Tim Peters36eb4df2003-03-23 03:33:13 +00003931#ifdef Py_TRACE_REFS
3932 /* PyType_Ready is the closest thing we have to a choke point
3933 * for type objects, so is the best place I can think of to try
3934 * to get type objects into the doubly-linked list of all objects.
3935 * Still, not all type objects go thru PyType_Ready.
3936 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003937 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003938#endif
3939
Tim Peters6d6c1a32001-08-02 04:15:00 +00003940 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3941 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003942 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003943 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003944 Py_INCREF(base);
3945 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003946
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003947 /* Now the only way base can still be NULL is if type is
3948 * &PyBaseObject_Type.
3949 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003950
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003951 /* Initialize the base class */
3952 if (base && base->tp_dict == NULL) {
3953 if (PyType_Ready(base) < 0)
3954 goto error;
3955 }
3956
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003957 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003958 compilable separately on Windows can call PyType_Ready() instead of
3959 initializing the ob_type field of their type objects. */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003960 /* The test for base != NULL is really unnecessary, since base is only
3961 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3962 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3963 know that. */
Christian Heimese93237d2007-12-19 02:37:44 +00003964 if (Py_TYPE(type) == NULL && base != NULL)
3965 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003966
Tim Peters6d6c1a32001-08-02 04:15:00 +00003967 /* Initialize tp_bases */
3968 bases = type->tp_bases;
3969 if (bases == NULL) {
3970 if (base == NULL)
3971 bases = PyTuple_New(0);
3972 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003973 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003974 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003975 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003976 type->tp_bases = bases;
3977 }
3978
Guido van Rossum687ae002001-10-15 22:03:32 +00003979 /* Initialize tp_dict */
3980 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003981 if (dict == NULL) {
3982 dict = PyDict_New();
3983 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003984 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003985 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003986 }
3987
Guido van Rossum687ae002001-10-15 22:03:32 +00003988 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003989 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003990 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003991 if (type->tp_methods != NULL) {
3992 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003993 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003994 }
3995 if (type->tp_members != NULL) {
3996 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003997 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003998 }
3999 if (type->tp_getset != NULL) {
4000 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00004001 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004002 }
4003
Tim Peters6d6c1a32001-08-02 04:15:00 +00004004 /* Calculate method resolution order */
4005 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00004006 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004007 }
4008
Guido van Rossum13d52f02001-08-10 21:24:08 +00004009 /* Inherit special flags from dominant base */
4010 if (type->tp_base != NULL)
4011 inherit_special(type, type->tp_base);
4012
Tim Peters6d6c1a32001-08-02 04:15:00 +00004013 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00004014 bases = type->tp_mro;
4015 assert(bases != NULL);
4016 assert(PyTuple_Check(bases));
4017 n = PyTuple_GET_SIZE(bases);
4018 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00004019 PyObject *b = PyTuple_GET_ITEM(bases, i);
4020 if (PyType_Check(b))
4021 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004022 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004023
Tim Peters3cfe7542003-05-21 21:29:48 +00004024 /* Sanity check for tp_free. */
4025 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4026 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004027 /* This base class needs to call tp_free, but doesn't have
4028 * one, or its tp_free is for non-gc'ed objects.
4029 */
Tim Peters3cfe7542003-05-21 21:29:48 +00004030 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4031 "gc and is a base type but has inappropriate "
4032 "tp_free slot",
4033 type->tp_name);
4034 goto error;
4035 }
4036
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004037 /* if the type dictionary doesn't contain a __doc__, set it from
4038 the tp_doc slot.
4039 */
4040 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
4041 if (type->tp_doc != NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00004042 PyObject *doc = PyString_FromString(type->tp_doc);
Neal Norwitze1fdb322006-07-21 05:32:28 +00004043 if (doc == NULL)
4044 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004045 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
4046 Py_DECREF(doc);
4047 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00004048 PyDict_SetItemString(type->tp_dict,
4049 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00004050 }
4051 }
4052
Guido van Rossum13d52f02001-08-10 21:24:08 +00004053 /* Some more special stuff */
4054 base = type->tp_base;
4055 if (base != NULL) {
4056 if (type->tp_as_number == NULL)
4057 type->tp_as_number = base->tp_as_number;
4058 if (type->tp_as_sequence == NULL)
4059 type->tp_as_sequence = base->tp_as_sequence;
4060 if (type->tp_as_mapping == NULL)
4061 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00004062 if (type->tp_as_buffer == NULL)
4063 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00004064 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004065
Guido van Rossum1c450732001-10-08 15:18:27 +00004066 /* Link into each base class's list of subclasses */
4067 bases = type->tp_bases;
4068 n = PyTuple_GET_SIZE(bases);
4069 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00004070 PyObject *b = PyTuple_GET_ITEM(bases, i);
4071 if (PyType_Check(b) &&
4072 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00004073 goto error;
4074 }
4075
Guido van Rossum13d52f02001-08-10 21:24:08 +00004076 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00004077 assert(type->tp_dict != NULL);
4078 type->tp_flags =
4079 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004080 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004081
4082 error:
4083 type->tp_flags &= ~Py_TPFLAGS_READYING;
4084 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004085}
4086
Guido van Rossum1c450732001-10-08 15:18:27 +00004087static int
4088add_subclass(PyTypeObject *base, PyTypeObject *type)
4089{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004090 Py_ssize_t i;
4091 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00004092 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004093
4094 list = base->tp_subclasses;
4095 if (list == NULL) {
4096 base->tp_subclasses = list = PyList_New(0);
4097 if (list == NULL)
4098 return -1;
4099 }
4100 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00004101 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00004102 i = PyList_GET_SIZE(list);
4103 while (--i >= 0) {
4104 ref = PyList_GET_ITEM(list, i);
4105 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00004106 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00004107 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00004108 }
Anthony Baxtera6286212006-04-11 07:42:36 +00004109 result = PyList_Append(list, newobj);
4110 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004111 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004112}
4113
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004114static void
4115remove_subclass(PyTypeObject *base, PyTypeObject *type)
4116{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004117 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004118 PyObject *list, *ref;
4119
4120 list = base->tp_subclasses;
4121 if (list == NULL) {
4122 return;
4123 }
4124 assert(PyList_Check(list));
4125 i = PyList_GET_SIZE(list);
4126 while (--i >= 0) {
4127 ref = PyList_GET_ITEM(list, i);
4128 assert(PyWeakref_CheckRef(ref));
4129 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4130 /* this can't fail, right? */
4131 PySequence_DelItem(list, i);
4132 return;
4133 }
4134 }
4135}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004136
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004137static int
4138check_num_args(PyObject *ob, int n)
4139{
4140 if (!PyTuple_CheckExact(ob)) {
4141 PyErr_SetString(PyExc_SystemError,
4142 "PyArg_UnpackTuple() argument list is not a tuple");
4143 return 0;
4144 }
4145 if (n == PyTuple_GET_SIZE(ob))
4146 return 1;
4147 PyErr_Format(
4148 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00004149 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004150 return 0;
4151}
4152
Tim Peters6d6c1a32001-08-02 04:15:00 +00004153/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4154
4155/* There's a wrapper *function* for each distinct function typedef used
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004156 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004157 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4158 Most tables have only one entry; the tables for binary operators have two
4159 entries, one regular and one with reversed arguments. */
4160
4161static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004162wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004163{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004164 lenfunc func = (lenfunc)wrapped;
4165 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004166
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004167 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004168 return NULL;
4169 res = (*func)(self);
4170 if (res == -1 && PyErr_Occurred())
4171 return NULL;
4172 return PyInt_FromLong((long)res);
4173}
4174
Tim Peters6d6c1a32001-08-02 04:15:00 +00004175static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004176wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4177{
4178 inquiry func = (inquiry)wrapped;
4179 int res;
4180
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004181 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004182 return NULL;
4183 res = (*func)(self);
4184 if (res == -1 && PyErr_Occurred())
4185 return NULL;
4186 return PyBool_FromLong((long)res);
4187}
4188
4189static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004190wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4191{
4192 binaryfunc func = (binaryfunc)wrapped;
4193 PyObject *other;
4194
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004195 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004196 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004197 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004198 return (*func)(self, other);
4199}
4200
4201static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004202wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4203{
4204 binaryfunc func = (binaryfunc)wrapped;
4205 PyObject *other;
4206
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004207 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004208 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004209 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004210 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004211 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004212 Py_INCREF(Py_NotImplemented);
4213 return Py_NotImplemented;
4214 }
4215 return (*func)(self, other);
4216}
4217
4218static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004219wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4220{
4221 binaryfunc func = (binaryfunc)wrapped;
4222 PyObject *other;
4223
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004224 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004225 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004226 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004227 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004228 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004229 Py_INCREF(Py_NotImplemented);
4230 return Py_NotImplemented;
4231 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004232 return (*func)(other, self);
4233}
4234
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004235static PyObject *
4236wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
4237{
4238 coercion func = (coercion)wrapped;
4239 PyObject *other, *res;
4240 int ok;
4241
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004242 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004243 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004244 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004245 ok = func(&self, &other);
4246 if (ok < 0)
4247 return NULL;
4248 if (ok > 0) {
4249 Py_INCREF(Py_NotImplemented);
4250 return Py_NotImplemented;
4251 }
4252 res = PyTuple_New(2);
4253 if (res == NULL) {
4254 Py_DECREF(self);
4255 Py_DECREF(other);
4256 return NULL;
4257 }
4258 PyTuple_SET_ITEM(res, 0, self);
4259 PyTuple_SET_ITEM(res, 1, other);
4260 return res;
4261}
4262
Tim Peters6d6c1a32001-08-02 04:15:00 +00004263static PyObject *
4264wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4265{
4266 ternaryfunc func = (ternaryfunc)wrapped;
4267 PyObject *other;
4268 PyObject *third = Py_None;
4269
4270 /* Note: This wrapper only works for __pow__() */
4271
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004272 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004273 return NULL;
4274 return (*func)(self, other, third);
4275}
4276
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004277static PyObject *
4278wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4279{
4280 ternaryfunc func = (ternaryfunc)wrapped;
4281 PyObject *other;
4282 PyObject *third = Py_None;
4283
4284 /* Note: This wrapper only works for __pow__() */
4285
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004286 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004287 return NULL;
4288 return (*func)(other, self, third);
4289}
4290
Tim Peters6d6c1a32001-08-02 04:15:00 +00004291static PyObject *
4292wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4293{
4294 unaryfunc func = (unaryfunc)wrapped;
4295
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004296 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004297 return NULL;
4298 return (*func)(self);
4299}
4300
Tim Peters6d6c1a32001-08-02 04:15:00 +00004301static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00004302wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004303{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004304 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00004305 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004306 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004307
Armin Rigo314861c2006-03-30 14:04:02 +00004308 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4309 return NULL;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004310 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Armin Rigo314861c2006-03-30 14:04:02 +00004311 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004312 return NULL;
4313 return (*func)(self, i);
4314}
4315
Martin v. Löwis18e16552006-02-15 17:27:45 +00004316static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004317getindex(PyObject *self, PyObject *arg)
4318{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004319 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004320
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004321 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004322 if (i == -1 && PyErr_Occurred())
4323 return -1;
4324 if (i < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00004325 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004326 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00004327 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004328 if (n < 0)
4329 return -1;
4330 i += n;
4331 }
4332 }
4333 return i;
4334}
4335
4336static PyObject *
4337wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4338{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004339 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004340 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004341 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004342
Guido van Rossumf4593e02001-10-03 12:09:30 +00004343 if (PyTuple_GET_SIZE(args) == 1) {
4344 arg = PyTuple_GET_ITEM(args, 0);
4345 i = getindex(self, arg);
4346 if (i == -1 && PyErr_Occurred())
4347 return NULL;
4348 return (*func)(self, i);
4349 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004350 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004351 assert(PyErr_Occurred());
4352 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004353}
4354
Tim Peters6d6c1a32001-08-02 04:15:00 +00004355static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004356wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004357{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004358 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
4359 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004360
Martin v. Löwis18e16552006-02-15 17:27:45 +00004361 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004362 return NULL;
4363 return (*func)(self, i, j);
4364}
4365
Tim Peters6d6c1a32001-08-02 04:15:00 +00004366static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004367wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004368{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004369 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4370 Py_ssize_t i;
4371 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004372 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004373
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004374 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004375 return NULL;
4376 i = getindex(self, arg);
4377 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004378 return NULL;
4379 res = (*func)(self, i, value);
4380 if (res == -1 && PyErr_Occurred())
4381 return NULL;
4382 Py_INCREF(Py_None);
4383 return Py_None;
4384}
4385
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004386static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004387wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004388{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004389 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4390 Py_ssize_t i;
4391 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004392 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004393
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004394 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004395 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004396 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004397 i = getindex(self, arg);
4398 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004399 return NULL;
4400 res = (*func)(self, i, NULL);
4401 if (res == -1 && PyErr_Occurred())
4402 return NULL;
4403 Py_INCREF(Py_None);
4404 return Py_None;
4405}
4406
Tim Peters6d6c1a32001-08-02 04:15:00 +00004407static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004408wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004409{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004410 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4411 Py_ssize_t i, j;
4412 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004413 PyObject *value;
4414
Martin v. Löwis18e16552006-02-15 17:27:45 +00004415 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004416 return NULL;
4417 res = (*func)(self, i, j, value);
4418 if (res == -1 && PyErr_Occurred())
4419 return NULL;
4420 Py_INCREF(Py_None);
4421 return Py_None;
4422}
4423
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004424static PyObject *
4425wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
4426{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004427 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4428 Py_ssize_t i, j;
4429 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004430
Martin v. Löwis18e16552006-02-15 17:27:45 +00004431 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004432 return NULL;
4433 res = (*func)(self, i, j, NULL);
4434 if (res == -1 && PyErr_Occurred())
4435 return NULL;
4436 Py_INCREF(Py_None);
4437 return Py_None;
4438}
4439
Tim Peters6d6c1a32001-08-02 04:15:00 +00004440/* XXX objobjproc is a misnomer; should be objargpred */
4441static PyObject *
4442wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4443{
4444 objobjproc func = (objobjproc)wrapped;
4445 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004446 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004447
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004448 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004449 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004450 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004451 res = (*func)(self, value);
4452 if (res == -1 && PyErr_Occurred())
4453 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004454 else
4455 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004456}
4457
Tim Peters6d6c1a32001-08-02 04:15:00 +00004458static PyObject *
4459wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4460{
4461 objobjargproc func = (objobjargproc)wrapped;
4462 int res;
4463 PyObject *key, *value;
4464
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004465 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004466 return NULL;
4467 res = (*func)(self, key, value);
4468 if (res == -1 && PyErr_Occurred())
4469 return NULL;
4470 Py_INCREF(Py_None);
4471 return Py_None;
4472}
4473
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004474static PyObject *
4475wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4476{
4477 objobjargproc func = (objobjargproc)wrapped;
4478 int res;
4479 PyObject *key;
4480
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004481 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004482 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004483 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004484 res = (*func)(self, key, NULL);
4485 if (res == -1 && PyErr_Occurred())
4486 return NULL;
4487 Py_INCREF(Py_None);
4488 return Py_None;
4489}
4490
Tim Peters6d6c1a32001-08-02 04:15:00 +00004491static PyObject *
4492wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
4493{
4494 cmpfunc func = (cmpfunc)wrapped;
4495 int res;
4496 PyObject *other;
4497
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004498 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004499 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004500 other = PyTuple_GET_ITEM(args, 0);
Christian Heimese93237d2007-12-19 02:37:44 +00004501 if (Py_TYPE(other)->tp_compare != func &&
4502 !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
Guido van Rossumceccae52001-09-18 20:03:57 +00004503 PyErr_Format(
4504 PyExc_TypeError,
4505 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +00004506 Py_TYPE(self)->tp_name,
4507 Py_TYPE(self)->tp_name,
4508 Py_TYPE(other)->tp_name);
Guido van Rossumceccae52001-09-18 20:03:57 +00004509 return NULL;
4510 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004511 res = (*func)(self, other);
4512 if (PyErr_Occurred())
4513 return NULL;
4514 return PyInt_FromLong((long)res);
4515}
4516
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004517/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004518 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004519static int
4520hackcheck(PyObject *self, setattrofunc func, char *what)
4521{
Christian Heimese93237d2007-12-19 02:37:44 +00004522 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004523 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4524 type = type->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004525 /* If type is NULL now, this is a really weird type.
4526 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004527 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004528 PyErr_Format(PyExc_TypeError,
4529 "can't apply this %s to %s object",
4530 what,
4531 type->tp_name);
4532 return 0;
4533 }
4534 return 1;
4535}
4536
Tim Peters6d6c1a32001-08-02 04:15:00 +00004537static PyObject *
4538wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4539{
4540 setattrofunc func = (setattrofunc)wrapped;
4541 int res;
4542 PyObject *name, *value;
4543
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004544 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004545 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004546 if (!hackcheck(self, func, "__setattr__"))
4547 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004548 res = (*func)(self, name, value);
4549 if (res < 0)
4550 return NULL;
4551 Py_INCREF(Py_None);
4552 return Py_None;
4553}
4554
4555static PyObject *
4556wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4557{
4558 setattrofunc func = (setattrofunc)wrapped;
4559 int res;
4560 PyObject *name;
4561
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004562 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004563 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004564 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004565 if (!hackcheck(self, func, "__delattr__"))
4566 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004567 res = (*func)(self, name, NULL);
4568 if (res < 0)
4569 return NULL;
4570 Py_INCREF(Py_None);
4571 return Py_None;
4572}
4573
Tim Peters6d6c1a32001-08-02 04:15:00 +00004574static PyObject *
4575wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4576{
4577 hashfunc func = (hashfunc)wrapped;
4578 long res;
4579
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004580 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004581 return NULL;
4582 res = (*func)(self);
4583 if (res == -1 && PyErr_Occurred())
4584 return NULL;
4585 return PyInt_FromLong(res);
4586}
4587
Tim Peters6d6c1a32001-08-02 04:15:00 +00004588static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004589wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004590{
4591 ternaryfunc func = (ternaryfunc)wrapped;
4592
Guido van Rossumc8e56452001-10-22 00:43:43 +00004593 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004594}
4595
Tim Peters6d6c1a32001-08-02 04:15:00 +00004596static PyObject *
4597wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4598{
4599 richcmpfunc func = (richcmpfunc)wrapped;
4600 PyObject *other;
4601
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004602 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004603 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004604 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004605 return (*func)(self, other, op);
4606}
4607
4608#undef RICHCMP_WRAPPER
4609#define RICHCMP_WRAPPER(NAME, OP) \
4610static PyObject * \
4611richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4612{ \
4613 return wrap_richcmpfunc(self, args, wrapped, OP); \
4614}
4615
Jack Jansen8e938b42001-08-08 15:29:49 +00004616RICHCMP_WRAPPER(lt, Py_LT)
4617RICHCMP_WRAPPER(le, Py_LE)
4618RICHCMP_WRAPPER(eq, Py_EQ)
4619RICHCMP_WRAPPER(ne, Py_NE)
4620RICHCMP_WRAPPER(gt, Py_GT)
4621RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004622
Tim Peters6d6c1a32001-08-02 04:15:00 +00004623static PyObject *
4624wrap_next(PyObject *self, PyObject *args, void *wrapped)
4625{
4626 unaryfunc func = (unaryfunc)wrapped;
4627 PyObject *res;
4628
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004629 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004630 return NULL;
4631 res = (*func)(self);
4632 if (res == NULL && !PyErr_Occurred())
4633 PyErr_SetNone(PyExc_StopIteration);
4634 return res;
4635}
4636
Tim Peters6d6c1a32001-08-02 04:15:00 +00004637static PyObject *
4638wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4639{
4640 descrgetfunc func = (descrgetfunc)wrapped;
4641 PyObject *obj;
4642 PyObject *type = NULL;
4643
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004644 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004645 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004646 if (obj == Py_None)
4647 obj = NULL;
4648 if (type == Py_None)
4649 type = NULL;
4650 if (type == NULL &&obj == NULL) {
4651 PyErr_SetString(PyExc_TypeError,
4652 "__get__(None, None) is invalid");
4653 return NULL;
4654 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004655 return (*func)(self, obj, type);
4656}
4657
Tim Peters6d6c1a32001-08-02 04:15:00 +00004658static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004659wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004660{
4661 descrsetfunc func = (descrsetfunc)wrapped;
4662 PyObject *obj, *value;
4663 int ret;
4664
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004665 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004666 return NULL;
4667 ret = (*func)(self, obj, value);
4668 if (ret < 0)
4669 return NULL;
4670 Py_INCREF(Py_None);
4671 return Py_None;
4672}
Guido van Rossum22b13872002-08-06 21:41:44 +00004673
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004674static PyObject *
4675wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4676{
4677 descrsetfunc func = (descrsetfunc)wrapped;
4678 PyObject *obj;
4679 int ret;
4680
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004681 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004682 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004683 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004684 ret = (*func)(self, obj, NULL);
4685 if (ret < 0)
4686 return NULL;
4687 Py_INCREF(Py_None);
4688 return Py_None;
4689}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004690
Tim Peters6d6c1a32001-08-02 04:15:00 +00004691static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004692wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004693{
4694 initproc func = (initproc)wrapped;
4695
Guido van Rossumc8e56452001-10-22 00:43:43 +00004696 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004697 return NULL;
4698 Py_INCREF(Py_None);
4699 return Py_None;
4700}
4701
Tim Peters6d6c1a32001-08-02 04:15:00 +00004702static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004703tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004704{
Barry Warsaw60f01882001-08-22 19:24:42 +00004705 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004706 PyObject *arg0, *res;
4707
4708 if (self == NULL || !PyType_Check(self))
4709 Py_FatalError("__new__() called with non-type 'self'");
4710 type = (PyTypeObject *)self;
4711 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004712 PyErr_Format(PyExc_TypeError,
4713 "%s.__new__(): not enough arguments",
4714 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004715 return NULL;
4716 }
4717 arg0 = PyTuple_GET_ITEM(args, 0);
4718 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004719 PyErr_Format(PyExc_TypeError,
4720 "%s.__new__(X): X is not a type object (%s)",
4721 type->tp_name,
Christian Heimese93237d2007-12-19 02:37:44 +00004722 Py_TYPE(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004723 return NULL;
4724 }
4725 subtype = (PyTypeObject *)arg0;
4726 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004727 PyErr_Format(PyExc_TypeError,
4728 "%s.__new__(%s): %s is not a subtype of %s",
4729 type->tp_name,
4730 subtype->tp_name,
4731 subtype->tp_name,
4732 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004733 return NULL;
4734 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004735
4736 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004737 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004738 most derived base that's not a heap type is this type. */
4739 staticbase = subtype;
4740 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4741 staticbase = staticbase->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004742 /* If staticbase is NULL now, it is a really weird type.
4743 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004744 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004745 PyErr_Format(PyExc_TypeError,
4746 "%s.__new__(%s) is not safe, use %s.__new__()",
4747 type->tp_name,
4748 subtype->tp_name,
4749 staticbase == NULL ? "?" : staticbase->tp_name);
4750 return NULL;
4751 }
4752
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004753 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4754 if (args == NULL)
4755 return NULL;
4756 res = type->tp_new(subtype, args, kwds);
4757 Py_DECREF(args);
4758 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004759}
4760
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004761static struct PyMethodDef tp_new_methoddef[] = {
Neal Norwitza84dcd72007-05-22 07:16:44 +00004762 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004763 PyDoc_STR("T.__new__(S, ...) -> "
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004764 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004765 {0}
4766};
4767
4768static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004769add_tp_new_wrapper(PyTypeObject *type)
4770{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004771 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004772
Guido van Rossum687ae002001-10-15 22:03:32 +00004773 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004774 return 0;
4775 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004776 if (func == NULL)
4777 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004778 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004779 Py_DECREF(func);
4780 return -1;
4781 }
4782 Py_DECREF(func);
4783 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004784}
4785
Guido van Rossumf040ede2001-08-07 16:40:56 +00004786/* Slot wrappers that call the corresponding __foo__ slot. See comments
4787 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004788
Guido van Rossumdc91b992001-08-08 22:26:22 +00004789#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004790static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004791FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004792{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004793 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004794 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004795}
4796
Guido van Rossumdc91b992001-08-08 22:26:22 +00004797#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004798static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004799FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004800{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004801 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004802 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004803}
4804
Guido van Rossumcd118802003-01-06 22:57:47 +00004805/* Boolean helper for SLOT1BINFULL().
4806 right.__class__ is a nontrivial subclass of left.__class__. */
4807static int
4808method_is_overloaded(PyObject *left, PyObject *right, char *name)
4809{
4810 PyObject *a, *b;
4811 int ok;
4812
Christian Heimese93237d2007-12-19 02:37:44 +00004813 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004814 if (b == NULL) {
4815 PyErr_Clear();
4816 /* If right doesn't have it, it's not overloaded */
4817 return 0;
4818 }
4819
Christian Heimese93237d2007-12-19 02:37:44 +00004820 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004821 if (a == NULL) {
4822 PyErr_Clear();
4823 Py_DECREF(b);
4824 /* If right has it but left doesn't, it's overloaded */
4825 return 1;
4826 }
4827
4828 ok = PyObject_RichCompareBool(a, b, Py_NE);
4829 Py_DECREF(a);
4830 Py_DECREF(b);
4831 if (ok < 0) {
4832 PyErr_Clear();
4833 return 0;
4834 }
4835
4836 return ok;
4837}
4838
Guido van Rossumdc91b992001-08-08 22:26:22 +00004839
4840#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004841static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004842FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004843{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004844 static PyObject *cache_str, *rcache_str; \
Christian Heimese93237d2007-12-19 02:37:44 +00004845 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4846 Py_TYPE(other)->tp_as_number != NULL && \
4847 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4848 if (Py_TYPE(self)->tp_as_number != NULL && \
4849 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004850 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004851 if (do_other && \
Christian Heimese93237d2007-12-19 02:37:44 +00004852 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004853 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004854 r = call_maybe( \
4855 other, ROPSTR, &rcache_str, "(O)", self); \
4856 if (r != Py_NotImplemented) \
4857 return r; \
4858 Py_DECREF(r); \
4859 do_other = 0; \
4860 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004861 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004862 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004863 if (r != Py_NotImplemented || \
Christian Heimese93237d2007-12-19 02:37:44 +00004864 Py_TYPE(other) == Py_TYPE(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004865 return r; \
4866 Py_DECREF(r); \
4867 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004868 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004869 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004870 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004871 } \
4872 Py_INCREF(Py_NotImplemented); \
4873 return Py_NotImplemented; \
4874}
4875
4876#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4877 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4878
4879#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4880static PyObject * \
4881FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4882{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004883 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004884 return call_method(self, OPSTR, &cache_str, \
4885 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004886}
4887
Martin v. Löwis18e16552006-02-15 17:27:45 +00004888static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004889slot_sq_length(PyObject *self)
4890{
Guido van Rossum2730b132001-08-28 18:22:14 +00004891 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004892 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004893 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004894
4895 if (res == NULL)
4896 return -1;
Neal Norwitz1872b1c2006-08-12 18:44:06 +00004897 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004898 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004899 if (len < 0) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00004900 if (!PyErr_Occurred())
4901 PyErr_SetString(PyExc_ValueError,
4902 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004903 return -1;
4904 }
Guido van Rossum26111622001-10-01 16:42:49 +00004905 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004906}
4907
Guido van Rossumf4593e02001-10-03 12:09:30 +00004908/* Super-optimized version of slot_sq_item.
4909 Other slots could do the same... */
4910static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004911slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004912{
4913 static PyObject *getitem_str;
4914 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4915 descrgetfunc f;
4916
4917 if (getitem_str == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00004918 getitem_str = PyString_InternFromString("__getitem__");
Guido van Rossumf4593e02001-10-03 12:09:30 +00004919 if (getitem_str == NULL)
4920 return NULL;
4921 }
Christian Heimese93237d2007-12-19 02:37:44 +00004922 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004923 if (func != NULL) {
Christian Heimese93237d2007-12-19 02:37:44 +00004924 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004925 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004926 else {
Christian Heimese93237d2007-12-19 02:37:44 +00004927 func = f(func, self, (PyObject *)(Py_TYPE(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004928 if (func == NULL) {
4929 return NULL;
4930 }
4931 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004932 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004933 if (ival != NULL) {
4934 args = PyTuple_New(1);
4935 if (args != NULL) {
4936 PyTuple_SET_ITEM(args, 0, ival);
4937 retval = PyObject_Call(func, args, NULL);
4938 Py_XDECREF(args);
4939 Py_XDECREF(func);
4940 return retval;
4941 }
4942 }
4943 }
4944 else {
4945 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4946 }
4947 Py_XDECREF(args);
4948 Py_XDECREF(ival);
4949 Py_XDECREF(func);
4950 return NULL;
4951}
4952
Benjamin Peterson712ee922008-08-24 18:10:20 +00004953static PyObject*
4954slot_sq_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j)
4955{
4956 static PyObject *getslice_str;
4957
4958 if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
4959 "use __getitem__", 1) < 0)
4960 return NULL;
4961 return call_method(self, "__getslice__", &getslice_str,
4962 "nn", i, j);
4963}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004964
4965static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004966slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004967{
4968 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004969 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004970
4971 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004972 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004973 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004974 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004975 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004976 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004977 if (res == NULL)
4978 return -1;
4979 Py_DECREF(res);
4980 return 0;
4981}
4982
4983static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004984slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004985{
4986 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004987 static PyObject *delslice_str, *setslice_str;
Benjamin Peterson712ee922008-08-24 18:10:20 +00004988
4989 if (value == NULL) {
4990 if (PyErr_WarnPy3k("in 3.x, __delslice__ has been removed; "
4991 "use __delitem__", 1) < 0)
4992 return -1;
Guido van Rossum2730b132001-08-28 18:22:14 +00004993 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004994 "(nn)", i, j);
Benjamin Peterson712ee922008-08-24 18:10:20 +00004995 }
4996 else {
4997 if (PyErr_WarnPy3k("in 3.x, __setslice__ has been removed; "
4998 "use __setitem__", 1) < 0)
4999 return -1;
Guido van Rossum2730b132001-08-28 18:22:14 +00005000 res = call_method(self, "__setslice__", &setslice_str,
Benjamin Peterson712ee922008-08-24 18:10:20 +00005001 "(nnO)", i, j, value);
5002 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005003 if (res == NULL)
5004 return -1;
5005 Py_DECREF(res);
5006 return 0;
5007}
5008
5009static int
5010slot_sq_contains(PyObject *self, PyObject *value)
5011{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005012 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00005013 int result = -1;
5014
Guido van Rossum60718732001-08-28 17:47:51 +00005015 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005016
Guido van Rossum55f20992001-10-01 17:18:22 +00005017 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005018 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005019 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005020 if (args == NULL)
5021 res = NULL;
5022 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005023 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005024 Py_DECREF(args);
5025 }
5026 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00005027 if (res != NULL) {
5028 result = PyObject_IsTrue(res);
5029 Py_DECREF(res);
5030 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005031 }
Tim Petersbf9b2442003-03-23 05:35:36 +00005032 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005033 /* Possible results: -1 and 1 */
5034 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00005035 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005036 }
Tim Petersbf9b2442003-03-23 05:35:36 +00005037 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005038}
5039
Tim Peters6d6c1a32001-08-02 04:15:00 +00005040#define slot_mp_length slot_sq_length
5041
Guido van Rossumdc91b992001-08-08 22:26:22 +00005042SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005043
5044static int
5045slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5046{
5047 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005048 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005049
5050 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00005051 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005052 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005053 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005054 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005055 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005056 if (res == NULL)
5057 return -1;
5058 Py_DECREF(res);
5059 return 0;
5060}
5061
Guido van Rossumdc91b992001-08-08 22:26:22 +00005062SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5063SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5064SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
5065SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
5066SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5067SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5068
Jeremy Hylton938ace62002-07-17 16:30:39 +00005069static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00005070
5071SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
5072 nb_power, "__pow__", "__rpow__")
5073
5074static PyObject *
5075slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5076{
Guido van Rossum2730b132001-08-28 18:22:14 +00005077 static PyObject *pow_str;
5078
Guido van Rossumdc91b992001-08-08 22:26:22 +00005079 if (modulus == Py_None)
5080 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00005081 /* Three-arg power doesn't use __rpow__. But ternary_op
5082 can call this when the second argument's type uses
5083 slot_nb_power, so check before calling self.__pow__. */
Christian Heimese93237d2007-12-19 02:37:44 +00005084 if (Py_TYPE(self)->tp_as_number != NULL &&
5085 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00005086 return call_method(self, "__pow__", &pow_str,
5087 "(OO)", other, modulus);
5088 }
5089 Py_INCREF(Py_NotImplemented);
5090 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005091}
5092
5093SLOT0(slot_nb_negative, "__neg__")
5094SLOT0(slot_nb_positive, "__pos__")
5095SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005096
5097static int
5098slot_nb_nonzero(PyObject *self)
5099{
Tim Petersea7f75d2002-12-07 21:39:16 +00005100 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00005101 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00005102 int result = -1;
Georg Brandled4cefb2009-03-15 21:43:38 +00005103 int using_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005104
Guido van Rossum55f20992001-10-01 17:18:22 +00005105 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005106 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00005107 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00005108 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00005109 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00005110 if (func == NULL)
5111 return PyErr_Occurred() ? -1 : 1;
Georg Brandled4cefb2009-03-15 21:43:38 +00005112 using_len = 1;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005113 }
Tim Petersea7f75d2002-12-07 21:39:16 +00005114 args = PyTuple_New(0);
5115 if (args != NULL) {
5116 PyObject *temp = PyObject_Call(func, args, NULL);
5117 Py_DECREF(args);
5118 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00005119 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00005120 result = PyObject_IsTrue(temp);
5121 else {
5122 PyErr_Format(PyExc_TypeError,
Georg Brandled4cefb2009-03-15 21:43:38 +00005123 "%s should return "
Jeremy Hylton090a3492003-06-27 16:46:45 +00005124 "bool or int, returned %s",
Georg Brandled4cefb2009-03-15 21:43:38 +00005125 (using_len ? "__len__"
5126 : "__nonzero__"),
Jeremy Hylton090a3492003-06-27 16:46:45 +00005127 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00005128 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00005129 }
Tim Petersea7f75d2002-12-07 21:39:16 +00005130 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00005131 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005132 }
Guido van Rossum55f20992001-10-01 17:18:22 +00005133 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00005134 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005135}
5136
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005137
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005138static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005139slot_nb_index(PyObject *self)
5140{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005141 static PyObject *index_str;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005142 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005143}
5144
5145
Guido van Rossumdc91b992001-08-08 22:26:22 +00005146SLOT0(slot_nb_invert, "__invert__")
5147SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5148SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5149SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5150SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5151SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005152
5153static int
5154slot_nb_coerce(PyObject **a, PyObject **b)
5155{
5156 static PyObject *coerce_str;
5157 PyObject *self = *a, *other = *b;
5158
5159 if (self->ob_type->tp_as_number != NULL &&
5160 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5161 PyObject *r;
5162 r = call_maybe(
5163 self, "__coerce__", &coerce_str, "(O)", other);
5164 if (r == NULL)
5165 return -1;
5166 if (r == Py_NotImplemented) {
5167 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005168 }
Guido van Rossum55f20992001-10-01 17:18:22 +00005169 else {
5170 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5171 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005172 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00005173 Py_DECREF(r);
5174 return -1;
5175 }
5176 *a = PyTuple_GET_ITEM(r, 0);
5177 Py_INCREF(*a);
5178 *b = PyTuple_GET_ITEM(r, 1);
5179 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005180 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00005181 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005182 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005183 }
5184 if (other->ob_type->tp_as_number != NULL &&
5185 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5186 PyObject *r;
5187 r = call_maybe(
5188 other, "__coerce__", &coerce_str, "(O)", self);
5189 if (r == NULL)
5190 return -1;
5191 if (r == Py_NotImplemented) {
5192 Py_DECREF(r);
5193 return 1;
5194 }
5195 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5196 PyErr_SetString(PyExc_TypeError,
5197 "__coerce__ didn't return a 2-tuple");
5198 Py_DECREF(r);
5199 return -1;
5200 }
5201 *a = PyTuple_GET_ITEM(r, 1);
5202 Py_INCREF(*a);
5203 *b = PyTuple_GET_ITEM(r, 0);
5204 Py_INCREF(*b);
5205 Py_DECREF(r);
5206 return 0;
5207 }
5208 return 1;
5209}
5210
Guido van Rossumdc91b992001-08-08 22:26:22 +00005211SLOT0(slot_nb_int, "__int__")
5212SLOT0(slot_nb_long, "__long__")
5213SLOT0(slot_nb_float, "__float__")
5214SLOT0(slot_nb_oct, "__oct__")
5215SLOT0(slot_nb_hex, "__hex__")
5216SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5217SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5218SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
5219SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
5220SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Martin v. Löwisfd963262007-02-09 12:19:32 +00005221/* Can't use SLOT1 here, because nb_inplace_power is ternary */
5222static PyObject *
5223slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5224{
5225 static PyObject *cache_str;
5226 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
5227}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005228SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5229SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5230SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5231SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5232SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5233SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
5234 "__floordiv__", "__rfloordiv__")
5235SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5236SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5237SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005238
5239static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00005240half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005241{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005242 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005243 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005244 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005245
Guido van Rossum60718732001-08-28 17:47:51 +00005246 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005247 if (func == NULL) {
5248 PyErr_Clear();
5249 }
5250 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005251 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005252 if (args == NULL)
5253 res = NULL;
5254 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005255 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005256 Py_DECREF(args);
5257 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00005258 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005259 if (res != Py_NotImplemented) {
5260 if (res == NULL)
5261 return -2;
5262 c = PyInt_AsLong(res);
5263 Py_DECREF(res);
5264 if (c == -1 && PyErr_Occurred())
5265 return -2;
5266 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
5267 }
5268 Py_DECREF(res);
5269 }
5270 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005271}
5272
Guido van Rossumab3b0342001-09-18 20:38:53 +00005273/* This slot is published for the benefit of try_3way_compare in object.c */
5274int
5275_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00005276{
5277 int c;
5278
Christian Heimese93237d2007-12-19 02:37:44 +00005279 if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005280 c = half_compare(self, other);
5281 if (c <= 1)
5282 return c;
5283 }
Christian Heimese93237d2007-12-19 02:37:44 +00005284 if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005285 c = half_compare(other, self);
5286 if (c < -1)
5287 return -2;
5288 if (c <= 1)
5289 return -c;
5290 }
5291 return (void *)self < (void *)other ? -1 :
5292 (void *)self > (void *)other ? 1 : 0;
5293}
5294
5295static PyObject *
5296slot_tp_repr(PyObject *self)
5297{
5298 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005299 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005300
Guido van Rossum60718732001-08-28 17:47:51 +00005301 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005302 if (func != NULL) {
5303 res = PyEval_CallObject(func, NULL);
5304 Py_DECREF(func);
5305 return res;
5306 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00005307 PyErr_Clear();
Gregory P. Smithdd96db62008-06-09 04:58:54 +00005308 return PyString_FromFormat("<%s object at %p>",
Christian Heimese93237d2007-12-19 02:37:44 +00005309 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005310}
5311
5312static PyObject *
5313slot_tp_str(PyObject *self)
5314{
5315 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005316 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005317
Guido van Rossum60718732001-08-28 17:47:51 +00005318 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005319 if (func != NULL) {
5320 res = PyEval_CallObject(func, NULL);
5321 Py_DECREF(func);
5322 return res;
5323 }
5324 else {
5325 PyErr_Clear();
5326 return slot_tp_repr(self);
5327 }
5328}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005329
5330static long
5331slot_tp_hash(PyObject *self)
5332{
Tim Peters61ce0a92002-12-06 23:38:02 +00005333 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00005334 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005335 long h;
5336
Guido van Rossum60718732001-08-28 17:47:51 +00005337 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005338
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005339 if (func != NULL && func != Py_None) {
Tim Peters61ce0a92002-12-06 23:38:02 +00005340 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005341 Py_DECREF(func);
5342 if (res == NULL)
5343 return -1;
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00005344 if (PyLong_Check(res))
Armin Rigo51fc8c42006-08-09 14:55:26 +00005345 h = PyLong_Type.tp_hash(res);
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00005346 else
5347 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00005348 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005349 }
5350 else {
Georg Brandl30b78042007-12-20 21:03:02 +00005351 Py_XDECREF(func); /* may be None */
Guido van Rossumb8f63662001-08-15 23:57:02 +00005352 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005353 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005354 if (func == NULL) {
5355 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005356 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005357 }
5358 if (func != NULL) {
5359 Py_DECREF(func);
Nick Coghlan53663a62008-07-15 14:27:37 +00005360 return PyObject_HashNotImplemented(self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005361 }
5362 PyErr_Clear();
5363 h = _Py_HashPointer((void *)self);
5364 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005365 if (h == -1 && !PyErr_Occurred())
5366 h = -2;
5367 return h;
5368}
5369
5370static PyObject *
5371slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5372{
Guido van Rossum60718732001-08-28 17:47:51 +00005373 static PyObject *call_str;
5374 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005375 PyObject *res;
5376
5377 if (meth == NULL)
5378 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00005379
Tim Peters6d6c1a32001-08-02 04:15:00 +00005380 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00005381
Tim Peters6d6c1a32001-08-02 04:15:00 +00005382 Py_DECREF(meth);
5383 return res;
5384}
5385
Guido van Rossum14a6f832001-10-17 13:59:09 +00005386/* There are two slot dispatch functions for tp_getattro.
5387
5388 - slot_tp_getattro() is used when __getattribute__ is overridden
5389 but no __getattr__ hook is present;
5390
5391 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5392
Guido van Rossumc334df52002-04-04 23:44:47 +00005393 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5394 detects the absence of __getattr__ and then installs the simpler slot if
5395 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005396
Tim Peters6d6c1a32001-08-02 04:15:00 +00005397static PyObject *
5398slot_tp_getattro(PyObject *self, PyObject *name)
5399{
Guido van Rossum14a6f832001-10-17 13:59:09 +00005400 static PyObject *getattribute_str = NULL;
5401 return call_method(self, "__getattribute__", &getattribute_str,
5402 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005403}
5404
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005405static PyObject *
Benjamin Peterson273c2332008-11-17 22:39:09 +00005406call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5407{
5408 PyObject *res, *descr = NULL;
5409 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
5410
5411 if (f != NULL) {
5412 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5413 if (descr == NULL)
5414 return NULL;
5415 else
5416 attr = descr;
5417 }
5418 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5419 Py_XDECREF(descr);
5420 return res;
5421}
5422
5423static PyObject *
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005424slot_tp_getattr_hook(PyObject *self, PyObject *name)
5425{
Christian Heimese93237d2007-12-19 02:37:44 +00005426 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005427 PyObject *getattr, *getattribute, *res;
5428 static PyObject *getattribute_str = NULL;
5429 static PyObject *getattr_str = NULL;
5430
5431 if (getattr_str == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00005432 getattr_str = PyString_InternFromString("__getattr__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005433 if (getattr_str == NULL)
5434 return NULL;
5435 }
5436 if (getattribute_str == NULL) {
5437 getattribute_str =
Gregory P. Smithdd96db62008-06-09 04:58:54 +00005438 PyString_InternFromString("__getattribute__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005439 if (getattribute_str == NULL)
5440 return NULL;
5441 }
Benjamin Peterson273c2332008-11-17 22:39:09 +00005442 /* speed hack: we could use lookup_maybe, but that would resolve the
5443 method fully for each attribute lookup for classes with
5444 __getattr__, even when the attribute is present. So we use
5445 _PyType_Lookup and create the method only when needed, with
5446 call_attribute. */
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005447 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005448 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005449 /* No __getattr__ hook: use a simpler dispatcher */
5450 tp->tp_getattro = slot_tp_getattro;
5451 return slot_tp_getattro(self, name);
5452 }
Benjamin Peterson273c2332008-11-17 22:39:09 +00005453 Py_INCREF(getattr);
5454 /* speed hack: we could use lookup_maybe, but that would resolve the
5455 method fully for each attribute lookup for classes with
5456 __getattr__, even when self has the default __getattribute__
5457 method. So we use _PyType_Lookup and create the method only when
5458 needed, with call_attribute. */
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005459 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005460 if (getattribute == NULL ||
Christian Heimese93237d2007-12-19 02:37:44 +00005461 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00005462 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5463 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005464 res = PyObject_GenericGetAttr(self, name);
Benjamin Peterson273c2332008-11-17 22:39:09 +00005465 else {
5466 Py_INCREF(getattribute);
5467 res = call_attribute(self, getattribute, name);
5468 Py_DECREF(getattribute);
5469 }
Guido van Rossum14a6f832001-10-17 13:59:09 +00005470 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005471 PyErr_Clear();
Benjamin Peterson273c2332008-11-17 22:39:09 +00005472 res = call_attribute(self, getattr, name);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005473 }
Benjamin Peterson273c2332008-11-17 22:39:09 +00005474 Py_DECREF(getattr);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005475 return res;
5476}
5477
Tim Peters6d6c1a32001-08-02 04:15:00 +00005478static int
5479slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5480{
5481 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005482 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005483
5484 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00005485 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005486 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005487 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005488 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005489 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005490 if (res == NULL)
5491 return -1;
5492 Py_DECREF(res);
5493 return 0;
5494}
5495
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005496static char *name_op[] = {
5497 "__lt__",
5498 "__le__",
5499 "__eq__",
5500 "__ne__",
5501 "__gt__",
5502 "__ge__",
5503};
5504
Tim Peters6d6c1a32001-08-02 04:15:00 +00005505static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005506half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005507{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005508 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005509 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005510
Guido van Rossum60718732001-08-28 17:47:51 +00005511 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005512 if (func == NULL) {
5513 PyErr_Clear();
5514 Py_INCREF(Py_NotImplemented);
5515 return Py_NotImplemented;
5516 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005517 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005518 if (args == NULL)
5519 res = NULL;
5520 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005521 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005522 Py_DECREF(args);
5523 }
5524 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005525 return res;
5526}
5527
Guido van Rossumb8f63662001-08-15 23:57:02 +00005528static PyObject *
5529slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5530{
5531 PyObject *res;
5532
Christian Heimese93237d2007-12-19 02:37:44 +00005533 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005534 res = half_richcompare(self, other, op);
5535 if (res != Py_NotImplemented)
5536 return res;
5537 Py_DECREF(res);
5538 }
Christian Heimese93237d2007-12-19 02:37:44 +00005539 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00005540 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005541 if (res != Py_NotImplemented) {
5542 return res;
5543 }
5544 Py_DECREF(res);
5545 }
5546 Py_INCREF(Py_NotImplemented);
5547 return Py_NotImplemented;
5548}
5549
5550static PyObject *
5551slot_tp_iter(PyObject *self)
5552{
5553 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005554 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005555
Guido van Rossum60718732001-08-28 17:47:51 +00005556 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005557 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00005558 PyObject *args;
5559 args = res = PyTuple_New(0);
5560 if (args != NULL) {
5561 res = PyObject_Call(func, args, NULL);
5562 Py_DECREF(args);
5563 }
5564 Py_DECREF(func);
5565 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005566 }
5567 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005568 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005569 if (func == NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00005570 PyErr_Format(PyExc_TypeError,
5571 "'%.200s' object is not iterable",
Christian Heimese93237d2007-12-19 02:37:44 +00005572 Py_TYPE(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005573 return NULL;
5574 }
5575 Py_DECREF(func);
5576 return PySeqIter_New(self);
5577}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005578
5579static PyObject *
5580slot_tp_iternext(PyObject *self)
5581{
Guido van Rossum2730b132001-08-28 18:22:14 +00005582 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00005583 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005584}
5585
Guido van Rossum1a493502001-08-17 16:47:50 +00005586static PyObject *
5587slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5588{
Christian Heimese93237d2007-12-19 02:37:44 +00005589 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00005590 PyObject *get;
5591 static PyObject *get_str = NULL;
5592
5593 if (get_str == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00005594 get_str = PyString_InternFromString("__get__");
Guido van Rossum1a493502001-08-17 16:47:50 +00005595 if (get_str == NULL)
5596 return NULL;
5597 }
5598 get = _PyType_Lookup(tp, get_str);
5599 if (get == NULL) {
5600 /* Avoid further slowdowns */
5601 if (tp->tp_descr_get == slot_tp_descr_get)
5602 tp->tp_descr_get = NULL;
5603 Py_INCREF(self);
5604 return self;
5605 }
Guido van Rossum2c252392001-08-24 10:13:31 +00005606 if (obj == NULL)
5607 obj = Py_None;
5608 if (type == NULL)
5609 type = Py_None;
Georg Brandl684fd0c2006-05-25 19:15:31 +00005610 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005611}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005612
5613static int
5614slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5615{
Guido van Rossum2c252392001-08-24 10:13:31 +00005616 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005617 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005618
5619 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00005620 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005621 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00005622 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005623 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005624 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005625 if (res == NULL)
5626 return -1;
5627 Py_DECREF(res);
5628 return 0;
5629}
5630
5631static int
5632slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5633{
Guido van Rossum60718732001-08-28 17:47:51 +00005634 static PyObject *init_str;
5635 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005636 PyObject *res;
5637
5638 if (meth == NULL)
5639 return -1;
5640 res = PyObject_Call(meth, args, kwds);
5641 Py_DECREF(meth);
5642 if (res == NULL)
5643 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005644 if (res != Py_None) {
Georg Brandlccff7852006-06-18 22:17:29 +00005645 PyErr_Format(PyExc_TypeError,
5646 "__init__() should return None, not '%.200s'",
Christian Heimese93237d2007-12-19 02:37:44 +00005647 Py_TYPE(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005648 Py_DECREF(res);
5649 return -1;
5650 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005651 Py_DECREF(res);
5652 return 0;
5653}
5654
5655static PyObject *
5656slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5657{
Guido van Rossum7bed2132002-08-08 21:57:53 +00005658 static PyObject *new_str;
5659 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005660 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005661 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005662
Guido van Rossum7bed2132002-08-08 21:57:53 +00005663 if (new_str == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00005664 new_str = PyString_InternFromString("__new__");
Guido van Rossum7bed2132002-08-08 21:57:53 +00005665 if (new_str == NULL)
5666 return NULL;
5667 }
5668 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005669 if (func == NULL)
5670 return NULL;
5671 assert(PyTuple_Check(args));
5672 n = PyTuple_GET_SIZE(args);
5673 newargs = PyTuple_New(n+1);
5674 if (newargs == NULL)
5675 return NULL;
5676 Py_INCREF(type);
5677 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5678 for (i = 0; i < n; i++) {
5679 x = PyTuple_GET_ITEM(args, i);
5680 Py_INCREF(x);
5681 PyTuple_SET_ITEM(newargs, i+1, x);
5682 }
5683 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005684 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005685 Py_DECREF(func);
5686 return x;
5687}
5688
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005689static void
5690slot_tp_del(PyObject *self)
5691{
5692 static PyObject *del_str = NULL;
5693 PyObject *del, *res;
5694 PyObject *error_type, *error_value, *error_traceback;
5695
5696 /* Temporarily resurrect the object. */
5697 assert(self->ob_refcnt == 0);
5698 self->ob_refcnt = 1;
5699
5700 /* Save the current exception, if any. */
5701 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5702
5703 /* Execute __del__ method, if any. */
5704 del = lookup_maybe(self, "__del__", &del_str);
5705 if (del != NULL) {
5706 res = PyEval_CallObject(del, NULL);
5707 if (res == NULL)
5708 PyErr_WriteUnraisable(del);
5709 else
5710 Py_DECREF(res);
5711 Py_DECREF(del);
5712 }
5713
5714 /* Restore the saved exception. */
5715 PyErr_Restore(error_type, error_value, error_traceback);
5716
5717 /* Undo the temporary resurrection; can't use DECREF here, it would
5718 * cause a recursive call.
5719 */
5720 assert(self->ob_refcnt > 0);
5721 if (--self->ob_refcnt == 0)
5722 return; /* this is the normal path out */
5723
5724 /* __del__ resurrected it! Make it look like the original Py_DECREF
5725 * never happened.
5726 */
5727 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005728 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005729 _Py_NewReference(self);
5730 self->ob_refcnt = refcnt;
5731 }
Christian Heimese93237d2007-12-19 02:37:44 +00005732 assert(!PyType_IS_GC(Py_TYPE(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005733 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005734 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5735 * we need to undo that. */
5736 _Py_DEC_REFTOTAL;
5737 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5738 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005739 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5740 * _Py_NewReference bumped tp_allocs: both of those need to be
5741 * undone.
5742 */
5743#ifdef COUNT_ALLOCS
Christian Heimese93237d2007-12-19 02:37:44 +00005744 --Py_TYPE(self)->tp_frees;
5745 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005746#endif
5747}
5748
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005749
5750/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005751 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005752 structure, which incorporates the additional structures used for numbers,
5753 sequences and mappings.
5754 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005755 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005756 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5757 terminated with an all-zero entry. (This table is further initialized and
5758 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005759
Guido van Rossum6d204072001-10-21 00:44:31 +00005760typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005761
5762#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005763#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005764#undef ETSLOT
5765#undef SQSLOT
5766#undef MPSLOT
5767#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005768#undef UNSLOT
5769#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005770#undef BINSLOT
5771#undef RBINSLOT
5772
Guido van Rossum6d204072001-10-21 00:44:31 +00005773#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005774 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5775 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005776#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5777 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005778 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005779#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005780 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005781 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005782#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5783 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5784#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5785 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5786#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5787 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5788#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5789 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5790 "x." NAME "() <==> " DOC)
5791#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5792 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5793 "x." NAME "(y) <==> x" DOC "y")
5794#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5795 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5796 "x." NAME "(y) <==> x" DOC "y")
5797#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5798 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5799 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005800#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5801 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5802 "x." NAME "(y) <==> " DOC)
5803#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5804 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5805 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005806
5807static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005808 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005809 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005810 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5811 The logic in abstract.c always falls back to nb_add/nb_multiply in
5812 this case. Defining both the nb_* and the sq_* slots to call the
5813 user-defined methods has unexpected side-effects, as shown by
5814 test_descr.notimplemented() */
5815 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005816 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00005817 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005818 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005819 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005820 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005821 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5822 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005823 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005824 "x.__getslice__(i, j) <==> x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005825 \n\
5826 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005827 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005828 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005829 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005830 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005831 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005832 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005833 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005834 \n\
5835 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005836 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005837 "x.__delslice__(i, j) <==> del x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005838 \n\
5839 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005840 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5841 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005842 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005843 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005844 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005845 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005846
Martin v. Löwis18e16552006-02-15 17:27:45 +00005847 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005848 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005849 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005850 wrap_binaryfunc,
5851 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005852 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005853 wrap_objobjargproc,
5854 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005855 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005856 wrap_delitem,
5857 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005858
Guido van Rossum6d204072001-10-21 00:44:31 +00005859 BINSLOT("__add__", nb_add, slot_nb_add,
5860 "+"),
5861 RBINSLOT("__radd__", nb_add, slot_nb_add,
5862 "+"),
5863 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5864 "-"),
5865 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5866 "-"),
5867 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5868 "*"),
5869 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5870 "*"),
5871 BINSLOT("__div__", nb_divide, slot_nb_divide,
5872 "/"),
5873 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5874 "/"),
5875 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5876 "%"),
5877 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5878 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005879 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005880 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005881 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005882 "divmod(y, x)"),
5883 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5884 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5885 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5886 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5887 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5888 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5889 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5890 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005891 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005892 "x != 0"),
5893 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5894 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5895 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5896 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5897 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5898 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5899 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5900 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5901 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5902 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5903 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5904 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5905 "x.__coerce__(y) <==> coerce(x, y)"),
5906 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5907 "int(x)"),
5908 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5909 "long(x)"),
5910 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5911 "float(x)"),
5912 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5913 "oct(x)"),
5914 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5915 "hex(x)"),
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005916 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005917 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005918 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5919 wrap_binaryfunc, "+"),
5920 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5921 wrap_binaryfunc, "-"),
5922 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5923 wrap_binaryfunc, "*"),
5924 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5925 wrap_binaryfunc, "/"),
5926 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5927 wrap_binaryfunc, "%"),
5928 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005929 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005930 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5931 wrap_binaryfunc, "<<"),
5932 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5933 wrap_binaryfunc, ">>"),
5934 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5935 wrap_binaryfunc, "&"),
5936 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5937 wrap_binaryfunc, "^"),
5938 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5939 wrap_binaryfunc, "|"),
5940 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5941 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5942 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5943 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5944 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5945 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5946 IBSLOT("__itruediv__", nb_inplace_true_divide,
5947 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005948
Guido van Rossum6d204072001-10-21 00:44:31 +00005949 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5950 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005951 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005952 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5953 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005954 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005955 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5956 "x.__cmp__(y) <==> cmp(x,y)"),
5957 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5958 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005959 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5960 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005961 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005962 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5963 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5964 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5965 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5966 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5967 "x.__setattr__('name', value) <==> x.name = value"),
5968 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5969 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5970 "x.__delattr__('name') <==> del x.name"),
5971 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5972 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5973 "x.__lt__(y) <==> x<y"),
5974 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5975 "x.__le__(y) <==> x<=y"),
5976 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5977 "x.__eq__(y) <==> x==y"),
5978 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5979 "x.__ne__(y) <==> x!=y"),
5980 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5981 "x.__gt__(y) <==> x>y"),
5982 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5983 "x.__ge__(y) <==> x>=y"),
5984 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5985 "x.__iter__() <==> iter(x)"),
5986 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5987 "x.next() -> the next value, or raise StopIteration"),
5988 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5989 "descr.__get__(obj[, type]) -> value"),
5990 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5991 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005992 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5993 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005994 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005995 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005996 "see x.__class__.__doc__ for signature",
5997 PyWrapperFlag_KEYWORDS),
5998 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005999 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006000 {NULL}
6001};
6002
Guido van Rossumc334df52002-04-04 23:44:47 +00006003/* Given a type pointer and an offset gotten from a slotdef entry, return a
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006004 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00006005 the offset to the type pointer, since it takes care to indirect through the
6006 proper indirection pointer (as_buffer, etc.); it returns NULL if the
6007 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006008static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00006009slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006010{
6011 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006012 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006013
Guido van Rossume5c691a2003-03-07 15:13:17 +00006014 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006015 assert(offset >= 0);
Skip Montanaro429433b2006-04-18 00:35:43 +00006016 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
6017 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00006018 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00006019 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006020 }
Skip Montanaro429433b2006-04-18 00:35:43 +00006021 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00006022 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00006023 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00006024 }
Skip Montanaro429433b2006-04-18 00:35:43 +00006025 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00006026 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00006027 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006028 }
6029 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00006030 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006031 }
6032 if (ptr != NULL)
6033 ptr += offset;
6034 return (void **)ptr;
6035}
Guido van Rossumf040ede2001-08-07 16:40:56 +00006036
Guido van Rossumc334df52002-04-04 23:44:47 +00006037/* Length of array of slotdef pointers used to store slots with the
6038 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
6039 the same __name__, for any __name__. Since that's a static property, it is
6040 appropriate to declare fixed-size arrays for this. */
6041#define MAX_EQUIV 10
6042
6043/* Return a slot pointer for a given name, but ONLY if the attribute has
6044 exactly one slot function. The name must be an interned string. */
6045static void **
6046resolve_slotdups(PyTypeObject *type, PyObject *name)
6047{
6048 /* XXX Maybe this could be optimized more -- but is it worth it? */
6049
6050 /* pname and ptrs act as a little cache */
6051 static PyObject *pname;
6052 static slotdef *ptrs[MAX_EQUIV];
6053 slotdef *p, **pp;
6054 void **res, **ptr;
6055
6056 if (pname != name) {
6057 /* Collect all slotdefs that match name into ptrs. */
6058 pname = name;
6059 pp = ptrs;
6060 for (p = slotdefs; p->name_strobj; p++) {
6061 if (p->name_strobj == name)
6062 *pp++ = p;
6063 }
6064 *pp = NULL;
6065 }
6066
6067 /* Look in all matching slots of the type; if exactly one of these has
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006068 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00006069 res = NULL;
6070 for (pp = ptrs; *pp; pp++) {
6071 ptr = slotptr(type, (*pp)->offset);
6072 if (ptr == NULL || *ptr == NULL)
6073 continue;
6074 if (res != NULL)
6075 return NULL;
6076 res = ptr;
6077 }
6078 return res;
6079}
6080
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006081/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00006082 does some incredibly complex thinking and then sticks something into the
6083 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
6084 interests, and then stores a generic wrapper or a specific function into
6085 the slot.) Return a pointer to the next slotdef with a different offset,
6086 because that's convenient for fixup_slot_dispatchers(). */
6087static slotdef *
6088update_one_slot(PyTypeObject *type, slotdef *p)
6089{
6090 PyObject *descr;
6091 PyWrapperDescrObject *d;
6092 void *generic = NULL, *specific = NULL;
6093 int use_generic = 0;
6094 int offset = p->offset;
6095 void **ptr = slotptr(type, offset);
6096
6097 if (ptr == NULL) {
6098 do {
6099 ++p;
6100 } while (p->offset == offset);
6101 return p;
6102 }
6103 do {
6104 descr = _PyType_Lookup(type, p->name_strobj);
Amaury Forgeot d'Arca40d5732009-01-12 23:36:55 +00006105 if (descr == NULL) {
6106 if (ptr == (void**)&type->tp_iternext) {
6107 specific = _PyObject_NextNotImplemented;
6108 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006109 continue;
Amaury Forgeot d'Arca40d5732009-01-12 23:36:55 +00006110 }
Christian Heimese93237d2007-12-19 02:37:44 +00006111 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00006112 void **tptr = resolve_slotdups(type, p->name_strobj);
6113 if (tptr == NULL || tptr == ptr)
6114 generic = p->function;
6115 d = (PyWrapperDescrObject *)descr;
6116 if (d->d_base->wrapper == p->wrapper &&
6117 PyType_IsSubtype(type, d->d_type))
6118 {
6119 if (specific == NULL ||
6120 specific == d->d_wrapped)
6121 specific = d->d_wrapped;
6122 else
6123 use_generic = 1;
6124 }
6125 }
Christian Heimese93237d2007-12-19 02:37:44 +00006126 else if (Py_TYPE(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00006127 PyCFunction_GET_FUNCTION(descr) ==
6128 (PyCFunction)tp_new_wrapper &&
Amaury Forgeot d'Arcbd55c522009-01-17 17:11:50 +00006129 ptr == (void**)&type->tp_new)
Guido van Rossum721f62e2002-08-09 02:14:34 +00006130 {
6131 /* The __new__ wrapper is not a wrapper descriptor,
6132 so must be special-cased differently.
6133 If we don't do this, creating an instance will
6134 always use slot_tp_new which will look up
6135 __new__ in the MRO which will call tp_new_wrapper
6136 which will look through the base classes looking
6137 for a static base and call its tp_new (usually
6138 PyType_GenericNew), after performing various
6139 sanity checks and constructing a new argument
6140 list. Cut all that nonsense short -- this speeds
6141 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00006142 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00006143 /* XXX I'm not 100% sure that there isn't a hole
6144 in this reasoning that requires additional
6145 sanity checks. I'll buy the first person to
6146 point out a bug in this reasoning a beer. */
6147 }
Nick Coghlan53663a62008-07-15 14:27:37 +00006148 else if (descr == Py_None &&
Amaury Forgeot d'Arcbd55c522009-01-17 17:11:50 +00006149 ptr == (void**)&type->tp_hash) {
Nick Coghlan53663a62008-07-15 14:27:37 +00006150 /* We specifically allow __hash__ to be set to None
6151 to prevent inheritance of the default
6152 implementation from object.__hash__ */
6153 specific = PyObject_HashNotImplemented;
6154 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006155 else {
6156 use_generic = 1;
6157 generic = p->function;
6158 }
6159 } while ((++p)->offset == offset);
6160 if (specific && !use_generic)
6161 *ptr = specific;
6162 else
6163 *ptr = generic;
6164 return p;
6165}
6166
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006167/* In the type, update the slots whose slotdefs are gathered in the pp array.
6168 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006169static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006170update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006171{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006172 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006173
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006174 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00006175 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006176 return 0;
6177}
6178
Guido van Rossumc334df52002-04-04 23:44:47 +00006179/* Comparison function for qsort() to compare slotdefs by their offset, and
6180 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006181static int
6182slotdef_cmp(const void *aa, const void *bb)
6183{
6184 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
6185 int c = a->offset - b->offset;
6186 if (c != 0)
6187 return c;
6188 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00006189 /* Cannot use a-b, as this gives off_t,
6190 which may lose precision when converted to int. */
6191 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006192}
6193
Guido van Rossumc334df52002-04-04 23:44:47 +00006194/* Initialize the slotdefs table by adding interned string objects for the
6195 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006196static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006197init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006198{
6199 slotdef *p;
6200 static int initialized = 0;
6201
6202 if (initialized)
6203 return;
6204 for (p = slotdefs; p->name; p++) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00006205 p->name_strobj = PyString_InternFromString(p->name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006206 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00006207 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006208 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006209 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
6210 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006211 initialized = 1;
6212}
6213
Guido van Rossumc334df52002-04-04 23:44:47 +00006214/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006215static int
6216update_slot(PyTypeObject *type, PyObject *name)
6217{
Guido van Rossumc334df52002-04-04 23:44:47 +00006218 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006219 slotdef *p;
6220 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006221 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006222
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00006223 /* Clear the VALID_VERSION flag of 'type' and all its
6224 subclasses. This could possibly be unified with the
6225 update_subclasses() recursion below, but carefully:
6226 they each have their own conditions on which to stop
6227 recursing into subclasses. */
Georg Brandl74a1dea2008-05-28 11:21:39 +00006228 PyType_Modified(type);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00006229
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006230 init_slotdefs();
6231 pp = ptrs;
6232 for (p = slotdefs; p->name; p++) {
6233 /* XXX assume name is interned! */
6234 if (p->name_strobj == name)
6235 *pp++ = p;
6236 }
6237 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006238 for (pp = ptrs; *pp; pp++) {
6239 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006240 offset = p->offset;
6241 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006242 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006243 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006244 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006245 if (ptrs[0] == NULL)
6246 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006247 return update_subclasses(type, name,
6248 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006249}
6250
Guido van Rossumc334df52002-04-04 23:44:47 +00006251/* Store the proper functions in the slot dispatches at class (type)
6252 definition time, based upon which operations the class overrides in its
6253 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006254static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006255fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006256{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006257 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006258
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006259 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00006260 for (p = slotdefs; p->name; )
6261 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006262}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006263
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006264static void
6265update_all_slots(PyTypeObject* type)
6266{
6267 slotdef *p;
6268
6269 init_slotdefs();
6270 for (p = slotdefs; p->name; p++) {
6271 /* update_slot returns int but can't actually fail */
6272 update_slot(type, p->name_strobj);
6273 }
6274}
6275
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006276/* recurse_down_subclasses() and update_subclasses() are mutually
6277 recursive functions to call a callback for all subclasses,
6278 but refraining from recursing into subclasses that define 'name'. */
6279
6280static int
6281update_subclasses(PyTypeObject *type, PyObject *name,
6282 update_callback callback, void *data)
6283{
6284 if (callback(type, data) < 0)
6285 return -1;
6286 return recurse_down_subclasses(type, name, callback, data);
6287}
6288
6289static int
6290recurse_down_subclasses(PyTypeObject *type, PyObject *name,
6291 update_callback callback, void *data)
6292{
6293 PyTypeObject *subclass;
6294 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006295 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006296
6297 subclasses = type->tp_subclasses;
6298 if (subclasses == NULL)
6299 return 0;
6300 assert(PyList_Check(subclasses));
6301 n = PyList_GET_SIZE(subclasses);
6302 for (i = 0; i < n; i++) {
6303 ref = PyList_GET_ITEM(subclasses, i);
6304 assert(PyWeakref_CheckRef(ref));
6305 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6306 assert(subclass != NULL);
6307 if ((PyObject *)subclass == Py_None)
6308 continue;
6309 assert(PyType_Check(subclass));
6310 /* Avoid recursing down into unaffected classes */
6311 dict = subclass->tp_dict;
6312 if (dict != NULL && PyDict_Check(dict) &&
6313 PyDict_GetItem(dict, name) != NULL)
6314 continue;
6315 if (update_subclasses(subclass, name, callback, data) < 0)
6316 return -1;
6317 }
6318 return 0;
6319}
6320
Guido van Rossum6d204072001-10-21 00:44:31 +00006321/* This function is called by PyType_Ready() to populate the type's
6322 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006323 function slot (like tp_repr) that's defined in the type, one or more
6324 corresponding descriptors are added in the type's tp_dict dictionary
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006325 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006326 cause more than one descriptor to be added (for example, the nb_add
6327 slot adds both __add__ and __radd__ descriptors) and some function
6328 slots compete for the same descriptor (for example both sq_item and
6329 mp_subscript generate a __getitem__ descriptor).
6330
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006331 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006332 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006333 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006334 between competing slots: the members of PyHeapTypeObject are listed
6335 from most general to least general, so the most general slot is
6336 preferred. In particular, because as_mapping comes before as_sequence,
6337 for a type that defines both mp_subscript and sq_item, mp_subscript
6338 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006339
6340 This only adds new descriptors and doesn't overwrite entries in
6341 tp_dict that were previously defined. The descriptors contain a
6342 reference to the C function they must call, so that it's safe if they
6343 are copied into a subtype's __dict__ and the subtype has a different
6344 C function in its slot -- calling the method defined by the
6345 descriptor will call the C function that was used to create it,
6346 rather than the C function present in the slot when it is called.
6347 (This is important because a subtype may have a C function in the
6348 slot that calls the method from the dictionary, and we want to avoid
6349 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006350
6351static int
6352add_operators(PyTypeObject *type)
6353{
6354 PyObject *dict = type->tp_dict;
6355 slotdef *p;
6356 PyObject *descr;
6357 void **ptr;
6358
6359 init_slotdefs();
6360 for (p = slotdefs; p->name; p++) {
6361 if (p->wrapper == NULL)
6362 continue;
6363 ptr = slotptr(type, p->offset);
6364 if (!ptr || !*ptr)
6365 continue;
6366 if (PyDict_GetItem(dict, p->name_strobj))
6367 continue;
Nick Coghlan53663a62008-07-15 14:27:37 +00006368 if (*ptr == PyObject_HashNotImplemented) {
6369 /* Classes may prevent the inheritance of the tp_hash
6370 slot by storing PyObject_HashNotImplemented in it. Make it
6371 visible as a None value for the __hash__ attribute. */
6372 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6373 return -1;
6374 }
6375 else {
6376 descr = PyDescr_NewWrapper(type, p, *ptr);
6377 if (descr == NULL)
6378 return -1;
6379 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6380 return -1;
6381 Py_DECREF(descr);
6382 }
Guido van Rossum6d204072001-10-21 00:44:31 +00006383 }
6384 if (type->tp_new != NULL) {
6385 if (add_tp_new_wrapper(type) < 0)
6386 return -1;
6387 }
6388 return 0;
6389}
6390
Guido van Rossum705f0f52001-08-24 16:47:00 +00006391
6392/* Cooperative 'super' */
6393
6394typedef struct {
6395 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00006396 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006397 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006398 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006399} superobject;
6400
Guido van Rossum6f799372001-09-20 20:46:19 +00006401static PyMemberDef super_members[] = {
6402 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6403 "the class invoking super()"},
6404 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6405 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006406 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00006407 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006408 {0}
6409};
6410
Guido van Rossum705f0f52001-08-24 16:47:00 +00006411static void
6412super_dealloc(PyObject *self)
6413{
6414 superobject *su = (superobject *)self;
6415
Guido van Rossum048eb752001-10-02 21:24:57 +00006416 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006417 Py_XDECREF(su->obj);
6418 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006419 Py_XDECREF(su->obj_type);
Christian Heimese93237d2007-12-19 02:37:44 +00006420 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006421}
6422
6423static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006424super_repr(PyObject *self)
6425{
6426 superobject *su = (superobject *)self;
6427
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006428 if (su->obj_type)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00006429 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00006430 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006431 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006432 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006433 else
Gregory P. Smithdd96db62008-06-09 04:58:54 +00006434 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00006435 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006436 su->type ? su->type->tp_name : "NULL");
6437}
6438
6439static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006440super_getattro(PyObject *self, PyObject *name)
6441{
6442 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006443 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006444
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006445 if (!skip) {
6446 /* We want __class__ to return the class of the super object
6447 (i.e. super, or a subclass), not the class of su->obj. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00006448 skip = (PyString_Check(name) &&
6449 PyString_GET_SIZE(name) == 9 &&
6450 strcmp(PyString_AS_STRING(name), "__class__") == 0);
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006451 }
6452
6453 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00006454 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006455 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006456 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006457 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006458
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006459 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006460 mro = starttype->tp_mro;
6461
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006462 if (mro == NULL)
6463 n = 0;
6464 else {
6465 assert(PyTuple_Check(mro));
6466 n = PyTuple_GET_SIZE(mro);
6467 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006468 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00006469 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00006470 break;
6471 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006472 i++;
6473 res = NULL;
6474 for (; i < n; i++) {
6475 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00006476 if (PyType_Check(tmp))
6477 dict = ((PyTypeObject *)tmp)->tp_dict;
6478 else if (PyClass_Check(tmp))
6479 dict = ((PyClassObject *)tmp)->cl_dict;
6480 else
6481 continue;
6482 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00006483 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00006484 Py_INCREF(res);
Christian Heimese93237d2007-12-19 02:37:44 +00006485 f = Py_TYPE(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006486 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006487 tmp = f(res,
6488 /* Only pass 'obj' param if
6489 this is instance-mode super
6490 (See SF ID #743627)
6491 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00006492 (su->obj == (PyObject *)
6493 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006494 ? (PyObject *)NULL
6495 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00006496 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006497 Py_DECREF(res);
6498 res = tmp;
6499 }
6500 return res;
6501 }
6502 }
6503 }
6504 return PyObject_GenericGetAttr(self, name);
6505}
6506
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006507static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006508supercheck(PyTypeObject *type, PyObject *obj)
6509{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006510 /* Check that a super() call makes sense. Return a type object.
6511
6512 obj can be a new-style class, or an instance of one:
6513
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006514 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006515 used for class methods; the return value is obj.
6516
6517 - If it is an instance, it must be an instance of 'type'. This is
6518 the normal case; the return value is obj.__class__.
6519
6520 But... when obj is an instance, we want to allow for the case where
Christian Heimese93237d2007-12-19 02:37:44 +00006521 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006522 This will allow using super() with a proxy for obj.
6523 */
6524
Guido van Rossum8e80a722003-02-18 19:22:22 +00006525 /* Check for first bullet above (special case) */
6526 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6527 Py_INCREF(obj);
6528 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006529 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006530
6531 /* Normal case */
Christian Heimese93237d2007-12-19 02:37:44 +00006532 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6533 Py_INCREF(Py_TYPE(obj));
6534 return Py_TYPE(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006535 }
6536 else {
6537 /* Try the slow way */
6538 static PyObject *class_str = NULL;
6539 PyObject *class_attr;
6540
6541 if (class_str == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00006542 class_str = PyString_FromString("__class__");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006543 if (class_str == NULL)
6544 return NULL;
6545 }
6546
6547 class_attr = PyObject_GetAttr(obj, class_str);
6548
6549 if (class_attr != NULL &&
6550 PyType_Check(class_attr) &&
Christian Heimese93237d2007-12-19 02:37:44 +00006551 (PyTypeObject *)class_attr != Py_TYPE(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006552 {
6553 int ok = PyType_IsSubtype(
6554 (PyTypeObject *)class_attr, type);
6555 if (ok)
6556 return (PyTypeObject *)class_attr;
6557 }
6558
6559 if (class_attr == NULL)
6560 PyErr_Clear();
6561 else
6562 Py_DECREF(class_attr);
6563 }
6564
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006565 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006566 "super(type, obj): "
6567 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006568 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006569}
6570
Guido van Rossum705f0f52001-08-24 16:47:00 +00006571static PyObject *
6572super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6573{
6574 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00006575 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006576
6577 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6578 /* Not binding to an object, or already bound */
6579 Py_INCREF(self);
6580 return self;
6581 }
Christian Heimese93237d2007-12-19 02:37:44 +00006582 if (Py_TYPE(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00006583 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006584 call its type */
Christian Heimese93237d2007-12-19 02:37:44 +00006585 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006586 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00006587 else {
6588 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006589 PyTypeObject *obj_type = supercheck(su->type, obj);
6590 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006591 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00006592 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006593 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00006594 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006595 return NULL;
6596 Py_INCREF(su->type);
6597 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00006598 newobj->type = su->type;
6599 newobj->obj = obj;
6600 newobj->obj_type = obj_type;
6601 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006602 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006603}
6604
6605static int
6606super_init(PyObject *self, PyObject *args, PyObject *kwds)
6607{
6608 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00006609 PyTypeObject *type;
6610 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006611 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006612
Georg Brandl5d59c092006-09-30 08:43:30 +00006613 if (!_PyArg_NoKeywords("super", kwds))
6614 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006615 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
6616 return -1;
6617 if (obj == Py_None)
6618 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006619 if (obj != NULL) {
6620 obj_type = supercheck(type, obj);
6621 if (obj_type == NULL)
6622 return -1;
6623 Py_INCREF(obj);
6624 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006625 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006626 su->type = type;
6627 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006628 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006629 return 0;
6630}
6631
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006632PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00006633"super(type) -> unbound super object\n"
6634"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006635"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006636"Typical use to call a cooperative superclass method:\n"
6637"class C(B):\n"
6638" def meth(self, arg):\n"
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006639" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006640
Guido van Rossum048eb752001-10-02 21:24:57 +00006641static int
6642super_traverse(PyObject *self, visitproc visit, void *arg)
6643{
6644 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006645
Thomas Woutersc6e55062006-04-15 21:47:09 +00006646 Py_VISIT(su->obj);
6647 Py_VISIT(su->type);
6648 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006649
6650 return 0;
6651}
6652
Guido van Rossum705f0f52001-08-24 16:47:00 +00006653PyTypeObject PySuper_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00006654 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00006655 "super", /* tp_name */
6656 sizeof(superobject), /* tp_basicsize */
6657 0, /* tp_itemsize */
6658 /* methods */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006659 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006660 0, /* tp_print */
6661 0, /* tp_getattr */
6662 0, /* tp_setattr */
6663 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006664 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006665 0, /* tp_as_number */
6666 0, /* tp_as_sequence */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006667 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006668 0, /* tp_hash */
6669 0, /* tp_call */
6670 0, /* tp_str */
6671 super_getattro, /* tp_getattro */
6672 0, /* tp_setattro */
6673 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006674 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6675 Py_TPFLAGS_BASETYPE, /* tp_flags */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006676 super_doc, /* tp_doc */
6677 super_traverse, /* tp_traverse */
6678 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006679 0, /* tp_richcompare */
6680 0, /* tp_weaklistoffset */
6681 0, /* tp_iter */
6682 0, /* tp_iternext */
6683 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006684 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006685 0, /* tp_getset */
6686 0, /* tp_base */
6687 0, /* tp_dict */
6688 super_descr_get, /* tp_descr_get */
6689 0, /* tp_descr_set */
6690 0, /* tp_dictoffset */
6691 super_init, /* tp_init */
6692 PyType_GenericAlloc, /* tp_alloc */
6693 PyType_GenericNew, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006694 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006695};