blob: c3aa0905855787d7e06e7c8319a7e14a462cec4f [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00008
9/* Support type attribute cache */
10
11/* The cache can keep references to the names alive for longer than
12 they normally would. This is why the maximum size is limited to
13 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
14 strings are used as attribute names. */
15#define MCACHE_MAX_ATTR_SIZE 100
16#define MCACHE_SIZE_EXP 10
17#define MCACHE_HASH(version, name_hash) \
18 (((unsigned int)(version) * (unsigned int)(name_hash)) \
19 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
20#define MCACHE_HASH_METHOD(type, name) \
21 MCACHE_HASH((type)->tp_version_tag, \
22 ((PyStringObject *)(name))->ob_shash)
23#define MCACHE_CACHEABLE_NAME(name) \
24 PyString_CheckExact(name) && \
25 PyString_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
26
27struct method_cache_entry {
28 unsigned int version;
29 PyObject *name; /* reference to exactly a str or None */
30 PyObject *value; /* borrowed */
31};
32
33static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
34static unsigned int next_version_tag = 0;
Christian Heimes908caac2008-01-27 23:34:59 +000035static void type_modified(PyTypeObject *);
36
37unsigned int
38PyType_ClearCache(void)
39{
40 Py_ssize_t i;
41 unsigned int cur_version_tag = next_version_tag - 1;
42
43 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
44 method_cache[i].version = 0;
45 Py_CLEAR(method_cache[i].name);
46 method_cache[i].value = NULL;
47 }
48 next_version_tag = 0;
49 /* mark all version tags as invalid */
50 type_modified(&PyBaseObject_Type);
51 return cur_version_tag;
52}
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000053
54static void
55type_modified(PyTypeObject *type)
56{
57 /* Invalidate any cached data for the specified type and all
58 subclasses. This function is called after the base
59 classes, mro, or attributes of the type are altered.
60
61 Invariants:
62
63 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
64 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
65 objects coming from non-recompiled extension modules)
66
67 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
68 it must first be set on all super types.
69
70 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
71 type (so it must first clear it on all subclasses). The
72 tp_version_tag value is meaningless unless this flag is set.
73 We don't assign new version tags eagerly, but only as
74 needed.
75 */
76 PyObject *raw, *ref;
77 Py_ssize_t i, n;
78
Neal Norwitze7bb9182008-01-27 17:10:14 +000079 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +000080 return;
81
82 raw = type->tp_subclasses;
83 if (raw != NULL) {
84 n = PyList_GET_SIZE(raw);
85 for (i = 0; i < n; i++) {
86 ref = PyList_GET_ITEM(raw, i);
87 ref = PyWeakref_GET_OBJECT(ref);
88 if (ref != Py_None) {
89 type_modified((PyTypeObject *)ref);
90 }
91 }
92 }
93 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
94}
95
96static void
97type_mro_modified(PyTypeObject *type, PyObject *bases) {
98 /*
99 Check that all base classes or elements of the mro of type are
100 able to be cached. This function is called after the base
101 classes or mro of the type are altered.
102
103 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
104 inherits from an old-style class, either directly or if it
105 appears in the MRO of a new-style class. No support either for
106 custom MROs that include types that are not officially super
107 types.
108
109 Called from mro_internal, which will subsequently be called on
110 each subclass when their mro is recursively updated.
111 */
112 Py_ssize_t i, n;
113 int clear = 0;
114
Neal Norwitze7bb9182008-01-27 17:10:14 +0000115 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000116 return;
117
118 n = PyTuple_GET_SIZE(bases);
119 for (i = 0; i < n; i++) {
120 PyObject *b = PyTuple_GET_ITEM(bases, i);
121 PyTypeObject *cls;
122
123 if (!PyType_Check(b) ) {
124 clear = 1;
125 break;
126 }
127
128 cls = (PyTypeObject *)b;
129
130 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
131 !PyType_IsSubtype(type, cls)) {
132 clear = 1;
133 break;
134 }
135 }
136
137 if (clear)
138 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
139 Py_TPFLAGS_VALID_VERSION_TAG);
140}
141
142static int
143assign_version_tag(PyTypeObject *type)
144{
145 /* Ensure that the tp_version_tag is valid and set
146 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
147 must first be done on all super classes. Return 0 if this
148 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
149 */
150 Py_ssize_t i, n;
151 PyObject *bases;
152
153 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
154 return 1;
155 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
156 return 0;
157 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
158 return 0;
159
160 type->tp_version_tag = next_version_tag++;
161 /* for stress-testing: next_version_tag &= 0xFF; */
162
163 if (type->tp_version_tag == 0) {
164 /* wrap-around or just starting Python - clear the whole
165 cache by filling names with references to Py_None.
166 Values are also set to NULL for added protection, as they
167 are borrowed reference */
168 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
169 method_cache[i].value = NULL;
170 Py_XDECREF(method_cache[i].name);
171 method_cache[i].name = Py_None;
172 Py_INCREF(Py_None);
173 }
174 /* mark all version tags as invalid */
175 type_modified(&PyBaseObject_Type);
176 return 1;
177 }
178 bases = type->tp_bases;
179 n = PyTuple_GET_SIZE(bases);
180 for (i = 0; i < n; i++) {
181 PyObject *b = PyTuple_GET_ITEM(bases, i);
182 assert(PyType_Check(b));
183 if (!assign_version_tag((PyTypeObject *)b))
184 return 0;
185 }
186 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
187 return 1;
188}
189
190
Guido van Rossum6f799372001-09-20 20:46:19 +0000191static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000192 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
193 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
194 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +0000195 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000196 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
197 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
198 {"__dictoffset__", T_LONG,
199 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000200 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
201 {0}
202};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000204static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +0000205type_name(PyTypeObject *type, void *context)
206{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000207 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +0000208
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000209 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +0000210 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +0000211
Georg Brandlc255c7b2006-02-20 22:27:28 +0000212 Py_INCREF(et->ht_name);
213 return et->ht_name;
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000214 }
215 else {
216 s = strrchr(type->tp_name, '.');
217 if (s == NULL)
218 s = type->tp_name;
219 else
220 s++;
221 return PyString_FromString(s);
222 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000223}
224
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000225static int
226type_set_name(PyTypeObject *type, PyObject *value, void *context)
227{
Guido van Rossume5c691a2003-03-07 15:13:17 +0000228 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000229
230 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
231 PyErr_Format(PyExc_TypeError,
232 "can't set %s.__name__", type->tp_name);
233 return -1;
234 }
235 if (!value) {
236 PyErr_Format(PyExc_TypeError,
237 "can't delete %s.__name__", type->tp_name);
238 return -1;
239 }
240 if (!PyString_Check(value)) {
241 PyErr_Format(PyExc_TypeError,
242 "can only assign string to %s.__name__, not '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +0000243 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000244 return -1;
245 }
Tim Petersea7f75d2002-12-07 21:39:16 +0000246 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000247 != (size_t)PyString_GET_SIZE(value)) {
248 PyErr_Format(PyExc_ValueError,
249 "__name__ must not contain null bytes");
250 return -1;
251 }
252
Guido van Rossume5c691a2003-03-07 15:13:17 +0000253 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000254
255 Py_INCREF(value);
256
Georg Brandlc255c7b2006-02-20 22:27:28 +0000257 Py_DECREF(et->ht_name);
258 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000259
260 type->tp_name = PyString_AS_STRING(value);
261
262 return 0;
263}
264
Guido van Rossumc3542212001-08-16 09:18:56 +0000265static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000266type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000267{
Guido van Rossumc3542212001-08-16 09:18:56 +0000268 PyObject *mod;
269 char *s;
270
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000271 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
272 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +0000273 if (!mod) {
274 PyErr_Format(PyExc_AttributeError, "__module__");
275 return 0;
276 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000277 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +0000278 return mod;
279 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000280 else {
281 s = strrchr(type->tp_name, '.');
282 if (s != NULL)
283 return PyString_FromStringAndSize(
Armin Rigo7ccbca92006-10-04 12:17:45 +0000284 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000285 return PyString_FromString("__builtin__");
286 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000287}
288
Guido van Rossum3926a632001-09-25 16:25:58 +0000289static int
290type_set_module(PyTypeObject *type, PyObject *value, void *context)
291{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000292 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000293 PyErr_Format(PyExc_TypeError,
294 "can't set %s.__module__", type->tp_name);
295 return -1;
296 }
297 if (!value) {
298 PyErr_Format(PyExc_TypeError,
299 "can't delete %s.__module__", type->tp_name);
300 return -1;
301 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000302
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +0000303 type_modified(type);
304
Guido van Rossum3926a632001-09-25 16:25:58 +0000305 return PyDict_SetItemString(type->tp_dict, "__module__", value);
306}
307
Tim Peters6d6c1a32001-08-02 04:15:00 +0000308static PyObject *
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +0000309type_abstractmethods(PyTypeObject *type, void *context)
310{
311 PyObject *mod = PyDict_GetItemString(type->tp_dict,
312 "__abstractmethods__");
313 if (!mod) {
314 PyErr_Format(PyExc_AttributeError, "__abstractmethods__");
315 return NULL;
316 }
317 Py_XINCREF(mod);
318 return mod;
319}
320
321static int
322type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
323{
324 /* __abstractmethods__ should only be set once on a type, in
325 abc.ABCMeta.__new__, so this function doesn't do anything
326 special to update subclasses.
327 */
328 int res = PyDict_SetItemString(type->tp_dict,
329 "__abstractmethods__", value);
330 if (res == 0) {
331 type_modified(type);
332 if (value && PyObject_IsTrue(value)) {
333 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
334 }
335 else {
336 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
337 }
338 }
339 return res;
340}
341
342static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000343type_get_bases(PyTypeObject *type, void *context)
344{
345 Py_INCREF(type->tp_bases);
346 return type->tp_bases;
347}
348
349static PyTypeObject *best_base(PyObject *);
350static int mro_internal(PyTypeObject *);
351static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
352static int add_subclass(PyTypeObject*, PyTypeObject*);
353static void remove_subclass(PyTypeObject *, PyTypeObject *);
354static void update_all_slots(PyTypeObject *);
355
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000356typedef int (*update_callback)(PyTypeObject *, void *);
357static int update_subclasses(PyTypeObject *type, PyObject *name,
358 update_callback callback, void *data);
359static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
360 update_callback callback, void *data);
361
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000362static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000363mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000364{
365 PyTypeObject *subclass;
366 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000367 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000368
369 subclasses = type->tp_subclasses;
370 if (subclasses == NULL)
371 return 0;
372 assert(PyList_Check(subclasses));
373 n = PyList_GET_SIZE(subclasses);
374 for (i = 0; i < n; i++) {
375 ref = PyList_GET_ITEM(subclasses, i);
376 assert(PyWeakref_CheckRef(ref));
377 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
378 assert(subclass != NULL);
379 if ((PyObject *)subclass == Py_None)
380 continue;
381 assert(PyType_Check(subclass));
382 old_mro = subclass->tp_mro;
383 if (mro_internal(subclass) < 0) {
384 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000385 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000386 }
387 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000388 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000389 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000390 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000391 if (!tuple)
392 return -1;
393 if (PyList_Append(temp, tuple) < 0)
394 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000395 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000396 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000397 if (mro_subclasses(subclass, temp) < 0)
398 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000399 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000400 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000401}
402
403static int
404type_set_bases(PyTypeObject *type, PyObject *value, void *context)
405{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000406 Py_ssize_t i;
407 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000408 PyObject *ob, *temp;
Armin Rigoc0ba52d2007-04-19 14:44:48 +0000409 PyTypeObject *new_base, *old_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000410 PyObject *old_bases, *old_mro;
411
412 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
413 PyErr_Format(PyExc_TypeError,
414 "can't set %s.__bases__", type->tp_name);
415 return -1;
416 }
417 if (!value) {
418 PyErr_Format(PyExc_TypeError,
419 "can't delete %s.__bases__", type->tp_name);
420 return -1;
421 }
422 if (!PyTuple_Check(value)) {
423 PyErr_Format(PyExc_TypeError,
424 "can only assign tuple to %s.__bases__, not %s",
Christian Heimese93237d2007-12-19 02:37:44 +0000425 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000426 return -1;
427 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000428 if (PyTuple_GET_SIZE(value) == 0) {
429 PyErr_Format(PyExc_TypeError,
430 "can only assign non-empty tuple to %s.__bases__, not ()",
431 type->tp_name);
432 return -1;
433 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000434 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
435 ob = PyTuple_GET_ITEM(value, i);
436 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
437 PyErr_Format(
438 PyExc_TypeError,
439 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +0000440 type->tp_name, Py_TYPE(ob)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000441 return -1;
442 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000443 if (PyType_Check(ob)) {
444 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
445 PyErr_SetString(PyExc_TypeError,
446 "a __bases__ item causes an inheritance cycle");
447 return -1;
448 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000449 }
450 }
451
452 new_base = best_base(value);
453
454 if (!new_base) {
455 return -1;
456 }
457
458 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
459 return -1;
460
461 Py_INCREF(new_base);
462 Py_INCREF(value);
463
464 old_bases = type->tp_bases;
465 old_base = type->tp_base;
466 old_mro = type->tp_mro;
467
468 type->tp_bases = value;
469 type->tp_base = new_base;
470
471 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000472 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000473 }
474
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000475 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000476 if (!temp)
477 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000478
479 r = mro_subclasses(type, temp);
480
481 if (r < 0) {
482 for (i = 0; i < PyList_Size(temp); i++) {
483 PyTypeObject* cls;
484 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000485 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
486 "", 2, 2, &cls, &mro);
Armin Rigo796fc992007-04-19 14:56:48 +0000487 Py_INCREF(mro);
488 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000489 cls->tp_mro = mro;
Armin Rigo796fc992007-04-19 14:56:48 +0000490 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000491 }
492 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000493 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000494 }
495
496 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000497
498 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000499 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000500 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000501 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000502
503 /* for now, sod that: just remove from all old_bases,
504 add to all new_bases */
505
506 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
507 ob = PyTuple_GET_ITEM(old_bases, i);
508 if (PyType_Check(ob)) {
509 remove_subclass(
510 (PyTypeObject*)ob, type);
511 }
512 }
513
514 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
515 ob = PyTuple_GET_ITEM(value, i);
516 if (PyType_Check(ob)) {
517 if (add_subclass((PyTypeObject*)ob, type) < 0)
518 r = -1;
519 }
520 }
521
522 update_all_slots(type);
523
524 Py_DECREF(old_bases);
525 Py_DECREF(old_base);
526 Py_DECREF(old_mro);
527
528 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000529
530 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000531 Py_DECREF(type->tp_bases);
532 Py_DECREF(type->tp_base);
533 if (type->tp_mro != old_mro) {
534 Py_DECREF(type->tp_mro);
535 }
536
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000537 type->tp_bases = old_bases;
538 type->tp_base = old_base;
539 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000540
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000541 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000542}
543
544static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000545type_dict(PyTypeObject *type, void *context)
546{
547 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548 Py_INCREF(Py_None);
549 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000550 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000551 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000552}
553
Tim Peters24008312002-03-17 18:56:20 +0000554static PyObject *
555type_get_doc(PyTypeObject *type, void *context)
556{
557 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000558 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000559 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000560 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000561 if (result == NULL) {
562 result = Py_None;
563 Py_INCREF(result);
564 }
Christian Heimese93237d2007-12-19 02:37:44 +0000565 else if (Py_TYPE(result)->tp_descr_get) {
566 result = Py_TYPE(result)->tp_descr_get(result, NULL,
Tim Peters2b858972002-04-18 04:12:28 +0000567 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000568 }
569 else {
570 Py_INCREF(result);
571 }
Tim Peters24008312002-03-17 18:56:20 +0000572 return result;
573}
574
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000575static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000576 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
577 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000578 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +0000579 {"__abstractmethods__", (getter)type_abstractmethods,
580 (setter)type_set_abstractmethods, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000581 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000582 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000583 {0}
584};
585
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000586static int
587type_compare(PyObject *v, PyObject *w)
588{
589 /* This is called with type objects only. So we
590 can just compare the addresses. */
591 Py_uintptr_t vv = (Py_uintptr_t)v;
592 Py_uintptr_t ww = (Py_uintptr_t)w;
593 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
594}
595
Steven Bethardae42f332008-03-18 17:26:10 +0000596static PyObject*
597type_richcompare(PyObject *v, PyObject *w, int op)
598{
599 PyObject *result;
600 Py_uintptr_t vv, ww;
601 int c;
602
603 /* Make sure both arguments are types. */
604 if (!PyType_Check(v) || !PyType_Check(w)) {
605 result = Py_NotImplemented;
606 goto out;
607 }
608
609 /* Py3K warning if comparison isn't == or != */
610 if (Py_Py3kWarningFlag && op != Py_EQ && op != Py_NE &&
Benjamin Peterson9f4f4812008-04-27 03:01:45 +0000611 PyErr_WarnEx(PyExc_DeprecationWarning,
Georg Brandld5b635f2008-03-25 08:29:14 +0000612 "type inequality comparisons not supported "
Benjamin Peterson9f4f4812008-04-27 03:01:45 +0000613 "in 3.x", 1) < 0) {
Steven Bethardae42f332008-03-18 17:26:10 +0000614 return NULL;
615 }
616
617 /* Compare addresses */
618 vv = (Py_uintptr_t)v;
619 ww = (Py_uintptr_t)w;
620 switch (op) {
621 case Py_LT: c = vv < ww; break;
622 case Py_LE: c = vv <= ww; break;
623 case Py_EQ: c = vv == ww; break;
624 case Py_NE: c = vv != ww; break;
625 case Py_GT: c = vv > ww; break;
626 case Py_GE: c = vv >= ww; break;
627 default:
628 result = Py_NotImplemented;
629 goto out;
630 }
631 result = c ? Py_True : Py_False;
632
633 /* incref and return */
634 out:
635 Py_INCREF(result);
636 return result;
637}
638
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000639static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000640type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000641{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000642 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000643 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000644
645 mod = type_module(type, NULL);
646 if (mod == NULL)
647 PyErr_Clear();
648 else if (!PyString_Check(mod)) {
649 Py_DECREF(mod);
650 mod = NULL;
651 }
652 name = type_name(type, NULL);
653 if (name == NULL)
654 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000655
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000656 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
657 kind = "class";
658 else
659 kind = "type";
660
Barry Warsaw7ce36942001-08-24 18:34:26 +0000661 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000662 rtn = PyString_FromFormat("<%s '%s.%s'>",
663 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000664 PyString_AS_STRING(mod),
665 PyString_AS_STRING(name));
666 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000667 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000668 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000669
Guido van Rossumc3542212001-08-16 09:18:56 +0000670 Py_XDECREF(mod);
671 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000672 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000673}
674
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675static PyObject *
676type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
677{
678 PyObject *obj;
679
680 if (type->tp_new == NULL) {
681 PyErr_Format(PyExc_TypeError,
682 "cannot create '%.100s' instances",
683 type->tp_name);
684 return NULL;
685 }
686
Tim Peters3f996e72001-09-13 19:18:27 +0000687 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000688 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000689 /* Ugly exception: when the call was type(something),
690 don't call tp_init on the result. */
691 if (type == &PyType_Type &&
692 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
693 (kwds == NULL ||
694 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
695 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000696 /* If the returned object is not an instance of type,
697 it won't be initialized. */
698 if (!PyType_IsSubtype(obj->ob_type, type))
699 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000701 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
702 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000703 type->tp_init(obj, args, kwds) < 0) {
704 Py_DECREF(obj);
705 obj = NULL;
706 }
707 }
708 return obj;
709}
710
711PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000712PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000713{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000714 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000715 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
716 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000717
718 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000719 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000720 else
Anthony Baxtera6286212006-04-11 07:42:36 +0000721 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000722
Neil Schemenauerc806c882001-08-29 23:54:54 +0000723 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000724 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000725
Neil Schemenauerc806c882001-08-29 23:54:54 +0000726 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000727
Tim Peters6d6c1a32001-08-02 04:15:00 +0000728 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
729 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000730
Tim Peters6d6c1a32001-08-02 04:15:00 +0000731 if (type->tp_itemsize == 0)
732 PyObject_INIT(obj, type);
733 else
734 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000735
Tim Peters6d6c1a32001-08-02 04:15:00 +0000736 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000737 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000738 return obj;
739}
740
741PyObject *
742PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
743{
744 return type->tp_alloc(type, 0);
745}
746
Guido van Rossum9475a232001-10-05 20:51:39 +0000747/* Helpers for subtyping */
748
749static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000750traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
751{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000752 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000753 PyMemberDef *mp;
754
Christian Heimese93237d2007-12-19 02:37:44 +0000755 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000756 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000757 for (i = 0; i < n; i++, mp++) {
758 if (mp->type == T_OBJECT_EX) {
759 char *addr = (char *)self + mp->offset;
760 PyObject *obj = *(PyObject **)addr;
761 if (obj != NULL) {
762 int err = visit(obj, arg);
763 if (err)
764 return err;
765 }
766 }
767 }
768 return 0;
769}
770
771static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000772subtype_traverse(PyObject *self, visitproc visit, void *arg)
773{
774 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000775 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000776
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000777 /* Find the nearest base with a different tp_traverse,
778 and traverse slots while we're at it */
Christian Heimese93237d2007-12-19 02:37:44 +0000779 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000780 base = type;
781 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
Christian Heimese93237d2007-12-19 02:37:44 +0000782 if (Py_SIZE(base)) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000783 int err = traverse_slots(base, self, visit, arg);
784 if (err)
785 return err;
786 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000787 base = base->tp_base;
788 assert(base);
789 }
790
791 if (type->tp_dictoffset != base->tp_dictoffset) {
792 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Woutersc6e55062006-04-15 21:47:09 +0000793 if (dictptr && *dictptr)
794 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000795 }
796
Thomas Woutersc6e55062006-04-15 21:47:09 +0000797 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000798 /* For a heaptype, the instances count as references
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000799 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000800 can find cycles involving this link. */
Thomas Woutersc6e55062006-04-15 21:47:09 +0000801 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000802
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000803 if (basetraverse)
804 return basetraverse(self, visit, arg);
805 return 0;
806}
807
808static void
809clear_slots(PyTypeObject *type, PyObject *self)
810{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000811 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000812 PyMemberDef *mp;
813
Christian Heimese93237d2007-12-19 02:37:44 +0000814 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000815 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000816 for (i = 0; i < n; i++, mp++) {
817 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
818 char *addr = (char *)self + mp->offset;
819 PyObject *obj = *(PyObject **)addr;
820 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000821 *(PyObject **)addr = NULL;
Thomas Woutersedf17d82006-04-15 17:28:34 +0000822 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000823 }
824 }
825 }
826}
827
828static int
829subtype_clear(PyObject *self)
830{
831 PyTypeObject *type, *base;
832 inquiry baseclear;
833
834 /* Find the nearest base with a different tp_clear
835 and clear slots while we're at it */
Christian Heimese93237d2007-12-19 02:37:44 +0000836 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000837 base = type;
838 while ((baseclear = base->tp_clear) == subtype_clear) {
Christian Heimese93237d2007-12-19 02:37:44 +0000839 if (Py_SIZE(base))
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000840 clear_slots(base, self);
841 base = base->tp_base;
842 assert(base);
843 }
844
Guido van Rossuma3862092002-06-10 15:24:42 +0000845 /* There's no need to clear the instance dict (if any);
846 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000847
848 if (baseclear)
849 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000850 return 0;
851}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000852
853static void
854subtype_dealloc(PyObject *self)
855{
Guido van Rossum14227b42001-12-06 02:35:58 +0000856 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000857 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000858
Guido van Rossum22b13872002-08-06 21:41:44 +0000859 /* Extract the type; we expect it to be a heap type */
Christian Heimese93237d2007-12-19 02:37:44 +0000860 type = Py_TYPE(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000861 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000862
Guido van Rossum22b13872002-08-06 21:41:44 +0000863 /* Test whether the type has GC exactly once */
864
865 if (!PyType_IS_GC(type)) {
866 /* It's really rare to find a dynamic type that doesn't have
867 GC; it can only happen when deriving from 'object' and not
868 adding any slots or instance variables. This allows
869 certain simplifications: there's no need to call
870 clear_slots(), or DECREF the dict, or clear weakrefs. */
871
872 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000873 if (type->tp_del) {
874 type->tp_del(self);
875 if (self->ob_refcnt > 0)
876 return;
877 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000878
879 /* Find the nearest base with a different tp_dealloc */
880 base = type;
881 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimese93237d2007-12-19 02:37:44 +0000882 assert(Py_SIZE(base) == 0);
Guido van Rossum22b13872002-08-06 21:41:44 +0000883 base = base->tp_base;
884 assert(base);
885 }
886
887 /* Call the base tp_dealloc() */
888 assert(basedealloc);
889 basedealloc(self);
890
891 /* Can't reference self beyond this point */
892 Py_DECREF(type);
893
894 /* Done */
895 return;
896 }
897
898 /* We get here only if the type has GC */
899
900 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000901 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000902 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000903 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000904 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000905 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000906 /* DO NOT restore GC tracking at this point. weakref callbacks
907 * (if any, and whether directly here or indirectly in something we
908 * call) may trigger GC, and if self is tracked at that point, it
909 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000910 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000911
Guido van Rossum59195fd2003-06-13 20:54:40 +0000912 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000913 base = type;
914 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000915 base = base->tp_base;
916 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000917 }
918
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000919 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000920 the finalizer (__del__), clearing slots, or clearing the instance
921 dict. */
922
Guido van Rossum1987c662003-05-29 14:29:23 +0000923 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
924 PyObject_ClearWeakRefs(self);
925
926 /* Maybe call finalizer; exit early if resurrected */
927 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000928 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000929 type->tp_del(self);
930 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000931 goto endlabel; /* resurrected */
932 else
933 _PyObject_GC_UNTRACK(self);
Brett Cannonf5bee302007-01-23 23:21:22 +0000934 /* New weakrefs could be created during the finalizer call.
935 If this occurs, clear them out without calling their
936 finalizers since they might rely on part of the object
937 being finalized that has already been destroyed. */
938 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
939 /* Modeled after GET_WEAKREFS_LISTPTR() */
940 PyWeakReference **list = (PyWeakReference **) \
941 PyObject_GET_WEAKREFS_LISTPTR(self);
942 while (*list)
943 _PyWeakref_ClearRef(*list);
944 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000945 }
946
Guido van Rossum59195fd2003-06-13 20:54:40 +0000947 /* Clear slots up to the nearest base with a different tp_dealloc */
948 base = type;
949 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimese93237d2007-12-19 02:37:44 +0000950 if (Py_SIZE(base))
Guido van Rossum59195fd2003-06-13 20:54:40 +0000951 clear_slots(base, self);
952 base = base->tp_base;
953 assert(base);
954 }
955
Tim Peters6d6c1a32001-08-02 04:15:00 +0000956 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000957 if (type->tp_dictoffset && !base->tp_dictoffset) {
958 PyObject **dictptr = _PyObject_GetDictPtr(self);
959 if (dictptr != NULL) {
960 PyObject *dict = *dictptr;
961 if (dict != NULL) {
962 Py_DECREF(dict);
963 *dictptr = NULL;
964 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000965 }
966 }
967
Tim Peters0bd743c2003-11-13 22:50:00 +0000968 /* Call the base tp_dealloc(); first retrack self if
969 * basedealloc knows about gc.
970 */
971 if (PyType_IS_GC(base))
972 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000973 assert(basedealloc);
974 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000975
976 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000977 Py_DECREF(type);
978
Guido van Rossum0906e072002-08-07 20:42:09 +0000979 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000980 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000981 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000982 --_PyTrash_delete_nesting;
983
984 /* Explanation of the weirdness around the trashcan macros:
985
986 Q. What do the trashcan macros do?
987
988 A. Read the comment titled "Trashcan mechanism" in object.h.
989 For one, this explains why there must be a call to GC-untrack
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000990 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000991 trashcan code, the answers to the following questions don't make
992 sense.
993
994 Q. Why do we GC-untrack before the trashcan and then immediately
995 GC-track again afterward?
996
997 A. In the case that the base class is GC-aware, the base class
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000998 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000999 UNTRACK macro, this will crash when the object is already
1000 untracked. Because we don't know what the base class does, the
1001 only safe thing is to make sure the object is tracked when we
1002 call the base class dealloc. But... The trashcan begin macro
1003 requires that the object is *untracked* before it is called. So
1004 the dance becomes:
1005
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001006 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001007 trashcan begin
1008 GC track
1009
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001010 Q. Why did the last question say "immediately GC-track again"?
1011 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +00001012
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001013 A. Because the code *used* to re-track immediately. Bad Idea.
1014 self has a refcount of 0, and if gc ever gets its hands on it
1015 (which can happen if any weakref callback gets invoked), it
1016 looks like trash to gc too, and gc also tries to delete self
1017 then. But we're already deleting self. Double dealloction is
1018 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +00001019
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001020 Q. Why the bizarre (net-zero) manipulation of
1021 _PyTrash_delete_nesting around the trashcan macros?
1022
1023 A. Some base classes (e.g. list) also use the trashcan mechanism.
1024 The following scenario used to be possible:
1025
1026 - suppose the trashcan level is one below the trashcan limit
1027
1028 - subtype_dealloc() is called
1029
1030 - the trashcan limit is not yet reached, so the trashcan level
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001031 is incremented and the code between trashcan begin and end is
1032 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001033
1034 - this destroys much of the object's contents, including its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001035 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001036
1037 - basedealloc() is called; this is really list_dealloc(), or
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001038 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001039
1040 - the trashcan limit is now reached, so the object is put on the
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001041 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001042
1043 - basedealloc() returns
1044
1045 - subtype_dealloc() decrefs the object's type
1046
1047 - subtype_dealloc() returns
1048
1049 - later, the trashcan code starts deleting the objects from its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001050 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001051
1052 - subtype_dealloc() is called *AGAIN* for the same object
1053
1054 - at the very least (if the destroyed slots and __dict__ don't
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001055 cause problems) the object's type gets decref'ed a second
1056 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001057
1058 The remedy is to make sure that if the code between trashcan
1059 begin and end in subtype_dealloc() is called, the code between
1060 trashcan begin and end in basedealloc() will also be called.
1061 This is done by decrementing the level after passing into the
1062 trashcan block, and incrementing it just before leaving the
1063 block.
1064
1065 But now it's possible that a chain of objects consisting solely
1066 of objects whose deallocator is subtype_dealloc() will defeat
1067 the trashcan mechanism completely: the decremented level means
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001068 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +00001069 *increment* the level *before* entering the trashcan block, and
1070 matchingly decrement it after leaving. This means the trashcan
1071 code will trigger a little early, but that's no big deal.
1072
1073 Q. Are there any live examples of code in need of all this
1074 complexity?
1075
1076 A. Yes. See SF bug 668433 for code that crashed (when Python was
1077 compiled in debug mode) before the trashcan level manipulations
1078 were added. For more discussion, see SF patches 581742, 575073
1079 and bug 574207.
1080 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001081}
1082
Jeremy Hylton938ace62002-07-17 16:30:39 +00001083static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001084
Tim Peters6d6c1a32001-08-02 04:15:00 +00001085/* type test with subclassing support */
1086
1087int
1088PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1089{
1090 PyObject *mro;
1091
Guido van Rossum9478d072001-09-07 18:52:13 +00001092 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1093 return b == a || b == &PyBaseObject_Type;
1094
Tim Peters6d6c1a32001-08-02 04:15:00 +00001095 mro = a->tp_mro;
1096 if (mro != NULL) {
1097 /* Deal with multiple inheritance without recursion
1098 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001099 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001100 assert(PyTuple_Check(mro));
1101 n = PyTuple_GET_SIZE(mro);
1102 for (i = 0; i < n; i++) {
1103 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1104 return 1;
1105 }
1106 return 0;
1107 }
1108 else {
1109 /* a is not completely initilized yet; follow tp_base */
1110 do {
1111 if (a == b)
1112 return 1;
1113 a = a->tp_base;
1114 } while (a != NULL);
1115 return b == &PyBaseObject_Type;
1116 }
1117}
1118
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001119/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +00001120 without looking in the instance dictionary
1121 (so we can't use PyObject_GetAttr) but still binding
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001122 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +00001123 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001124 static variable used to cache the interned Python string.
1125
1126 Two variants:
1127
1128 - lookup_maybe() returns NULL without raising an exception
1129 when the _PyType_Lookup() call fails;
1130
1131 - lookup_method() always raises an exception upon errors.
1132*/
Guido van Rossum60718732001-08-28 17:47:51 +00001133
1134static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001135lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +00001136{
1137 PyObject *res;
1138
1139 if (*attrobj == NULL) {
1140 *attrobj = PyString_InternFromString(attrstr);
1141 if (*attrobj == NULL)
1142 return NULL;
1143 }
Christian Heimese93237d2007-12-19 02:37:44 +00001144 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001145 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +00001146 descrgetfunc f;
Christian Heimese93237d2007-12-19 02:37:44 +00001147 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
Guido van Rossum60718732001-08-28 17:47:51 +00001148 Py_INCREF(res);
1149 else
Christian Heimese93237d2007-12-19 02:37:44 +00001150 res = f(res, self, (PyObject *)(Py_TYPE(self)));
Guido van Rossum60718732001-08-28 17:47:51 +00001151 }
1152 return res;
1153}
1154
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001155static PyObject *
1156lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1157{
1158 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1159 if (res == NULL && !PyErr_Occurred())
1160 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1161 return res;
1162}
1163
Guido van Rossum2730b132001-08-28 18:22:14 +00001164/* A variation of PyObject_CallMethod that uses lookup_method()
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001165 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +00001166 as lookup_method to cache the interned name string object. */
1167
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001168static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +00001169call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1170{
1171 va_list va;
1172 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +00001173 va_start(va, format);
1174
Guido van Rossumda21c012001-10-03 00:50:18 +00001175 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001176 if (func == NULL) {
1177 va_end(va);
1178 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +00001179 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001180 return NULL;
1181 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001182
1183 if (format && *format)
1184 args = Py_VaBuildValue(format, va);
1185 else
1186 args = PyTuple_New(0);
1187
1188 va_end(va);
1189
1190 if (args == NULL)
1191 return NULL;
1192
1193 assert(PyTuple_Check(args));
1194 retval = PyObject_Call(func, args, NULL);
1195
1196 Py_DECREF(args);
1197 Py_DECREF(func);
1198
1199 return retval;
1200}
1201
1202/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1203
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001204static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001205call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1206{
1207 va_list va;
1208 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001209 va_start(va, format);
1210
Guido van Rossumda21c012001-10-03 00:50:18 +00001211 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +00001212 if (func == NULL) {
1213 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +00001214 if (!PyErr_Occurred()) {
1215 Py_INCREF(Py_NotImplemented);
1216 return Py_NotImplemented;
1217 }
Guido van Rossum717ce002001-09-14 16:58:08 +00001218 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +00001219 }
1220
1221 if (format && *format)
1222 args = Py_VaBuildValue(format, va);
1223 else
1224 args = PyTuple_New(0);
1225
1226 va_end(va);
1227
Guido van Rossum717ce002001-09-14 16:58:08 +00001228 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00001229 return NULL;
1230
Guido van Rossum717ce002001-09-14 16:58:08 +00001231 assert(PyTuple_Check(args));
1232 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +00001233
1234 Py_DECREF(args);
1235 Py_DECREF(func);
1236
1237 return retval;
1238}
1239
Tim Petersa91e9642001-11-14 23:32:33 +00001240static int
1241fill_classic_mro(PyObject *mro, PyObject *cls)
1242{
1243 PyObject *bases, *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001244 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001245
1246 assert(PyList_Check(mro));
1247 assert(PyClass_Check(cls));
1248 i = PySequence_Contains(mro, cls);
1249 if (i < 0)
1250 return -1;
1251 if (!i) {
1252 if (PyList_Append(mro, cls) < 0)
1253 return -1;
1254 }
1255 bases = ((PyClassObject *)cls)->cl_bases;
1256 assert(bases && PyTuple_Check(bases));
1257 n = PyTuple_GET_SIZE(bases);
1258 for (i = 0; i < n; i++) {
1259 base = PyTuple_GET_ITEM(bases, i);
1260 if (fill_classic_mro(mro, base) < 0)
1261 return -1;
1262 }
1263 return 0;
1264}
1265
1266static PyObject *
1267classic_mro(PyObject *cls)
1268{
1269 PyObject *mro;
1270
1271 assert(PyClass_Check(cls));
1272 mro = PyList_New(0);
1273 if (mro != NULL) {
1274 if (fill_classic_mro(mro, cls) == 0)
1275 return mro;
1276 Py_DECREF(mro);
1277 }
1278 return NULL;
1279}
1280
Tim Petersea7f75d2002-12-07 21:39:16 +00001281/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001282 Method resolution order algorithm C3 described in
1283 "A Monotonic Superclass Linearization for Dylan",
1284 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001285 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001286 (OOPSLA 1996)
1287
Guido van Rossum98f33732002-11-25 21:36:54 +00001288 Some notes about the rules implied by C3:
1289
Tim Petersea7f75d2002-12-07 21:39:16 +00001290 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001291 It isn't legal to repeat a class in a list of base classes.
1292
1293 The next three properties are the 3 constraints in "C3".
1294
Tim Petersea7f75d2002-12-07 21:39:16 +00001295 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001296 If A precedes B in C's MRO, then A will precede B in the MRO of all
1297 subclasses of C.
1298
1299 Monotonicity.
1300 The MRO of a class must be an extension without reordering of the
1301 MRO of each of its superclasses.
1302
1303 Extended Precedence Graph (EPG).
1304 Linearization is consistent if there is a path in the EPG from
1305 each class to all its successors in the linearization. See
1306 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001307 */
1308
Tim Petersea7f75d2002-12-07 21:39:16 +00001309static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001310tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001311 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001312 size = PyList_GET_SIZE(list);
1313
1314 for (j = whence+1; j < size; j++) {
1315 if (PyList_GET_ITEM(list, j) == o)
1316 return 1;
1317 }
1318 return 0;
1319}
1320
Guido van Rossum98f33732002-11-25 21:36:54 +00001321static PyObject *
1322class_name(PyObject *cls)
1323{
1324 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1325 if (name == NULL) {
1326 PyErr_Clear();
1327 Py_XDECREF(name);
1328 name = PyObject_Repr(cls);
1329 }
1330 if (name == NULL)
1331 return NULL;
1332 if (!PyString_Check(name)) {
1333 Py_DECREF(name);
1334 return NULL;
1335 }
1336 return name;
1337}
1338
1339static int
1340check_duplicates(PyObject *list)
1341{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001342 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001343 /* Let's use a quadratic time algorithm,
1344 assuming that the bases lists is short.
1345 */
1346 n = PyList_GET_SIZE(list);
1347 for (i = 0; i < n; i++) {
1348 PyObject *o = PyList_GET_ITEM(list, i);
1349 for (j = i + 1; j < n; j++) {
1350 if (PyList_GET_ITEM(list, j) == o) {
1351 o = class_name(o);
1352 PyErr_Format(PyExc_TypeError,
1353 "duplicate base class %s",
1354 o ? PyString_AS_STRING(o) : "?");
1355 Py_XDECREF(o);
1356 return -1;
1357 }
1358 }
1359 }
1360 return 0;
1361}
1362
1363/* Raise a TypeError for an MRO order disagreement.
1364
1365 It's hard to produce a good error message. In the absence of better
1366 insight into error reporting, report the classes that were candidates
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001367 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001368 order in which they should be put in the MRO, but it's hard to
1369 diagnose what constraint can't be satisfied.
1370*/
1371
1372static void
1373set_mro_error(PyObject *to_merge, int *remain)
1374{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001375 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001376 char buf[1000];
1377 PyObject *k, *v;
1378 PyObject *set = PyDict_New();
Georg Brandl5c170fd2006-03-17 19:03:25 +00001379 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001380
1381 to_merge_size = PyList_GET_SIZE(to_merge);
1382 for (i = 0; i < to_merge_size; i++) {
1383 PyObject *L = PyList_GET_ITEM(to_merge, i);
1384 if (remain[i] < PyList_GET_SIZE(L)) {
1385 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Georg Brandl5c170fd2006-03-17 19:03:25 +00001386 if (PyDict_SetItem(set, c, Py_None) < 0) {
1387 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001388 return;
Georg Brandl5c170fd2006-03-17 19:03:25 +00001389 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001390 }
1391 }
1392 n = PyDict_Size(set);
1393
Raymond Hettingerf394df42003-04-06 19:13:41 +00001394 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1395consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001396 i = 0;
Skip Montanaro429433b2006-04-18 00:35:43 +00001397 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001398 PyObject *name = class_name(k);
1399 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1400 name ? PyString_AS_STRING(name) : "?");
1401 Py_XDECREF(name);
Skip Montanaro429433b2006-04-18 00:35:43 +00001402 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001403 buf[off++] = ',';
1404 buf[off] = '\0';
1405 }
1406 }
1407 PyErr_SetString(PyExc_TypeError, buf);
1408 Py_DECREF(set);
1409}
1410
Tim Petersea7f75d2002-12-07 21:39:16 +00001411static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001412pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001413 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001414 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001415 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001416
Guido van Rossum1f121312002-11-14 19:49:16 +00001417 to_merge_size = PyList_GET_SIZE(to_merge);
1418
Guido van Rossum98f33732002-11-25 21:36:54 +00001419 /* remain stores an index into each sublist of to_merge.
1420 remain[i] is the index of the next base in to_merge[i]
1421 that is not included in acc.
1422 */
Anthony Baxtera6286212006-04-11 07:42:36 +00001423 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001424 if (remain == NULL)
1425 return -1;
1426 for (i = 0; i < to_merge_size; i++)
1427 remain[i] = 0;
1428
1429 again:
1430 empty_cnt = 0;
1431 for (i = 0; i < to_merge_size; i++) {
1432 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001433
Guido van Rossum1f121312002-11-14 19:49:16 +00001434 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1435
1436 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1437 empty_cnt++;
1438 continue;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001439 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001440
Guido van Rossum98f33732002-11-25 21:36:54 +00001441 /* Choose next candidate for MRO.
1442
1443 The input sequences alone can determine the choice.
1444 If not, choose the class which appears in the MRO
1445 of the earliest direct superclass of the new class.
1446 */
1447
Guido van Rossum1f121312002-11-14 19:49:16 +00001448 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1449 for (j = 0; j < to_merge_size; j++) {
1450 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001451 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001452 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001453 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001454 }
1455 ok = PyList_Append(acc, candidate);
1456 if (ok < 0) {
1457 PyMem_Free(remain);
1458 return -1;
1459 }
1460 for (j = 0; j < to_merge_size; j++) {
1461 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001462 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1463 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001464 remain[j]++;
1465 }
1466 }
1467 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001468 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001469 }
1470
Guido van Rossum98f33732002-11-25 21:36:54 +00001471 if (empty_cnt == to_merge_size) {
1472 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001473 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001474 }
1475 set_mro_error(to_merge, remain);
1476 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001477 return -1;
1478}
1479
Tim Peters6d6c1a32001-08-02 04:15:00 +00001480static PyObject *
1481mro_implementation(PyTypeObject *type)
1482{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001483 Py_ssize_t i, n;
1484 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001485 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001486 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001487
Neal Norwitze7bb9182008-01-27 17:10:14 +00001488 if (type->tp_dict == NULL) {
1489 if (PyType_Ready(type) < 0)
Guido van Rossum63517572002-06-18 16:44:57 +00001490 return NULL;
1491 }
1492
Guido van Rossum98f33732002-11-25 21:36:54 +00001493 /* Find a superclass linearization that honors the constraints
1494 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001495 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001496
1497 to_merge is a list of lists, where each list is a superclass
1498 linearization implied by a base class. The last element of
1499 to_merge is the declared list of bases.
1500 */
1501
Tim Peters6d6c1a32001-08-02 04:15:00 +00001502 bases = type->tp_bases;
1503 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001504
1505 to_merge = PyList_New(n+1);
1506 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001507 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001508
Tim Peters6d6c1a32001-08-02 04:15:00 +00001509 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001510 PyObject *base = PyTuple_GET_ITEM(bases, i);
1511 PyObject *parentMRO;
1512 if (PyType_Check(base))
1513 parentMRO = PySequence_List(
1514 ((PyTypeObject*)base)->tp_mro);
1515 else
1516 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001517 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001518 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001519 return NULL;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001520 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001521
1522 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001523 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001524
1525 bases_aslist = PySequence_List(bases);
1526 if (bases_aslist == NULL) {
1527 Py_DECREF(to_merge);
1528 return NULL;
1529 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001530 /* This is just a basic sanity check. */
1531 if (check_duplicates(bases_aslist) < 0) {
1532 Py_DECREF(to_merge);
1533 Py_DECREF(bases_aslist);
1534 return NULL;
1535 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001536 PyList_SET_ITEM(to_merge, n, bases_aslist);
1537
1538 result = Py_BuildValue("[O]", (PyObject *)type);
1539 if (result == NULL) {
1540 Py_DECREF(to_merge);
1541 return NULL;
1542 }
1543
1544 ok = pmerge(result, to_merge);
1545 Py_DECREF(to_merge);
1546 if (ok < 0) {
1547 Py_DECREF(result);
1548 return NULL;
1549 }
1550
Tim Peters6d6c1a32001-08-02 04:15:00 +00001551 return result;
1552}
1553
1554static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001555mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001556{
1557 PyTypeObject *type = (PyTypeObject *)self;
1558
Tim Peters6d6c1a32001-08-02 04:15:00 +00001559 return mro_implementation(type);
1560}
1561
1562static int
1563mro_internal(PyTypeObject *type)
1564{
1565 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001566 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001567
Christian Heimese93237d2007-12-19 02:37:44 +00001568 if (Py_TYPE(type) == &PyType_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001569 result = mro_implementation(type);
1570 }
1571 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001572 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001573 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001574 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001575 if (mro == NULL)
1576 return -1;
1577 result = PyObject_CallObject(mro, NULL);
1578 Py_DECREF(mro);
1579 }
1580 if (result == NULL)
1581 return -1;
1582 tuple = PySequence_Tuple(result);
1583 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001584 if (tuple == NULL)
1585 return -1;
1586 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001587 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001588 PyObject *cls;
1589 PyTypeObject *solid;
1590
1591 solid = solid_base(type);
1592
1593 len = PyTuple_GET_SIZE(tuple);
1594
1595 for (i = 0; i < len; i++) {
1596 PyTypeObject *t;
1597 cls = PyTuple_GET_ITEM(tuple, i);
1598 if (PyClass_Check(cls))
1599 continue;
1600 else if (!PyType_Check(cls)) {
1601 PyErr_Format(PyExc_TypeError,
1602 "mro() returned a non-class ('%.500s')",
Christian Heimese93237d2007-12-19 02:37:44 +00001603 Py_TYPE(cls)->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001604 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001605 return -1;
1606 }
1607 t = (PyTypeObject*)cls;
1608 if (!PyType_IsSubtype(solid, solid_base(t))) {
1609 PyErr_Format(PyExc_TypeError,
1610 "mro() returned base with unsuitable layout ('%.500s')",
1611 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001612 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001613 return -1;
1614 }
1615 }
1616 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001617 type->tp_mro = tuple;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001618
1619 type_mro_modified(type, type->tp_mro);
1620 /* corner case: the old-style super class might have been hidden
1621 from the custom MRO */
1622 type_mro_modified(type, type->tp_bases);
1623
1624 type_modified(type);
1625
Tim Peters6d6c1a32001-08-02 04:15:00 +00001626 return 0;
1627}
1628
1629
1630/* Calculate the best base amongst multiple base classes.
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001631 This is the first one that's on the path to the "solid base". */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001632
1633static PyTypeObject *
1634best_base(PyObject *bases)
1635{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001636 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001637 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001638 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001639
1640 assert(PyTuple_Check(bases));
1641 n = PyTuple_GET_SIZE(bases);
1642 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001643 base = NULL;
1644 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001646 base_proto = PyTuple_GET_ITEM(bases, i);
1647 if (PyClass_Check(base_proto))
1648 continue;
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001649 if (!PyType_Check(base_proto)) {
1650 PyErr_SetString(
1651 PyExc_TypeError,
1652 "bases must be types");
1653 return NULL;
1654 }
Tim Petersa91e9642001-11-14 23:32:33 +00001655 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001656 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001657 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001658 return NULL;
1659 }
1660 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001661 if (winner == NULL) {
1662 winner = candidate;
1663 base = base_i;
1664 }
1665 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001666 ;
1667 else if (PyType_IsSubtype(candidate, winner)) {
1668 winner = candidate;
1669 base = base_i;
1670 }
1671 else {
1672 PyErr_SetString(
1673 PyExc_TypeError,
1674 "multiple bases have "
1675 "instance lay-out conflict");
1676 return NULL;
1677 }
1678 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001679 if (base == NULL)
1680 PyErr_SetString(PyExc_TypeError,
1681 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001682 return base;
1683}
1684
1685static int
1686extra_ivars(PyTypeObject *type, PyTypeObject *base)
1687{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001688 size_t t_size = type->tp_basicsize;
1689 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690
Guido van Rossum9676b222001-08-17 20:32:36 +00001691 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001692 if (type->tp_itemsize || base->tp_itemsize) {
1693 /* If itemsize is involved, stricter rules */
1694 return t_size != b_size ||
1695 type->tp_itemsize != base->tp_itemsize;
1696 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001697 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001698 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1699 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001700 t_size -= sizeof(PyObject *);
1701 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001702 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1703 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001704 t_size -= sizeof(PyObject *);
1705
1706 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001707}
1708
1709static PyTypeObject *
1710solid_base(PyTypeObject *type)
1711{
1712 PyTypeObject *base;
1713
1714 if (type->tp_base)
1715 base = solid_base(type->tp_base);
1716 else
1717 base = &PyBaseObject_Type;
1718 if (extra_ivars(type, base))
1719 return type;
1720 else
1721 return base;
1722}
1723
Jeremy Hylton938ace62002-07-17 16:30:39 +00001724static void object_dealloc(PyObject *);
1725static int object_init(PyObject *, PyObject *, PyObject *);
1726static int update_slot(PyTypeObject *, PyObject *);
1727static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001728
Armin Rigo9790a272007-05-02 19:23:31 +00001729/*
1730 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1731 * inherited from various builtin types. The builtin base usually provides
1732 * its own __dict__ descriptor, so we use that when we can.
1733 */
1734static PyTypeObject *
1735get_builtin_base_with_dict(PyTypeObject *type)
1736{
1737 while (type->tp_base != NULL) {
1738 if (type->tp_dictoffset != 0 &&
1739 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1740 return type;
1741 type = type->tp_base;
1742 }
1743 return NULL;
1744}
1745
1746static PyObject *
1747get_dict_descriptor(PyTypeObject *type)
1748{
1749 static PyObject *dict_str;
1750 PyObject *descr;
1751
1752 if (dict_str == NULL) {
1753 dict_str = PyString_InternFromString("__dict__");
1754 if (dict_str == NULL)
1755 return NULL;
1756 }
1757 descr = _PyType_Lookup(type, dict_str);
1758 if (descr == NULL || !PyDescr_IsData(descr))
1759 return NULL;
1760
1761 return descr;
1762}
1763
1764static void
1765raise_dict_descr_error(PyObject *obj)
1766{
1767 PyErr_Format(PyExc_TypeError,
1768 "this __dict__ descriptor does not support "
1769 "'%.200s' objects", obj->ob_type->tp_name);
1770}
1771
Tim Peters6d6c1a32001-08-02 04:15:00 +00001772static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001773subtype_dict(PyObject *obj, void *context)
1774{
Armin Rigo9790a272007-05-02 19:23:31 +00001775 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001776 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001777 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001778
Armin Rigo9790a272007-05-02 19:23:31 +00001779 base = get_builtin_base_with_dict(obj->ob_type);
1780 if (base != NULL) {
1781 descrgetfunc func;
1782 PyObject *descr = get_dict_descriptor(base);
1783 if (descr == NULL) {
1784 raise_dict_descr_error(obj);
1785 return NULL;
1786 }
1787 func = descr->ob_type->tp_descr_get;
1788 if (func == NULL) {
1789 raise_dict_descr_error(obj);
1790 return NULL;
1791 }
1792 return func(descr, obj, (PyObject *)(obj->ob_type));
1793 }
1794
1795 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001796 if (dictptr == NULL) {
1797 PyErr_SetString(PyExc_AttributeError,
1798 "This object has no __dict__");
1799 return NULL;
1800 }
1801 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001802 if (dict == NULL)
1803 *dictptr = dict = PyDict_New();
1804 Py_XINCREF(dict);
1805 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001806}
1807
Guido van Rossum6661be32001-10-26 04:26:12 +00001808static int
1809subtype_setdict(PyObject *obj, PyObject *value, void *context)
1810{
Armin Rigo9790a272007-05-02 19:23:31 +00001811 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001812 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001813 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001814
Armin Rigo9790a272007-05-02 19:23:31 +00001815 base = get_builtin_base_with_dict(obj->ob_type);
1816 if (base != NULL) {
1817 descrsetfunc func;
1818 PyObject *descr = get_dict_descriptor(base);
1819 if (descr == NULL) {
1820 raise_dict_descr_error(obj);
1821 return -1;
1822 }
1823 func = descr->ob_type->tp_descr_set;
1824 if (func == NULL) {
1825 raise_dict_descr_error(obj);
1826 return -1;
1827 }
1828 return func(descr, obj, value);
1829 }
1830
1831 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001832 if (dictptr == NULL) {
1833 PyErr_SetString(PyExc_AttributeError,
1834 "This object has no __dict__");
1835 return -1;
1836 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001837 if (value != NULL && !PyDict_Check(value)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001838 PyErr_Format(PyExc_TypeError,
1839 "__dict__ must be set to a dictionary, "
Christian Heimese93237d2007-12-19 02:37:44 +00001840 "not a '%.200s'", Py_TYPE(value)->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001841 return -1;
1842 }
1843 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001844 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001845 *dictptr = value;
1846 Py_XDECREF(dict);
1847 return 0;
1848}
1849
Guido van Rossumad47da02002-08-12 19:05:44 +00001850static PyObject *
1851subtype_getweakref(PyObject *obj, void *context)
1852{
1853 PyObject **weaklistptr;
1854 PyObject *result;
1855
Christian Heimese93237d2007-12-19 02:37:44 +00001856 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001857 PyErr_SetString(PyExc_AttributeError,
Fred Drake7a36f5f2006-08-04 05:17:21 +00001858 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001859 return NULL;
1860 }
Christian Heimese93237d2007-12-19 02:37:44 +00001861 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1862 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1863 (size_t)(Py_TYPE(obj)->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001864 weaklistptr = (PyObject **)
Christian Heimese93237d2007-12-19 02:37:44 +00001865 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001866 if (*weaklistptr == NULL)
1867 result = Py_None;
1868 else
1869 result = *weaklistptr;
1870 Py_INCREF(result);
1871 return result;
1872}
1873
Guido van Rossum373c7412003-01-07 13:41:37 +00001874/* Three variants on the subtype_getsets list. */
1875
1876static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001877 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001878 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001879 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001880 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001881 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001882};
1883
Guido van Rossum373c7412003-01-07 13:41:37 +00001884static PyGetSetDef subtype_getsets_dict_only[] = {
1885 {"__dict__", subtype_dict, subtype_setdict,
1886 PyDoc_STR("dictionary for instance variables (if defined)")},
1887 {0}
1888};
1889
1890static PyGetSetDef subtype_getsets_weakref_only[] = {
1891 {"__weakref__", subtype_getweakref, NULL,
1892 PyDoc_STR("list of weak references to the object (if defined)")},
1893 {0}
1894};
1895
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001896static int
1897valid_identifier(PyObject *s)
1898{
Guido van Rossum03013a02002-07-16 14:30:28 +00001899 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001900 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001901
1902 if (!PyString_Check(s)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001903 PyErr_Format(PyExc_TypeError,
1904 "__slots__ items must be strings, not '%.200s'",
Christian Heimese93237d2007-12-19 02:37:44 +00001905 Py_TYPE(s)->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001906 return 0;
1907 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001908 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001909 n = PyString_GET_SIZE(s);
1910 /* We must reject an empty name. As a hack, we bump the
1911 length to 1 so that the loop will balk on the trailing \0. */
1912 if (n == 0)
1913 n = 1;
1914 for (i = 0; i < n; i++, p++) {
1915 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1916 PyErr_SetString(PyExc_TypeError,
1917 "__slots__ must be identifiers");
1918 return 0;
1919 }
1920 }
1921 return 1;
1922}
1923
Martin v. Löwisd919a592002-10-14 21:07:28 +00001924#ifdef Py_USING_UNICODE
1925/* Replace Unicode objects in slots. */
1926
1927static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001928_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001929{
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001930 PyObject *tmp = NULL;
1931 PyObject *slot_name, *new_name;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001932 Py_ssize_t i;
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001933
Martin v. Löwisd919a592002-10-14 21:07:28 +00001934 for (i = 0; i < nslots; i++) {
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001935 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1936 if (tmp == NULL) {
1937 tmp = PySequence_List(slots);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001938 if (tmp == NULL)
1939 return NULL;
1940 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001941 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1942 NULL);
1943 if (new_name == NULL) {
Martin v. Löwisd919a592002-10-14 21:07:28 +00001944 Py_DECREF(tmp);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001945 return NULL;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001946 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001947 Py_INCREF(new_name);
1948 PyList_SET_ITEM(tmp, i, new_name);
1949 Py_DECREF(slot_name);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001950 }
1951 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001952 if (tmp != NULL) {
1953 slots = PyList_AsTuple(tmp);
1954 Py_DECREF(tmp);
1955 }
1956 return slots;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001957}
1958#endif
1959
Guido van Rossumf102e242007-03-23 18:53:03 +00001960/* Forward */
1961static int
1962object_init(PyObject *self, PyObject *args, PyObject *kwds);
1963
1964static int
1965type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1966{
1967 int res;
1968
1969 assert(args != NULL && PyTuple_Check(args));
1970 assert(kwds == NULL || PyDict_Check(kwds));
1971
1972 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1973 PyErr_SetString(PyExc_TypeError,
1974 "type.__init__() takes no keyword arguments");
1975 return -1;
1976 }
1977
1978 if (args != NULL && PyTuple_Check(args) &&
1979 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1980 PyErr_SetString(PyExc_TypeError,
1981 "type.__init__() takes 1 or 3 arguments");
1982 return -1;
1983 }
1984
1985 /* Call object.__init__(self) now. */
1986 /* XXX Could call super(type, cls).__init__() but what's the point? */
1987 args = PyTuple_GetSlice(args, 0, 0);
1988 res = object_init(cls, args, NULL);
1989 Py_DECREF(args);
1990 return res;
1991}
1992
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001993static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001994type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1995{
1996 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001997 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001998 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001999 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002000 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00002001 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002002 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00002003 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002004
Tim Peters3abca122001-10-27 19:37:48 +00002005 assert(args != NULL && PyTuple_Check(args));
2006 assert(kwds == NULL || PyDict_Check(kwds));
2007
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00002008 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00002009 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002010 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2011 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00002012
2013 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2014 PyObject *x = PyTuple_GET_ITEM(args, 0);
Christian Heimese93237d2007-12-19 02:37:44 +00002015 Py_INCREF(Py_TYPE(x));
2016 return (PyObject *) Py_TYPE(x);
Tim Peters3abca122001-10-27 19:37:48 +00002017 }
2018
2019 /* SF bug 475327 -- if that didn't trigger, we need 3
2020 arguments. but PyArg_ParseTupleAndKeywords below may give
2021 a msg saying type() needs exactly 3. */
2022 if (nargs + nkwds != 3) {
2023 PyErr_SetString(PyExc_TypeError,
2024 "type() takes 1 or 3 arguments");
2025 return NULL;
2026 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002027 }
2028
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00002029 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002030 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
2031 &name,
2032 &PyTuple_Type, &bases,
2033 &PyDict_Type, &dict))
2034 return NULL;
2035
Armin Rigoc0ba52d2007-04-19 14:44:48 +00002036 /* Determine the proper metatype to deal with this,
2037 and check for metatype conflicts while we're at it.
2038 Note that if some other metatype wins to contract,
2039 it's possible that its instances are not types. */
2040 nbases = PyTuple_GET_SIZE(bases);
2041 winner = metatype;
2042 for (i = 0; i < nbases; i++) {
2043 tmp = PyTuple_GET_ITEM(bases, i);
2044 tmptype = tmp->ob_type;
2045 if (tmptype == &PyClass_Type)
2046 continue; /* Special case classic classes */
2047 if (PyType_IsSubtype(winner, tmptype))
2048 continue;
2049 if (PyType_IsSubtype(tmptype, winner)) {
2050 winner = tmptype;
2051 continue;
Jeremy Hyltonfa955692007-02-27 18:29:45 +00002052 }
Armin Rigoc0ba52d2007-04-19 14:44:48 +00002053 PyErr_SetString(PyExc_TypeError,
2054 "metaclass conflict: "
2055 "the metaclass of a derived class "
2056 "must be a (non-strict) subclass "
2057 "of the metaclasses of all its bases");
2058 return NULL;
2059 }
2060 if (winner != metatype) {
2061 if (winner->tp_new != type_new) /* Pass it to the winner */
2062 return winner->tp_new(winner, args, kwds);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00002063 metatype = winner;
2064 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002065
2066 /* Adjust for empty tuple bases */
2067 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002068 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002069 if (bases == NULL)
2070 return NULL;
2071 nbases = 1;
2072 }
2073 else
2074 Py_INCREF(bases);
2075
2076 /* XXX From here until type is allocated, "return NULL" leaks bases! */
2077
2078 /* Calculate best base, and check that all bases are type objects */
2079 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002080 if (base == NULL) {
2081 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002082 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002083 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002084 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2085 PyErr_Format(PyExc_TypeError,
2086 "type '%.100s' is not an acceptable base type",
2087 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002088 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002089 return NULL;
2090 }
2091
Tim Peters6d6c1a32001-08-02 04:15:00 +00002092 /* Check for a __slots__ sequence variable in dict, and count it */
2093 slots = PyDict_GetItemString(dict, "__slots__");
2094 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00002095 add_dict = 0;
2096 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00002097 may_add_dict = base->tp_dictoffset == 0;
2098 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2099 if (slots == NULL) {
2100 if (may_add_dict) {
2101 add_dict++;
2102 }
2103 if (may_add_weak) {
2104 add_weak++;
2105 }
2106 }
2107 else {
2108 /* Have slots */
2109
Tim Peters6d6c1a32001-08-02 04:15:00 +00002110 /* Make it into a tuple */
Neal Norwitzcbd9ee62007-04-14 05:25:50 +00002111 if (PyString_Check(slots) || PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002112 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002113 else
2114 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002115 if (slots == NULL) {
2116 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002117 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002118 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002119 assert(PyTuple_Check(slots));
2120
2121 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002122 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00002123 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00002124 PyErr_Format(PyExc_TypeError,
2125 "nonempty __slots__ "
2126 "not supported for subtype of '%s'",
2127 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00002128 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002129 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00002130 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00002131 return NULL;
2132 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002133
Martin v. Löwisd919a592002-10-14 21:07:28 +00002134#ifdef Py_USING_UNICODE
2135 tmp = _unicode_to_string(slots, nslots);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00002136 if (tmp == NULL)
2137 goto bad_slots;
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00002138 if (tmp != slots) {
2139 Py_DECREF(slots);
2140 slots = tmp;
2141 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00002142#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00002143 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002144 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00002145 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2146 char *s;
2147 if (!valid_identifier(tmp))
2148 goto bad_slots;
2149 assert(PyString_Check(tmp));
2150 s = PyString_AS_STRING(tmp);
2151 if (strcmp(s, "__dict__") == 0) {
2152 if (!may_add_dict || add_dict) {
2153 PyErr_SetString(PyExc_TypeError,
2154 "__dict__ slot disallowed: "
2155 "we already got one");
2156 goto bad_slots;
2157 }
2158 add_dict++;
2159 }
2160 if (strcmp(s, "__weakref__") == 0) {
2161 if (!may_add_weak || add_weak) {
2162 PyErr_SetString(PyExc_TypeError,
2163 "__weakref__ slot disallowed: "
2164 "either we already got one, "
2165 "or __itemsize__ != 0");
2166 goto bad_slots;
2167 }
2168 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002169 }
2170 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002171
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002172 /* Copy slots into a list, mangle names and sort them.
2173 Sorted names are needed for __class__ assignment.
2174 Convert them back to tuple at the end.
2175 */
2176 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002177 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00002178 goto bad_slots;
2179 for (i = j = 0; i < nslots; i++) {
2180 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002181 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00002182 s = PyString_AS_STRING(tmp);
2183 if ((add_dict && strcmp(s, "__dict__") == 0) ||
2184 (add_weak && strcmp(s, "__weakref__") == 0))
2185 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002186 tmp =_Py_Mangle(name, tmp);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002187 if (!tmp)
2188 goto bad_slots;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002189 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00002190 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002191 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002192 assert(j == nslots - add_dict - add_weak);
2193 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002194 Py_DECREF(slots);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002195 if (PyList_Sort(newslots) == -1) {
2196 Py_DECREF(bases);
2197 Py_DECREF(newslots);
2198 return NULL;
2199 }
2200 slots = PyList_AsTuple(newslots);
2201 Py_DECREF(newslots);
2202 if (slots == NULL) {
2203 Py_DECREF(bases);
2204 return NULL;
2205 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00002206
Guido van Rossumad47da02002-08-12 19:05:44 +00002207 /* Secondary bases may provide weakrefs or dict */
2208 if (nbases > 1 &&
2209 ((may_add_dict && !add_dict) ||
2210 (may_add_weak && !add_weak))) {
2211 for (i = 0; i < nbases; i++) {
2212 tmp = PyTuple_GET_ITEM(bases, i);
2213 if (tmp == (PyObject *)base)
2214 continue; /* Skip primary base */
2215 if (PyClass_Check(tmp)) {
2216 /* Classic base class provides both */
2217 if (may_add_dict && !add_dict)
2218 add_dict++;
2219 if (may_add_weak && !add_weak)
2220 add_weak++;
2221 break;
2222 }
2223 assert(PyType_Check(tmp));
2224 tmptype = (PyTypeObject *)tmp;
2225 if (may_add_dict && !add_dict &&
2226 tmptype->tp_dictoffset != 0)
2227 add_dict++;
2228 if (may_add_weak && !add_weak &&
2229 tmptype->tp_weaklistoffset != 0)
2230 add_weak++;
2231 if (may_add_dict && !add_dict)
2232 continue;
2233 if (may_add_weak && !add_weak)
2234 continue;
2235 /* Nothing more to check */
2236 break;
2237 }
2238 }
Guido van Rossum9676b222001-08-17 20:32:36 +00002239 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002240
2241 /* XXX From here until type is safely allocated,
2242 "return NULL" may leak slots! */
2243
2244 /* Allocate the type object */
2245 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00002246 if (type == NULL) {
2247 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00002248 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002249 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00002250 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002251
2252 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002253 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002254 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002255 et->ht_name = name;
2256 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002257
Guido van Rossumdc91b992001-08-08 22:26:22 +00002258 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002259 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2260 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00002261 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2262 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00002263
2264 /* It's a new-style number unless it specifically inherits any
2265 old-style numeric behavior */
2266 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
2267 (base->tp_as_number == NULL))
2268 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
2269
2270 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002271 type->tp_as_number = &et->as_number;
2272 type->tp_as_sequence = &et->as_sequence;
2273 type->tp_as_mapping = &et->as_mapping;
2274 type->tp_as_buffer = &et->as_buffer;
2275 type->tp_name = PyString_AS_STRING(name);
2276
2277 /* Set tp_base and tp_bases */
2278 type->tp_bases = bases;
2279 Py_INCREF(base);
2280 type->tp_base = base;
2281
Guido van Rossum687ae002001-10-15 22:03:32 +00002282 /* Initialize tp_dict from passed-in dict */
2283 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002284 if (dict == NULL) {
2285 Py_DECREF(type);
2286 return NULL;
2287 }
2288
Guido van Rossumc3542212001-08-16 09:18:56 +00002289 /* Set __module__ in the dict */
2290 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2291 tmp = PyEval_GetGlobals();
2292 if (tmp != NULL) {
2293 tmp = PyDict_GetItemString(tmp, "__name__");
2294 if (tmp != NULL) {
2295 if (PyDict_SetItemString(dict, "__module__",
2296 tmp) < 0)
2297 return NULL;
2298 }
2299 }
2300 }
2301
Tim Peters2f93e282001-10-04 05:27:00 +00002302 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00002303 and is a string. The __doc__ accessor will first look for tp_doc;
2304 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00002305 */
2306 {
2307 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2308 if (doc != NULL && PyString_Check(doc)) {
2309 const size_t n = (size_t)PyString_GET_SIZE(doc);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002310 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002311 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00002312 Py_DECREF(type);
2313 return NULL;
2314 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002315 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002316 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00002317 }
2318 }
2319
Tim Peters6d6c1a32001-08-02 04:15:00 +00002320 /* Special-case __new__: if it's a plain function,
2321 make it a static function */
2322 tmp = PyDict_GetItemString(dict, "__new__");
2323 if (tmp != NULL && PyFunction_Check(tmp)) {
2324 tmp = PyStaticMethod_New(tmp);
2325 if (tmp == NULL) {
2326 Py_DECREF(type);
2327 return NULL;
2328 }
2329 PyDict_SetItemString(dict, "__new__", tmp);
2330 Py_DECREF(tmp);
2331 }
2332
2333 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002334 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00002335 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002336 if (slots != NULL) {
2337 for (i = 0; i < nslots; i++, mp++) {
2338 mp->name = PyString_AS_STRING(
2339 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00002340 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002341 mp->offset = slotoffset;
Žiga Seilnacht89032082007-03-11 15:54:54 +00002342
2343 /* __dict__ and __weakref__ are already filtered out */
2344 assert(strcmp(mp->name, "__dict__") != 0);
2345 assert(strcmp(mp->name, "__weakref__") != 0);
2346
Tim Peters6d6c1a32001-08-02 04:15:00 +00002347 slotoffset += sizeof(PyObject *);
2348 }
2349 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002350 if (add_dict) {
2351 if (base->tp_itemsize)
2352 type->tp_dictoffset = -(long)sizeof(PyObject *);
2353 else
2354 type->tp_dictoffset = slotoffset;
2355 slotoffset += sizeof(PyObject *);
2356 }
2357 if (add_weak) {
2358 assert(!base->tp_itemsize);
2359 type->tp_weaklistoffset = slotoffset;
2360 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002361 }
2362 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002363 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002364 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002365
2366 if (type->tp_weaklistoffset && type->tp_dictoffset)
2367 type->tp_getset = subtype_getsets_full;
2368 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2369 type->tp_getset = subtype_getsets_weakref_only;
2370 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2371 type->tp_getset = subtype_getsets_dict_only;
2372 else
2373 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002374
2375 /* Special case some slots */
2376 if (type->tp_dictoffset != 0 || nslots > 0) {
2377 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2378 type->tp_getattro = PyObject_GenericGetAttr;
2379 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2380 type->tp_setattro = PyObject_GenericSetAttr;
2381 }
2382 type->tp_dealloc = subtype_dealloc;
2383
Guido van Rossum9475a232001-10-05 20:51:39 +00002384 /* Enable GC unless there are really no instance variables possible */
2385 if (!(type->tp_basicsize == sizeof(PyObject) &&
2386 type->tp_itemsize == 0))
2387 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2388
Tim Peters6d6c1a32001-08-02 04:15:00 +00002389 /* Always override allocation strategy to use regular heap */
2390 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002391 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002392 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002393 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002394 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002395 }
2396 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002397 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002398
2399 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002400 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002401 Py_DECREF(type);
2402 return NULL;
2403 }
2404
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002405 /* Put the proper slots in place */
2406 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002407
Tim Peters6d6c1a32001-08-02 04:15:00 +00002408 return (PyObject *)type;
2409}
2410
2411/* Internal API to look for a name through the MRO.
2412 This returns a borrowed reference, and doesn't set an exception! */
2413PyObject *
2414_PyType_Lookup(PyTypeObject *type, PyObject *name)
2415{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002416 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002417 PyObject *mro, *res, *base, *dict;
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002418 unsigned int h;
2419
2420 if (MCACHE_CACHEABLE_NAME(name) &&
Neal Norwitze7bb9182008-01-27 17:10:14 +00002421 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002422 /* fast path */
2423 h = MCACHE_HASH_METHOD(type, name);
2424 if (method_cache[h].version == type->tp_version_tag &&
2425 method_cache[h].name == name)
2426 return method_cache[h].value;
2427 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002428
Guido van Rossum687ae002001-10-15 22:03:32 +00002429 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002430 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002431
2432 /* If mro is NULL, the type is either not yet initialized
2433 by PyType_Ready(), or already cleared by type_clear().
2434 Either way the safest thing to do is to return NULL. */
2435 if (mro == NULL)
2436 return NULL;
2437
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002438 res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002439 assert(PyTuple_Check(mro));
2440 n = PyTuple_GET_SIZE(mro);
2441 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002442 base = PyTuple_GET_ITEM(mro, i);
2443 if (PyClass_Check(base))
2444 dict = ((PyClassObject *)base)->cl_dict;
2445 else {
2446 assert(PyType_Check(base));
2447 dict = ((PyTypeObject *)base)->tp_dict;
2448 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002449 assert(dict && PyDict_Check(dict));
2450 res = PyDict_GetItem(dict, name);
2451 if (res != NULL)
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002452 break;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002453 }
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00002454
2455 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2456 h = MCACHE_HASH_METHOD(type, name);
2457 method_cache[h].version = type->tp_version_tag;
2458 method_cache[h].value = res; /* borrowed */
2459 Py_INCREF(name);
2460 Py_DECREF(method_cache[h].name);
2461 method_cache[h].name = name;
2462 }
2463 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002464}
2465
2466/* This is similar to PyObject_GenericGetAttr(),
2467 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2468static PyObject *
2469type_getattro(PyTypeObject *type, PyObject *name)
2470{
Christian Heimese93237d2007-12-19 02:37:44 +00002471 PyTypeObject *metatype = Py_TYPE(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002472 PyObject *meta_attribute, *attribute;
2473 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002474
2475 /* Initialize this type (we'll assume the metatype is initialized) */
2476 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002477 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002478 return NULL;
2479 }
2480
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002481 /* No readable descriptor found yet */
2482 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002483
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002484 /* Look for the attribute in the metatype */
2485 meta_attribute = _PyType_Lookup(metatype, name);
2486
2487 if (meta_attribute != NULL) {
Christian Heimese93237d2007-12-19 02:37:44 +00002488 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002489
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002490 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2491 /* Data descriptors implement tp_descr_set to intercept
2492 * writes. Assume the attribute is not overridden in
2493 * type's tp_dict (and bases): call the descriptor now.
2494 */
2495 return meta_get(meta_attribute, (PyObject *)type,
2496 (PyObject *)metatype);
2497 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002498 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002499 }
2500
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002501 /* No data descriptor found on metatype. Look in tp_dict of this
2502 * type and its bases */
2503 attribute = _PyType_Lookup(type, name);
2504 if (attribute != NULL) {
2505 /* Implement descriptor functionality, if any */
Christian Heimese93237d2007-12-19 02:37:44 +00002506 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002507
2508 Py_XDECREF(meta_attribute);
2509
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002510 if (local_get != NULL) {
2511 /* NULL 2nd argument indicates the descriptor was
2512 * found on the target object itself (or a base) */
2513 return local_get(attribute, (PyObject *)NULL,
2514 (PyObject *)type);
2515 }
Tim Peters34592512002-07-11 06:23:50 +00002516
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002517 Py_INCREF(attribute);
2518 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002519 }
2520
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002521 /* No attribute found in local __dict__ (or bases): use the
2522 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002523 if (meta_get != NULL) {
2524 PyObject *res;
2525 res = meta_get(meta_attribute, (PyObject *)type,
2526 (PyObject *)metatype);
2527 Py_DECREF(meta_attribute);
2528 return res;
2529 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002530
2531 /* If an ordinary attribute was found on the metatype, return it now */
2532 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002533 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002534 }
2535
2536 /* Give up */
2537 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002538 "type object '%.50s' has no attribute '%.400s'",
2539 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002540 return NULL;
2541}
2542
2543static int
2544type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2545{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002546 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2547 PyErr_Format(
2548 PyExc_TypeError,
2549 "can't set attributes of built-in/extension type '%s'",
2550 type->tp_name);
2551 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002552 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002553 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2554 return -1;
2555 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002556}
2557
2558static void
2559type_dealloc(PyTypeObject *type)
2560{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002561 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002562
2563 /* Assert this is a heap-allocated type object */
2564 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002565 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002566 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002567 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002568 Py_XDECREF(type->tp_base);
2569 Py_XDECREF(type->tp_dict);
2570 Py_XDECREF(type->tp_bases);
2571 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002572 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002573 Py_XDECREF(type->tp_subclasses);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002574 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2575 * of most other objects. It's okay to cast it to char *.
2576 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002577 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002578 Py_XDECREF(et->ht_name);
2579 Py_XDECREF(et->ht_slots);
Christian Heimese93237d2007-12-19 02:37:44 +00002580 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002581}
2582
Guido van Rossum1c450732001-10-08 15:18:27 +00002583static PyObject *
2584type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2585{
2586 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002587 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002588
2589 list = PyList_New(0);
2590 if (list == NULL)
2591 return NULL;
2592 raw = type->tp_subclasses;
2593 if (raw == NULL)
2594 return list;
2595 assert(PyList_Check(raw));
2596 n = PyList_GET_SIZE(raw);
2597 for (i = 0; i < n; i++) {
2598 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002599 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002600 ref = PyWeakref_GET_OBJECT(ref);
2601 if (ref != Py_None) {
2602 if (PyList_Append(list, ref) < 0) {
2603 Py_DECREF(list);
2604 return NULL;
2605 }
2606 }
2607 }
2608 return list;
2609}
2610
Tim Peters6d6c1a32001-08-02 04:15:00 +00002611static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002612 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002613 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002614 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002615 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002616 {0}
2617};
2618
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002619PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002620"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002621"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002622
Guido van Rossum048eb752001-10-02 21:24:57 +00002623static int
2624type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2625{
Guido van Rossuma3862092002-06-10 15:24:42 +00002626 /* Because of type_is_gc(), the collector only calls this
2627 for heaptypes. */
2628 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002629
Thomas Woutersc6e55062006-04-15 21:47:09 +00002630 Py_VISIT(type->tp_dict);
2631 Py_VISIT(type->tp_cache);
2632 Py_VISIT(type->tp_mro);
2633 Py_VISIT(type->tp_bases);
2634 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002635
2636 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002637 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002638 in cycles; tp_subclasses is a list of weak references,
2639 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002640
Guido van Rossum048eb752001-10-02 21:24:57 +00002641 return 0;
2642}
2643
2644static int
2645type_clear(PyTypeObject *type)
2646{
Guido van Rossuma3862092002-06-10 15:24:42 +00002647 /* Because of type_is_gc(), the collector only calls this
2648 for heaptypes. */
2649 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002650
Guido van Rossuma3862092002-06-10 15:24:42 +00002651 /* The only field we need to clear is tp_mro, which is part of a
2652 hard cycle (its first element is the class itself) that won't
2653 be broken otherwise (it's a tuple and tuples don't have a
2654 tp_clear handler). None of the other fields need to be
2655 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002656
Guido van Rossuma3862092002-06-10 15:24:42 +00002657 tp_dict:
2658 It is a dict, so the collector will call its tp_clear.
2659
2660 tp_cache:
2661 Not used; if it were, it would be a dict.
2662
2663 tp_bases, tp_base:
2664 If these are involved in a cycle, there must be at least
2665 one other, mutable object in the cycle, e.g. a base
2666 class's dict; the cycle will be broken that way.
2667
2668 tp_subclasses:
2669 A list of weak references can't be part of a cycle; and
2670 lists have their own tp_clear.
2671
Guido van Rossume5c691a2003-03-07 15:13:17 +00002672 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002673 A tuple of strings can't be part of a cycle.
2674 */
2675
Thomas Woutersedf17d82006-04-15 17:28:34 +00002676 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002677
2678 return 0;
2679}
2680
2681static int
2682type_is_gc(PyTypeObject *type)
2683{
2684 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2685}
2686
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002687PyTypeObject PyType_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002688 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002689 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002690 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002691 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002692 (destructor)type_dealloc, /* tp_dealloc */
2693 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002694 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002695 0, /* tp_setattr */
2696 type_compare, /* tp_compare */
2697 (reprfunc)type_repr, /* tp_repr */
2698 0, /* tp_as_number */
2699 0, /* tp_as_sequence */
2700 0, /* tp_as_mapping */
2701 (hashfunc)_Py_HashPointer, /* tp_hash */
2702 (ternaryfunc)type_call, /* tp_call */
2703 0, /* tp_str */
2704 (getattrofunc)type_getattro, /* tp_getattro */
2705 (setattrofunc)type_setattro, /* tp_setattro */
2706 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002707 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002708 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002709 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002710 (traverseproc)type_traverse, /* tp_traverse */
2711 (inquiry)type_clear, /* tp_clear */
Steven Bethardae42f332008-03-18 17:26:10 +00002712 type_richcompare, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002713 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002714 0, /* tp_iter */
2715 0, /* tp_iternext */
2716 type_methods, /* tp_methods */
2717 type_members, /* tp_members */
2718 type_getsets, /* tp_getset */
2719 0, /* tp_base */
2720 0, /* tp_dict */
2721 0, /* tp_descr_get */
2722 0, /* tp_descr_set */
2723 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumf102e242007-03-23 18:53:03 +00002724 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002725 0, /* tp_alloc */
2726 type_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002727 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002728 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002729};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730
2731
2732/* The base type of all types (eventually)... except itself. */
2733
Guido van Rossum143b5642007-03-23 04:58:42 +00002734/* You may wonder why object.__new__() only complains about arguments
2735 when object.__init__() is not overridden, and vice versa.
2736
2737 Consider the use cases:
2738
2739 1. When neither is overridden, we want to hear complaints about
2740 excess (i.e., any) arguments, since their presence could
2741 indicate there's a bug.
2742
2743 2. When defining an Immutable type, we are likely to override only
2744 __new__(), since __init__() is called too late to initialize an
2745 Immutable object. Since __new__() defines the signature for the
2746 type, it would be a pain to have to override __init__() just to
2747 stop it from complaining about excess arguments.
2748
2749 3. When defining a Mutable type, we are likely to override only
2750 __init__(). So here the converse reasoning applies: we don't
2751 want to have to override __new__() just to stop it from
2752 complaining.
2753
2754 4. When __init__() is overridden, and the subclass __init__() calls
2755 object.__init__(), the latter should complain about excess
2756 arguments; ditto for __new__().
2757
2758 Use cases 2 and 3 make it unattractive to unconditionally check for
2759 excess arguments. The best solution that addresses all four use
2760 cases is as follows: __init__() complains about excess arguments
2761 unless __new__() is overridden and __init__() is not overridden
2762 (IOW, if __init__() is overridden or __new__() is not overridden);
2763 symmetrically, __new__() complains about excess arguments unless
2764 __init__() is overridden and __new__() is not overridden
2765 (IOW, if __new__() is overridden or __init__() is not overridden).
2766
2767 However, for backwards compatibility, this breaks too much code.
2768 Therefore, in 2.6, we'll *warn* about excess arguments when both
2769 methods are overridden; for all other cases we'll use the above
2770 rules.
2771
2772*/
2773
2774/* Forward */
2775static PyObject *
2776object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2777
2778static int
2779excess_args(PyObject *args, PyObject *kwds)
2780{
2781 return PyTuple_GET_SIZE(args) ||
2782 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2783}
2784
Tim Peters6d6c1a32001-08-02 04:15:00 +00002785static int
2786object_init(PyObject *self, PyObject *args, PyObject *kwds)
2787{
Guido van Rossum143b5642007-03-23 04:58:42 +00002788 int err = 0;
2789 if (excess_args(args, kwds)) {
Christian Heimese93237d2007-12-19 02:37:44 +00002790 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum143b5642007-03-23 04:58:42 +00002791 if (type->tp_init != object_init &&
2792 type->tp_new != object_new)
2793 {
2794 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2795 "object.__init__() takes no parameters",
2796 1);
2797 }
2798 else if (type->tp_init != object_init ||
2799 type->tp_new == object_new)
2800 {
2801 PyErr_SetString(PyExc_TypeError,
2802 "object.__init__() takes no parameters");
2803 err = -1;
2804 }
2805 }
2806 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002807}
2808
Guido van Rossum298e4212003-02-13 16:30:16 +00002809static PyObject *
2810object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2811{
Guido van Rossum143b5642007-03-23 04:58:42 +00002812 int err = 0;
2813 if (excess_args(args, kwds)) {
2814 if (type->tp_new != object_new &&
2815 type->tp_init != object_init)
2816 {
2817 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2818 "object.__new__() takes no parameters",
2819 1);
2820 }
2821 else if (type->tp_new != object_new ||
2822 type->tp_init == object_init)
2823 {
2824 PyErr_SetString(PyExc_TypeError,
2825 "object.__new__() takes no parameters");
2826 err = -1;
2827 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002828 }
Guido van Rossum143b5642007-03-23 04:58:42 +00002829 if (err < 0)
2830 return NULL;
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00002831
2832 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2833 static PyObject *comma = NULL;
2834 PyObject *abstract_methods = NULL;
2835 PyObject *builtins;
2836 PyObject *sorted;
2837 PyObject *sorted_methods = NULL;
2838 PyObject *joined = NULL;
2839 const char *joined_str;
2840
2841 /* Compute ", ".join(sorted(type.__abstractmethods__))
2842 into joined. */
2843 abstract_methods = type_abstractmethods(type, NULL);
2844 if (abstract_methods == NULL)
2845 goto error;
2846 builtins = PyEval_GetBuiltins();
2847 if (builtins == NULL)
2848 goto error;
2849 sorted = PyDict_GetItemString(builtins, "sorted");
2850 if (sorted == NULL)
2851 goto error;
2852 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2853 abstract_methods,
2854 NULL);
2855 if (sorted_methods == NULL)
2856 goto error;
2857 if (comma == NULL) {
2858 comma = PyString_InternFromString(", ");
2859 if (comma == NULL)
2860 goto error;
2861 }
2862 joined = PyObject_CallMethod(comma, "join",
2863 "O", sorted_methods);
2864 if (joined == NULL)
2865 goto error;
2866 joined_str = PyString_AsString(joined);
2867 if (joined_str == NULL)
2868 goto error;
2869
2870 PyErr_Format(PyExc_TypeError,
2871 "Can't instantiate abstract class %s "
2872 "with abstract methods %s",
2873 type->tp_name,
2874 joined_str);
2875 error:
2876 Py_XDECREF(joined);
2877 Py_XDECREF(sorted_methods);
2878 Py_XDECREF(abstract_methods);
2879 return NULL;
2880 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002881 return type->tp_alloc(type, 0);
2882}
2883
Tim Peters6d6c1a32001-08-02 04:15:00 +00002884static void
2885object_dealloc(PyObject *self)
2886{
Christian Heimese93237d2007-12-19 02:37:44 +00002887 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002888}
2889
Guido van Rossum8e248182001-08-12 05:17:56 +00002890static PyObject *
2891object_repr(PyObject *self)
2892{
Guido van Rossum76e69632001-08-16 18:52:43 +00002893 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002894 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002895
Christian Heimese93237d2007-12-19 02:37:44 +00002896 type = Py_TYPE(self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002897 mod = type_module(type, NULL);
2898 if (mod == NULL)
2899 PyErr_Clear();
2900 else if (!PyString_Check(mod)) {
2901 Py_DECREF(mod);
2902 mod = NULL;
2903 }
2904 name = type_name(type, NULL);
2905 if (name == NULL)
2906 return NULL;
2907 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002908 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002909 PyString_AS_STRING(mod),
2910 PyString_AS_STRING(name),
2911 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002912 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002913 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002914 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002915 Py_XDECREF(mod);
2916 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002917 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002918}
2919
Guido van Rossumb8f63662001-08-15 23:57:02 +00002920static PyObject *
2921object_str(PyObject *self)
2922{
2923 unaryfunc f;
2924
Christian Heimese93237d2007-12-19 02:37:44 +00002925 f = Py_TYPE(self)->tp_repr;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002926 if (f == NULL)
2927 f = object_repr;
2928 return f(self);
2929}
2930
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002931static PyObject *
2932object_get_class(PyObject *self, void *closure)
2933{
Christian Heimese93237d2007-12-19 02:37:44 +00002934 Py_INCREF(Py_TYPE(self));
2935 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002936}
2937
2938static int
2939equiv_structs(PyTypeObject *a, PyTypeObject *b)
2940{
2941 return a == b ||
2942 (a != NULL &&
2943 b != NULL &&
2944 a->tp_basicsize == b->tp_basicsize &&
2945 a->tp_itemsize == b->tp_itemsize &&
2946 a->tp_dictoffset == b->tp_dictoffset &&
2947 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2948 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2949 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2950}
2951
2952static int
2953same_slots_added(PyTypeObject *a, PyTypeObject *b)
2954{
2955 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002956 Py_ssize_t size;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002957 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002958
2959 if (base != b->tp_base)
2960 return 0;
2961 if (equiv_structs(a, base) && equiv_structs(b, base))
2962 return 1;
2963 size = base->tp_basicsize;
2964 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2965 size += sizeof(PyObject *);
2966 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2967 size += sizeof(PyObject *);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002968
2969 /* Check slots compliance */
2970 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2971 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2972 if (slots_a && slots_b) {
2973 if (PyObject_Compare(slots_a, slots_b) != 0)
2974 return 0;
2975 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2976 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002977 return size == a->tp_basicsize && size == b->tp_basicsize;
2978}
2979
2980static int
Anthony Baxtera6286212006-04-11 07:42:36 +00002981compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002982{
2983 PyTypeObject *newbase, *oldbase;
2984
Anthony Baxtera6286212006-04-11 07:42:36 +00002985 if (newto->tp_dealloc != oldto->tp_dealloc ||
2986 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002987 {
2988 PyErr_Format(PyExc_TypeError,
2989 "%s assignment: "
2990 "'%s' deallocator differs from '%s'",
2991 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002992 newto->tp_name,
2993 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002994 return 0;
2995 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002996 newbase = newto;
2997 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002998 while (equiv_structs(newbase, newbase->tp_base))
2999 newbase = newbase->tp_base;
3000 while (equiv_structs(oldbase, oldbase->tp_base))
3001 oldbase = oldbase->tp_base;
3002 if (newbase != oldbase &&
3003 (newbase->tp_base != oldbase->tp_base ||
3004 !same_slots_added(newbase, oldbase))) {
3005 PyErr_Format(PyExc_TypeError,
3006 "%s assignment: "
3007 "'%s' object layout differs from '%s'",
3008 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00003009 newto->tp_name,
3010 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003011 return 0;
3012 }
Tim Petersea7f75d2002-12-07 21:39:16 +00003013
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003014 return 1;
3015}
3016
3017static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003018object_set_class(PyObject *self, PyObject *value, void *closure)
3019{
Christian Heimese93237d2007-12-19 02:37:44 +00003020 PyTypeObject *oldto = Py_TYPE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00003021 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003022
Guido van Rossumb6b89422002-04-15 01:03:30 +00003023 if (value == NULL) {
3024 PyErr_SetString(PyExc_TypeError,
3025 "can't delete __class__ attribute");
3026 return -1;
3027 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003028 if (!PyType_Check(value)) {
3029 PyErr_Format(PyExc_TypeError,
3030 "__class__ must be set to new-style class, not '%s' object",
Christian Heimese93237d2007-12-19 02:37:44 +00003031 Py_TYPE(value)->tp_name);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003032 return -1;
3033 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003034 newto = (PyTypeObject *)value;
3035 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3036 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00003037 {
3038 PyErr_Format(PyExc_TypeError,
3039 "__class__ assignment: only for heap types");
3040 return -1;
3041 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003042 if (compatible_for_assignment(newto, oldto, "__class__")) {
3043 Py_INCREF(newto);
Christian Heimese93237d2007-12-19 02:37:44 +00003044 Py_TYPE(self) = newto;
Anthony Baxtera6286212006-04-11 07:42:36 +00003045 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003046 return 0;
3047 }
3048 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00003049 return -1;
3050 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003051}
3052
3053static PyGetSetDef object_getsets[] = {
3054 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00003055 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003056 {0}
3057};
3058
Guido van Rossumc53f0092003-02-18 22:05:12 +00003059
Guido van Rossum036f9992003-02-21 22:02:54 +00003060/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
Georg Brandldffbf5f2008-05-20 07:49:57 +00003061 We fall back to helpers in copy_reg for:
Guido van Rossum036f9992003-02-21 22:02:54 +00003062 - pickle protocols < 2
3063 - calculating the list of slot names (done only once per class)
3064 - the __newobj__ function (which is used as a token but never called)
3065*/
3066
3067static PyObject *
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003068import_copyreg(void)
Guido van Rossum036f9992003-02-21 22:02:54 +00003069{
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003070 static PyObject *copyreg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00003071
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003072 if (!copyreg_str) {
Georg Brandldffbf5f2008-05-20 07:49:57 +00003073 copyreg_str = PyString_InternFromString("copy_reg");
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003074 if (copyreg_str == NULL)
Guido van Rossum3926a632001-09-25 16:25:58 +00003075 return NULL;
3076 }
Guido van Rossum036f9992003-02-21 22:02:54 +00003077
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003078 return PyImport_Import(copyreg_str);
Guido van Rossum036f9992003-02-21 22:02:54 +00003079}
3080
3081static PyObject *
3082slotnames(PyObject *cls)
3083{
3084 PyObject *clsdict;
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003085 PyObject *copyreg;
Guido van Rossum036f9992003-02-21 22:02:54 +00003086 PyObject *slotnames;
3087
3088 if (!PyType_Check(cls)) {
3089 Py_INCREF(Py_None);
3090 return Py_None;
3091 }
3092
3093 clsdict = ((PyTypeObject *)cls)->tp_dict;
3094 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00003095 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00003096 Py_INCREF(slotnames);
3097 return slotnames;
3098 }
3099
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003100 copyreg = import_copyreg();
3101 if (copyreg == NULL)
Guido van Rossum036f9992003-02-21 22:02:54 +00003102 return NULL;
3103
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003104 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
3105 Py_DECREF(copyreg);
Guido van Rossum036f9992003-02-21 22:02:54 +00003106 if (slotnames != NULL &&
3107 slotnames != Py_None &&
3108 !PyList_Check(slotnames))
3109 {
3110 PyErr_SetString(PyExc_TypeError,
Georg Brandldffbf5f2008-05-20 07:49:57 +00003111 "copy_reg._slotnames didn't return a list or None");
Guido van Rossum036f9992003-02-21 22:02:54 +00003112 Py_DECREF(slotnames);
3113 slotnames = NULL;
3114 }
3115
3116 return slotnames;
3117}
3118
3119static PyObject *
3120reduce_2(PyObject *obj)
3121{
3122 PyObject *cls, *getnewargs;
3123 PyObject *args = NULL, *args2 = NULL;
3124 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3125 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003126 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003127 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00003128
3129 cls = PyObject_GetAttrString(obj, "__class__");
3130 if (cls == NULL)
3131 return NULL;
3132
3133 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
3134 if (getnewargs != NULL) {
3135 args = PyObject_CallObject(getnewargs, NULL);
3136 Py_DECREF(getnewargs);
3137 if (args != NULL && !PyTuple_Check(args)) {
Georg Brandlccff7852006-06-18 22:17:29 +00003138 PyErr_Format(PyExc_TypeError,
3139 "__getnewargs__ should return a tuple, "
Christian Heimese93237d2007-12-19 02:37:44 +00003140 "not '%.200s'", Py_TYPE(args)->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00003141 goto end;
3142 }
3143 }
3144 else {
3145 PyErr_Clear();
3146 args = PyTuple_New(0);
3147 }
3148 if (args == NULL)
3149 goto end;
3150
3151 getstate = PyObject_GetAttrString(obj, "__getstate__");
3152 if (getstate != NULL) {
3153 state = PyObject_CallObject(getstate, NULL);
3154 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00003155 if (state == NULL)
3156 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00003157 }
3158 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00003159 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00003160 state = PyObject_GetAttrString(obj, "__dict__");
3161 if (state == NULL) {
3162 PyErr_Clear();
3163 state = Py_None;
3164 Py_INCREF(state);
3165 }
3166 names = slotnames(cls);
3167 if (names == NULL)
3168 goto end;
3169 if (names != Py_None) {
3170 assert(PyList_Check(names));
3171 slots = PyDict_New();
3172 if (slots == NULL)
3173 goto end;
3174 n = 0;
3175 /* Can't pre-compute the list size; the list
3176 is stored on the class so accessible to other
3177 threads, which may be run by DECREF */
3178 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3179 PyObject *name, *value;
3180 name = PyList_GET_ITEM(names, i);
3181 value = PyObject_GetAttr(obj, name);
3182 if (value == NULL)
3183 PyErr_Clear();
3184 else {
3185 int err = PyDict_SetItem(slots, name,
3186 value);
3187 Py_DECREF(value);
3188 if (err)
3189 goto end;
3190 n++;
3191 }
3192 }
3193 if (n) {
3194 state = Py_BuildValue("(NO)", state, slots);
3195 if (state == NULL)
3196 goto end;
3197 }
3198 }
3199 }
3200
3201 if (!PyList_Check(obj)) {
3202 listitems = Py_None;
3203 Py_INCREF(listitems);
3204 }
3205 else {
3206 listitems = PyObject_GetIter(obj);
3207 if (listitems == NULL)
3208 goto end;
3209 }
3210
3211 if (!PyDict_Check(obj)) {
3212 dictitems = Py_None;
3213 Py_INCREF(dictitems);
3214 }
3215 else {
3216 dictitems = PyObject_CallMethod(obj, "iteritems", "");
3217 if (dictitems == NULL)
3218 goto end;
3219 }
3220
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003221 copyreg = import_copyreg();
3222 if (copyreg == NULL)
Guido van Rossum036f9992003-02-21 22:02:54 +00003223 goto end;
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003224 newobj = PyObject_GetAttrString(copyreg, "__newobj__");
Guido van Rossum036f9992003-02-21 22:02:54 +00003225 if (newobj == NULL)
3226 goto end;
3227
3228 n = PyTuple_GET_SIZE(args);
3229 args2 = PyTuple_New(n+1);
3230 if (args2 == NULL)
3231 goto end;
3232 PyTuple_SET_ITEM(args2, 0, cls);
3233 cls = NULL;
3234 for (i = 0; i < n; i++) {
3235 PyObject *v = PyTuple_GET_ITEM(args, i);
3236 Py_INCREF(v);
3237 PyTuple_SET_ITEM(args2, i+1, v);
3238 }
3239
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003240 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00003241
3242 end:
3243 Py_XDECREF(cls);
3244 Py_XDECREF(args);
3245 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00003246 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00003247 Py_XDECREF(state);
3248 Py_XDECREF(names);
3249 Py_XDECREF(listitems);
3250 Py_XDECREF(dictitems);
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003251 Py_XDECREF(copyreg);
Guido van Rossum036f9992003-02-21 22:02:54 +00003252 Py_XDECREF(newobj);
3253 return res;
3254}
3255
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003256/*
3257 * There were two problems when object.__reduce__ and object.__reduce_ex__
3258 * were implemented in the same function:
3259 * - trying to pickle an object with a custom __reduce__ method that
3260 * fell back to object.__reduce__ in certain circumstances led to
3261 * infinite recursion at Python level and eventual RuntimeError.
3262 * - Pickling objects that lied about their type by overwriting the
3263 * __class__ descriptor could lead to infinite recursion at C level
3264 * and eventual segfault.
3265 *
3266 * Because of backwards compatibility, the two methods still have to
3267 * behave in the same way, even if this is not required by the pickle
3268 * protocol. This common functionality was moved to the _common_reduce
3269 * function.
3270 */
3271static PyObject *
3272_common_reduce(PyObject *self, int proto)
3273{
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003274 PyObject *copyreg, *res;
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003275
3276 if (proto >= 2)
3277 return reduce_2(self);
3278
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003279 copyreg = import_copyreg();
3280 if (!copyreg)
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003281 return NULL;
3282
Alexandre Vassalotti9510e4a2008-05-11 08:25:28 +00003283 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3284 Py_DECREF(copyreg);
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003285
3286 return res;
3287}
3288
3289static PyObject *
3290object_reduce(PyObject *self, PyObject *args)
3291{
3292 int proto = 0;
3293
3294 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3295 return NULL;
3296
3297 return _common_reduce(self, proto);
3298}
3299
Guido van Rossum036f9992003-02-21 22:02:54 +00003300static PyObject *
3301object_reduce_ex(PyObject *self, PyObject *args)
3302{
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003303 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00003304 int proto = 0;
3305
3306 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3307 return NULL;
3308
3309 reduce = PyObject_GetAttrString(self, "__reduce__");
3310 if (reduce == NULL)
3311 PyErr_Clear();
3312 else {
3313 PyObject *cls, *clsreduce, *objreduce;
3314 int override;
3315 cls = PyObject_GetAttrString(self, "__class__");
3316 if (cls == NULL) {
3317 Py_DECREF(reduce);
3318 return NULL;
3319 }
3320 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3321 Py_DECREF(cls);
3322 if (clsreduce == NULL) {
3323 Py_DECREF(reduce);
3324 return NULL;
3325 }
3326 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3327 "__reduce__");
3328 override = (clsreduce != objreduce);
3329 Py_DECREF(clsreduce);
3330 if (override) {
3331 res = PyObject_CallObject(reduce, NULL);
3332 Py_DECREF(reduce);
3333 return res;
3334 }
3335 else
3336 Py_DECREF(reduce);
3337 }
3338
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003339 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003340}
3341
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00003342static PyObject *
3343object_subclasshook(PyObject *cls, PyObject *args)
3344{
3345 Py_INCREF(Py_NotImplemented);
3346 return Py_NotImplemented;
3347}
3348
3349PyDoc_STRVAR(object_subclasshook_doc,
3350"Abstract classes can override this to customize issubclass().\n"
3351"\n"
3352"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3353"It should return True, False or NotImplemented. If it returns\n"
3354"NotImplemented, the normal algorithm is used. Otherwise, it\n"
3355"overrides the normal algorithm (and the outcome is cached).\n");
3356
Eric Smitha9f7d622008-02-17 19:46:49 +00003357/*
3358 from PEP 3101, this code implements:
3359
3360 class object:
3361 def __format__(self, format_spec):
3362 if isinstance(format_spec, str):
3363 return format(str(self), format_spec)
3364 elif isinstance(format_spec, unicode):
3365 return format(unicode(self), format_spec)
3366*/
3367static PyObject *
3368object_format(PyObject *self, PyObject *args)
3369{
3370 PyObject *format_spec;
3371 PyObject *self_as_str = NULL;
3372 PyObject *result = NULL;
3373 PyObject *format_meth = NULL;
3374
3375 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3376 return NULL;
3377 if (PyUnicode_Check(format_spec)) {
3378 self_as_str = PyObject_Unicode(self);
3379 } else if (PyString_Check(format_spec)) {
3380 self_as_str = PyObject_Str(self);
3381 } else {
3382 PyErr_SetString(PyExc_TypeError, "argument to __format__ must be unicode or str");
3383 return NULL;
3384 }
3385
3386 if (self_as_str != NULL) {
3387 /* find the format function */
3388 format_meth = PyObject_GetAttrString(self_as_str, "__format__");
3389 if (format_meth != NULL) {
3390 /* and call it */
3391 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
3392 }
3393 }
3394
3395 Py_XDECREF(self_as_str);
3396 Py_XDECREF(format_meth);
3397
3398 return result;
3399}
3400
Guido van Rossum3926a632001-09-25 16:25:58 +00003401static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00003402 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3403 PyDoc_STR("helper for pickle")},
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003404 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003405 PyDoc_STR("helper for pickle")},
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +00003406 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3407 object_subclasshook_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00003408 {"__format__", object_format, METH_VARARGS,
3409 PyDoc_STR("default object formatter")},
Guido van Rossum3926a632001-09-25 16:25:58 +00003410 {0}
3411};
3412
Guido van Rossum036f9992003-02-21 22:02:54 +00003413
Tim Peters6d6c1a32001-08-02 04:15:00 +00003414PyTypeObject PyBaseObject_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00003415 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003416 "object", /* tp_name */
3417 sizeof(PyObject), /* tp_basicsize */
3418 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003419 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003420 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003421 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003422 0, /* tp_setattr */
3423 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003424 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003425 0, /* tp_as_number */
3426 0, /* tp_as_sequence */
3427 0, /* tp_as_mapping */
Guido van Rossum64c06e32007-11-22 00:55:51 +00003428 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003429 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003430 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003431 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003432 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003433 0, /* tp_as_buffer */
3434 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003435 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003436 0, /* tp_traverse */
3437 0, /* tp_clear */
3438 0, /* tp_richcompare */
3439 0, /* tp_weaklistoffset */
3440 0, /* tp_iter */
3441 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00003442 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003443 0, /* tp_members */
3444 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003445 0, /* tp_base */
3446 0, /* tp_dict */
3447 0, /* tp_descr_get */
3448 0, /* tp_descr_set */
3449 0, /* tp_dictoffset */
3450 object_init, /* tp_init */
3451 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003452 object_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003453 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003454};
3455
3456
3457/* Initialize the __dict__ in a type object */
3458
3459static int
3460add_methods(PyTypeObject *type, PyMethodDef *meth)
3461{
Guido van Rossum687ae002001-10-15 22:03:32 +00003462 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003463
3464 for (; meth->ml_name != NULL; meth++) {
3465 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003466 if (PyDict_GetItemString(dict, meth->ml_name) &&
3467 !(meth->ml_flags & METH_COEXIST))
3468 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003469 if (meth->ml_flags & METH_CLASS) {
3470 if (meth->ml_flags & METH_STATIC) {
3471 PyErr_SetString(PyExc_ValueError,
3472 "method cannot be both class and static");
3473 return -1;
3474 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003475 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003476 }
3477 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003478 PyObject *cfunc = PyCFunction_New(meth, NULL);
3479 if (cfunc == NULL)
3480 return -1;
3481 descr = PyStaticMethod_New(cfunc);
3482 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003483 }
3484 else {
3485 descr = PyDescr_NewMethod(type, meth);
3486 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003487 if (descr == NULL)
3488 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003489 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003490 return -1;
3491 Py_DECREF(descr);
3492 }
3493 return 0;
3494}
3495
3496static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003497add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003498{
Guido van Rossum687ae002001-10-15 22:03:32 +00003499 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003500
3501 for (; memb->name != NULL; memb++) {
3502 PyObject *descr;
3503 if (PyDict_GetItemString(dict, memb->name))
3504 continue;
3505 descr = PyDescr_NewMember(type, memb);
3506 if (descr == NULL)
3507 return -1;
3508 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3509 return -1;
3510 Py_DECREF(descr);
3511 }
3512 return 0;
3513}
3514
3515static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003516add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003517{
Guido van Rossum687ae002001-10-15 22:03:32 +00003518 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003519
3520 for (; gsp->name != NULL; gsp++) {
3521 PyObject *descr;
3522 if (PyDict_GetItemString(dict, gsp->name))
3523 continue;
3524 descr = PyDescr_NewGetSet(type, gsp);
3525
3526 if (descr == NULL)
3527 return -1;
3528 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3529 return -1;
3530 Py_DECREF(descr);
3531 }
3532 return 0;
3533}
3534
Guido van Rossum13d52f02001-08-10 21:24:08 +00003535static void
3536inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003537{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003538 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003539
Guido van Rossum13d52f02001-08-10 21:24:08 +00003540 /* Special flag magic */
3541 if (!type->tp_as_buffer && base->tp_as_buffer) {
3542 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
3543 type->tp_flags |=
3544 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
3545 }
3546 if (!type->tp_as_sequence && base->tp_as_sequence) {
3547 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3548 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3549 }
3550 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3551 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3552 if ((!type->tp_as_number && base->tp_as_number) ||
3553 (!type->tp_as_sequence && base->tp_as_sequence)) {
3554 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3555 if (!type->tp_as_number && !type->tp_as_sequence) {
3556 type->tp_flags |= base->tp_flags &
3557 Py_TPFLAGS_HAVE_INPLACEOPS;
3558 }
3559 }
3560 /* Wow */
3561 }
3562 if (!type->tp_as_number && base->tp_as_number) {
3563 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3564 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3565 }
3566
3567 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003568 oldsize = base->tp_basicsize;
3569 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3570 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3571 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003572 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3573 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003574 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003575 if (type->tp_traverse == NULL)
3576 type->tp_traverse = base->tp_traverse;
3577 if (type->tp_clear == NULL)
3578 type->tp_clear = base->tp_clear;
3579 }
3580 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00003581 /* The condition below could use some explanation.
3582 It appears that tp_new is not inherited for static types
3583 whose base class is 'object'; this seems to be a precaution
3584 so that old extension types don't suddenly become
3585 callable (object.__new__ wouldn't insure the invariants
3586 that the extension type's own factory function ensures).
3587 Heap types, of course, are under our control, so they do
3588 inherit tp_new; static extension types that specify some
3589 other built-in type as the default are considered
3590 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003591 if (base != &PyBaseObject_Type ||
3592 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3593 if (type->tp_new == NULL)
3594 type->tp_new = base->tp_new;
3595 }
3596 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003597 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003598
3599 /* Copy other non-function slots */
3600
3601#undef COPYVAL
3602#define COPYVAL(SLOT) \
3603 if (type->SLOT == 0) type->SLOT = base->SLOT
3604
3605 COPYVAL(tp_itemsize);
3606 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3607 COPYVAL(tp_weaklistoffset);
3608 }
3609 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3610 COPYVAL(tp_dictoffset);
3611 }
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003612
3613 /* Setup fast subclass flags */
3614 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3615 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3616 else if (PyType_IsSubtype(base, &PyType_Type))
3617 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3618 else if (PyType_IsSubtype(base, &PyInt_Type))
3619 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3620 else if (PyType_IsSubtype(base, &PyLong_Type))
3621 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3622 else if (PyType_IsSubtype(base, &PyString_Type))
3623 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003624#ifdef Py_USING_UNICODE
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003625 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3626 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
Georg Brandldfe5dc82008-01-07 18:16:36 +00003627#endif
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003628 else if (PyType_IsSubtype(base, &PyTuple_Type))
3629 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3630 else if (PyType_IsSubtype(base, &PyList_Type))
3631 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3632 else if (PyType_IsSubtype(base, &PyDict_Type))
3633 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003634}
3635
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003636static char *hash_name_op[] = {
3637 "__eq__",
3638 "__cmp__",
3639 "__hash__",
3640 NULL
Guido van Rossum64c06e32007-11-22 00:55:51 +00003641};
3642
3643static int
3644overrides_hash(PyTypeObject *type)
3645{
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003646 char **p;
Guido van Rossum64c06e32007-11-22 00:55:51 +00003647 PyObject *dict = type->tp_dict;
3648
3649 assert(dict != NULL);
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00003650 for (p = hash_name_op; *p; p++) {
3651 if (PyDict_GetItemString(dict, *p) != NULL)
Guido van Rossum64c06e32007-11-22 00:55:51 +00003652 return 1;
3653 }
3654 return 0;
3655}
3656
Guido van Rossum13d52f02001-08-10 21:24:08 +00003657static void
3658inherit_slots(PyTypeObject *type, PyTypeObject *base)
3659{
3660 PyTypeObject *basebase;
3661
3662#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003663#undef COPYSLOT
3664#undef COPYNUM
3665#undef COPYSEQ
3666#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003667#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003668
3669#define SLOTDEFINED(SLOT) \
3670 (base->SLOT != 0 && \
3671 (basebase == NULL || base->SLOT != basebase->SLOT))
3672
Tim Peters6d6c1a32001-08-02 04:15:00 +00003673#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003674 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003675
3676#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3677#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3678#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003679#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003680
Guido van Rossum13d52f02001-08-10 21:24:08 +00003681 /* This won't inherit indirect slots (from tp_as_number etc.)
3682 if type doesn't provide the space. */
3683
3684 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3685 basebase = base->tp_base;
3686 if (basebase->tp_as_number == NULL)
3687 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003688 COPYNUM(nb_add);
3689 COPYNUM(nb_subtract);
3690 COPYNUM(nb_multiply);
3691 COPYNUM(nb_divide);
3692 COPYNUM(nb_remainder);
3693 COPYNUM(nb_divmod);
3694 COPYNUM(nb_power);
3695 COPYNUM(nb_negative);
3696 COPYNUM(nb_positive);
3697 COPYNUM(nb_absolute);
3698 COPYNUM(nb_nonzero);
3699 COPYNUM(nb_invert);
3700 COPYNUM(nb_lshift);
3701 COPYNUM(nb_rshift);
3702 COPYNUM(nb_and);
3703 COPYNUM(nb_xor);
3704 COPYNUM(nb_or);
3705 COPYNUM(nb_coerce);
3706 COPYNUM(nb_int);
3707 COPYNUM(nb_long);
3708 COPYNUM(nb_float);
3709 COPYNUM(nb_oct);
3710 COPYNUM(nb_hex);
3711 COPYNUM(nb_inplace_add);
3712 COPYNUM(nb_inplace_subtract);
3713 COPYNUM(nb_inplace_multiply);
3714 COPYNUM(nb_inplace_divide);
3715 COPYNUM(nb_inplace_remainder);
3716 COPYNUM(nb_inplace_power);
3717 COPYNUM(nb_inplace_lshift);
3718 COPYNUM(nb_inplace_rshift);
3719 COPYNUM(nb_inplace_and);
3720 COPYNUM(nb_inplace_xor);
3721 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003722 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3723 COPYNUM(nb_true_divide);
3724 COPYNUM(nb_floor_divide);
3725 COPYNUM(nb_inplace_true_divide);
3726 COPYNUM(nb_inplace_floor_divide);
3727 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003728 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3729 COPYNUM(nb_index);
3730 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003731 }
3732
Guido van Rossum13d52f02001-08-10 21:24:08 +00003733 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3734 basebase = base->tp_base;
3735 if (basebase->tp_as_sequence == NULL)
3736 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003737 COPYSEQ(sq_length);
3738 COPYSEQ(sq_concat);
3739 COPYSEQ(sq_repeat);
3740 COPYSEQ(sq_item);
3741 COPYSEQ(sq_slice);
3742 COPYSEQ(sq_ass_item);
3743 COPYSEQ(sq_ass_slice);
3744 COPYSEQ(sq_contains);
3745 COPYSEQ(sq_inplace_concat);
3746 COPYSEQ(sq_inplace_repeat);
3747 }
3748
Guido van Rossum13d52f02001-08-10 21:24:08 +00003749 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3750 basebase = base->tp_base;
3751 if (basebase->tp_as_mapping == NULL)
3752 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003753 COPYMAP(mp_length);
3754 COPYMAP(mp_subscript);
3755 COPYMAP(mp_ass_subscript);
3756 }
3757
Tim Petersfc57ccb2001-10-12 02:38:24 +00003758 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3759 basebase = base->tp_base;
3760 if (basebase->tp_as_buffer == NULL)
3761 basebase = NULL;
3762 COPYBUF(bf_getreadbuffer);
3763 COPYBUF(bf_getwritebuffer);
3764 COPYBUF(bf_getsegcount);
3765 COPYBUF(bf_getcharbuffer);
Christian Heimes1a6387e2008-03-26 12:49:49 +00003766 COPYBUF(bf_getbuffer);
3767 COPYBUF(bf_releasebuffer);
Tim Petersfc57ccb2001-10-12 02:38:24 +00003768 }
3769
Guido van Rossum13d52f02001-08-10 21:24:08 +00003770 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003771
Tim Peters6d6c1a32001-08-02 04:15:00 +00003772 COPYSLOT(tp_dealloc);
3773 COPYSLOT(tp_print);
3774 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3775 type->tp_getattr = base->tp_getattr;
3776 type->tp_getattro = base->tp_getattro;
3777 }
3778 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3779 type->tp_setattr = base->tp_setattr;
3780 type->tp_setattro = base->tp_setattro;
3781 }
3782 /* tp_compare see tp_richcompare */
3783 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003784 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003785 COPYSLOT(tp_call);
3786 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003787 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003788 if (type->tp_compare == NULL &&
3789 type->tp_richcompare == NULL &&
Guido van Rossum64c06e32007-11-22 00:55:51 +00003790 type->tp_hash == NULL &&
3791 !overrides_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003792 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003793 type->tp_compare = base->tp_compare;
3794 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003795 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003796 }
3797 }
3798 else {
3799 COPYSLOT(tp_compare);
3800 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003801 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3802 COPYSLOT(tp_iter);
3803 COPYSLOT(tp_iternext);
3804 }
3805 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3806 COPYSLOT(tp_descr_get);
3807 COPYSLOT(tp_descr_set);
3808 COPYSLOT(tp_dictoffset);
3809 COPYSLOT(tp_init);
3810 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003811 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003812 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3813 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3814 /* They agree about gc. */
3815 COPYSLOT(tp_free);
3816 }
3817 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3818 type->tp_free == NULL &&
3819 base->tp_free == _PyObject_Del) {
3820 /* A bit of magic to plug in the correct default
3821 * tp_free function when a derived class adds gc,
3822 * didn't define tp_free, and the base uses the
3823 * default non-gc tp_free.
3824 */
3825 type->tp_free = PyObject_GC_Del;
3826 }
3827 /* else they didn't agree about gc, and there isn't something
3828 * obvious to be done -- the type is on its own.
3829 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003830 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003831}
3832
Jeremy Hylton938ace62002-07-17 16:30:39 +00003833static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003834
Tim Peters6d6c1a32001-08-02 04:15:00 +00003835int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003836PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003837{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003838 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003839 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003840 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003841
Guido van Rossumcab05802002-06-10 15:29:03 +00003842 if (type->tp_flags & Py_TPFLAGS_READY) {
3843 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003844 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003845 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003846 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003847
3848 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003849
Tim Peters36eb4df2003-03-23 03:33:13 +00003850#ifdef Py_TRACE_REFS
3851 /* PyType_Ready is the closest thing we have to a choke point
3852 * for type objects, so is the best place I can think of to try
3853 * to get type objects into the doubly-linked list of all objects.
3854 * Still, not all type objects go thru PyType_Ready.
3855 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003856 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003857#endif
3858
Tim Peters6d6c1a32001-08-02 04:15:00 +00003859 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3860 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003861 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003862 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003863 Py_INCREF(base);
3864 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003865
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003866 /* Now the only way base can still be NULL is if type is
3867 * &PyBaseObject_Type.
3868 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003869
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003870 /* Initialize the base class */
3871 if (base && base->tp_dict == NULL) {
3872 if (PyType_Ready(base) < 0)
3873 goto error;
3874 }
3875
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003876 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003877 compilable separately on Windows can call PyType_Ready() instead of
3878 initializing the ob_type field of their type objects. */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003879 /* The test for base != NULL is really unnecessary, since base is only
3880 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3881 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3882 know that. */
Christian Heimese93237d2007-12-19 02:37:44 +00003883 if (Py_TYPE(type) == NULL && base != NULL)
3884 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003885
Tim Peters6d6c1a32001-08-02 04:15:00 +00003886 /* Initialize tp_bases */
3887 bases = type->tp_bases;
3888 if (bases == NULL) {
3889 if (base == NULL)
3890 bases = PyTuple_New(0);
3891 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003892 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003893 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003894 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003895 type->tp_bases = bases;
3896 }
3897
Guido van Rossum687ae002001-10-15 22:03:32 +00003898 /* Initialize tp_dict */
3899 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003900 if (dict == NULL) {
3901 dict = PyDict_New();
3902 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003903 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003904 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003905 }
3906
Guido van Rossum687ae002001-10-15 22:03:32 +00003907 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003908 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003909 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003910 if (type->tp_methods != NULL) {
3911 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003912 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003913 }
3914 if (type->tp_members != NULL) {
3915 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003916 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003917 }
3918 if (type->tp_getset != NULL) {
3919 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003920 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003921 }
3922
Tim Peters6d6c1a32001-08-02 04:15:00 +00003923 /* Calculate method resolution order */
3924 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003925 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003926 }
3927
Guido van Rossum13d52f02001-08-10 21:24:08 +00003928 /* Inherit special flags from dominant base */
3929 if (type->tp_base != NULL)
3930 inherit_special(type, type->tp_base);
3931
Tim Peters6d6c1a32001-08-02 04:15:00 +00003932 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003933 bases = type->tp_mro;
3934 assert(bases != NULL);
3935 assert(PyTuple_Check(bases));
3936 n = PyTuple_GET_SIZE(bases);
3937 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003938 PyObject *b = PyTuple_GET_ITEM(bases, i);
3939 if (PyType_Check(b))
3940 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003941 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003942
Tim Peters3cfe7542003-05-21 21:29:48 +00003943 /* Sanity check for tp_free. */
3944 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3945 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003946 /* This base class needs to call tp_free, but doesn't have
3947 * one, or its tp_free is for non-gc'ed objects.
3948 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003949 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3950 "gc and is a base type but has inappropriate "
3951 "tp_free slot",
3952 type->tp_name);
3953 goto error;
3954 }
3955
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003956 /* if the type dictionary doesn't contain a __doc__, set it from
3957 the tp_doc slot.
3958 */
3959 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3960 if (type->tp_doc != NULL) {
3961 PyObject *doc = PyString_FromString(type->tp_doc);
Neal Norwitze1fdb322006-07-21 05:32:28 +00003962 if (doc == NULL)
3963 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003964 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3965 Py_DECREF(doc);
3966 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003967 PyDict_SetItemString(type->tp_dict,
3968 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003969 }
3970 }
3971
Guido van Rossum64c06e32007-11-22 00:55:51 +00003972 /* Hack for tp_hash and __hash__.
3973 If after all that, tp_hash is still NULL, and __hash__ is not in
3974 tp_dict, set tp_dict['__hash__'] equal to None.
3975 This signals that __hash__ is not inherited.
3976 */
3977 if (type->tp_hash == NULL &&
3978 PyDict_GetItemString(type->tp_dict, "__hash__") == NULL &&
3979 PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3980 {
3981 goto error;
3982 }
3983
Guido van Rossum13d52f02001-08-10 21:24:08 +00003984 /* Some more special stuff */
3985 base = type->tp_base;
3986 if (base != NULL) {
3987 if (type->tp_as_number == NULL)
3988 type->tp_as_number = base->tp_as_number;
3989 if (type->tp_as_sequence == NULL)
3990 type->tp_as_sequence = base->tp_as_sequence;
3991 if (type->tp_as_mapping == NULL)
3992 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003993 if (type->tp_as_buffer == NULL)
3994 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003995 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003996
Guido van Rossum1c450732001-10-08 15:18:27 +00003997 /* Link into each base class's list of subclasses */
3998 bases = type->tp_bases;
3999 n = PyTuple_GET_SIZE(bases);
4000 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00004001 PyObject *b = PyTuple_GET_ITEM(bases, i);
4002 if (PyType_Check(b) &&
4003 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00004004 goto error;
4005 }
4006
Guido van Rossum13d52f02001-08-10 21:24:08 +00004007 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00004008 assert(type->tp_dict != NULL);
4009 type->tp_flags =
4010 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004011 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00004012
4013 error:
4014 type->tp_flags &= ~Py_TPFLAGS_READYING;
4015 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004016}
4017
Guido van Rossum1c450732001-10-08 15:18:27 +00004018static int
4019add_subclass(PyTypeObject *base, PyTypeObject *type)
4020{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004021 Py_ssize_t i;
4022 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00004023 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00004024
4025 list = base->tp_subclasses;
4026 if (list == NULL) {
4027 base->tp_subclasses = list = PyList_New(0);
4028 if (list == NULL)
4029 return -1;
4030 }
4031 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00004032 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00004033 i = PyList_GET_SIZE(list);
4034 while (--i >= 0) {
4035 ref = PyList_GET_ITEM(list, i);
4036 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00004037 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00004038 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00004039 }
Anthony Baxtera6286212006-04-11 07:42:36 +00004040 result = PyList_Append(list, newobj);
4041 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004042 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00004043}
4044
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004045static void
4046remove_subclass(PyTypeObject *base, PyTypeObject *type)
4047{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004048 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004049 PyObject *list, *ref;
4050
4051 list = base->tp_subclasses;
4052 if (list == NULL) {
4053 return;
4054 }
4055 assert(PyList_Check(list));
4056 i = PyList_GET_SIZE(list);
4057 while (--i >= 0) {
4058 ref = PyList_GET_ITEM(list, i);
4059 assert(PyWeakref_CheckRef(ref));
4060 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4061 /* this can't fail, right? */
4062 PySequence_DelItem(list, i);
4063 return;
4064 }
4065 }
4066}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004067
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004068static int
4069check_num_args(PyObject *ob, int n)
4070{
4071 if (!PyTuple_CheckExact(ob)) {
4072 PyErr_SetString(PyExc_SystemError,
4073 "PyArg_UnpackTuple() argument list is not a tuple");
4074 return 0;
4075 }
4076 if (n == PyTuple_GET_SIZE(ob))
4077 return 1;
4078 PyErr_Format(
4079 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00004080 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004081 return 0;
4082}
4083
Tim Peters6d6c1a32001-08-02 04:15:00 +00004084/* Generic wrappers for overloadable 'operators' such as __getitem__ */
4085
4086/* There's a wrapper *function* for each distinct function typedef used
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004087 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00004088 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4089 Most tables have only one entry; the tables for binary operators have two
4090 entries, one regular and one with reversed arguments. */
4091
4092static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004093wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004094{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004095 lenfunc func = (lenfunc)wrapped;
4096 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004097
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004098 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004099 return NULL;
4100 res = (*func)(self);
4101 if (res == -1 && PyErr_Occurred())
4102 return NULL;
4103 return PyInt_FromLong((long)res);
4104}
4105
Tim Peters6d6c1a32001-08-02 04:15:00 +00004106static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004107wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4108{
4109 inquiry func = (inquiry)wrapped;
4110 int res;
4111
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004112 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004113 return NULL;
4114 res = (*func)(self);
4115 if (res == -1 && PyErr_Occurred())
4116 return NULL;
4117 return PyBool_FromLong((long)res);
4118}
4119
4120static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004121wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4122{
4123 binaryfunc func = (binaryfunc)wrapped;
4124 PyObject *other;
4125
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004126 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004127 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004128 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004129 return (*func)(self, other);
4130}
4131
4132static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004133wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4134{
4135 binaryfunc func = (binaryfunc)wrapped;
4136 PyObject *other;
4137
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004138 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004139 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004140 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004141 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004142 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004143 Py_INCREF(Py_NotImplemented);
4144 return Py_NotImplemented;
4145 }
4146 return (*func)(self, other);
4147}
4148
4149static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00004150wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4151{
4152 binaryfunc func = (binaryfunc)wrapped;
4153 PyObject *other;
4154
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004155 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004156 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004157 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004158 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004159 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00004160 Py_INCREF(Py_NotImplemented);
4161 return Py_NotImplemented;
4162 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004163 return (*func)(other, self);
4164}
4165
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004166static PyObject *
4167wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
4168{
4169 coercion func = (coercion)wrapped;
4170 PyObject *other, *res;
4171 int ok;
4172
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004173 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004174 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004175 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004176 ok = func(&self, &other);
4177 if (ok < 0)
4178 return NULL;
4179 if (ok > 0) {
4180 Py_INCREF(Py_NotImplemented);
4181 return Py_NotImplemented;
4182 }
4183 res = PyTuple_New(2);
4184 if (res == NULL) {
4185 Py_DECREF(self);
4186 Py_DECREF(other);
4187 return NULL;
4188 }
4189 PyTuple_SET_ITEM(res, 0, self);
4190 PyTuple_SET_ITEM(res, 1, other);
4191 return res;
4192}
4193
Tim Peters6d6c1a32001-08-02 04:15:00 +00004194static PyObject *
4195wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4196{
4197 ternaryfunc func = (ternaryfunc)wrapped;
4198 PyObject *other;
4199 PyObject *third = Py_None;
4200
4201 /* Note: This wrapper only works for __pow__() */
4202
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004203 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004204 return NULL;
4205 return (*func)(self, other, third);
4206}
4207
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004208static PyObject *
4209wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4210{
4211 ternaryfunc func = (ternaryfunc)wrapped;
4212 PyObject *other;
4213 PyObject *third = Py_None;
4214
4215 /* Note: This wrapper only works for __pow__() */
4216
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004217 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00004218 return NULL;
4219 return (*func)(other, self, third);
4220}
4221
Tim Peters6d6c1a32001-08-02 04:15:00 +00004222static PyObject *
4223wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4224{
4225 unaryfunc func = (unaryfunc)wrapped;
4226
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004227 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004228 return NULL;
4229 return (*func)(self);
4230}
4231
Tim Peters6d6c1a32001-08-02 04:15:00 +00004232static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00004233wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004234{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004235 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00004236 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004237 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004238
Armin Rigo314861c2006-03-30 14:04:02 +00004239 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4240 return NULL;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004241 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Armin Rigo314861c2006-03-30 14:04:02 +00004242 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004243 return NULL;
4244 return (*func)(self, i);
4245}
4246
Martin v. Löwis18e16552006-02-15 17:27:45 +00004247static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00004248getindex(PyObject *self, PyObject *arg)
4249{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004250 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004251
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004252 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004253 if (i == -1 && PyErr_Occurred())
4254 return -1;
4255 if (i < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00004256 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004257 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00004258 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004259 if (n < 0)
4260 return -1;
4261 i += n;
4262 }
4263 }
4264 return i;
4265}
4266
4267static PyObject *
4268wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4269{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004270 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004271 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004272 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004273
Guido van Rossumf4593e02001-10-03 12:09:30 +00004274 if (PyTuple_GET_SIZE(args) == 1) {
4275 arg = PyTuple_GET_ITEM(args, 0);
4276 i = getindex(self, arg);
4277 if (i == -1 && PyErr_Occurred())
4278 return NULL;
4279 return (*func)(self, i);
4280 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004281 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004282 assert(PyErr_Occurred());
4283 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004284}
4285
Tim Peters6d6c1a32001-08-02 04:15:00 +00004286static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004287wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004288{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004289 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
4290 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004291
Martin v. Löwis18e16552006-02-15 17:27:45 +00004292 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004293 return NULL;
4294 return (*func)(self, i, j);
4295}
4296
Tim Peters6d6c1a32001-08-02 04:15:00 +00004297static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004298wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004299{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004300 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4301 Py_ssize_t i;
4302 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004303 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004304
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004305 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004306 return NULL;
4307 i = getindex(self, arg);
4308 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00004309 return NULL;
4310 res = (*func)(self, i, value);
4311 if (res == -1 && PyErr_Occurred())
4312 return NULL;
4313 Py_INCREF(Py_None);
4314 return Py_None;
4315}
4316
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004317static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00004318wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004319{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004320 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4321 Py_ssize_t i;
4322 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00004323 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004324
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004325 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00004326 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004327 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00004328 i = getindex(self, arg);
4329 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004330 return NULL;
4331 res = (*func)(self, i, NULL);
4332 if (res == -1 && PyErr_Occurred())
4333 return NULL;
4334 Py_INCREF(Py_None);
4335 return Py_None;
4336}
4337
Tim Peters6d6c1a32001-08-02 04:15:00 +00004338static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004339wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004340{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004341 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4342 Py_ssize_t i, j;
4343 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004344 PyObject *value;
4345
Martin v. Löwis18e16552006-02-15 17:27:45 +00004346 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004347 return NULL;
4348 res = (*func)(self, i, j, value);
4349 if (res == -1 && PyErr_Occurred())
4350 return NULL;
4351 Py_INCREF(Py_None);
4352 return Py_None;
4353}
4354
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004355static PyObject *
4356wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
4357{
Martin v. Löwis18e16552006-02-15 17:27:45 +00004358 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4359 Py_ssize_t i, j;
4360 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004361
Martin v. Löwis18e16552006-02-15 17:27:45 +00004362 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004363 return NULL;
4364 res = (*func)(self, i, j, NULL);
4365 if (res == -1 && PyErr_Occurred())
4366 return NULL;
4367 Py_INCREF(Py_None);
4368 return Py_None;
4369}
4370
Tim Peters6d6c1a32001-08-02 04:15:00 +00004371/* XXX objobjproc is a misnomer; should be objargpred */
4372static PyObject *
4373wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4374{
4375 objobjproc func = (objobjproc)wrapped;
4376 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004377 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004378
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004379 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004380 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004381 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004382 res = (*func)(self, value);
4383 if (res == -1 && PyErr_Occurred())
4384 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00004385 else
4386 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004387}
4388
Tim Peters6d6c1a32001-08-02 04:15:00 +00004389static PyObject *
4390wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4391{
4392 objobjargproc func = (objobjargproc)wrapped;
4393 int res;
4394 PyObject *key, *value;
4395
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004396 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004397 return NULL;
4398 res = (*func)(self, key, value);
4399 if (res == -1 && PyErr_Occurred())
4400 return NULL;
4401 Py_INCREF(Py_None);
4402 return Py_None;
4403}
4404
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004405static PyObject *
4406wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4407{
4408 objobjargproc func = (objobjargproc)wrapped;
4409 int res;
4410 PyObject *key;
4411
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004412 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004413 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004414 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00004415 res = (*func)(self, key, NULL);
4416 if (res == -1 && PyErr_Occurred())
4417 return NULL;
4418 Py_INCREF(Py_None);
4419 return Py_None;
4420}
4421
Tim Peters6d6c1a32001-08-02 04:15:00 +00004422static PyObject *
4423wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
4424{
4425 cmpfunc func = (cmpfunc)wrapped;
4426 int res;
4427 PyObject *other;
4428
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004429 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004430 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004431 other = PyTuple_GET_ITEM(args, 0);
Christian Heimese93237d2007-12-19 02:37:44 +00004432 if (Py_TYPE(other)->tp_compare != func &&
4433 !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
Guido van Rossumceccae52001-09-18 20:03:57 +00004434 PyErr_Format(
4435 PyExc_TypeError,
4436 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +00004437 Py_TYPE(self)->tp_name,
4438 Py_TYPE(self)->tp_name,
4439 Py_TYPE(other)->tp_name);
Guido van Rossumceccae52001-09-18 20:03:57 +00004440 return NULL;
4441 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004442 res = (*func)(self, other);
4443 if (PyErr_Occurred())
4444 return NULL;
4445 return PyInt_FromLong((long)res);
4446}
4447
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004448/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004449 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004450static int
4451hackcheck(PyObject *self, setattrofunc func, char *what)
4452{
Christian Heimese93237d2007-12-19 02:37:44 +00004453 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004454 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4455 type = type->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004456 /* If type is NULL now, this is a really weird type.
4457 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004458 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004459 PyErr_Format(PyExc_TypeError,
4460 "can't apply this %s to %s object",
4461 what,
4462 type->tp_name);
4463 return 0;
4464 }
4465 return 1;
4466}
4467
Tim Peters6d6c1a32001-08-02 04:15:00 +00004468static PyObject *
4469wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4470{
4471 setattrofunc func = (setattrofunc)wrapped;
4472 int res;
4473 PyObject *name, *value;
4474
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004475 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004476 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004477 if (!hackcheck(self, func, "__setattr__"))
4478 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004479 res = (*func)(self, name, value);
4480 if (res < 0)
4481 return NULL;
4482 Py_INCREF(Py_None);
4483 return Py_None;
4484}
4485
4486static PyObject *
4487wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4488{
4489 setattrofunc func = (setattrofunc)wrapped;
4490 int res;
4491 PyObject *name;
4492
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004493 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004494 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004495 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004496 if (!hackcheck(self, func, "__delattr__"))
4497 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004498 res = (*func)(self, name, NULL);
4499 if (res < 0)
4500 return NULL;
4501 Py_INCREF(Py_None);
4502 return Py_None;
4503}
4504
Tim Peters6d6c1a32001-08-02 04:15:00 +00004505static PyObject *
4506wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4507{
4508 hashfunc func = (hashfunc)wrapped;
4509 long res;
4510
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004511 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004512 return NULL;
4513 res = (*func)(self);
4514 if (res == -1 && PyErr_Occurred())
4515 return NULL;
4516 return PyInt_FromLong(res);
4517}
4518
Tim Peters6d6c1a32001-08-02 04:15:00 +00004519static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004520wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004521{
4522 ternaryfunc func = (ternaryfunc)wrapped;
4523
Guido van Rossumc8e56452001-10-22 00:43:43 +00004524 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004525}
4526
Tim Peters6d6c1a32001-08-02 04:15:00 +00004527static PyObject *
4528wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4529{
4530 richcmpfunc func = (richcmpfunc)wrapped;
4531 PyObject *other;
4532
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004533 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004534 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004535 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004536 return (*func)(self, other, op);
4537}
4538
4539#undef RICHCMP_WRAPPER
4540#define RICHCMP_WRAPPER(NAME, OP) \
4541static PyObject * \
4542richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4543{ \
4544 return wrap_richcmpfunc(self, args, wrapped, OP); \
4545}
4546
Jack Jansen8e938b42001-08-08 15:29:49 +00004547RICHCMP_WRAPPER(lt, Py_LT)
4548RICHCMP_WRAPPER(le, Py_LE)
4549RICHCMP_WRAPPER(eq, Py_EQ)
4550RICHCMP_WRAPPER(ne, Py_NE)
4551RICHCMP_WRAPPER(gt, Py_GT)
4552RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004553
Tim Peters6d6c1a32001-08-02 04:15:00 +00004554static PyObject *
4555wrap_next(PyObject *self, PyObject *args, void *wrapped)
4556{
4557 unaryfunc func = (unaryfunc)wrapped;
4558 PyObject *res;
4559
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004560 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004561 return NULL;
4562 res = (*func)(self);
4563 if (res == NULL && !PyErr_Occurred())
4564 PyErr_SetNone(PyExc_StopIteration);
4565 return res;
4566}
4567
Tim Peters6d6c1a32001-08-02 04:15:00 +00004568static PyObject *
4569wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4570{
4571 descrgetfunc func = (descrgetfunc)wrapped;
4572 PyObject *obj;
4573 PyObject *type = NULL;
4574
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004575 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004576 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004577 if (obj == Py_None)
4578 obj = NULL;
4579 if (type == Py_None)
4580 type = NULL;
4581 if (type == NULL &&obj == NULL) {
4582 PyErr_SetString(PyExc_TypeError,
4583 "__get__(None, None) is invalid");
4584 return NULL;
4585 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004586 return (*func)(self, obj, type);
4587}
4588
Tim Peters6d6c1a32001-08-02 04:15:00 +00004589static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004590wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004591{
4592 descrsetfunc func = (descrsetfunc)wrapped;
4593 PyObject *obj, *value;
4594 int ret;
4595
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004596 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004597 return NULL;
4598 ret = (*func)(self, obj, value);
4599 if (ret < 0)
4600 return NULL;
4601 Py_INCREF(Py_None);
4602 return Py_None;
4603}
Guido van Rossum22b13872002-08-06 21:41:44 +00004604
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004605static PyObject *
4606wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4607{
4608 descrsetfunc func = (descrsetfunc)wrapped;
4609 PyObject *obj;
4610 int ret;
4611
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004612 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004613 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004614 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004615 ret = (*func)(self, obj, NULL);
4616 if (ret < 0)
4617 return NULL;
4618 Py_INCREF(Py_None);
4619 return Py_None;
4620}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004621
Tim Peters6d6c1a32001-08-02 04:15:00 +00004622static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004623wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004624{
4625 initproc func = (initproc)wrapped;
4626
Guido van Rossumc8e56452001-10-22 00:43:43 +00004627 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004628 return NULL;
4629 Py_INCREF(Py_None);
4630 return Py_None;
4631}
4632
Tim Peters6d6c1a32001-08-02 04:15:00 +00004633static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004634tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004635{
Barry Warsaw60f01882001-08-22 19:24:42 +00004636 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004637 PyObject *arg0, *res;
4638
4639 if (self == NULL || !PyType_Check(self))
4640 Py_FatalError("__new__() called with non-type 'self'");
4641 type = (PyTypeObject *)self;
4642 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004643 PyErr_Format(PyExc_TypeError,
4644 "%s.__new__(): not enough arguments",
4645 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004646 return NULL;
4647 }
4648 arg0 = PyTuple_GET_ITEM(args, 0);
4649 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004650 PyErr_Format(PyExc_TypeError,
4651 "%s.__new__(X): X is not a type object (%s)",
4652 type->tp_name,
Christian Heimese93237d2007-12-19 02:37:44 +00004653 Py_TYPE(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004654 return NULL;
4655 }
4656 subtype = (PyTypeObject *)arg0;
4657 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004658 PyErr_Format(PyExc_TypeError,
4659 "%s.__new__(%s): %s is not a subtype of %s",
4660 type->tp_name,
4661 subtype->tp_name,
4662 subtype->tp_name,
4663 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004664 return NULL;
4665 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004666
4667 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004668 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004669 most derived base that's not a heap type is this type. */
4670 staticbase = subtype;
4671 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4672 staticbase = staticbase->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004673 /* If staticbase is NULL now, it is a really weird type.
4674 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004675 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004676 PyErr_Format(PyExc_TypeError,
4677 "%s.__new__(%s) is not safe, use %s.__new__()",
4678 type->tp_name,
4679 subtype->tp_name,
4680 staticbase == NULL ? "?" : staticbase->tp_name);
4681 return NULL;
4682 }
4683
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004684 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4685 if (args == NULL)
4686 return NULL;
4687 res = type->tp_new(subtype, args, kwds);
4688 Py_DECREF(args);
4689 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004690}
4691
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004692static struct PyMethodDef tp_new_methoddef[] = {
Neal Norwitza84dcd72007-05-22 07:16:44 +00004693 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004694 PyDoc_STR("T.__new__(S, ...) -> "
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004695 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004696 {0}
4697};
4698
4699static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004700add_tp_new_wrapper(PyTypeObject *type)
4701{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004702 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004703
Guido van Rossum687ae002001-10-15 22:03:32 +00004704 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004705 return 0;
4706 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004707 if (func == NULL)
4708 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004709 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004710 Py_DECREF(func);
4711 return -1;
4712 }
4713 Py_DECREF(func);
4714 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004715}
4716
Guido van Rossumf040ede2001-08-07 16:40:56 +00004717/* Slot wrappers that call the corresponding __foo__ slot. See comments
4718 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004719
Guido van Rossumdc91b992001-08-08 22:26:22 +00004720#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004721static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004722FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004723{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004724 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004725 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004726}
4727
Guido van Rossumdc91b992001-08-08 22:26:22 +00004728#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004729static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004730FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004731{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004732 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004733 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004734}
4735
Guido van Rossumcd118802003-01-06 22:57:47 +00004736/* Boolean helper for SLOT1BINFULL().
4737 right.__class__ is a nontrivial subclass of left.__class__. */
4738static int
4739method_is_overloaded(PyObject *left, PyObject *right, char *name)
4740{
4741 PyObject *a, *b;
4742 int ok;
4743
Christian Heimese93237d2007-12-19 02:37:44 +00004744 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004745 if (b == NULL) {
4746 PyErr_Clear();
4747 /* If right doesn't have it, it's not overloaded */
4748 return 0;
4749 }
4750
Christian Heimese93237d2007-12-19 02:37:44 +00004751 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004752 if (a == NULL) {
4753 PyErr_Clear();
4754 Py_DECREF(b);
4755 /* If right has it but left doesn't, it's overloaded */
4756 return 1;
4757 }
4758
4759 ok = PyObject_RichCompareBool(a, b, Py_NE);
4760 Py_DECREF(a);
4761 Py_DECREF(b);
4762 if (ok < 0) {
4763 PyErr_Clear();
4764 return 0;
4765 }
4766
4767 return ok;
4768}
4769
Guido van Rossumdc91b992001-08-08 22:26:22 +00004770
4771#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004772static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004773FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004774{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004775 static PyObject *cache_str, *rcache_str; \
Christian Heimese93237d2007-12-19 02:37:44 +00004776 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4777 Py_TYPE(other)->tp_as_number != NULL && \
4778 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4779 if (Py_TYPE(self)->tp_as_number != NULL && \
4780 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004781 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004782 if (do_other && \
Christian Heimese93237d2007-12-19 02:37:44 +00004783 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004784 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004785 r = call_maybe( \
4786 other, ROPSTR, &rcache_str, "(O)", self); \
4787 if (r != Py_NotImplemented) \
4788 return r; \
4789 Py_DECREF(r); \
4790 do_other = 0; \
4791 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004792 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004793 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004794 if (r != Py_NotImplemented || \
Christian Heimese93237d2007-12-19 02:37:44 +00004795 Py_TYPE(other) == Py_TYPE(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004796 return r; \
4797 Py_DECREF(r); \
4798 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004799 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004800 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004801 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004802 } \
4803 Py_INCREF(Py_NotImplemented); \
4804 return Py_NotImplemented; \
4805}
4806
4807#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4808 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4809
4810#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4811static PyObject * \
4812FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4813{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004814 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004815 return call_method(self, OPSTR, &cache_str, \
4816 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004817}
4818
Martin v. Löwis18e16552006-02-15 17:27:45 +00004819static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004820slot_sq_length(PyObject *self)
4821{
Guido van Rossum2730b132001-08-28 18:22:14 +00004822 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004823 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004824 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004825
4826 if (res == NULL)
4827 return -1;
Neal Norwitz1872b1c2006-08-12 18:44:06 +00004828 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004829 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004830 if (len < 0) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00004831 if (!PyErr_Occurred())
4832 PyErr_SetString(PyExc_ValueError,
4833 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004834 return -1;
4835 }
Guido van Rossum26111622001-10-01 16:42:49 +00004836 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004837}
4838
Guido van Rossumf4593e02001-10-03 12:09:30 +00004839/* Super-optimized version of slot_sq_item.
4840 Other slots could do the same... */
4841static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004842slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004843{
4844 static PyObject *getitem_str;
4845 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4846 descrgetfunc f;
4847
4848 if (getitem_str == NULL) {
4849 getitem_str = PyString_InternFromString("__getitem__");
4850 if (getitem_str == NULL)
4851 return NULL;
4852 }
Christian Heimese93237d2007-12-19 02:37:44 +00004853 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004854 if (func != NULL) {
Christian Heimese93237d2007-12-19 02:37:44 +00004855 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004856 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004857 else {
Christian Heimese93237d2007-12-19 02:37:44 +00004858 func = f(func, self, (PyObject *)(Py_TYPE(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004859 if (func == NULL) {
4860 return NULL;
4861 }
4862 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004863 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004864 if (ival != NULL) {
4865 args = PyTuple_New(1);
4866 if (args != NULL) {
4867 PyTuple_SET_ITEM(args, 0, ival);
4868 retval = PyObject_Call(func, args, NULL);
4869 Py_XDECREF(args);
4870 Py_XDECREF(func);
4871 return retval;
4872 }
4873 }
4874 }
4875 else {
4876 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4877 }
4878 Py_XDECREF(args);
4879 Py_XDECREF(ival);
4880 Py_XDECREF(func);
4881 return NULL;
4882}
4883
Martin v. Löwis18e16552006-02-15 17:27:45 +00004884SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004885
4886static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004887slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004888{
4889 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004890 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004891
4892 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004893 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004894 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004895 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004896 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004897 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004898 if (res == NULL)
4899 return -1;
4900 Py_DECREF(res);
4901 return 0;
4902}
4903
4904static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004905slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004906{
4907 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004908 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004909
4910 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004911 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004912 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004913 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004914 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004915 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004916 if (res == NULL)
4917 return -1;
4918 Py_DECREF(res);
4919 return 0;
4920}
4921
4922static int
4923slot_sq_contains(PyObject *self, PyObject *value)
4924{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004925 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004926 int result = -1;
4927
Guido van Rossum60718732001-08-28 17:47:51 +00004928 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004929
Guido van Rossum55f20992001-10-01 17:18:22 +00004930 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004931 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004932 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004933 if (args == NULL)
4934 res = NULL;
4935 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004936 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004937 Py_DECREF(args);
4938 }
4939 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004940 if (res != NULL) {
4941 result = PyObject_IsTrue(res);
4942 Py_DECREF(res);
4943 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004944 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004945 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004946 /* Possible results: -1 and 1 */
4947 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004948 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004949 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004950 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004951}
4952
Tim Peters6d6c1a32001-08-02 04:15:00 +00004953#define slot_mp_length slot_sq_length
4954
Guido van Rossumdc91b992001-08-08 22:26:22 +00004955SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004956
4957static int
4958slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4959{
4960 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004961 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004962
4963 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004964 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004965 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004966 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004967 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004968 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004969 if (res == NULL)
4970 return -1;
4971 Py_DECREF(res);
4972 return 0;
4973}
4974
Guido van Rossumdc91b992001-08-08 22:26:22 +00004975SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4976SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4977SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4978SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4979SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4980SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4981
Jeremy Hylton938ace62002-07-17 16:30:39 +00004982static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004983
4984SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4985 nb_power, "__pow__", "__rpow__")
4986
4987static PyObject *
4988slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4989{
Guido van Rossum2730b132001-08-28 18:22:14 +00004990 static PyObject *pow_str;
4991
Guido van Rossumdc91b992001-08-08 22:26:22 +00004992 if (modulus == Py_None)
4993 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004994 /* Three-arg power doesn't use __rpow__. But ternary_op
4995 can call this when the second argument's type uses
4996 slot_nb_power, so check before calling self.__pow__. */
Christian Heimese93237d2007-12-19 02:37:44 +00004997 if (Py_TYPE(self)->tp_as_number != NULL &&
4998 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00004999 return call_method(self, "__pow__", &pow_str,
5000 "(OO)", other, modulus);
5001 }
5002 Py_INCREF(Py_NotImplemented);
5003 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00005004}
5005
5006SLOT0(slot_nb_negative, "__neg__")
5007SLOT0(slot_nb_positive, "__pos__")
5008SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005009
5010static int
5011slot_nb_nonzero(PyObject *self)
5012{
Tim Petersea7f75d2002-12-07 21:39:16 +00005013 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00005014 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00005015 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005016
Guido van Rossum55f20992001-10-01 17:18:22 +00005017 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005018 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00005019 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00005020 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00005021 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00005022 if (func == NULL)
5023 return PyErr_Occurred() ? -1 : 1;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005024 }
Tim Petersea7f75d2002-12-07 21:39:16 +00005025 args = PyTuple_New(0);
5026 if (args != NULL) {
5027 PyObject *temp = PyObject_Call(func, args, NULL);
5028 Py_DECREF(args);
5029 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00005030 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00005031 result = PyObject_IsTrue(temp);
5032 else {
5033 PyErr_Format(PyExc_TypeError,
5034 "__nonzero__ should return "
5035 "bool or int, returned %s",
5036 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00005037 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00005038 }
Tim Petersea7f75d2002-12-07 21:39:16 +00005039 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00005040 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00005041 }
Guido van Rossum55f20992001-10-01 17:18:22 +00005042 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00005043 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005044}
5045
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005046
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005047static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005048slot_nb_index(PyObject *self)
5049{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005050 static PyObject *index_str;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005051 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005052}
5053
5054
Guido van Rossumdc91b992001-08-08 22:26:22 +00005055SLOT0(slot_nb_invert, "__invert__")
5056SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5057SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5058SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5059SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5060SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005061
5062static int
5063slot_nb_coerce(PyObject **a, PyObject **b)
5064{
5065 static PyObject *coerce_str;
5066 PyObject *self = *a, *other = *b;
5067
5068 if (self->ob_type->tp_as_number != NULL &&
5069 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5070 PyObject *r;
5071 r = call_maybe(
5072 self, "__coerce__", &coerce_str, "(O)", other);
5073 if (r == NULL)
5074 return -1;
5075 if (r == Py_NotImplemented) {
5076 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005077 }
Guido van Rossum55f20992001-10-01 17:18:22 +00005078 else {
5079 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5080 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005081 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00005082 Py_DECREF(r);
5083 return -1;
5084 }
5085 *a = PyTuple_GET_ITEM(r, 0);
5086 Py_INCREF(*a);
5087 *b = PyTuple_GET_ITEM(r, 1);
5088 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005089 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00005090 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005091 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00005092 }
5093 if (other->ob_type->tp_as_number != NULL &&
5094 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5095 PyObject *r;
5096 r = call_maybe(
5097 other, "__coerce__", &coerce_str, "(O)", self);
5098 if (r == NULL)
5099 return -1;
5100 if (r == Py_NotImplemented) {
5101 Py_DECREF(r);
5102 return 1;
5103 }
5104 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5105 PyErr_SetString(PyExc_TypeError,
5106 "__coerce__ didn't return a 2-tuple");
5107 Py_DECREF(r);
5108 return -1;
5109 }
5110 *a = PyTuple_GET_ITEM(r, 1);
5111 Py_INCREF(*a);
5112 *b = PyTuple_GET_ITEM(r, 0);
5113 Py_INCREF(*b);
5114 Py_DECREF(r);
5115 return 0;
5116 }
5117 return 1;
5118}
5119
Guido van Rossumdc91b992001-08-08 22:26:22 +00005120SLOT0(slot_nb_int, "__int__")
5121SLOT0(slot_nb_long, "__long__")
5122SLOT0(slot_nb_float, "__float__")
5123SLOT0(slot_nb_oct, "__oct__")
5124SLOT0(slot_nb_hex, "__hex__")
5125SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5126SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5127SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
5128SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
5129SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Martin v. Löwisfd963262007-02-09 12:19:32 +00005130/* Can't use SLOT1 here, because nb_inplace_power is ternary */
5131static PyObject *
5132slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5133{
5134 static PyObject *cache_str;
5135 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
5136}
Guido van Rossumdc91b992001-08-08 22:26:22 +00005137SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5138SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5139SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5140SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5141SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5142SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
5143 "__floordiv__", "__rfloordiv__")
5144SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5145SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5146SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00005147
5148static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00005149half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005150{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005151 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005152 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005153 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005154
Guido van Rossum60718732001-08-28 17:47:51 +00005155 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005156 if (func == NULL) {
5157 PyErr_Clear();
5158 }
5159 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005160 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005161 if (args == NULL)
5162 res = NULL;
5163 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005164 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005165 Py_DECREF(args);
5166 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00005167 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005168 if (res != Py_NotImplemented) {
5169 if (res == NULL)
5170 return -2;
5171 c = PyInt_AsLong(res);
5172 Py_DECREF(res);
5173 if (c == -1 && PyErr_Occurred())
5174 return -2;
5175 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
5176 }
5177 Py_DECREF(res);
5178 }
5179 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005180}
5181
Guido van Rossumab3b0342001-09-18 20:38:53 +00005182/* This slot is published for the benefit of try_3way_compare in object.c */
5183int
5184_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00005185{
5186 int c;
5187
Christian Heimese93237d2007-12-19 02:37:44 +00005188 if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005189 c = half_compare(self, other);
5190 if (c <= 1)
5191 return c;
5192 }
Christian Heimese93237d2007-12-19 02:37:44 +00005193 if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005194 c = half_compare(other, self);
5195 if (c < -1)
5196 return -2;
5197 if (c <= 1)
5198 return -c;
5199 }
5200 return (void *)self < (void *)other ? -1 :
5201 (void *)self > (void *)other ? 1 : 0;
5202}
5203
5204static PyObject *
5205slot_tp_repr(PyObject *self)
5206{
5207 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005208 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005209
Guido van Rossum60718732001-08-28 17:47:51 +00005210 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005211 if (func != NULL) {
5212 res = PyEval_CallObject(func, NULL);
5213 Py_DECREF(func);
5214 return res;
5215 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00005216 PyErr_Clear();
5217 return PyString_FromFormat("<%s object at %p>",
Christian Heimese93237d2007-12-19 02:37:44 +00005218 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005219}
5220
5221static PyObject *
5222slot_tp_str(PyObject *self)
5223{
5224 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005225 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005226
Guido van Rossum60718732001-08-28 17:47:51 +00005227 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005228 if (func != NULL) {
5229 res = PyEval_CallObject(func, NULL);
5230 Py_DECREF(func);
5231 return res;
5232 }
5233 else {
5234 PyErr_Clear();
5235 return slot_tp_repr(self);
5236 }
5237}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005238
5239static long
5240slot_tp_hash(PyObject *self)
5241{
Tim Peters61ce0a92002-12-06 23:38:02 +00005242 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00005243 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005244 long h;
5245
Guido van Rossum60718732001-08-28 17:47:51 +00005246 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005247
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005248 if (func != NULL && func != Py_None) {
Tim Peters61ce0a92002-12-06 23:38:02 +00005249 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005250 Py_DECREF(func);
5251 if (res == NULL)
5252 return -1;
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00005253 if (PyLong_Check(res))
Armin Rigo51fc8c42006-08-09 14:55:26 +00005254 h = PyLong_Type.tp_hash(res);
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00005255 else
5256 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00005257 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005258 }
5259 else {
Georg Brandl30b78042007-12-20 21:03:02 +00005260 Py_XDECREF(func); /* may be None */
Guido van Rossumb8f63662001-08-15 23:57:02 +00005261 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005262 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005263 if (func == NULL) {
5264 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005265 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005266 }
5267 if (func != NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00005268 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
5269 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005270 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005271 return -1;
5272 }
5273 PyErr_Clear();
5274 h = _Py_HashPointer((void *)self);
5275 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005276 if (h == -1 && !PyErr_Occurred())
5277 h = -2;
5278 return h;
5279}
5280
5281static PyObject *
5282slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5283{
Guido van Rossum60718732001-08-28 17:47:51 +00005284 static PyObject *call_str;
5285 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005286 PyObject *res;
5287
5288 if (meth == NULL)
5289 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00005290
Tim Peters6d6c1a32001-08-02 04:15:00 +00005291 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00005292
Tim Peters6d6c1a32001-08-02 04:15:00 +00005293 Py_DECREF(meth);
5294 return res;
5295}
5296
Guido van Rossum14a6f832001-10-17 13:59:09 +00005297/* There are two slot dispatch functions for tp_getattro.
5298
5299 - slot_tp_getattro() is used when __getattribute__ is overridden
5300 but no __getattr__ hook is present;
5301
5302 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5303
Guido van Rossumc334df52002-04-04 23:44:47 +00005304 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5305 detects the absence of __getattr__ and then installs the simpler slot if
5306 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00005307
Tim Peters6d6c1a32001-08-02 04:15:00 +00005308static PyObject *
5309slot_tp_getattro(PyObject *self, PyObject *name)
5310{
Guido van Rossum14a6f832001-10-17 13:59:09 +00005311 static PyObject *getattribute_str = NULL;
5312 return call_method(self, "__getattribute__", &getattribute_str,
5313 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005314}
5315
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005316static PyObject *
5317slot_tp_getattr_hook(PyObject *self, PyObject *name)
5318{
Christian Heimese93237d2007-12-19 02:37:44 +00005319 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005320 PyObject *getattr, *getattribute, *res;
5321 static PyObject *getattribute_str = NULL;
5322 static PyObject *getattr_str = NULL;
5323
5324 if (getattr_str == NULL) {
5325 getattr_str = PyString_InternFromString("__getattr__");
5326 if (getattr_str == NULL)
5327 return NULL;
5328 }
5329 if (getattribute_str == NULL) {
5330 getattribute_str =
5331 PyString_InternFromString("__getattribute__");
5332 if (getattribute_str == NULL)
5333 return NULL;
5334 }
5335 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005336 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005337 /* No __getattr__ hook: use a simpler dispatcher */
5338 tp->tp_getattro = slot_tp_getattro;
5339 return slot_tp_getattro(self, name);
5340 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005341 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005342 if (getattribute == NULL ||
Christian Heimese93237d2007-12-19 02:37:44 +00005343 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00005344 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5345 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005346 res = PyObject_GenericGetAttr(self, name);
5347 else
Georg Brandl684fd0c2006-05-25 19:15:31 +00005348 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00005349 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005350 PyErr_Clear();
Georg Brandl684fd0c2006-05-25 19:15:31 +00005351 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00005352 }
5353 return res;
5354}
5355
Tim Peters6d6c1a32001-08-02 04:15:00 +00005356static int
5357slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5358{
5359 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005360 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005361
5362 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00005363 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005364 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005365 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005366 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005367 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005368 if (res == NULL)
5369 return -1;
5370 Py_DECREF(res);
5371 return 0;
5372}
5373
Guido van Rossum0b7b6fd2007-12-19 22:51:13 +00005374static char *name_op[] = {
5375 "__lt__",
5376 "__le__",
5377 "__eq__",
5378 "__ne__",
5379 "__gt__",
5380 "__ge__",
5381};
5382
Tim Peters6d6c1a32001-08-02 04:15:00 +00005383static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00005384half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005385{
Guido van Rossumb8f63662001-08-15 23:57:02 +00005386 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005387 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00005388
Guido van Rossum60718732001-08-28 17:47:51 +00005389 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005390 if (func == NULL) {
5391 PyErr_Clear();
5392 Py_INCREF(Py_NotImplemented);
5393 return Py_NotImplemented;
5394 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00005395 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005396 if (args == NULL)
5397 res = NULL;
5398 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00005399 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005400 Py_DECREF(args);
5401 }
5402 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005403 return res;
5404}
5405
Guido van Rossumb8f63662001-08-15 23:57:02 +00005406static PyObject *
5407slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5408{
5409 PyObject *res;
5410
Christian Heimese93237d2007-12-19 02:37:44 +00005411 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00005412 res = half_richcompare(self, other, op);
5413 if (res != Py_NotImplemented)
5414 return res;
5415 Py_DECREF(res);
5416 }
Christian Heimese93237d2007-12-19 02:37:44 +00005417 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00005418 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005419 if (res != Py_NotImplemented) {
5420 return res;
5421 }
5422 Py_DECREF(res);
5423 }
5424 Py_INCREF(Py_NotImplemented);
5425 return Py_NotImplemented;
5426}
5427
5428static PyObject *
5429slot_tp_iter(PyObject *self)
5430{
5431 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005432 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005433
Guido van Rossum60718732001-08-28 17:47:51 +00005434 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005435 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00005436 PyObject *args;
5437 args = res = PyTuple_New(0);
5438 if (args != NULL) {
5439 res = PyObject_Call(func, args, NULL);
5440 Py_DECREF(args);
5441 }
5442 Py_DECREF(func);
5443 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005444 }
5445 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005446 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005447 if (func == NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00005448 PyErr_Format(PyExc_TypeError,
5449 "'%.200s' object is not iterable",
Christian Heimese93237d2007-12-19 02:37:44 +00005450 Py_TYPE(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005451 return NULL;
5452 }
5453 Py_DECREF(func);
5454 return PySeqIter_New(self);
5455}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005456
5457static PyObject *
5458slot_tp_iternext(PyObject *self)
5459{
Guido van Rossum2730b132001-08-28 18:22:14 +00005460 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00005461 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005462}
5463
Guido van Rossum1a493502001-08-17 16:47:50 +00005464static PyObject *
5465slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5466{
Christian Heimese93237d2007-12-19 02:37:44 +00005467 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00005468 PyObject *get;
5469 static PyObject *get_str = NULL;
5470
5471 if (get_str == NULL) {
5472 get_str = PyString_InternFromString("__get__");
5473 if (get_str == NULL)
5474 return NULL;
5475 }
5476 get = _PyType_Lookup(tp, get_str);
5477 if (get == NULL) {
5478 /* Avoid further slowdowns */
5479 if (tp->tp_descr_get == slot_tp_descr_get)
5480 tp->tp_descr_get = NULL;
5481 Py_INCREF(self);
5482 return self;
5483 }
Guido van Rossum2c252392001-08-24 10:13:31 +00005484 if (obj == NULL)
5485 obj = Py_None;
5486 if (type == NULL)
5487 type = Py_None;
Georg Brandl684fd0c2006-05-25 19:15:31 +00005488 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005489}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005490
5491static int
5492slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5493{
Guido van Rossum2c252392001-08-24 10:13:31 +00005494 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005495 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005496
5497 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00005498 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005499 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00005500 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005501 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005502 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005503 if (res == NULL)
5504 return -1;
5505 Py_DECREF(res);
5506 return 0;
5507}
5508
5509static int
5510slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5511{
Guido van Rossum60718732001-08-28 17:47:51 +00005512 static PyObject *init_str;
5513 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005514 PyObject *res;
5515
5516 if (meth == NULL)
5517 return -1;
5518 res = PyObject_Call(meth, args, kwds);
5519 Py_DECREF(meth);
5520 if (res == NULL)
5521 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005522 if (res != Py_None) {
Georg Brandlccff7852006-06-18 22:17:29 +00005523 PyErr_Format(PyExc_TypeError,
5524 "__init__() should return None, not '%.200s'",
Christian Heimese93237d2007-12-19 02:37:44 +00005525 Py_TYPE(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005526 Py_DECREF(res);
5527 return -1;
5528 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005529 Py_DECREF(res);
5530 return 0;
5531}
5532
5533static PyObject *
5534slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5535{
Guido van Rossum7bed2132002-08-08 21:57:53 +00005536 static PyObject *new_str;
5537 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005538 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005539 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005540
Guido van Rossum7bed2132002-08-08 21:57:53 +00005541 if (new_str == NULL) {
5542 new_str = PyString_InternFromString("__new__");
5543 if (new_str == NULL)
5544 return NULL;
5545 }
5546 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005547 if (func == NULL)
5548 return NULL;
5549 assert(PyTuple_Check(args));
5550 n = PyTuple_GET_SIZE(args);
5551 newargs = PyTuple_New(n+1);
5552 if (newargs == NULL)
5553 return NULL;
5554 Py_INCREF(type);
5555 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5556 for (i = 0; i < n; i++) {
5557 x = PyTuple_GET_ITEM(args, i);
5558 Py_INCREF(x);
5559 PyTuple_SET_ITEM(newargs, i+1, x);
5560 }
5561 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005562 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005563 Py_DECREF(func);
5564 return x;
5565}
5566
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005567static void
5568slot_tp_del(PyObject *self)
5569{
5570 static PyObject *del_str = NULL;
5571 PyObject *del, *res;
5572 PyObject *error_type, *error_value, *error_traceback;
5573
5574 /* Temporarily resurrect the object. */
5575 assert(self->ob_refcnt == 0);
5576 self->ob_refcnt = 1;
5577
5578 /* Save the current exception, if any. */
5579 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5580
5581 /* Execute __del__ method, if any. */
5582 del = lookup_maybe(self, "__del__", &del_str);
5583 if (del != NULL) {
5584 res = PyEval_CallObject(del, NULL);
5585 if (res == NULL)
5586 PyErr_WriteUnraisable(del);
5587 else
5588 Py_DECREF(res);
5589 Py_DECREF(del);
5590 }
5591
5592 /* Restore the saved exception. */
5593 PyErr_Restore(error_type, error_value, error_traceback);
5594
5595 /* Undo the temporary resurrection; can't use DECREF here, it would
5596 * cause a recursive call.
5597 */
5598 assert(self->ob_refcnt > 0);
5599 if (--self->ob_refcnt == 0)
5600 return; /* this is the normal path out */
5601
5602 /* __del__ resurrected it! Make it look like the original Py_DECREF
5603 * never happened.
5604 */
5605 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005606 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005607 _Py_NewReference(self);
5608 self->ob_refcnt = refcnt;
5609 }
Christian Heimese93237d2007-12-19 02:37:44 +00005610 assert(!PyType_IS_GC(Py_TYPE(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005611 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005612 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5613 * we need to undo that. */
5614 _Py_DEC_REFTOTAL;
5615 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5616 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005617 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5618 * _Py_NewReference bumped tp_allocs: both of those need to be
5619 * undone.
5620 */
5621#ifdef COUNT_ALLOCS
Christian Heimese93237d2007-12-19 02:37:44 +00005622 --Py_TYPE(self)->tp_frees;
5623 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005624#endif
5625}
5626
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005627
5628/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005629 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005630 structure, which incorporates the additional structures used for numbers,
5631 sequences and mappings.
5632 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005633 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005634 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5635 terminated with an all-zero entry. (This table is further initialized and
5636 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005637
Guido van Rossum6d204072001-10-21 00:44:31 +00005638typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005639
5640#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005641#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005642#undef ETSLOT
5643#undef SQSLOT
5644#undef MPSLOT
5645#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005646#undef UNSLOT
5647#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005648#undef BINSLOT
5649#undef RBINSLOT
5650
Guido van Rossum6d204072001-10-21 00:44:31 +00005651#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005652 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5653 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005654#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5655 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005656 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005657#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005658 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005659 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005660#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5661 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5662#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5663 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5664#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5665 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5666#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5667 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5668 "x." NAME "() <==> " DOC)
5669#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5670 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5671 "x." NAME "(y) <==> x" DOC "y")
5672#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5673 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5674 "x." NAME "(y) <==> x" DOC "y")
5675#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5676 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5677 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005678#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5679 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5680 "x." NAME "(y) <==> " DOC)
5681#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5682 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5683 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005684
5685static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005686 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005687 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005688 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5689 The logic in abstract.c always falls back to nb_add/nb_multiply in
5690 this case. Defining both the nb_* and the sq_* slots to call the
5691 user-defined methods has unexpected side-effects, as shown by
5692 test_descr.notimplemented() */
5693 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005694 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00005695 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005696 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005697 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005698 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005699 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5700 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005701 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005702 "x.__getslice__(i, j) <==> x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005703 \n\
5704 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005705 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005706 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005707 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005708 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005709 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005710 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005711 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005712 \n\
5713 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005714 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005715 "x.__delslice__(i, j) <==> del x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005716 \n\
5717 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005718 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5719 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005720 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005721 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005722 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005723 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005724
Martin v. Löwis18e16552006-02-15 17:27:45 +00005725 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005726 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005727 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005728 wrap_binaryfunc,
5729 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005730 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005731 wrap_objobjargproc,
5732 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005733 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005734 wrap_delitem,
5735 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005736
Guido van Rossum6d204072001-10-21 00:44:31 +00005737 BINSLOT("__add__", nb_add, slot_nb_add,
5738 "+"),
5739 RBINSLOT("__radd__", nb_add, slot_nb_add,
5740 "+"),
5741 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5742 "-"),
5743 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5744 "-"),
5745 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5746 "*"),
5747 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5748 "*"),
5749 BINSLOT("__div__", nb_divide, slot_nb_divide,
5750 "/"),
5751 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5752 "/"),
5753 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5754 "%"),
5755 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5756 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005757 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005758 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005759 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005760 "divmod(y, x)"),
5761 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5762 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5763 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5764 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5765 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5766 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5767 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5768 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005769 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005770 "x != 0"),
5771 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5772 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5773 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5774 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5775 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5776 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5777 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5778 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5779 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5780 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5781 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5782 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5783 "x.__coerce__(y) <==> coerce(x, y)"),
5784 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5785 "int(x)"),
5786 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5787 "long(x)"),
5788 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5789 "float(x)"),
5790 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5791 "oct(x)"),
5792 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5793 "hex(x)"),
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005794 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005795 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005796 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5797 wrap_binaryfunc, "+"),
5798 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5799 wrap_binaryfunc, "-"),
5800 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5801 wrap_binaryfunc, "*"),
5802 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5803 wrap_binaryfunc, "/"),
5804 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5805 wrap_binaryfunc, "%"),
5806 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005807 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005808 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5809 wrap_binaryfunc, "<<"),
5810 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5811 wrap_binaryfunc, ">>"),
5812 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5813 wrap_binaryfunc, "&"),
5814 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5815 wrap_binaryfunc, "^"),
5816 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5817 wrap_binaryfunc, "|"),
5818 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5819 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5820 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5821 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5822 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5823 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5824 IBSLOT("__itruediv__", nb_inplace_true_divide,
5825 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005826
Guido van Rossum6d204072001-10-21 00:44:31 +00005827 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5828 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005829 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005830 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5831 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005832 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005833 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5834 "x.__cmp__(y) <==> cmp(x,y)"),
5835 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5836 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005837 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5838 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005839 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005840 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5841 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5842 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5843 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5844 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5845 "x.__setattr__('name', value) <==> x.name = value"),
5846 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5847 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5848 "x.__delattr__('name') <==> del x.name"),
5849 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5850 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5851 "x.__lt__(y) <==> x<y"),
5852 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5853 "x.__le__(y) <==> x<=y"),
5854 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5855 "x.__eq__(y) <==> x==y"),
5856 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5857 "x.__ne__(y) <==> x!=y"),
5858 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5859 "x.__gt__(y) <==> x>y"),
5860 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5861 "x.__ge__(y) <==> x>=y"),
5862 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5863 "x.__iter__() <==> iter(x)"),
5864 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5865 "x.next() -> the next value, or raise StopIteration"),
5866 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5867 "descr.__get__(obj[, type]) -> value"),
5868 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5869 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005870 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5871 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005872 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005873 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005874 "see x.__class__.__doc__ for signature",
5875 PyWrapperFlag_KEYWORDS),
5876 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005877 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005878 {NULL}
5879};
5880
Guido van Rossumc334df52002-04-04 23:44:47 +00005881/* Given a type pointer and an offset gotten from a slotdef entry, return a
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005882 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005883 the offset to the type pointer, since it takes care to indirect through the
5884 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5885 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005886static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005887slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005888{
5889 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005890 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005891
Guido van Rossume5c691a2003-03-07 15:13:17 +00005892 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005893 assert(offset >= 0);
Skip Montanaro429433b2006-04-18 00:35:43 +00005894 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5895 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005896 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005897 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005898 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005899 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005900 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005901 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005902 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005903 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005904 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005905 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005906 }
5907 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005908 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005909 }
5910 if (ptr != NULL)
5911 ptr += offset;
5912 return (void **)ptr;
5913}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005914
Guido van Rossumc334df52002-04-04 23:44:47 +00005915/* Length of array of slotdef pointers used to store slots with the
5916 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5917 the same __name__, for any __name__. Since that's a static property, it is
5918 appropriate to declare fixed-size arrays for this. */
5919#define MAX_EQUIV 10
5920
5921/* Return a slot pointer for a given name, but ONLY if the attribute has
5922 exactly one slot function. The name must be an interned string. */
5923static void **
5924resolve_slotdups(PyTypeObject *type, PyObject *name)
5925{
5926 /* XXX Maybe this could be optimized more -- but is it worth it? */
5927
5928 /* pname and ptrs act as a little cache */
5929 static PyObject *pname;
5930 static slotdef *ptrs[MAX_EQUIV];
5931 slotdef *p, **pp;
5932 void **res, **ptr;
5933
5934 if (pname != name) {
5935 /* Collect all slotdefs that match name into ptrs. */
5936 pname = name;
5937 pp = ptrs;
5938 for (p = slotdefs; p->name_strobj; p++) {
5939 if (p->name_strobj == name)
5940 *pp++ = p;
5941 }
5942 *pp = NULL;
5943 }
5944
5945 /* Look in all matching slots of the type; if exactly one of these has
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005946 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005947 res = NULL;
5948 for (pp = ptrs; *pp; pp++) {
5949 ptr = slotptr(type, (*pp)->offset);
5950 if (ptr == NULL || *ptr == NULL)
5951 continue;
5952 if (res != NULL)
5953 return NULL;
5954 res = ptr;
5955 }
5956 return res;
5957}
5958
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005959/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005960 does some incredibly complex thinking and then sticks something into the
5961 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5962 interests, and then stores a generic wrapper or a specific function into
5963 the slot.) Return a pointer to the next slotdef with a different offset,
5964 because that's convenient for fixup_slot_dispatchers(). */
5965static slotdef *
5966update_one_slot(PyTypeObject *type, slotdef *p)
5967{
5968 PyObject *descr;
5969 PyWrapperDescrObject *d;
5970 void *generic = NULL, *specific = NULL;
5971 int use_generic = 0;
5972 int offset = p->offset;
5973 void **ptr = slotptr(type, offset);
5974
5975 if (ptr == NULL) {
5976 do {
5977 ++p;
5978 } while (p->offset == offset);
5979 return p;
5980 }
5981 do {
5982 descr = _PyType_Lookup(type, p->name_strobj);
5983 if (descr == NULL)
5984 continue;
Christian Heimese93237d2007-12-19 02:37:44 +00005985 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00005986 void **tptr = resolve_slotdups(type, p->name_strobj);
5987 if (tptr == NULL || tptr == ptr)
5988 generic = p->function;
5989 d = (PyWrapperDescrObject *)descr;
5990 if (d->d_base->wrapper == p->wrapper &&
5991 PyType_IsSubtype(type, d->d_type))
5992 {
5993 if (specific == NULL ||
5994 specific == d->d_wrapped)
5995 specific = d->d_wrapped;
5996 else
5997 use_generic = 1;
5998 }
5999 }
Christian Heimese93237d2007-12-19 02:37:44 +00006000 else if (Py_TYPE(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00006001 PyCFunction_GET_FUNCTION(descr) ==
6002 (PyCFunction)tp_new_wrapper &&
6003 strcmp(p->name, "__new__") == 0)
6004 {
6005 /* The __new__ wrapper is not a wrapper descriptor,
6006 so must be special-cased differently.
6007 If we don't do this, creating an instance will
6008 always use slot_tp_new which will look up
6009 __new__ in the MRO which will call tp_new_wrapper
6010 which will look through the base classes looking
6011 for a static base and call its tp_new (usually
6012 PyType_GenericNew), after performing various
6013 sanity checks and constructing a new argument
6014 list. Cut all that nonsense short -- this speeds
6015 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00006016 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00006017 /* XXX I'm not 100% sure that there isn't a hole
6018 in this reasoning that requires additional
6019 sanity checks. I'll buy the first person to
6020 point out a bug in this reasoning a beer. */
6021 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006022 else {
6023 use_generic = 1;
6024 generic = p->function;
6025 }
6026 } while ((++p)->offset == offset);
6027 if (specific && !use_generic)
6028 *ptr = specific;
6029 else
6030 *ptr = generic;
6031 return p;
6032}
6033
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006034/* In the type, update the slots whose slotdefs are gathered in the pp array.
6035 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006036static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006037update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006038{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006039 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006040
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006041 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00006042 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006043 return 0;
6044}
6045
Guido van Rossumc334df52002-04-04 23:44:47 +00006046/* Comparison function for qsort() to compare slotdefs by their offset, and
6047 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006048static int
6049slotdef_cmp(const void *aa, const void *bb)
6050{
6051 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
6052 int c = a->offset - b->offset;
6053 if (c != 0)
6054 return c;
6055 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00006056 /* Cannot use a-b, as this gives off_t,
6057 which may lose precision when converted to int. */
6058 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006059}
6060
Guido van Rossumc334df52002-04-04 23:44:47 +00006061/* Initialize the slotdefs table by adding interned string objects for the
6062 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006063static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006064init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006065{
6066 slotdef *p;
6067 static int initialized = 0;
6068
6069 if (initialized)
6070 return;
6071 for (p = slotdefs; p->name; p++) {
6072 p->name_strobj = PyString_InternFromString(p->name);
6073 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00006074 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006075 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006076 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
6077 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006078 initialized = 1;
6079}
6080
Guido van Rossumc334df52002-04-04 23:44:47 +00006081/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006082static int
6083update_slot(PyTypeObject *type, PyObject *name)
6084{
Guido van Rossumc334df52002-04-04 23:44:47 +00006085 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006086 slotdef *p;
6087 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006088 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006089
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00006090 /* Clear the VALID_VERSION flag of 'type' and all its
6091 subclasses. This could possibly be unified with the
6092 update_subclasses() recursion below, but carefully:
6093 they each have their own conditions on which to stop
6094 recursing into subclasses. */
6095 type_modified(type);
6096
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006097 init_slotdefs();
6098 pp = ptrs;
6099 for (p = slotdefs; p->name; p++) {
6100 /* XXX assume name is interned! */
6101 if (p->name_strobj == name)
6102 *pp++ = p;
6103 }
6104 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006105 for (pp = ptrs; *pp; pp++) {
6106 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006107 offset = p->offset;
6108 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006109 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00006110 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006111 }
Guido van Rossumc334df52002-04-04 23:44:47 +00006112 if (ptrs[0] == NULL)
6113 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006114 return update_subclasses(type, name,
6115 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00006116}
6117
Guido van Rossumc334df52002-04-04 23:44:47 +00006118/* Store the proper functions in the slot dispatches at class (type)
6119 definition time, based upon which operations the class overrides in its
6120 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00006121static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006122fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00006123{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00006124 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00006125
Guido van Rossumd396b9c2001-10-13 20:02:41 +00006126 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00006127 for (p = slotdefs; p->name; )
6128 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00006129}
Guido van Rossum705f0f52001-08-24 16:47:00 +00006130
Michael W. Hudson98bbc492002-11-26 14:47:27 +00006131static void
6132update_all_slots(PyTypeObject* type)
6133{
6134 slotdef *p;
6135
6136 init_slotdefs();
6137 for (p = slotdefs; p->name; p++) {
6138 /* update_slot returns int but can't actually fail */
6139 update_slot(type, p->name_strobj);
6140 }
6141}
6142
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006143/* recurse_down_subclasses() and update_subclasses() are mutually
6144 recursive functions to call a callback for all subclasses,
6145 but refraining from recursing into subclasses that define 'name'. */
6146
6147static int
6148update_subclasses(PyTypeObject *type, PyObject *name,
6149 update_callback callback, void *data)
6150{
6151 if (callback(type, data) < 0)
6152 return -1;
6153 return recurse_down_subclasses(type, name, callback, data);
6154}
6155
6156static int
6157recurse_down_subclasses(PyTypeObject *type, PyObject *name,
6158 update_callback callback, void *data)
6159{
6160 PyTypeObject *subclass;
6161 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006162 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006163
6164 subclasses = type->tp_subclasses;
6165 if (subclasses == NULL)
6166 return 0;
6167 assert(PyList_Check(subclasses));
6168 n = PyList_GET_SIZE(subclasses);
6169 for (i = 0; i < n; i++) {
6170 ref = PyList_GET_ITEM(subclasses, i);
6171 assert(PyWeakref_CheckRef(ref));
6172 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6173 assert(subclass != NULL);
6174 if ((PyObject *)subclass == Py_None)
6175 continue;
6176 assert(PyType_Check(subclass));
6177 /* Avoid recursing down into unaffected classes */
6178 dict = subclass->tp_dict;
6179 if (dict != NULL && PyDict_Check(dict) &&
6180 PyDict_GetItem(dict, name) != NULL)
6181 continue;
6182 if (update_subclasses(subclass, name, callback, data) < 0)
6183 return -1;
6184 }
6185 return 0;
6186}
6187
Guido van Rossum6d204072001-10-21 00:44:31 +00006188/* This function is called by PyType_Ready() to populate the type's
6189 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00006190 function slot (like tp_repr) that's defined in the type, one or more
6191 corresponding descriptors are added in the type's tp_dict dictionary
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006192 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00006193 cause more than one descriptor to be added (for example, the nb_add
6194 slot adds both __add__ and __radd__ descriptors) and some function
6195 slots compete for the same descriptor (for example both sq_item and
6196 mp_subscript generate a __getitem__ descriptor).
6197
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006198 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00006199 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00006200 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00006201 between competing slots: the members of PyHeapTypeObject are listed
6202 from most general to least general, so the most general slot is
6203 preferred. In particular, because as_mapping comes before as_sequence,
6204 for a type that defines both mp_subscript and sq_item, mp_subscript
6205 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00006206
6207 This only adds new descriptors and doesn't overwrite entries in
6208 tp_dict that were previously defined. The descriptors contain a
6209 reference to the C function they must call, so that it's safe if they
6210 are copied into a subtype's __dict__ and the subtype has a different
6211 C function in its slot -- calling the method defined by the
6212 descriptor will call the C function that was used to create it,
6213 rather than the C function present in the slot when it is called.
6214 (This is important because a subtype may have a C function in the
6215 slot that calls the method from the dictionary, and we want to avoid
6216 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00006217
6218static int
6219add_operators(PyTypeObject *type)
6220{
6221 PyObject *dict = type->tp_dict;
6222 slotdef *p;
6223 PyObject *descr;
6224 void **ptr;
6225
6226 init_slotdefs();
6227 for (p = slotdefs; p->name; p++) {
6228 if (p->wrapper == NULL)
6229 continue;
6230 ptr = slotptr(type, p->offset);
6231 if (!ptr || !*ptr)
6232 continue;
6233 if (PyDict_GetItem(dict, p->name_strobj))
6234 continue;
6235 descr = PyDescr_NewWrapper(type, p, *ptr);
6236 if (descr == NULL)
6237 return -1;
6238 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6239 return -1;
6240 Py_DECREF(descr);
6241 }
6242 if (type->tp_new != NULL) {
6243 if (add_tp_new_wrapper(type) < 0)
6244 return -1;
6245 }
6246 return 0;
6247}
6248
Guido van Rossum705f0f52001-08-24 16:47:00 +00006249
6250/* Cooperative 'super' */
6251
6252typedef struct {
6253 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00006254 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006255 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006256 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006257} superobject;
6258
Guido van Rossum6f799372001-09-20 20:46:19 +00006259static PyMemberDef super_members[] = {
6260 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6261 "the class invoking super()"},
6262 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6263 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006264 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00006265 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006266 {0}
6267};
6268
Guido van Rossum705f0f52001-08-24 16:47:00 +00006269static void
6270super_dealloc(PyObject *self)
6271{
6272 superobject *su = (superobject *)self;
6273
Guido van Rossum048eb752001-10-02 21:24:57 +00006274 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006275 Py_XDECREF(su->obj);
6276 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006277 Py_XDECREF(su->obj_type);
Christian Heimese93237d2007-12-19 02:37:44 +00006278 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006279}
6280
6281static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006282super_repr(PyObject *self)
6283{
6284 superobject *su = (superobject *)self;
6285
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006286 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006287 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00006288 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006289 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006290 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006291 else
6292 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00006293 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006294 su->type ? su->type->tp_name : "NULL");
6295}
6296
6297static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00006298super_getattro(PyObject *self, PyObject *name)
6299{
6300 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006301 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006302
Guido van Rossum76ba09f2003-04-16 19:40:58 +00006303 if (!skip) {
6304 /* We want __class__ to return the class of the super object
6305 (i.e. super, or a subclass), not the class of su->obj. */
6306 skip = (PyString_Check(name) &&
6307 PyString_GET_SIZE(name) == 9 &&
6308 strcmp(PyString_AS_STRING(name), "__class__") == 0);
6309 }
6310
6311 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00006312 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006313 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006314 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006315 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006316
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006317 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00006318 mro = starttype->tp_mro;
6319
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006320 if (mro == NULL)
6321 n = 0;
6322 else {
6323 assert(PyTuple_Check(mro));
6324 n = PyTuple_GET_SIZE(mro);
6325 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006326 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00006327 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00006328 break;
6329 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006330 i++;
6331 res = NULL;
6332 for (; i < n; i++) {
6333 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00006334 if (PyType_Check(tmp))
6335 dict = ((PyTypeObject *)tmp)->tp_dict;
6336 else if (PyClass_Check(tmp))
6337 dict = ((PyClassObject *)tmp)->cl_dict;
6338 else
6339 continue;
6340 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00006341 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00006342 Py_INCREF(res);
Christian Heimese93237d2007-12-19 02:37:44 +00006343 f = Py_TYPE(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006344 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006345 tmp = f(res,
6346 /* Only pass 'obj' param if
6347 this is instance-mode super
6348 (See SF ID #743627)
6349 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00006350 (su->obj == (PyObject *)
6351 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00006352 ? (PyObject *)NULL
6353 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00006354 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006355 Py_DECREF(res);
6356 res = tmp;
6357 }
6358 return res;
6359 }
6360 }
6361 }
6362 return PyObject_GenericGetAttr(self, name);
6363}
6364
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006365static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00006366supercheck(PyTypeObject *type, PyObject *obj)
6367{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006368 /* Check that a super() call makes sense. Return a type object.
6369
6370 obj can be a new-style class, or an instance of one:
6371
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006372 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006373 used for class methods; the return value is obj.
6374
6375 - If it is an instance, it must be an instance of 'type'. This is
6376 the normal case; the return value is obj.__class__.
6377
6378 But... when obj is an instance, we want to allow for the case where
Christian Heimese93237d2007-12-19 02:37:44 +00006379 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006380 This will allow using super() with a proxy for obj.
6381 */
6382
Guido van Rossum8e80a722003-02-18 19:22:22 +00006383 /* Check for first bullet above (special case) */
6384 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6385 Py_INCREF(obj);
6386 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006387 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00006388
6389 /* Normal case */
Christian Heimese93237d2007-12-19 02:37:44 +00006390 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6391 Py_INCREF(Py_TYPE(obj));
6392 return Py_TYPE(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006393 }
6394 else {
6395 /* Try the slow way */
6396 static PyObject *class_str = NULL;
6397 PyObject *class_attr;
6398
6399 if (class_str == NULL) {
6400 class_str = PyString_FromString("__class__");
6401 if (class_str == NULL)
6402 return NULL;
6403 }
6404
6405 class_attr = PyObject_GetAttr(obj, class_str);
6406
6407 if (class_attr != NULL &&
6408 PyType_Check(class_attr) &&
Christian Heimese93237d2007-12-19 02:37:44 +00006409 (PyTypeObject *)class_attr != Py_TYPE(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006410 {
6411 int ok = PyType_IsSubtype(
6412 (PyTypeObject *)class_attr, type);
6413 if (ok)
6414 return (PyTypeObject *)class_attr;
6415 }
6416
6417 if (class_attr == NULL)
6418 PyErr_Clear();
6419 else
6420 Py_DECREF(class_attr);
6421 }
6422
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006423 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006424 "super(type, obj): "
6425 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006426 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006427}
6428
Guido van Rossum705f0f52001-08-24 16:47:00 +00006429static PyObject *
6430super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6431{
6432 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00006433 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006434
6435 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6436 /* Not binding to an object, or already bound */
6437 Py_INCREF(self);
6438 return self;
6439 }
Christian Heimese93237d2007-12-19 02:37:44 +00006440 if (Py_TYPE(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00006441 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006442 call its type */
Christian Heimese93237d2007-12-19 02:37:44 +00006443 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006444 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00006445 else {
6446 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006447 PyTypeObject *obj_type = supercheck(su->type, obj);
6448 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006449 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00006450 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006451 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00006452 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006453 return NULL;
6454 Py_INCREF(su->type);
6455 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00006456 newobj->type = su->type;
6457 newobj->obj = obj;
6458 newobj->obj_type = obj_type;
6459 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006460 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006461}
6462
6463static int
6464super_init(PyObject *self, PyObject *args, PyObject *kwds)
6465{
6466 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00006467 PyTypeObject *type;
6468 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006469 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006470
Georg Brandl5d59c092006-09-30 08:43:30 +00006471 if (!_PyArg_NoKeywords("super", kwds))
6472 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006473 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
6474 return -1;
6475 if (obj == Py_None)
6476 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006477 if (obj != NULL) {
6478 obj_type = supercheck(type, obj);
6479 if (obj_type == NULL)
6480 return -1;
6481 Py_INCREF(obj);
6482 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006483 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006484 su->type = type;
6485 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006486 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006487 return 0;
6488}
6489
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006490PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00006491"super(type) -> unbound super object\n"
6492"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006493"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006494"Typical use to call a cooperative superclass method:\n"
6495"class C(B):\n"
6496" def meth(self, arg):\n"
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006497" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006498
Guido van Rossum048eb752001-10-02 21:24:57 +00006499static int
6500super_traverse(PyObject *self, visitproc visit, void *arg)
6501{
6502 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006503
Thomas Woutersc6e55062006-04-15 21:47:09 +00006504 Py_VISIT(su->obj);
6505 Py_VISIT(su->type);
6506 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006507
6508 return 0;
6509}
6510
Guido van Rossum705f0f52001-08-24 16:47:00 +00006511PyTypeObject PySuper_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00006512 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00006513 "super", /* tp_name */
6514 sizeof(superobject), /* tp_basicsize */
6515 0, /* tp_itemsize */
6516 /* methods */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006517 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006518 0, /* tp_print */
6519 0, /* tp_getattr */
6520 0, /* tp_setattr */
6521 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006522 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006523 0, /* tp_as_number */
6524 0, /* tp_as_sequence */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006525 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006526 0, /* tp_hash */
6527 0, /* tp_call */
6528 0, /* tp_str */
6529 super_getattro, /* tp_getattro */
6530 0, /* tp_setattro */
6531 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006532 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6533 Py_TPFLAGS_BASETYPE, /* tp_flags */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006534 super_doc, /* tp_doc */
6535 super_traverse, /* tp_traverse */
6536 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006537 0, /* tp_richcompare */
6538 0, /* tp_weaklistoffset */
6539 0, /* tp_iter */
6540 0, /* tp_iternext */
6541 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006542 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006543 0, /* tp_getset */
6544 0, /* tp_base */
6545 0, /* tp_dict */
6546 super_descr_get, /* tp_descr_get */
6547 0, /* tp_descr_set */
6548 0, /* tp_dictoffset */
6549 super_init, /* tp_init */
6550 PyType_GenericAlloc, /* tp_alloc */
6551 PyType_GenericNew, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006552 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006553};